+ 19
Can anyone clear my confusion about this code?
https://code.sololearn.com/cJkdYh5OKjEX/?ref=app Output : 0120 How???
6 odpowiedzi
+ 6
Let function test ==T
All test where n<=0 will return to main without printing anything
T(3)
/ | \
/ 2 \
T(2) |. T(1)
/|\ |. /|\
T(1) 1 T(0) |.T(0) 0 T(-1)
/|\ \. |. |.
T(0)0T(-1)\. |. |.
|. |. |. |.
|. |. |. |.
0 1 2 0
+ 47
Great explanation Shadow 👌👌👏👏👏
+ 21
Let's handtrace the steps:
test( 3 ) is called
x > 0 -> true
test( 2 ) is called
x > 0 -> true
test( 1 ) is called
x > 0 -> true
test( 0 ) is called
x > 0 -> false
Nothing happens inside test( 0 ), so now we return to its caller, test( 1).
Since x = 1 was decremented inside test( 1 ), x is now 0, which is then printed. Afterwards
test( --0 ) <=> test( -1 ) is called.
x > 0 -> false
Here test( 1 ) finishes and we return to test( 2 ). Same principle, x was decremented, so now in test( 2 ), x = 1, which is printed. Then test ( 0 ) is called, without consequence, since the condition fails. Returning to test( 3 ),
2 is printed, and test( 1 ) is called, which prints 0 as we know from earlier. Afterwards, test( 3 ) is complete, hence the entire function call is resolved.
Finally, putting things together, we get 0 1 2 0 as the output. If my answer didn't help, try drawing yourself a sketch on paper to visualize the function calls.
+ 11
Thank you so much Shadow
+ 5
the steps run like this
test0
print0-->0
test-1
print1-->1
test0
print2-->2
test0
print0-->0
test-1
return0
- 2
Hello