I found the following code to reverse a string in C in my university notes. I do not understand how the recursion works in this example since it seems magic to me! To be more specific, if I type the word “one” the program prints out the word “eno”. According to the explanation, the function reads characters from the user recursively until the user presses Enter(‘\n’) and then prints out the reversed word. But how is it possible to print the word if the last time the function calls itself recursively is when the user presses Enter and after that the program can’t get into the function again in order to call the printf? Does it use some kind of buffer and how it works?? Here is the C source code:
#include <stdio.h>
void readCharsAndReverse(void);
int main (void)
{
printf ("Give characters to reverse:");
readCharsAndReverse();
printf ("\n\n");
system("PAUSE");
}
void readCharsAndReverse(void)
{
char ch;
scanf ("%c", &ch);
if (ch != '\n')
readCharsAndReverse();
printf ("%c", ch);
}
As soon as you enter
Enter, your methodreadCharsAndReversestarts returning ie., first it will print the last entered character and all other recursive calls on stack start being poped off..thus by printing all the characters one by one in reverse order..Its just like you keep something in bottom shelf and move onto upper shelf to do the same thing..and when you encounter
Enteryou paste whatever you have, on the wall and come back to below shelf and paste whatever you have kept there, on the wall next to previously pasted content, so on..