Search code examples
javarecursionconcept

How to understand the concept of recursion in java?


I'm new to java programming, and our teacher taught us the concept of recursion and I found it to be a bit complicated. All I understood that it works like a loop(like the factorial of 4) but I still don't quite get it why it works like that. Can I get a detailed explanation on this topic? Here is the piece of code and a picture my teacher used to explain.

package javaapplication1;

public class JavaApplication1 {

static int factorial(int n){
    int t;
    if(n == 0){
        return 1;
    } else {
        t = factorial(n - 1);
        return n * t;
    }
}
public static void main(String[] args) {
    System.out.println(factorial(5));
    }
}

In the following image, the blue color represents stack winding, and the green is stack unwinding, and again I don't know what stack winding and unwinding is.

https://i.sstatic.net/pjqJy.png


Solution

  • A recursive function is a function that calls itself until it reaches a return statement, that stops it from recalling itself. Take your example, the Factorial function. Factorial is a mathematical function that returns the number multiplied by itself - 1 multiplied by itself - 2, ... multiplied by 1, example: factorial of 5 = 5! = 5x4x3x2x1 = 120. it is also equal to itself multiplied by the factorial of itself -1, which is: 5! = 5x4! Take into consideration that 0! = 1. to represent this in a Java code, you need a loop that multiplies the numbers starting from 1, and going till the number you are calculating its factorial. Further more, explaining your code, let us calculate Factorial(5): Factorial() returns an integer.

    Initial Call from main(): 5 != 0, then skip the condition (n == 0); t = Factorial(5-1) = Factorial(4);

    Second call from Factorial(4): 4 != 0, then skip the condition (n == 0); t = Factorial(4-1) = Factorial(3);

    Third call from Factorial(3): 3 != 0, then skip the condition (n == 0); t = Factorial(3-1) = Factorial(2);

    Fourth call from Factorial(2): 2 != 0, then skip the condition (n == 0); t = Factorial(2-1) = Factorial(1);

    Fifth call from Factorial(1): 1 != 0, then skip the condition (n == 0); t = Factorial(1-1) = Factorial(0);

    Sixth call from Factorial(0): 0 == 0, then return value 1;

    First return, 1, to Fifth call (Factorial(1)): return n*t = return 1*1 = return value 1;

    Second return, 1, to Fourth call (Factorial(2)): return n*t = return 2*1 = return value 2;

    Third return, 2, to third call (Factorial(3)): return n*t = return 3*2 = return value 6;

    Second return, 6, to second call (Factorial(4)): return n*t = return 4*6 = return value 24;

    Second return, 24, to First call (Factorial(5)): return n*t = return 5*24 = return value 120;

    Second return, 120, to Initial call (from main()): print(120);

    Hope this helps you understand recursion.