C Program to print the following series. 1 3 5 7 9 .....n
Objective
Write a C program to print an odd number series: 1 3 5 7 9 ..... n.
Algorithm / Approach
- Read an integer
n. - Start a
forloop from 1 ton. - Inside the loop, check if the current number is odd using
if(i % 2 != 0). - If true, print the number.
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 1 3 5 7 9 11 13 15
Explanation of the Program
- Similar to the even numbers series, this uses the modulo operator but checks for a non-zero remainder.
- An alternative, more efficient approach to printing odd numbers is to change the loop increment to
i = i + 2instead of checking every single number with anifstatement.
Complexity
Time Complexity
O(n)
Space Complexity
O(1)