JavaScript Program to Print Number Pattern
for loops in JavaScript to print a number pattern, for example: for(let i=1; i<=5; i++){ let line=''; for(let j=1; j<=i; j++){ line += j + ' '; } console.log(line); } prints numbers in increasing order per line.Examples
How to Think About It
Algorithm
Code
const n = 5; for (let i = 1; i <= n; i++) { let line = ''; for (let j = 1; j <= i; j++) { line += j + ' '; } console.log(line); }
Dry Run
Let's trace the example where n=3 through the code.
Start outer loop with i=1
Inner loop runs j=1 to 1, line becomes '1 '
Print line for i=1
Output: '1 '
Outer loop i=2
Inner loop j=1 to 2, line becomes '1 2 '
Print line for i=2
Output: '1 2 '
Outer loop i=3
Inner loop j=1 to 3, line becomes '1 2 3 '
Print line for i=3
Output: '1 2 3 '
| i (row) | j (column) | line content |
|---|---|---|
| 1 | 1 | 1 |
| 2 | 1 | 1 |
| 2 | 2 | 1 2 |
| 3 | 1 | 1 |
| 3 | 2 | 1 2 |
| 3 | 3 | 1 2 3 |
Why This Works
Step 1: Outer loop controls rows
The outer for loop runs from 1 to n, each iteration represents a new row.
Step 2: Inner loop prints numbers
The inner for loop runs from 1 to the current row number, printing numbers in sequence.
Step 3: Building the line string
Numbers are added to a string with spaces, then printed after the inner loop ends to form the pattern line.
Alternative Approaches
const n = 5; let i = 1; while (i <= n) { let j = 1; let line = ''; while (j <= i) { line += j + ' '; j++; } console.log(line); i++; }
const n = 5; for (let i = 1; i <= n; i++) { let line = ''; for (let j = i; j >= 1; j--) { line += j + ' '; } console.log(line); }
Complexity: O(n^2) time, O(n) space
Time Complexity
The nested loops run roughly n*(n+1)/2 times, which is O(n^2), because for each row i, the inner loop runs i times.
Space Complexity
We use a string to build each line, which takes O(n) space for the longest line; no extra large data structures are used.
Which Approach is Fastest?
All approaches have similar O(n^2) time; using for loops is more concise and readable than while loops.
| Approach | Time | Space | Best For |
|---|---|---|---|
| Nested for loops | O(n^2) | O(n) | Simple and readable pattern printing |
| Nested while loops | O(n^2) | O(n) | When you prefer while loops or need more control |
| Decreasing number pattern | O(n^2) | O(n) | Different pattern style, same complexity |