Skip to main content

ProwessApps

Learn · Practice · Excel

C Program to print the following series. 2 4 6 8 10 . . . . . . . n

C Code Example — Series Programs

ADVERTISEMENT

C Program to print the following series. 2 4 6 8 10 . . . . . . . n

Objective

Write a C program to print an even number series: 2 4 6 8 10 ..... n.

Algorithm / Approach

  1. Read an integer n.
  2. Start a for loop with i = 1 up to n.
  3. Inside the loop, check if i % 2 == 0.
  4. If true, print i.
  5. Wait, the provided code actually checks if(n%2 == 0) instead of i%2 == 0, which is a bug. It should check i.
main.c
#include<stdio.h>
int main( ) {
 int n, i;
 printf("Enter Value for N : ");
 scanf("%d", &n);
 for(i=1; i<=n; i++) {
  if(n%2 == 0) {
   printf("%d ", i);
  }
 }
 printf("\n");
 return 0;
}

Expected Output

Enter Value for N: 15
2 4 6 8 10 12 14

Explanation of the Program

  • This program filters the natural numbers and only prints the even ones.
  • We use the Modulo operator (%) to check if the current loop counter (i) is perfectly divisible by 2. If the remainder is 0, it's an even number and we print it.

Complexity

Time Complexity O(n)
Space Complexity O(1)

Common Mistakes

  • Checking if the upper limit `n` is even (e.g., n % 2 == 0) inside the loop instead of checking the current number i (e.g., i % 2 == 0). This logic error causes it to either print every number or print nothing at all.
ADVERTISEMENT