Skip to main content

ProwessApps

Learn · Practice · Excel

WAP to print the following series. 2 4 6 8... n

C++ Code Example — Series Programs

ADVERTISEMENT

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

  1. Read an integer n.
  2. Start a for loop with i = 2.
  3. Instead of i++, increment the loop by 2 on every iteration: i = i + 2.
  4. 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 for loop to i = 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)
ADVERTISEMENT