Open In App

JavaScript Program to Print Inverted Hollow Star Pyramid

In this article, we will write a Program to Print an Inverted Hollow Star pyramid.

Possible Inverted Hollow Star Pyramid Patterns are

There will be two different approaches based on alignments i.e. horizontal and vertical:

Horizontally Inverted Pyramid

Example: Here we are printing a Inverted hollow start pyramid.

// Function to print an inverted hollow star pyramid
function printInvertedHollowStarPyramid(rows) {

    // Loop through each row
    for (let i = 1; i <= rows; i++) {
    
       // Initialize a string for the current row
        let rowString = ''; 
        
        // Print spaces before the stars
        for (let j = 1; j < i; j++) {
        
          // Add a space to the row string
            rowString += " "; 
        }
        
        // Print stars or spaces for each row
        for (let j = 1; j <= (rows * 2 - (2 * i - 1)); j++) {
        
            // Check conditions to print stars or spaces
            if (i === 1 || j === 1 || j === (rows * 2 - (2 * i - 1))) {
            
               // Add a star to the row string
                rowString += "*"; 
            } else {
            
               // Add a space to the row string
                rowString += " "; 
            }
        }
        
        // Print the row
        console.log(rowString);
    }
}

// Example usage:
const rows = 5;
printInvertedHollowStarPyramid(rows);

Output
*********
 *     *
  *   *
   * *
    *

Vertically Inverted Pyramid

Example 1: The following code demonstrates the Right inverted pyramid.

let n = 5; 
for (let i = 1; i <= n; i++) { 
    let str = ''
    for(let j = 1; j <= n ; ++j){ 
        if(i==j||j==1) 
        str+='* '; 
        else
        str+='  '; 
    } 
  
    console.log(str); 
} 

for (let i = n-1; i >= 1; i--) {     
  let str = ''
    for(let j = 1; j <= n ; ++j){ 
        if(i==j||j==1) 
        str+='* '; 
        else
        str+='  '; 
    } 
    console.log(str); 
}

Output
*         
* *       
*   *     
*     *   
*       * 
*     *   
*   *     
* *       
*         

Example 2: The following code demonstrates the Left inverted pyramid.

let n = 5; 
for (let i = 1; i <= n; i++) { 
    let str = ''
    for(let j = 1; j <= n ; ++j){ 
        if(i+j==1+n||j==n) 
        str+='* '; 
        else
        str+='  '; 
    }   
    console.log(str); 
} 
for (let i = n-1; i >= 1; i--) {     
  let str = ''
    for(let j = 1; j <= n ; ++j){ 
        if(i+j==n+1||j==n) 
        str+='* '; 
        else
        str+='  '; 
    } 
    console.log(str); 
}

Output
        * 
      * * 
    *   * 
  *     * 
*       * 
  *     * 
    *   * 
      * * 
        * 
Article Tags :