top button
Flag Notify
    Connect to us
      Site Registration

Site Registration

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

+1 vote
724 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 by anonymous

Share this question
Facebook Share Button Twitter Share Button LinkedIn Share Button

2 Answers

0 votes
#include<stdio.h>

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

int add(int n)
{
    if(n!=0)
     return n+add(n-1);  /* recursive call */
}
answer Mar 9, 2016 by Ashish Kumar Khanna
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.
0 votes
#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 by Arshad Khan
...