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
- Read an integer
n. - Start a
forloop withi = 1up ton. - Inside the loop, check if
i % 2 == 0. - If true, print
i. - Wait, the provided code actually checks
if(n%2 == 0)instead ofi%2 == 0, which is a bug. It should checki.
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 numberi(e.g.,i % 2 == 0). This logic error causes it to either print every number or print nothing at all.