JavaScript Program to Print Reverse Pyramid Star Pattern

Introduction

A reverse pyramid star pattern consists of stars (*) arranged in a triangular shape, where the number of stars decreases with each row, forming an inverted pyramid. This is a great exercise for practicing loops and formatting in JavaScript.

Problem Statement

Create a JavaScript program that:

  • Accepts the number of rows for the reverse pyramid.
  • Prints a reverse pyramid pattern using stars (*).

Example:

  • Input: rows = 5
  • Output:
    *********
     *******
      *****
       ***
        *
    

Solution Steps

  1. Input the Number of Rows: The user specifies how many rows the reverse pyramid should have.
  2. Use Nested Loops: The outer loop handles the rows, and the inner loops handle printing the stars and spaces.
  3. Display the Reverse Pyramid: Print stars in decreasing order for each row, with spaces for alignment.

JavaScript Program

// Step 1: Input the number of rows for the reverse pyramid
let rows = parseInt(prompt("Enter the number of rows: "));

// Step 2: Outer loop for rows (decreasing stars)
for (let i = rows; i >= 1; i--) {
    let output = '';
    
    // Step 3: Print spaces for alignment
    for (let j = 0; j < rows - i; j++) {
        output += ' ';
    }
    
    // Step 4: Print stars for the current row
    for (let k = 0; k < 2 * i - 1; k++) {
        output += '*';
    }
    
    // Print the output for the current row
    console.log(output);
}

Explanation

Step 1: Input the Number of Rows

  • The program starts by asking the user to input the number of rows for the reverse pyramid. This input is converted to an integer using parseInt().

Step 2: Outer Loop for Rows

  • The outer loop controls how many rows are printed. It runs from rows to 1, ensuring that the number of stars decreases as the row number decreases.

Step 3: Print Spaces for Alignment

  • The first inner loop prints spaces to align the stars. The number of spaces increases as the row number decreases.

Step 4: Print Stars

  • The second inner loop prints stars (*) in decreasing order. The number of stars printed follows the formula 2 * i - 1, where i is the current row number.

Step 5: Output the Row

  • After constructing the row with spaces and stars, it is printed using console.log().

Output Example

For rows = 5, the output will be:

*********
 *******
  *****
   ***
    *

For rows = 4, the output will be:

*******
 *****
  ***
   *

Conclusion

This JavaScript program prints a reverse pyramid star pattern using nested loops. The number of stars decreases with each row, and spaces are printed to align the stars in the center. This exercise is helpful for practicing loop control and output formatting in JavaScript.

Comments