Thanks for your question :clap:, if someone gives you an answer it would be great if you thanked them with a :white_check_mark: in response. This response will earn you both points for special roles on this server.
#need help understanding recursive function
4 messages · Page 1 of 1 (latest)
It should run 3times and the output should be: ```Cpp
3
2
1
0
```Cpp
#include<stdio.h>
void solve(int x);
int main()
{
solve(3);
return 0;
}
void solve(int x)
{
if(x==0) // only gets executed when x is 0
{
printf(" %d", x);
return; // ends the loop
}
printf(" %d", x);
solve(x-1); // calls itself with x-1,
// printf(" %d", x); /* I am not sure if this will ever be executed */
}
Basically it keeps calling itself with smaller values for x until x == 0 and then breaks the cycle by returning.
I hope that helps, otherwise tell me what the exact issue is.
Ah okay i see
the last line gets executed, so after x==0, returns, x==1 has 1 instruction more to execute, before is done so outputs 1, then x==2 executes the last instruction and then x==3 executes the last instruction. The return statement ends only the last call to solve, so the other 3 calls can resolve