What is the output of the following code? And please why :) | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
+ 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);

22nd Mar 2021, 8:34 PM
Hodeni
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 ?
22nd Mar 2021, 8:55 PM
Hodeni
+ 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?
22nd Mar 2021, 8:42 PM
visph
visph - avatar
+ 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)..
22nd Mar 2021, 8:44 PM
Jayakrishna 🇮🇳
+ 1
visph I got (012345) but shouldn’t it be (543210)? i just don’t understand why :)
22nd Mar 2021, 8:45 PM
Hodeni
+ 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/
22nd Mar 2021, 9:33 PM
visph
visph - avatar
0
no, because the recursive call occurs before the print statement ;)
22nd Mar 2021, 8:46 PM
visph
visph - avatar
0
because after printing zero it return just after the call, print 1, then recursively return and print all nums from 2 to 5 ^^
22nd Mar 2021, 9:01 PM
visph
visph - avatar
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.
22nd Mar 2021, 9:17 PM
Jayakrishna 🇮🇳
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.
23rd Mar 2021, 6:31 PM
Coco L'asticot
Coco L'asticot - avatar