Home / Programs / Program to display numbers from 1 to n and their sum
Programming Example

Program to display numbers from 1 to n and their sum

👁 796 Views
💻 Practical Program
📘 Step by Step Learning
Program to display numbers from 1 to n and their sum

Program Code

#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

How to learn from this program

First read the algorithm, then study the program code line by line. After that, compare the code with the output and finally go through the explanation. This approach helps learners understand both the logic and the implementation properly.