Search code examples
c++recursioncallstackfunction-definition

Recursion- sum of n natural number


function to calculate the sum of n natural number

int solve(int n)
{
    if(n==0 or n==1)
    return n;
    int sum=0;

    sum=sum+n;
    solve(n-1);   // gives me wrong output

    return sum;
}

int solve(int n)
{
    if(n==0 or n==1)
    return n;
    int sum=0;

    sum=sum+solve(n-1);  // gives me correct output

    return sum;
}

what is the difference in the working or output of both the function as call stack works same in both the cases


Solution

  • solve function in the first method does not have any effect in your program

    int solve(int n)
    {
        if(n==0 or n==1)
        return n;
        int sum=0;
    
        sum=sum+n;
        solve(n-1);   // has not any effect
    
        return sum;
    }
    

    In the second method, returned value will always be 1 while it must return the sum of the numbers, correct code for calculate sum of numbers is:

    int solve(int n)
    {
        if (n == 0 || n == 1)
            return n;
    
        int sum = 0;
    
        sum = n + solve(n - 1);  // change 'sum' with 'n'
    
        return sum;
    }
    

    Run:

    solve(5);

    Output:

    5 + 4 + 3 + 2 + 1 = 15