I’m confused how Recursion works in this example. If ‘ABC\n’ is inputted, CBA is outputted. If someone could step through the process I would greatly appreciate it.
- In main(), ReverseLine() is called
-
local automtic myInput takes in ‘ABC\n’
-
Then it checks myInput for ‘\n’ and EOF, this is where I start getting confused
I think it says, A != ‘\n’ and A != EOF so ReverseLine() is called again, but then what???
How does the recursion work, I just want to understand the process
THANKS
using namespace std;
void ReverseLine(){
int myInput;
myInput = cin.get();
if (myInput != '\n' && myInput != EOF)
ReverseLine();
if (myInput != EOF)
cout.put(myInput);
}
int main(){
ReverseLine();
return 0;
}
When you call ReverseLine, it reads a character. If the character isn’t a newline or EOF, it calls itself again (recurses) to read the next character until it encounters a newline at which point it prints the character it just read, then returns to ReverseLine which prints the character it read and so forth until it returns to the initial call to ReverseLine, prints the first character read, then exits.