Python Program to Print Even Numbers from 1 to n
if i % 2 == 0, like this: for i in range(1, n+1): if i % 2 == 0: print(i).Examples
How to Think About It
% operator to find the remainder when divided by 2. If the remainder is zero, the number is even.Algorithm
Code
n = int(input("Enter the value of n: ")) for i in range(1, n + 1): if i % 2 == 0: print(i)
Dry Run
Let's trace the program with input n = 5 to see how it prints even numbers.
Input
User enters n = 5
Loop start
i starts at 1
Check if i is even
1 % 2 = 1 (not zero), so skip printing
Next i
i = 2, 2 % 2 = 0, print 2
Continue loop
i = 3, 3 % 2 = 1, skip; i = 4, 4 % 2 = 0, print 4; i = 5, 5 % 2 = 1, skip
Loop ends
All numbers checked up to 5
| i | i % 2 | Print? |
|---|---|---|
| 1 | 1 | No |
| 2 | 0 | Yes (2) |
| 3 | 1 | No |
| 4 | 0 | Yes (4) |
| 5 | 1 | No |
Why This Works
Step 1: Loop through numbers
The program uses a for loop to go through every number from 1 to n.
Step 2: Check even condition
It uses i % 2 == 0 to check if the number is even, meaning no remainder when divided by 2.
Step 3: Print even numbers
If the condition is true, it prints the number, so only even numbers appear in the output.
Alternative Approaches
n = int(input("Enter the value of n: ")) for i in range(2, n + 1, 2): print(i)
n = int(input("Enter the value of n: ")) evens = [str(i) for i in range(1, n + 1) if i % 2 == 0] print('\n'.join(evens))
Complexity: O(n) time, O(1) space
Time Complexity
The program checks each number from 1 to n once, so it runs in linear time O(n).
Space Complexity
It uses constant extra space O(1) because it prints numbers directly without storing them.
Which Approach is Fastest?
Using range(2, n+1, 2) is faster because it skips odd numbers, reducing loop iterations by half.
| Approach | Time | Space | Best For |
|---|---|---|---|
| Check each number with % 2 | O(n) | O(1) | Simple and clear logic |
| Range with step 2 | O(n/2) | O(1) | More efficient looping |
| List comprehension | O(n) | O(n) | When you need a list of even numbers |
range(2, n+1, 2) to loop only over even numbers for better efficiency.range(1, n) instead of range(1, n+1).