Programming Example
Program to display numbers from 1 to n and their sum
Program to display numbers from 1 to n and their sum
#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()*/
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 . . .
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.
After understanding this example, try to rewrite the same program without looking at the code. Then change some values or logic and run it again. This helps improve confidence and keeps learners engaged on the page for longer.