Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Why does this Java code output "3210123"?

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")?

>Solution :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading