0

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

1
  • Surprised no-one has told you to use a debugger to step through the execution and examine the values of the variables.... An alternative that should be obvious is for you to use "print debugging", adding enough print statements revealing the values and the flow of the code so that YOUR program lets YOU know how it is doing what it is doing... Commented Nov 5, 2022 at 8:50

1 Answer 1

2

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.

Sign up to request clarification or add additional context in comments.

1 Comment

yeah thanks for you reply. I confused with the last step. Now I understand thanks

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.