   # Calculates the sum of the numbers from x to max using recursion?

+1 vote
137 views

Write a recursive function:

``````int sum( int x, int max )
{
/* complete the code */
}
``````

that calculates the sum of the numbers from x to max (inclusive). For example, sum (4, 7) would compute 4 + 5 + 6 + 7 and return the value 22.

Note: The function must be recursive. posted Mar 8, 2016

``````#include<stdio.h>

int main()
{
int n;
printf("Enter an positive integer: ");
scanf("%d",&n);
return 0;
}

{
if(n!=0)
return n+add(n-1);  /* recursive call */
}
`````` answer Mar 9, 2016
I think u have missed the query, it said the addition of all number between x to max not 1 to max. Do you like to edit it.
``````#include <stdio.h>

int cal_sum(int x, int sum)
{
if(x == sum) { /* break the recursion call when number is equal to max number */
return x;
}
return (x + cal_sum((x + 1), sum));  /* recursive call */
}

int main()
{
int x, max;
int sum = 0;

printf("Enter the number from where you wnat to start the sum : ");
scanf("%d",&x);

printf("Enter the max number upto where you wnat to perform the sum : ");
scanf("%d",&max);

sum = cal_sum(x, max);
printf("The sum(%d, %d) = %d\n", x, max, sum);

return 0;
}
`````` answer Dec 20, 2016
Similar Questions
Can we consider `"a car a man a maraca"` as palindrome string?