JavaScript Program to Print Right Arrow Star Pattern

Introduction

A right-arrow star pattern consists of stars (*) arranged in a way that resembles a right-pointing arrow. The stars start from one and increase to the middle row, then decrease back to one in the lower half. This is a useful exercise for practicing loops and formatting in JavaScript.

Problem Statement

Create a JavaScript program that:

  • Accepts the number of rows for the right arrow pattern.
  • Prints a right arrow-shaped pattern using stars (*).

Example:

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

Solution Steps

  1. Input the Number of Rows: The user specifies the number of rows for the arrow (upper half of the arrow).
  2. Use Nested Loops: The outer loop handles the rows, and the inner loops handle printing the stars.
  3. Display the Right Arrow Pattern: Print stars in increasing order for the upper part of the arrow and decreasing order for the lower part.

JavaScript Program

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

// Step 2: Print the upper part of the right arrow
for (let i = 1; i <= rows; i++) {
    let output = '';
    
    // Print stars for the current row
    for (let j = 1; j <= i; j++) {
        output += '*';
    }
    
    // Print the output for the current row
    console.log(output);
}

// Step 3: Print the lower part of the right arrow
for (let i = rows - 1; i >= 1; i--) {
    let output = '';
    
    // Print stars for the current row
    for (let j = 1; j <= i; j++) {
        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 right arrow pattern. This input is converted to an integer using parseInt().

Step 2: Print the Upper Part of the Right Arrow

  • The first loop handles printing the upper part of the arrow. The number of stars printed increases with each row, starting from 1 to rows.

Step 3: Print the Lower Part of the Right Arrow

  • The second loop handles printing the lower part of the arrow. The number of stars decreases with each row, starting from rows - 1 to 1.

Step 4: Output the Rows

  • After constructing the row with 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 right arrow star pattern using nested loops. The number of stars increases with each row in the upper part and decreases in the lower part, creating a right arrow shape. This exercise is useful for practicing loop control and formatting output in JavaScript.

Comments