Rajinikanth Kala
Rajinikanth Kala

Reputation: 1

Return Value in Recursive Function

I have the following recursive function

#include <stdio.h>
#include <string.h>

 int mult(int a, int b);
int main()
{
  printf("mul: %d\n", mult(5,4));
}

int mult(int a, int b){
    if(b==0){
        return 0;
    }else{
      return a +mult(a, b-1);   
    }
   
}

In the function there are two return statements. As of my understanding a return statement either terminate the program or return the value that is present next to it in the return statement.

Here whatever happens at the end the value of b becomes zero eventually and the condition b==0 satisfies and return 0 statement get executed. So now the function mult return value should be zero. But it is giving the exact answer i.e multiplication.

when I change return value say 10 this 10 is getting added to the answer. let us say i gave mult(5,4) the answer is 20 if return value in b==0 condition is zero the answer is 21 if return value in b==0 condition is 1 the answer is 30 if return value in b==0 condition is 10 and so on..

So whats happening is whatever the return value is else statement it getting added to the return value in if statement.

Can someone explain this why this is happening why the function is returning correct value but it supposed to return 0 since it is the last statement getting executed.your text

Upvotes: 0

Views: 111

Answers (1)

Some programmer dude
Some programmer dude

Reputation: 409136

I suggest you draw out all the calls to mult using pen and paper. Write down the actual values being passed to the function calls, write down what each will return.

For this time I'll show it done, but next time please do it yourself.

We start with mult(5, 4). It will return 5 + mult(5, 3).

The call mult(5, 3) will return 5 + mult(5, 2).

The call mult(5, 2) will return 5 + mult(5, 1).

The call mult(5, 1) will return 5 + mult(5, 0).

The call mult(5, 0) will return 0.

Now we go back up the call stack:

5 + mult(5, 0) is the same as 5 + 0 which is 5.

5 + mult(5, 1) is the same as 5 + 5 which is 10.

5 + mult(5, 2) is the same as 5 + 10 which is 15.

5 + mult(5, 3) is the same as 5 + 15 which is 20.

So mult(5, 4) will return 20.

Upvotes: 2

Related Questions