JavaScript Program to Print Right Triangle Pattern
for loops in JavaScript where the outer loop controls the rows and the inner loop prints stars * to form a right triangle pattern, like for(let i=1; i<=n; i++){ let row = ''; for(let j=1; j<=i; j++){ row += '*'; } console.log(row); }.Examples
How to Think About It
Algorithm
Code
const n = 5; for (let i = 1; i <= n; i++) { let row = ''; for (let j = 1; j <= i; j++) { row += '*'; } console.log(row); }
Dry Run
Let's trace the code for n = 3 to see how the right triangle pattern is printed.
Start outer loop with i = 1
Initialize row = ''; inner loop runs j from 1 to 1; row becomes '*'; print '*'
Outer loop i = 2
Initialize row = ''; inner loop runs j from 1 to 2; row becomes '**'; print '**'
Outer loop i = 3
Initialize row = ''; inner loop runs j from 1 to 3; row becomes '***'; print '***'
| i (row) | j (stars) | row string |
|---|---|---|
| 1 | 1 | * |
| 2 | 1,2 | ** |
| 3 | 1,2,3 | *** |
Why This Works
Step 1: Outer loop controls rows
The outer for loop runs from 1 to n, representing each row of the triangle.
Step 2: Inner loop prints stars
The inner for loop runs from 1 to the current row number, adding stars to the row string.
Step 3: Print each row
After building the row string with stars, console.log prints the row, forming the triangle shape.
Alternative Approaches
const n = 5; for (let i = 1; i <= n; i++) { console.log('*'.repeat(i)); }
let i = 1; const n = 5; while (i <= n) { let j = 1; let row = ''; while (j <= i) { row += '*'; j++; } console.log(row); i++; }
Complexity: O(n^2) time, O(n) space
Time Complexity
The outer loop runs n times and the inner loop runs up to n times in the last iteration, resulting in O(n^2) time.
Space Complexity
The space used is O(n) for the string that holds stars for the largest row.
Which Approach is Fastest?
Using the string repeat() method is faster and cleaner than nested loops because it avoids manual concatenation.
| Approach | Time | Space | Best For |
|---|---|---|---|
| Nested loops | O(n^2) | O(n) | Understanding loops and manual string building |
| String repeat method | O(n^2) | O(n) | Cleaner and faster star printing |
| While loops | O(n^2) | O(n) | Beginners preferring while loops |
repeat() method to print stars quickly without an inner loop.