#include<stdio.h>
int series(int n);
int rseries(int n);
main( )
{
int n;
printf("Enter number of terms : ");
scanf("%d", &n);
printf("\b\b = %d\n", series(n)); /* \b to erase last +sign */
printf("\b\b = %d\n\n\n", rseries(n));
}/*End of main()*/
/*Iterative function*/
int series(int n)
{
int i, sum=0;
for(i=1; i<=n; i++)
{
printf("%d + ", i);
sum+=i;
}
return sum;
}/*End of series()*/
/*Recursive function*/
int rseries(int n)
{
int sum;
if(n == 0)
return 0;
sum = (n + rseries(n-1));
printf("%d + ",n);
return sum;
}/*End of rseries()*/
Enter number of terms : 10
1 + 2 + 3 + 4 + 5 + 6 + 7 + 8 + 9 + 10 = 55
1 + 2 + 3 + 4 + 5 + 6 + 7 + 8 + 9 + 10 = 55
Press any key to continue . . .
First understand the algorithm carefully. Then study the program line-by-line and compare it with the output. Finally, review the explanation section to strengthen your logic and programming understanding.
Rewrite the program without looking at the code. Modify values, conditions or logic and run it again. This helps improve confidence and strengthens coding skills much faster.