Reputation: 1
Does stack come into the frame in the following code? If num=5. Why am i getting the output as zero..what about the numbers from 5 to 1?
void rec(int num)
{
cout << num << endl;
if( num > 0 )
return rec(num-1);
cout << "after" << num << endl;
}
does it include the concept of stack?
Upvotes: 0
Views: 70
Reputation: 129314
If you want to see the "returned value", you could do something like this:
void rec(int num)
{
cout << num << endl;
if( num > 0 )
rec(num-1);
cout << "after" << num << endl;
}
The return rec(num-1);
is technically valid, but since the function doesn't actually return soemthing, it's the same as writing:
if (num > 0)
{
rec(num-1);
return;
}
Upvotes: 0
Reputation: 1350
"Why am i getting the output as zero"
Look at the logic of you function. if(num>0)
- return rec(num-1);
.
So for every nubmer above 0
, the function will just call itself again with num-1
.
And only when num==0
you will get to this line
cout<<"after"<<num<<endl;
Meaning that for every number you will enter, the function will do nothing and call itself again with number-1
before the cout<<"after"<<num<<endl;
line, and at the last time it will not call it self again (since num > 0
condition is false) and it will print 0
.
Upvotes: 1