JavaScript Program to Print Hollow Right-Angled Triangle Pattern

Introduction

A hollow right-angled triangle pattern consists of stars (*) forming the boundary of a triangle, while the inside of the triangle remains hollow (filled with spaces). This pattern is an excellent exercise to practice nested loops and conditional logic in JavaScript.

Problem Statement

Create a JavaScript program that:

  • Accepts the number of rows for the triangle.
  • Prints a hollow right-angled triangle pattern using stars (*).

Example:

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

Solution Steps

  1. Input the Number of Rows: The user specifies how many rows the triangle should have.
  2. Use Nested Loops: The outer loop handles the rows, and the inner loop handles printing stars and spaces.
  3. Conditionally Print Stars and Spaces: Stars are printed at the boundary (first row, last row, and the first and last columns of each row), while spaces are printed inside to create the hollow effect.

JavaScript Program

// Step 1: Input the number of rows for the hollow triangle
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: Inner loop for columns
    for (let j = 1; j <= i; j++) {
        // Step 4: Print stars at the boundary, else print spaces
        if (i === rows || j === 1 || j === i) {
            output += '*';
        } else {
            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 hollow right-angled triangle. 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: Inner Loop for Columns

  • The inner loop controls the number of columns printed in each row. It runs from 1 to i (where i is the current row number).

Step 4: Conditional Printing of Stars and Spaces

  • Stars (*) are printed at the boundary:
    • On the first column (j === 1),
    • On the last column of each row (j === i),
    • On the last row (i === rows).
  • Spaces are printed inside the triangle to create the hollow effect.

Output Example

For rows = 5, the output will be:

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

For rows = 6, the output will be:

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

Conclusion

This JavaScript program prints a hollow right-angled triangle star pattern using nested loops and conditional logic. The stars are printed along the boundary of the triangle, while spaces are printed inside to create the hollow effect. This exercise is helpful for practicing loop control and conditional logic in JavaScript.

Comments