I've seen answers using a for loop which I understood, however I came across this code recently and I have no idea how it works.
public class learn {
public static int factorial (int N){
if (N<=1 ) return 1; // won't this mean that "1" is returned at the end all the time?
else return (N*factorial (N-1)); /* since there's no variable storing the sum
I don't get how this is working out either,
won't it just be returned and lost?*/
}
public static void main(String[] args) {
System.out.println(factorial(4));
}
}
Coming from a python background, so maybe I am misunderstanding something about returns in java... [Edit] seems like return 1
is also written in Python, so it's probably not a language issue, I just don't get how recursive functions end (I get how the process goes - it's a function that calls itself).
Here's an illustration of how I interpret this code (wrongly):
factorial(4)
is called- 4 is more than 1, so the
else
statement will run --4*factorial(3)
factorial(3)
is called -else
statement runs again --3*factorial(2)
factorial(2)
is called --2*factorial(1)
. At this point, we have 4*3*2*1 but the fact that the code only stops at theif (N<=1) return 1
line means that 1 is returned instead of the sum right? (I'm obviously wrong because the console printed the right number -24
)