C Program to print the following series 1 2 3 4 ..... n
Objective
Write a C program to print the natural number series 1 2 3 4 ..... n.
Algorithm / Approach
- Read an integer
nfrom the user. - Start a
forloop withi = 1and conditioni <= n. - Inside the loop, print
ifollowed by a space. - Increment
i++until it reachesn.
main.c
#include<stdio.h>
int main( ) {
int n, i;
printf("Enter Value for N : ");
scanf("%d", &n);
for(i=1; i<=n; i++) {
printf("%d ", i);
}
printf("\n");
return 0;
}
Expected Output
Enter Value for N: 11 1 2 3 4 5 6 7 8 9 10 11
Explanation of the Program
- This is the most fundamental series program, printing a sequence of natural numbers.
- The loop counter
iautomatically generates the series for us, so we just print it directly on each iteration.
Complexity
Time Complexity
O(n) - The loop runs n times.
Space Complexity
O(1)