Ad

Using While Loop Vs If Statement To Reverse A String Using Recursion Explanation

So I'm unable to understand logic for using the if statement to reverse a string in this program, shouldn't the while loop perform the task similarly, but when you replace the if((c=getchar())!='\n') with while((c=getchar())!='\n') it only prints the last character of the string. I need help with how this recursion works differently in these two cases.

    #include <stdio.h>
void wrt_t(void);
int main(void)
{
    wrt_t();
    putchar('\n');
    return 0;
}

void wrt_t(void){
    int c;
    if((c=getchar())!='\n'){
            wrt_t();
    }
            
    putchar(c);
}
Ad

Answer

if ((c = getchar()) != '\n') {
      wrt_t();
}

If you use the if statement, only one character will be fetched per recursion. If it isn't a newline (\n) it goes into the next deepest recursion level and the, in this level fetched, character is not printed yet.

When the newline provided in the input is finally reached, the order of the input characters will be printed reversely, as the deepest (last) recursion level prints its fetched character first and so goes the order up to the highest recursion level.

There is nothing more to do in each higher recursion level than to just print the character, which was fetched at that recursion level and return into the next highest recursion level.

The result is the input of the characters until the first newline has been found in reverse order.


while ((c = getchar()) != '\n') {
      wrt_t();
}

When you use a while loop instead, the behavior is different. After the newline is finally reached in the deepest recursion level, it will print the last character of the input (the character fetched at this last recursion level), return into the next highest recursion level and iterates the respective while loop until it finds another newline in the input to break out of the loop and return into the next highest recursion level.

If you don't provide as much newlines as recursion levels in the input, the unwinding of the whole recursion will stuck.

For example for an input of 5 characters like "hello", you would need 6 trailing newlines to get out of the recursion:

hello\n\n\n\n\n\n

Notice that in this case the output would be similar wrong. It would print only 6 newlines as the appended newlines overwrite the characters stored previously in the respective c variable at each recursion level.

In your case, if it only gets one newline, it will only print the last character (actually the newline character) of the input which was fetched of the deepest recursion level and wait for more input.


Beside that if you got an input error and getchar() returned EOF you will get an endless loop in any of the recursion levels.

Ad
source: stackoverflow.com
Ad