-1

Can anyone tell me in the simplest way why this prints out 321123 when generate(123) is called? I understand why it prints out 321, but the 123 part eludes me.

 /** @param x an integer such that x >= 0
 */ 

public void generate(int x) {     

     System.out.print(x % 10);     

     if ((x / 10) != 0) {         
        generate(x / 10);     
     }     
     System.out.print(x % 10); 
}
2
  • 1
    Draw a graph with the stack calls of the method maybe it should be easier to see.
    – Alexis C.
    Jun 1, 2015 at 21:00
  • 5
    I suggest you grab a piece of paper and write out what you think each step of the code will do. Afterwards, execute your program and see if it corresponds. If it doesn't, use a debugger or println statements to find where you're wrong. Jun 1, 2015 at 21:01

3 Answers 3

4

The recursion goes "in", then comes back "out". Think of it this way:

generate(123) {
    System.out.print(123 % 10)          // 3

    generate(12) {
        System.out.print(12 % 10)       // 2

        generate(1) {
            System.out.print(1 % 10)    // 1
            System.out.print(1 % 10)    // 1
        }

        System.out.print(12 % 10)       // 2
    }

    System.out.print(123 % 10)          // 3
}
2
  • Thanks a bunch. I understand in theory better, but what i realize is that my real problem is that i'm not fully understanding recursion. Time to sharpen up a bit.
    – Ron
    Jun 1, 2015 at 21:26
  • Each time generate is called, it opens a new scope just like any other method call. The way I have pictured it is very close to what actually happens, except that the inner scopes cannot see the outer scopes.
    – Radiodef
    Jun 1, 2015 at 21:29
0

Because you print x%10 both before and after your recursive call. When the number is 123, it prints 3, does the work for 12, then prints 3 again.

When it gets 12, it prints 2, does the work for 1, then prints 2 again.

Same for the 1. So you get "nested" prints of the remainder in each call.

-1

Entrance to deeper function levels:

if ((x / 10) != 0) {
generate(x / 10);
}

is also exit with the filo order which reverses 321 to 123

becasue there is another

System.out.print(x % 10);

after that.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.