Can anyone explain what's going on , I'm lost 🤕🤕 | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
+ 1

Can anyone explain what's going on , I'm lost 🤕🤕

void func(int x){ if(x>0){ func(--x); std::cout << x; } else return; } int main() { func(5); return 0; } This is a c++ challenge question. My guess was 43210. But output = 01234. I guess this has to do with recursion

19th Nov 2021, 7:40 PM
Bãrt Simpson
Bãrt Simpson - avatar
4 Answers
+ 3
Brian ohh i get it. Thank you 💕
19th Nov 2021, 8:29 PM
Bãrt Simpson
Bãrt Simpson - avatar
+ 2
khalid raji yes, it reverses the count because of recursion. First it goes deep into the stack by calling itself, and then it begins printing the output while returning back up the stack. Here is how it could be diagrammed as nested statement calls: func(5) { func(4) { func(3) { func(2) { func(1) { func(0) { return; } cout << 0; } cout << 1; } cout << 2; } cout << 3; } cout << 4; } cout << 5;
19th Nov 2021, 8:06 PM
Brian
Brian - avatar
+ 1
Brian when it decreased to 4 why did it not got printed as the next statement says print out. I still don't get it
19th Nov 2021, 8:16 PM
Bãrt Simpson
Bãrt Simpson - avatar
+ 1
khalid raji when func(5) calls func(4), func(4) must process and return before func(5) proceeds to the next statement (cout). Meanwhile, func(4) waits for func(3); func(3) waits for func(2)... and so on.
19th Nov 2021, 8:23 PM
Brian
Brian - avatar