GfG QA is closing soon... Please refer PRACTICE or GfG now on wards !!

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. The function must be recursive so you are not allowed to use any conventional loop constructs.

Been struggling with this question for some time and cannot be 'include iosstream' must be stdio.h, any help would be greatly appreciated!

Thanks.

asked Feb 26, 2017 by programmec2017

1 Answer

Here is the solution you are looking for:

#include<stdio.h>
#include<stdlib.h>

int sum = 0;

int recursive(int x, int MAX)
{
    if(x>MAX)  //base condition
        return 0; 

    return (x+recursive(x+1,MAX));
}

int main()
{
    int start = 4, MAX = 7;
    int result = recursive(4,7);
    
    printf("%d ", result);
    return 0;
}

Hope this helps, do up vote it if you are satisfied or let me know if there is any confusion.

Thank you

answered Feb 28, 2017 by Mazhar MIK
...