Can anyone please tell me how is the answer of this program 8 ?
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18
#include<iostream>
usingnamespace std;
int unknown(int x)
{
int result; //return type is declared.
int y=2;
if (x>=6)
return 1;
else
result=unknown(x+2)*y;
return result;
}
int main()
{
cout<<unknown(1);
return 0;
}
If you are confused about it, the best way, I feel, to learn about recursion is by using gdb.
Try debugging the code by stepping each time the function is called and you'll see how the code is working.
no that is confusing, i get 8 too. lets see here, unknown 1 ok, so x is less then 6 so we go to the else where the result equals unknown x+2 times y which is 2... ok so we go around again with x= 3 this time, still less then 6 so again the return is unknow x+2 times 2 which is then passed back again to the first call AHHH thats how it works ok lets follow this, because when unknow is called again it passes the new one back and multiplies that by 2 and passes it back again... ok so now x is 5 still less then 6, now its 7 so the answer is 1 times 2, is two, for the five answer, times 2 again is 4 for the 3 answer and again time 2 which brings you to 8 for the 1 answer... That, was extremely overcomplicated and unessecary, but yeah it keeps looping itself until x is greater then 6 which at the rate of +2 per loop, it take it 3 more loops before it gets to its termination point where it returns one, multiples by 2 and returns, 3 times and 2^3 is 8
its 1 for the first run. less then 6, so it runs again after adding 2 to get 3, still less then 6, runs again after adding 2 to get 5, STILL less then 6, runs again adding 2 to get 7, more then six, returns 1, mutiplies by 2 and returns again to get 2, multiples by 2 and returns again to get 4, mulplies by 2 and returns with the final result... tadadada 8.
so be honest here, all these posts you make about little programs you "made" but theres something wrong with them and you post here asking for someones help... thats your homework and you dont feel like doing it, right?