WAP to print the following series. 2 4 6 8... n
Objective
Write a C++ program to print the even number series: 2, 4, 6, 8 ... N.
Algorithm / Approach
- Read an integer
n. - Start a
forloop withi = 2. - Instead of
i++, increment the loop by 2 on every iteration:i = i + 2. - Print
i.
main.cpp
#include<iostream>
using namespace std;
int main() {
int n;
cout<<"Enter the Value for N : ";
cin>>n;
for(int i = 2; i<=n; i=i+2) {
cout<< i<<" ";
}
cout<< endl;
return 0;
}
Expected Output
Enter the Value for N : 20 2 4 6 8 10 12 14 16 18 20
Explanation of the Program
- Loops don't have to increment by 1. By changing the update statement of the
forloop toi = i + 2, we can skip over all the odd numbers completely. - This is mathematically much faster (O(n/2)) than checking every single number with an
if (i % 2 == 0)condition.
Complexity
Time Complexity
O(n) - Specifically O(n/2).
Space Complexity
O(1)