loops - c++ confusion on outputs -
this might seem stupid question, dont understand difference between these functions. setting both of these 0, why xxx() print 0,2,4,6,4,2,0 , xxy() print regular 0,1,2,3,4,5. question i'm asking is, why xxx() reduce after hits max value allowed '6'
void xxx(int n) { cout << n; if (n < 5) { xxx(n + 2); cout << n;; } } void xxy(int n) { cout << n; if (n < 5) xxy(n + 1); } int main() { xxx(0); xxy(0); }
well... pay atenciĆ³n here:
cout << n; if (n < 5) { xxx(n + 2); cout << n; }
when have recursive call xxx(n+2) current "iteration" stacked start new function. when function ends, previous iteration proceeds normally.
therefore when max value (6) reached, iteration end continuing cout of previous "iteration"... in previous iteration n value 4... value displayed , iteration end continuing cout of n in previous iteration 2 , on...
in second function notes there isnt cout after of xxy recursive call, if put it, similar behavior displayed.
i hope have understood me... greetings
Comments
Post a Comment