Home > other >  Why does this Java code output "3210123"?
Why does this Java code output "3210123"?

Time:04-28

public static void downup(int n) {
    System.out.println(n);
    if(n>0) {
        downup(n-1);
        System.out.println(n);
    }   
}

I saw this code and do not understand why the output is 3210123 when n is 3. I can only understand that it has to be "3210". What about the rest of the output ("123")?

CodePudding user response:

The exeuction can be visualized like this:

downup(3)
    println(3)
    downup(3-1)
        println(2)
        downup(2-1)
            println(1)
            downup(1-1)
                println(0)
                condition false, recursion stopped
                return
            println(1)
            return
        println(2)
        return
    println(3)
    return

Every time downup() is called (recursively), indentation increases. When execution returns from downup(), indentation decreases.

  • Related