I am trying to learn programming and I am on the phase of learning recursion. Before this, I have successfully solve the problem but using loops. Right now, since recursion is quite interesting to me, I was wondering if I could convert the loop into a recursive method. I have done my attempts but I’ve been getting a sort of infinite computation whatsoever.
Can somebody give me a hand with this? Thanks.
This is my code.
public class RecursiveProduct {
public static void main (String[] args) {
Scanner myInput = new Scanner(System.in);
System.out.print("Enter num1: ");
int num1 = myInput.nextInt();
System.out.print("Enter num2: ");
int num2 = myInput.nextInt();
int product = recursiveProduct(num1, num2);
System.out.print(num1 +" * " +num2 +" = " +product);
}
public static int recursiveProduct(int a, int b)
{
int result = 0;
if(b == 0)
return result;
else
{
result += a;
return result += recursiveProduct(a, b--);
}
}
}
Try this: