JavaScript Program to Print Numbers 1 to n
for loop in JavaScript like for(let i = 1; i <= n; i++) { console.log(i); } to print numbers from 1 to n.Examples
How to Think About It
Algorithm
Code
const n = 5; for (let i = 1; i <= n; i++) { console.log(i); }
Dry Run
Let's trace the program with n = 3 to see how it prints numbers.
Initialize n and i
n = 3, i = 1
Check if i <= n
1 <= 3 is true, so print 1
Increment i
i becomes 2
Check if i <= n
2 <= 3 is true, so print 2
Increment i
i becomes 3
Check if i <= n
3 <= 3 is true, so print 3
Increment i
i becomes 4
Check if i <= n
4 <= 3 is false, stop loop
| i | Condition i <= n | Action |
|---|---|---|
| 1 | true | Print 1 |
| 2 | true | Print 2 |
| 3 | true | Print 3 |
| 4 | false | Stop |
Why This Works
Step 1: Start from 1
We begin counting at 1 because the task is to print numbers starting from 1.
Step 2: Use a loop to repeat
The for loop repeats the printing action until the number reaches n.
Step 3: Stop after n
The loop stops when the number goes beyond n, ensuring only numbers 1 to n are printed.
Alternative Approaches
const n = 5; let i = 1; while (i <= n) { console.log(i); i++; }
function printNumbers(i, n) { if (i > n) return; console.log(i); printNumbers(i + 1, n); } printNumbers(1, 5);
const n = 5; Array.from({ length: n }, (_, i) => i + 1).forEach(num => console.log(num));
Complexity: O(n) time, O(1) space
Time Complexity
The loop runs from 1 to n, so it executes n times, making the time complexity O(n).
Space Complexity
The program uses a fixed amount of extra space regardless of n, so space complexity is O(1).
Which Approach is Fastest?
The simple for loop is fastest and most readable; recursion adds overhead and risk of stack overflow; array methods use extra memory.
| Approach | Time | Space | Best For |
|---|---|---|---|
| For loop | O(n) | O(1) | Simple and efficient counting |
| While loop | O(n) | O(1) | Similar to for loop, slightly less concise |
| Recursive function | O(n) | O(n) | Elegant but risky for large n due to stack |
| Array with forEach | O(n) | O(n) | When working with arrays or functional style |
for loop for simple counting tasks like printing numbers from 1 to n.