0

so I've been recently studying recursion in Java, and while i fundamentally understand it, I don't quite have a grasp on what is happening behind the code. So for example, finding the factorial of 4.

public static long factorial(int n) {
    if (n == 0) // Base case
        return 1;
    else 
        return n * factorial(n - 1); // Recursive call
}

Can someone explain to me how the code would run. How does n* factorial(n-1) know what factorial(n-1) is equal to as it just recalled itself? I'm quite confused, any explanation would be appreciated, thanks!

khelwood
  • 55,782
  • 14
  • 81
  • 108
RiFF RAFF
  • 131
  • 2
  • 11

0 Answers0