C# Program to Print Even Numbers
for loop with a condition to check if a number is even using i % 2 == 0, then print it with Console.WriteLine(i).Examples
How to Think About It
% operator. If yes, print it. Repeat until the end of the range.Algorithm
Code
using System; class Program { static void Main() { int start = 1; int end = 10; for (int i = start; i <= end; i++) { if (i % 2 == 0) { Console.WriteLine(i); } } } }
Dry Run
Let's trace printing even numbers from 1 to 10 through the code.
Initialize variables
start = 1, end = 10
Loop from 1 to 10
i takes values 1, 2, 3, ..., 10
Check if i is even
For i=1, 1 % 2 = 1 (odd), skip For i=2, 2 % 2 = 0 (even), print 2 For i=3, 3 % 2 = 1 (odd), skip ... and so on
Print even numbers
Print 2, 4, 6, 8, 10
| i | i % 2 == 0? | Action |
|---|---|---|
| 1 | false | skip |
| 2 | true | print 2 |
| 3 | false | skip |
| 4 | true | print 4 |
| 5 | false | skip |
| 6 | true | print 6 |
| 7 | false | skip |
| 8 | true | print 8 |
| 9 | false | skip |
| 10 | true | print 10 |
Why This Works
Step 1: Loop through numbers
The for loop goes through each number from start to end to check all candidates.
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
Only numbers passing the even check are printed using Console.WriteLine.
Alternative Approaches
using System; class Program { static void Main() { for (int i = 2; i <= 10; i += 2) { Console.WriteLine(i); } } }
using System; class Program { static void Main() { int i = 1; while (i <= 10) { if (i % 2 == 0) Console.WriteLine(i); i++; } } }
Complexity: O(n) time, O(1) space
Time Complexity
The program loops through all numbers from start to end once, so it runs in linear time O(n).
Space Complexity
It uses a fixed amount of memory regardless of input size, so space complexity is O(1).
Which Approach is Fastest?
Incrementing by 2 is faster because it skips odd numbers, reducing the number of iterations by half.
| Approach | Time | Space | Best For |
|---|---|---|---|
| Check each number with % 2 | O(n) | O(1) | Simple and clear logic |
| Increment by 2 starting at 2 | O(n/2) | O(1) | More efficient for large ranges |
| While loop with % 2 check | O(n) | O(1) | Alternative loop style |
% 2 == 0 and printing all numbers instead.