Input: abcd
Output: dcba
Code:#include<stdio.h> #include<stdlib.h> void mystery(void); main() { mystery(); } void mystery(void) { int c; if((c=getchar()) != EOF){ mystery(); putchar(c); } }
Input: abcd
Output: dcba
Code:#include<stdio.h> #include<stdlib.h> void mystery(void); main() { mystery(); } void mystery(void) { int c; if((c=getchar()) != EOF){ mystery(); putchar(c); } }
Last edited by SauceGod; 07-15-2016 at 03:23 PM.
Very simple!
The program uses recursion to reverse the string entered.
main() calls mystery()
getchar() gets the first character
mystery() then calls itself
getchar() gets the second character
mystery() then calls itself
getchar() gets the third character
...
When no more characters to get,
putchar() displays the last character retrieved.
mystery() returns to the calling function, mystery()
putchar() displays the previous character retrieved.
mystery() returns to the calling function, mystery()
...
Until all characters have been displayed, and control returns to main().
The program exits main() and returns to the O/S.
In each separate call to mystery() a new and different integer 'c' is created, containing each one of the characters entered.
I would not want to redirect the text from "War & Peace" into this program as you would blow the stack! There is no control here as to the maximum level of recursion allowed! ;^)
If the input is coming from the command line it would require the user to press [Ctrl-D] on a Linux/UNIX system, or [Ctrl-Z] on a Windows/DOS system to force the EOF!
In other words, this simple program could use some improvement.