C program to Reverse a Sentence Using Recusrion

This program takes a sentence from user and reverses that sentence using recursion. This program does not use string to reverse the sentence or store the sentence.

Source code to reverse a sentence using recursion.


/* Example to reverse a sentence entered by user without using strings. */

#include <stdio.h>
void Reverse();
int main()
{
    printf("Enter a sentence: ");
    Reverse();
    return 0;
}
void Reverse()
{
    char c;
    scanf("%c",&c);
    if( c != '\n')
    {
        Reverse();
        printf("%c",c);
    }
}

Output

Enter a sentence: margorp emosewa
awesome program

Explanation

This program prints "Enter a sentence: " then, Reverse() function is called. This function stores the first letter entered by user and stores in variable c. If that variable is other than '\n' [ enter character] then, again Reverse() function is called. Don't assume this Reverse() function and the Reverse() function before is same although they both have same name. Also, the variables are also different, i.e., c variable in both functions are also different. Then, the second character is stored in variable c of second Reverse function. This process goes on until user enters '\n'. When, user enters '\n', the last function Reverse() function returns to second last Reverse() function and prints the last character. Second last Reverse() function returns to the third last Reverse() function and prints second last character. This process goes on and the final output will be the reversed sentence.