+ 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; }
3 Réponses
+ 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
+ 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.
0
Gordon thanks m8