Program to display numbers from 1 to n and their sum

C Programming Language / Recursion in c

772

Program:

#include<stdio.h>
int summation(int n);
void display1(int n);
void display2(int n);
main( )
{
int n;
printf("Enter number of terms : ");
scanf("%d", &n);
display1(n);
printf("\n");
display2(n);
printf("\n");
printf("sum = %d\n", summation(n));
}/*End of main()*/

int summation( int n)
{
if(n==0)
	return 0;
return ( n + summation(n-1) );
}/*End of summation()*/

/*displays in reverse order*/
void display1(int n)
{
if( n==0 )
	return;
printf("%d ",n);

display1(n-1);

}/*End of display1()*/


void display2(int n)
{
if( n==0 )
	return;
	
display2(n-1);

printf("%d ",n);
}/*End of display2()*/

Output:

Enter number of terms : 10
10 9 8 7 6 5 4 3 2 1
1 2 3 4 5 6 7 8 9 10
sum = 55
Press any key to continue . . .

Explanation:

None

This Particular section is dedicated to Programs only. If you want learn more about C Programming Language. Then you can visit below links to get more depth on this subject.