JavaScript Program to Print Floyd Triangle
let num = 1; for(let i=1; i<=rows; i++){ let row = ''; for(let j=1; j<=i; j++){ row += num++ + ' '; } console.log(row); } where rows is the number of rows you want.Examples
How to Think About It
Algorithm
Code
const rows = 5; let num = 1; for (let i = 1; i <= rows; i++) { let row = ''; for (let j = 1; j <= i; j++) { row += num++ + ' '; } console.log(row); }
Dry Run
Let's trace printing Floyd's triangle for 3 rows through the code.
Initialize
rows = 3, num = 1
Row 1 loop
i=1, row='', inner loop runs once: row='1 ', num=2
Print Row 1
Output: '1 '
Row 2 loop
i=2, row='', inner loop runs twice: row='2 3 ', num=4
Print Row 2
Output: '2 3 '
Row 3 loop
i=3, row='', inner loop runs thrice: row='4 5 6 ', num=7
Print Row 3
Output: '4 5 6 '
| Row (i) | Numbers Printed | num after row |
|---|---|---|
| 1 | 1 | 2 |
| 2 | 2 3 | 4 |
| 3 | 4 5 6 | 7 |
Why This Works
Step 1: Outer loop controls rows
The outer for loop runs from 1 to the number of rows, deciding how many rows to print.
Step 2: Inner loop prints numbers per row
The inner for loop runs as many times as the current row number, printing that many numbers.
Step 3: Number increments after each print
After printing each number, we increase num by 1 to get the next number in the triangle.
Step 4: Print each row
We build a string for each row and print it, so the triangle forms line by line.
Alternative Approaches
const rows = 5; let num = 1; for (let i = 1; i <= (rows * (rows + 1)) / 2; i++) { process.stdout.write(num++ + ' '); if (i === (Math.sqrt(8 * i + 1) - 1) / 2) { console.log(''); } }
function printFloyd(rows, current = 1, row = 1) { if (row > rows) return; let line = ''; for (let i = 0; i < row; i++) { line += current++ + ' '; } console.log(line); printFloyd(rows, current, row + 1); } printFloyd(5);
Complexity: O(n^2) time, O(1) space
Time Complexity
The program uses nested loops where the inner loop runs increasing times per row, totaling about n(n+1)/2 operations, which is O(n^2).
Space Complexity
Only a few variables are used for counting and building strings, so space is O(1) constant.
Which Approach is Fastest?
The nested loop approach is simplest and fastest for Floyd's triangle. The math or recursion methods add complexity without speed benefits.
| Approach | Time | Space | Best For |
|---|---|---|---|
| Nested loops | O(n^2) | O(1) | Readability and simplicity |
| Single loop with math | O(n^2) | O(1) | Compact but complex logic |
| Recursion | O(n^2) | O(n) | Demonstrating recursion, less efficient |