JavaScript Program to Print Odd Numbers from 1 to n
for loop from 1 to n and print numbers where number % 2 !== 0, like: for(let i=1; i<=n; i++){ if(i % 2 !== 0) console.log(i); }.Examples
How to Think About It
%. If the number divided by 2 leaves a remainder of 1, it is odd, so print it. Continue this until you reach n.Algorithm
Code
const n = 10; for (let i = 1; i <= n; i++) { if (i % 2 !== 0) { console.log(i); } }
Dry Run
Let's trace the program with n = 5 through the code.
Initialize n and start loop
n = 5, i starts at 1
Check if i is odd
i = 1, 1 % 2 = 1 (odd), print 1
Increment i and repeat
i = 2, 2 % 2 = 0 (even), skip print
Continue checking
i = 3, 3 % 2 = 1 (odd), print 3
Continue checking
i = 4, 4 % 2 = 0 (even), skip print
Continue checking
i = 5, 5 % 2 = 1 (odd), print 5
| i | i % 2 | Print? |
|---|---|---|
| 1 | 1 | Yes (print 1) |
| 2 | 0 | No |
| 3 | 1 | Yes (print 3) |
| 4 | 0 | No |
| 5 | 1 | Yes (print 5) |
Why This Works
Step 1: Loop from 1 to n
The for loop goes through every number starting at 1 up to n to check each number.
Step 2: Check odd numbers
Using i % 2 !== 0 tests if the number leaves a remainder when divided by 2, meaning it is odd.
Step 3: Print odd numbers
Only numbers passing the odd check are printed, so the output shows all odd numbers from 1 to n.
Alternative Approaches
const n = 10; for (let i = 1; i <= n; i += 2) { console.log(i); }
const n = 10; let i = 1; while (i <= n) { if (i % 2 !== 0) console.log(i); i++; }
const n = 10; const odds = Array.from({length: n}, (_, i) => i + 1).filter(x => x % 2 !== 0); odds.forEach(x => console.log(x));
Complexity: O(n) time, O(1) space
Time Complexity
The loop runs from 1 to n once, so it takes linear time O(n). Checking oddness is constant time per iteration.
Space Complexity
The program uses a fixed amount of space regardless of n, so space complexity is O(1).
Which Approach is Fastest?
Incrementing by 2 is fastest because it skips even numbers, reducing iterations by half.
| Approach | Time | Space | Best For |
|---|---|---|---|
| Check each number with % 2 | O(n) | O(1) | Simple and clear |
| Increment by 2 | O(n/2) | O(1) | Faster, skips evens |
| Array filter method | O(n) | O(n) | Functional style, uses extra memory |
i += 2 to loop only through odd numbers for better performance.i % 2 !== 0 and print all numbers instead.