So I come across this simple lines of code from a tutorial on YouTube. It's about recursion.
public class whatever{
public static void main (string[] args){
factorial(7);
}
private static int factorial(int num){
if(num<1) return 1;
return num * factorial(num -1);
}
}
Wouldn't it run forever because once the num reaches 0, it will return 1, then it will be -1, still return 1, then -2, return 1? please correct me.
I know I am probably wrong logically so please correct me.
CodePudding user response:
this line would ensure that the flow doesnt continue to infinity: if(num<1) return 1; once the factorial method is called with 0 as num, return 1 would stop any furture calls to the factorial method, and the control goes back to the main method and exits from there on.
CodePudding user response:
It does not go to infinity - once you get down to calling factorial(0)
you return with 1
and don't call any method.
f(7) = n * f(6)
n * f(6) = n * n-1 * f(5)
.....
f(7) = n * n-1 * n-2 * ... * n-6 1