C Program to print the following series. 0 1 3 6 10 15 21 upto n terms
Objective
Write a C program to print Triangular numbers: 0 1 3 6 10 15 21 ..... n terms.
Algorithm / Approach
- Read the number of terms
n. - Initialize
j = 0. - Run a loop
ifrom 1 ton. - Inside the loop, print
j. - Calculate the next term by adding the loop counter to it:
j = j + i.
main.c
#include<stdio.h>
int main( ) {
int n,i,j=0;
printf("Enter a value for N : ");
scanf("%d",&n);
for(i = 1; i<=n; i++) {
printf("%d ",j);
j = j+i;
}
printf("\n");
return 0;
}
Expected Output
Enter a value for N : 8 0 1 3 6 10 15 21 28
Explanation of the Program
- This sequence represents Triangular numbers. The gap between each number increases by 1 each time (+1, +2, +3, +4, +5...).
- By using the loop counter
ias the increment amount, we effortlessly generate an expanding gap, resulting in the correct sequence.
Complexity
Time Complexity
O(n)
Space Complexity
O(1)