C++ Program to Print Even Numbers
for loop starting from 2 and increments by 2, like for(int i = 2; i <= n; i += 2) std::cout << i << ' '; to print even numbers up to n.Examples
How to Think About It
Algorithm
Code
#include <iostream> int main() { int n; std::cout << "Enter the maximum number: "; std::cin >> n; for (int i = 2; i <= n; i += 2) { std::cout << i << " "; } std::cout << std::endl; return 0; }
Dry Run
Let's trace input 10 through the code
Input
User enters n = 10
Loop start
i = 2, check if i <= 10 (true), print 2
Loop continues
i = 4, check if i <= 10 (true), print 4
Loop continues
i = 6, check if i <= 10 (true), print 6
Loop continues
i = 8, check if i <= 10 (true), print 8
Loop continues
i = 10, check if i <= 10 (true), print 10
Loop ends
i = 12, check if i <= 10 (false), stop loop
| i | Condition i <= n | Action |
|---|---|---|
| 2 | true | print 2 |
| 4 | true | print 4 |
| 6 | true | print 6 |
| 8 | true | print 8 |
| 10 | true | print 10 |
| 12 | false | stop |
Why This Works
Step 1: Start from 2
We start from 2 because it is the smallest even number and the first number we want to print.
Step 2: Increment by 2
Increasing the loop variable by 2 each time ensures we only get even numbers without extra checks.
Step 3: Loop condition
The loop runs while the current number is less than or equal to the input number, so we don't print numbers beyond the limit.
Alternative Approaches
#include <iostream> int main() { int n; std::cout << "Enter the maximum number: "; std::cin >> n; for (int i = 1; i <= n; i++) { if (i % 2 == 0) { std::cout << i << " "; } } std::cout << std::endl; return 0; }
#include <iostream> int main() { int n, i = 2; std::cout << "Enter the maximum number: "; std::cin >> n; while (i <= n) { std::cout << i << " "; i += 2; } std::cout << std::endl; return 0; }
Complexity: O(n/2) time, O(1) space
Time Complexity
The loop runs roughly n/2 times because it increments by 2, so time complexity is O(n/2), which simplifies to O(n).
Space Complexity
The program uses a fixed amount of memory for variables and does not use extra space proportional to input size, so space complexity is O(1).
Which Approach is Fastest?
Incrementing by 2 is faster than checking each number for evenness because it skips odd numbers entirely.
| Approach | Time | Space | Best For |
|---|---|---|---|
| Increment by 2 in for loop | O(n) | O(1) | Efficient and simple |
| Check each number if even | O(n) | O(1) | Easy to understand but less efficient |
| While loop increment by 2 | O(n) | O(1) | Alternative syntax, same efficiency |