sum of first n natural numbers in c using recursion code example
Example 1: Sum of digits of a number using recursion function c
/*
* C Program to find Sum of Digits of a Number using Recursion
*/
int sum (int a);
int main()
{
int num, result;
printf("Enter the number: ");
scanf("%d", &num);
result = sum(num);
printf("Sum of digits in %d is %d\n", num, result);
return 0;
}
int sum (int num)
{
if (num != 0)
{
return (num % 10 + sum (num / 10));
}
else
{
return 0;
}
}
Example 2: c program to find the sum of given number using recursion
int sum(int number);
int main
{
int n;
int a;
printf("enter a number");
scanf("%d,&n);
a=sum(n);
printf("sum=%d",a);
}
int sum(int number)
{
if (number==0)
return 0;
return(number%10+sum(number/10);
}
Example 3: recursive function to find the sum of the nth term
void recurse() {
.....
recurse() //recursive call
.....
}
int main() {
.....
recurse(); //function call
.....
}