Introduction
A right-angled triangle pattern consists of stars (*
) arranged in a triangular shape, where each row contains an increasing number of stars starting from 1. This is a simple yet useful exercise to practice using loops and formatting in JavaScript.
Problem Statement
Create a JavaScript program that:
- Accepts the number of rows for the right-angled triangle.
- Prints a right-angled triangle pattern using stars (
*
).
Example:
- Input:
rows = 5
- Output:
* ** *** **** *****
Solution Steps
- Input the Number of Rows: The user specifies how many rows the triangle should have.
- Use Nested Loops: The outer loop handles the rows, and the inner loop handles printing the stars.
- Display the Right-Angled Triangle: Print an increasing number of stars for each row.
JavaScript Program
// Step 1: Input the number of rows for the 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 to print stars for each 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-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
torows
, where each iteration represents a row.
Step 3: Inner Loop for Stars
- The inner loop controls the number of stars (
*
) printed for each row. The number of stars printed increases with each row (i
).
Step 4: Output the Row
- 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-angled triangle star pattern using nested loops. The number of stars increases with each row, creating a right-angled triangle shape. This exercise helps in practicing loop control and output formatting in JavaScript.
Comments
Post a Comment
Leave Comment