JavaScript Program to Print Even Numbers from 1 to n
Use a
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
Input5
Output2
4
Input10
Output2
4
6
8
10
Input1
Output
How to Think About It
To print even numbers from 1 to n, start counting from 1 up to n. For each number, check if it divides evenly by 2 using the remainder operator
%. If the remainder is zero, it means the number is even, so print it.Algorithm
1
Get the input number n.2
Start a loop from 1 to n.3
For each number, check if it is divisible by 2 with no remainder.4
If yes, print the number.5
Continue until the loop reaches n.Code
javascript
const n = 10; for (let i = 1; i <= n; i++) { if (i % 2 === 0) { console.log(i); } }
Output
2
4
6
8
10
Dry Run
Let's trace the program with n = 5 to see which numbers print.
1
Start loop
i = 1
2
Check if even
1 % 2 = 1 (not even, skip)
3
Next number
i = 2
4
Check if even
2 % 2 = 0 (even, print 2)
5
Next number
i = 3
6
Check if even
3 % 2 = 1 (not even, skip)
7
Next number
i = 4
8
Check if even
4 % 2 = 0 (even, print 4)
9
Next number
i = 5
10
Check if even
5 % 2 = 1 (not even, skip)
| i | i % 2 === 0? | Printed |
|---|---|---|
| 1 | false | |
| 2 | true | 2 |
| 3 | false | |
| 4 | true | 4 |
| 5 | false |
Why This Works
Step 1: Loop through numbers
The for loop goes from 1 to n, checking each number one by one.
Step 2: Check even condition
Using i % 2 === 0 tests if the number divides evenly by 2, meaning it is even.
Step 3: Print even numbers
If the condition is true, the number is printed using console.log.
Alternative Approaches
Increment by 2 starting from 2
javascript
const n = 10; for (let i = 2; i <= n; i += 2) { console.log(i); }
This skips odd numbers entirely, making the loop faster and simpler.
Using while loop
javascript
const n = 10; let i = 2; while (i <= n) { console.log(i); i += 2; }
A while loop can also print even numbers by increasing by 2 each time.
Using Array and filter
javascript
const n = 10; const evens = Array.from({length: n}, (_, i) => i + 1).filter(x => x % 2 === 0); evens.forEach(x => console.log(x));
This creates an array and filters even numbers, but uses more memory.
Complexity: O(n) time, O(1) space
Time Complexity
The loop runs from 1 to n, so it checks each number once, making it O(n).
Space Complexity
No extra space is used except a few variables, so space is O(1).
Which Approach is Fastest?
Incrementing by 2 is faster because it skips odd 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 starting at 2 | O(n/2) | O(1) | Faster, skips odd numbers |
| Array filter method | O(n) | O(n) | When working with arrays |
Start your loop at 2 and increase by 2 to print only even numbers efficiently.
Beginners often forget to check the remainder with
% 2 === 0 and print all numbers instead.