Sum Of n terms means that the sum from 1 to the number entered (n) by the user as an input. For e.g if the input is 10 then the output will be the sum of first 10 natural numbers i.e 1+2+3+4+5+6+7+8+9+10=55. So output of the program in c will be 55. Today we will write a program in c to find and print sum of n terms by using for loop, while loop and do while loop.
Program to print the sum of n terms In C using for loop
Note: Please use every loop one by one. I have uploaded picture to show all the three loops in one.
#include <stdio.h>
void main(){
int n, sum=0,i;
printf("Enter nth term= ");
scanf("%d",&n);
for(i=1;i<=n;i++) {
sum=sum+i;
}
printf("sum of %d terms is %d",n,sum);
getchar();
};
Program to print the sum of n terms In C using while loop
#include <stdio.h>
void main(){
int n, sum=0,i;
printf("Enter nth term= ");
scanf("%d",&n);
while(i<=n){
sum=sum+i;
i++;
}
printf("sum of %d terms is %d",n,sum);
getchar();
};
Program to print the sum of n terms In C using do while loop
#include <stdio.h>
void main(){
int n, sum=0,i;
printf("Enter nth term= ");
scanf("%d",&n);
do{
sum=sum+i;
i++;
}while(i<=n);
printf("sum of %d terms is %d",n,sum);
getchar();
};
INPUT/OUTPUT
If we enter nth term as 10 we will get 55 which is the sum of first 10 natural numbers. i.e 1+2+3+4+5+6+7+8+9+10=55
The output will be the same for while loop, do while loop and for loop also.
0 Comments