Introduction
Floyd's Triangle is a right-angled triangular arrangement of consecutive numbers. It starts from 1 at the top and continues with the next number in each row. This pattern is a great exercise for practicing loops and understanding how to handle incremental numbers in JavaScript.
Problem Statement
Create a JavaScript program that:
- Accepts the number of rows for Floyd's Triangle.
- Prints Floyd's Triangle, where the numbers are arranged consecutively in rows.
Example:
- Input:
rows = 5
- Output:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
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 numbers.
- Print the Numbers in Consecutive Order: Continuously print numbers in increasing order across the rows.
JavaScript Program
// Step 1: Input the number of rows for Floyd's Triangle
let rows = parseInt(prompt("Enter the number of rows: "));
// Step 2: Initialize a counter for the numbers
let num = 1;
// Step 3: Outer loop for rows
for (let i = 1; i <= rows; i++) {
let output = '';
// Step 4: Inner loop to print numbers in each row
for (let j = 1; j <= i; j++) {
output += num + ' ';
num++;
}
// Print the output for the current row
console.log(output.trim());
}
Explanation
Step 1: Input the Number of Rows
- The program starts by asking the user to input the number of rows for Floyd's Triangle. This input is converted to an integer using
parseInt()
.
Step 2: Initialize a Counter
- A variable
num
is initialized to1
, which keeps track of the current number being printed. The value ofnum
is incremented after each number is printed.
Step 3: 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 4: Inner Loop for Numbers
- The inner loop controls how many numbers are printed in each row. The number of numbers printed in each row corresponds to the row number (
i
).
Step 5: Output the Row
- After constructing the row with numbers, it is printed using
console.log()
.
Output Example
For rows = 5
, the output will be:
1
2 3
4 5 6
7 8 9 10
11 12 13 14 15
For rows = 4
, the output will be:
1
2 3
4 5 6
7 8 9 10
Conclusion
This JavaScript program prints Floyd's Triangle using nested loops. The numbers are printed in consecutive order across the rows, and the number of elements in each row increases as the triangle grows. This exercise helps in practicing loop control, number manipulation, and formatting output in JavaScript.
Comments
Post a Comment
Leave Comment