mardi 14 juillet 2020

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);
}

Aucun commentaire:

Enregistrer un commentaire