write a program to print the sum of first n natural numbers and also, print them in reverse.
//program to print the sum of first n natural numbers and also, print them in reverse.
#include<stdio.h>
int main()
{
int sum, n;
printf("enter any number\n");
scanf("%d", &n);
for(int i=1, j=n; i<=n && j>=1; i++, j--){
sum = sum+i;
printf("%d\n", j);
}
printf("sum of n numbers = %d\n", sum);
return 0;
}
Output :
enter any number
11
11
10
9
8
7
6
5
4
3
2
1
sum of n numbers = 66
--------------------------------
Process exited after 4.68 seconds with return value 0
Press any key to continue . . .
2nd method
#include<stdio.h>
int main()
{
int sum, n;
printf("enter any number\n");
scanf("%d", &n);
for(int j=n; j>=1; j--){
sum = sum+j;
printf("%d\n", j);
}
printf("sum of n numbers = %d\n", sum);
return 0;
}
Output :
enter any number
11
11
10
9
8
7
6
5
4
3
2
1
sum of n numbers = 66
--------------------------------
Process exited after 4.348 seconds with return value 0
Press any key to continue . . .
Comments
Post a Comment
Please do not enter any spam link in the comment box.