public static void main (String[] args)
{
System.out.println(factorial(5));
}
public int factorial(int n)
{
if(n <= 1){
return 1;
}
else{
Yes you have it right in the code, it first checks the value of n if it is less than or equal to 1, that is what is referred to as your base case. They are important, they tell your recursive function when to stop.
If the value of n is not less than or equal, it returns the value of n multiplied by the recursive call of factorial but with the value n-1 up until it reaches it's base case: if (n <= 1) where it returns 1
Your base case was set up by the factorial definiton of 0! and 1! which are both equal to 1.
Maybe this diagram might help to understand how the calls work.
5 * fact(5-1) ->
4 * fact(4-1) ->
3 * fact(3-1) ->
2 * fact(1)
1
Which is the same as 5! or 5 x 4 x 3 x 2 x 1
Hope this helps.