1
 #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

Alex
  • 81
  • 1
  • 6
  • 4
    Enabling all warnings in your compiler should give you a very accurate clue about what the problem is. – paddy Sep 03 '20 at 04:42

3 Answers3

3

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';
}
Swordfish
  • 12,971
  • 3
  • 21
  • 43
MikeCAT
  • 73,922
  • 11
  • 45
  • 70
0

The problem in your code is that you haven't defined what happens when num1 becomes zero. You have to define this case in your recursive function too.

#include<iostream>

int multiply (int num1, int num2)
{
    
    if (num1 > 0)
        return num2 + multiply(num1 - 1, num2);

    if(num1 <= 0) // or if (num1 == 0) or simply return 0; as pointed out by MikeCAT's answer
        return 0;
}
    
int main()
{
    std::cout << multiply(5, 6);
}

Also see this question:Why is “using namespace std;” considered bad practice?

dark_prince
  • 237
  • 2
  • 12
0

This code is for those who are looking for the same logic but in JAVA.

    import java.util.*;

    public class Main {

      public static void main(String[] args) {
        Scanner scn = new Scanner(System.in);
        int n = scn.nextInt();
        int m = scn.nextInt();
        int prod = multiplier(n, m);
        System.out.println(prod);
      }

      public static int multiplier(int n, int m) {
        if(m == 0) {
          return 0;
        }
        int nm1 = multiplier(n, m-1);
        int product = n + nm1;
        return product;
      }
    }
iminiki
  • 2,549
  • 12
  • 35
  • 45