Home / Programs / C program to Reverse a Sentence Using Recursion
🚀 Programming Example

C program to Reverse a Sentence Using Recursion

👁 3,386 Views
💻 Practical Program
📘 Step Learning
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.

💻 Program Code

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

#include <stdio.h>
void reverseSentence();

int main()
{
    printf("Enter a sentence: ");
    reverseSentence();

    return 0;
}

void reverseSentence()
{
    char c;
    scanf("%c", &c);

    if( c != '\n')
    {
        reverseSentence();
        printf("%c",c);
    }
}
                        

🖥 Program Output

Enter a sentence: margorp emosewa
awesome program
                            

📘 Explanation

This program first prints "Enter a sentence: ". Then, immediately reverseSentence() function is called.

This function stores the first letter entered by user in variable c. If the variable is any character other than '\n' [ enter character], reverseSentence() function is called again.

When reverseSentence() is called the second time, the second letter entered by the user is stored in c again.

But, the variable c in the second function isn't the same as the first. They both take different space in the memory.

This process goes on until user enters '\n'.

When, the user finally enters '\n', the last function reverseSentence() function prints the last character because of printf("%c", c); and returns to the second last reverseSentence()function.

Again, the second last reverseSentence() function prints the second last character and returns to the third last reverseSentence() function.

This process goes on and the final output will be the reversed sentence.

📚 Learning Subject

Master Programming Through Practical Examples

Improve your coding logic, problem-solving skills and programming confidence by practicing real-world examples with explanations.

🎯 How to learn from this example

First understand the algorithm carefully. Then study the program line-by-line and compare it with the output. Finally, review the explanation section to strengthen your logic and programming understanding.

🔥 Practice suggestion

Rewrite the program without looking at the code. Modify values, conditions or logic and run it again. This helps improve confidence and strengthens coding skills much faster.