As noted in the 2009 A MC explanations, this problem is more appropriately solved using the technique presented in recursive methods with print statements. The trace below is presented as a demonstration of tracing. It is not a suggestion that this problem should be traced.
This trace uses the technique demonstrated in tracing recursive methods. Familiarity with that material is assumed.
Step 1: initial call
Initial call stack
m(123456)
Step 2: mystery(123456)
- Checks if
123456 / 10
, which is12345
, is!= 0
, which istrue
- Computes
123456 / 10
, which is12345
- Calls
mystery(12345)
Resulting call stack
m(12345)
m(123456)
Step 3: mystery(12345)
- Checks if
12345 / 10
, which is1234
, is!= 0
, which istrue
- Computes
12345 / 10
, which is1234
- Calls
mystery(1234)
Resulting call stack
m(1234)
m(12345)
m(123456)
Step 4: mystery(1234)
- Checks if
1234 / 10
, which is123
, is!= 0
, which istrue
- Computes
1234 / 10
, which is123
- Calls
mystery(123)
Resulting call stack
m(123)
m(1234)
m(12345)
m(123456)
Step 5: mystery(123)
- Checks if
123 / 10
, which is12
, is!= 0
, which istrue
- Computes
123 / 10
, which is12
- Calls
mystery(12)
Resulting call stack
m(12)
m(123)
m(1234)
m(12345)
m(123456)
Step 6: mystery(12)
- Checks if
12 / 10
, which is1
, is!= 0
, which istrue
- Computes
12 / 10
, which is1
- Calls
mystery(1)
Resulting call stack
m(1)
m(12)
m(123)
m(1234)
m(12345)
m(123456)
Step 7: mystery(1)
- Checks if
1 / 10
, which is0
, is!= 0
, which isfalse
- Computes
1 % 10
, which is 1 - Prints
1
- Returns (ends)
Resulting call stack
m(1) returns
m(12)
m(123)
m(1234)
m(12345)
m(123456)
Printed
1
Step 8: Back in mystery(12)
- Back in
mystery(12)
- Finished the recursive call
- Computes
12 % 10
, which is2
- Prints
2
- Returns
Resulting call stack
m(1) returns
m(12) returns
m(123)
m(1234)
m(12345)
m(123456)
Printed
12
Step 9: Back in mystery(123)
- Back in
mystery(123)
- Finished the recursive call
- Computes
123 % 10
, which is3
- Prints
3
- Returns
Resulting call stack
m(1) returns
m(12) returns
m(123) returns
m(1234)
m(12345)
m(123456)
Printed
123
Step 10: Back in mystery(1234)
- Back in
mystery(1234)
- Finished the recursive call
- Computes
1234 % 10
, which is4
- Prints
4
- Returns
Resulting call stack
m(1) returns
m(12) returns
m(123) returns
m(1234) returns
m(12345)
m(123456)
Printed
1234
Step 11: Back in mystery(12345)
- Back in
mystery(12345)
- Finished the recursive call
- Computes
12345 % 10
, which is5
- Prints
5
- Returns
Resulting call stack
m(1) returns
m(12) returns
m(123) returns
m(1234) returns
m(12345) returns
m(123456)
Printed
12345
Step 12: Back in mystery(123456)
- Back in
mystery(123456)
- Finished the recursive call
- Computes
123456 % 10
, which is6
- Prints
6
- Returns
Resulting call stack
m(1) returns
m(12) returns
m(123) returns
m(1234) returns
m(12345) returns
m(123456) returns
Printed
123456