C and C++

Write a program using recursion to find the summation of numbers from 1 to n

We can say ‘sum of numbers from 1 to n can be represented as sum of numbers from 1 to n1 plus n’ i.e.
The sum of numbers from 1 to n = n + Sum of numbers from 1 to n-1
= n + n-1 + Sum of numbers from 1 to n-2
= n+ n-1 + n-2 + ……………. +1
The program which implements the above logic is as follows:
[wp_ad_camp_1]

#include
void main()
{
int n,s;
printf(“Enter a number”);
scanf(“%d”,&n);
s=sum(n);
printf(“Sum of numbers from 1 to %d is %d”,n,s);
}

int sum(int m) int r;
if(m==1)
return (1);
else
r=m+sum(m-1);/*Recursive Call*/
return r;
}
Output:
Enter a number 5
15