+ 1
What is the output of the following code? And please why :)
Thank you so much for taking time to answer my question first of all. What is the output of the following code? And why please ? int loopy (int i) { if (i==0) { printf("%i", i); } else{ loopy(i - 1); printf("%d", i); } } loopy(5);
9 Answers
+ 2
visph Jayakrishnađźđł I am sorry I know that my question seems elementary, but since the recursive call is before the print statement. why doesnât it only print 0 since this is when the recursion stops. why would it print the other numbers ?
+ 1
that's a recursive function: a function wich call itself before printing the received argument until modified argument reach a base case (case when the recursion stop)..
does it make sense for the output you get by running it in a code playground?
+ 1
012345
Its recursive function...
Recursive calls are
loopy(5) initial, it calls loopy(4) and at last after this call returns prints i=5
loopy(4) , it calls loopy(3) and at last after this call returns prints i=4
loopy(3), it calls loopy(2) and at last after this call returns prints i=3
loopy(2) , it calls loopy(1) and at last after this call returns prints i=2
loopy(1) , it calls loopy(0) and at last after this call returns prints i=1
loopy(0) prints i=0 at first and returns to loopy(1)..
+ 1
visph I got (012345) but shouldnât it be (543210)? i just donât understand why :)
+ 1
if you have a linux desktop/laptop you could run the code line by line by using GDB (GNU Debugger) to better figure how it works:
https://www.gnu.org/software/gdb/
0
no, because the recursive call occurs before the print statement ;)
0
because after printing zero it return just after the call, print 1, then recursively return and print all nums from 2 to 5 ^^
0
Because when it calls loopy(5-1) i=5, not printed until loopy(4) calls completes and returns but it doesn't take any value back.. (because loopy(4) is entirely different call from loopy(5)) so i value still 5 for loopy(5).
Similarly loopy(3), loopy(2), loopy(1).
loopy(0) not make any calls recursively...
Hope you understand it.
0
loopy(5) = loopy(4) then print(5)
= Loopy(3) then print(4) then print(5)
= Etc.
See ? Loopy(4) is replaced by one iteration of the loop, leaving a print() while the loop continues above it.