c++functionrecursionmultiplicationrecursive-backtracking

Multiply two numbers through recurssion


 #include<iostream>
using namespace std;
int multiply (int num1, int num2){

if (num1 > 0)

  return num2 + multiply(num1-1,num2);


}

int main(){

int mult = multiply(5,6);
cout<<mult;
}

I am trying to multiply two numbers through recurssion, but i am not getting the desired result, i want to print 30 but it is given me 36, i am unable to dry run it and make it's tree diagram


Solution

  • You are invoking undefined behavior by letting the execution reach at end of function definition without executing return statement in function whose return type is not void.

     #include<iostream>
    using namespace std;
    int multiply (int num1, int num2){
    
    if (num1 > 0)
    
      return num2 + multiply(num1-1,num2);
    
    return 0; // add this
    }
    
    int main(){
    
    int mult = multiply(5,6);
    cout<<mult;
    }
    

    Note: indentation looks bad, but I am respecting the original code. Readable:

    #include <iostream>
    
    int multiply (int num1, int num2)
    {
        if (num1 > 0)
            return num2 + multiply(num1 - 1, num2);
        return 0;
    }
        
    int main()
    {
        std::cout << multiply(5, 6) << '\n';
    }