Code is easier to work through when you format it properly, so please do that in the future. Sometimes code is also easier to work through when you make it more concise. Notice that you can "inline" the result
variable:
public static int factorial(int n) {
if (n == 0) {
return 1;
}
else {
int recurse = factorial(n - 1);
return recurse * n;
}
}
Or more simply:
public static int factorial(int n) {
if (n == 0) {
return 1;
}
return n * factorial(n-1);
}
Now let's try some values. Let's try with the value of "0":
public static int factorial(int n) {
if (n == 0) {
return 1; //<-- Returns 1
}
return n * factorial(n-1);
}
Ok, that's right: 0! = 1.
Let's try with the value of "1":
public static int factorial(int n) {
if (n == 0) {
return 1; //not reached
}
return n * factorial(n-1); //<-- 1 * factorial(0) = 1 * 1 = 1
}
Good: 1! = 1.
Let's try with the value of "8":
public static int factorial(int n) {
if (n == 0) {
return 1; //not reached
}
return n * factorial(n-1); //<-- 8 * factorial(8-1) = 8 * 7 * 6 * 5 * 4 * 3 * 2 * 1 = 40320
}
This makes sense since 8! = 40,320.
The way this is done is called recursion since the method is essentially calling itself. When done well, recursion is a beautiful part of programming since the code is typically fairly concise and is one of a "divide and conquer" mentality. This is an introductory concept in programming.
A good programmer will always be thinking about the system of values. So in this case, your function will provide a StackOverFlow
error if n is -1, for example. (You can change the code to read if (n <= 1)
).