JavaScript Program to Print Star Pyramid Pattern

Introduction

A star pyramid pattern consists of stars (*) arranged in a triangular shape, where the number of stars increases with each row, forming a pyramid. This pattern is a great exercise to practice loops and formatting in JavaScript.

Problem Statement

Create a JavaScript program that:

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

Example:

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

Solution Steps

  1. Input the Number of Rows: The user specifies how many rows the 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 Star Pyramid: Print stars in increasing order for each row, with spaces for alignment.

JavaScript Program

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

// Step 2: Outer loop for rows
for (let i = 1; i <= rows; i++) {
    let output = '';
    
    // Step 3: Print spaces for alignment
    for (let j = 1; j <= rows - i; j++) {
        output += ' ';
    }
    
    // Step 4: Print stars for the current row
    for (let k = 1; 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 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 1 to rows.

Step 3: Print Spaces for Alignment

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

Step 4: Print Stars

  • The second inner loop prints stars (*) in increasing 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 star pyramid pattern using nested loops. The stars are printed in increasing order, and spaces are printed to align the stars in the center. This exercise helps in practicing loop control and output formatting in JavaScript.

Comments