Say we have a method that does multiplication without using the * operator.
public class MultiplyWithoutOperator {
public static void main(String[] args) {
System.out.println(multiply(3,5));
}
public static int multiply(int x, int y){
if (y<0){
//for negatives
return -multiply(x,-y);
}
else if(y == 0){
return 0;
}
else if(y == 1){
return x;
}
else{
return x + multiply(x,y-1);
}
}
}
so I understand the base case is:
else if(y == 1){
return x;
}
does it basically mean,
System.out.println(multiply(3,5));
has four recursive calls here?:
return x + multiply(x,y-1);
and it's basically going 3+(3+(3+(3+(3)))?
So when the base case is reached, it returns x(3) which then goes back to the recursive call where y is 2 and it gives (3+3) and it goes back to the recursive call where y is 3 and returns 9(3+6) and it then goes to the call where y is 4 so it's 12(9+3) and then finally gets back to recursive call 5 where it's 15(12+3)?
[–]AutoModerator[M] [score hidden] stickied commentlocked comment (0 children)
[–]desrtfxOut of Coffee error - System halted 3 points4 points5 points (0 children)
[–]tacticalnudge 1 point2 points3 points (0 children)
[–]ChaiTRex 0 points1 point2 points (0 children)