Reputation:
I'm trying to understand recursive functions and I was trying to make a function that reverses the text read from the console. For example if one inputs "abcd" then the output will be "dcba".
This is what I have (I didn't come up with it myself).
void reverse() {
char c;
c=getchar();
if(c!='\n')
reverse();
cout<<c;
}
Most of the issue comes from if(c!='\n')
(or I thought so until now). Is there an intuitive explanation on how this function works?
And perhaps is there a better way to build the function(recursively)?
Upvotes: 0
Views: 165
Reputation: 152
Recursive functions use a call stack to store function calls. The last called function goes on top of the call stack (Last-in-First-Out).
Given that your string is "ABCD" the following recursion tree is generated:
A
: call reverse()
B
: call reverse()
C
: call reverse()
D
: call reverse()
\n
: At this point the control of execution passes back to the previous call until the call stack is depleted.
Note that every call to reverse()
is followed by a pending cout
, which executes once the control of execution is passed back.
Hence, the characters DCBA
are printed to the standard output
Upvotes: 1
Reputation: 477
\n
is the marker for a new line, so all your if statement does is check for a line end, and if it is a line end print out the whole thing.
Upvotes: 0