Explanation needed to understand this recursive C program to print a string in reverse

545 Views Asked by At

I cannot understand when does the putchar line is being executed and how it's helping to reverse the input lines ? If EOF occurs the return statement gets executed , but what happens after that line ?

#include<stdio.h>
int fun_reverse();
void main(){

    fun_reverse();
}

int fun_reverse(){

    int ch ;
    ch = getchar();
    if(ch==EOF)
        return;

    fun_reverse();
    putchar(ch);
}
2

There are 2 best solutions below

2
On BEST ANSWER

every time you're calling fun_reverse in your fun_reverse function, it doesn't print the inputted char immediately, just asks for input for another one, piling on the requests (and creating as much local variables storing each char) until EOF is reached.

When EOF is encountered, fun_reverse returns without calling fun_reverse again, ending the chain, making all callers return and eventually print the results.

The fact that the calls have been piled on due to recursion has the effect of reversing the output, because unpiling them is done the other way round.

This technique is often used to convert a number to string without any extra buffer. Converting a number to string gives the "wrong" end of the number first, so you have to buffer the numbers until the number digits are fully processed. A similar algorithm as the one above allows to store the digits and print them in the readable order.

0
On

Though your question is already been answered I would suggest you to read about 'head recursion' and 'tail recursion'. Have a look at accepted answer of this question.