0

Hello i was having some funny with my code lately and i met strange output of double recursion. I was trying to understand it but im not so lucky to know the answer yet. Maybe u ll help me with tis problem . Why this program has so weird output? output : 4 3 2 1 1 2 1 1 3 2 1 1 2 1 1. I figure out that firstly it just do first somefunc call so printing 4321 , next somefunc has output like 1234. firs it decrement 1 so its 0 next decrement 2 by 1 so its 1 and then decrement then 3 decrement by 1 its 2 and 1 , decrement 4 by 1 untill 0 so its 321 its logically output will be 4321 2 1 3 2 1 but i dont understand the rest.

#include <iostream>
using namespace std;
void  somefunc(int c)
{
    if(c>=1)
    {
        cout <<c<<" ";
        somefunc(c-1);
        somefunc(c-1);
    }
}
int main()
{
    somefunc(4);
    return 0;
}
Virozz
  • 69
  • 5
  • _Double recursion_ => _double worse_. – πάντα ῥεῖ Oct 28 '20 at 19:08
  • Step by step execution of each statement in the debugger, will clarify a lot. – πάντα ῥεῖ Oct 28 '20 at 19:10
  • Try thinking about the problem in terms of each function call's stack frame, and where in that stack frame the program's execution is. Draw it on paper, or step through it in a debugger. – paddy Oct 28 '20 at 19:10
  • 1
    I prefer to add structure to the output to debugging or thinking about how the program is executed (it's very nice to be able to view the entire execution at once and go back and forth just by looking). See [here](http://coliru.stacked-crooked.com/a/3b33c27353d31dd7) for an example. – molbdnilo Oct 28 '20 at 19:56

0 Answers0