+ 1

Can anyone explain this code snippet of recursive function working

#include <stdio.h> void fun(int x){ if(x>0){ fun(x-1); printf("%d\n",x); fun(x-1); } } int main() { fun(3); return 0; }

31st Jan 2020, 3:35 PM
Arshia
Arshia - avatar
3 odpowiedzi
+ 4
fun(3) ....3 > 0 true ......... fun(2) ............. 2 > 0 true ................. fun(1) ..................... 1 > 0 true ......................... fun(0) ............................. 0 > 0 false ......................... output 1 ......................... fun(0) ............................. 0 > 0 false ................. output 2 ................. fun(1) ..................... 1 > 0 true ......................... fun(0) ............................. 0 > 0 false ......................... output 1 ......................... fun(0) ............................. 0 > 0 false ......... output 3 ......... fun(2) again, so print 1 2 1 again. So result is 1 2 1 3 1 2 1
31st Jan 2020, 3:45 PM
Gordon
Gordon - avatar
+ 1
Arshia You are welcome. May I also show you how you can make use of code playground to track the states by adding printf(). https://code.sololearn.com/cHv4br3TeKQj/?ref=app The output for debugging nows looks the same as the program output because we are doing console based programming. When you are developing an application where GUI and console are separated, the debugging logs are in console and the output for users are on user interface. After understanding recursion, please program a factorial or a fibonacci as practice.
31st Jan 2020, 3:59 PM
Gordon
Gordon - avatar
0
Gordon thanks m8
31st Jan 2020, 3:49 PM
Arshia
Arshia - avatar