C program to Reverse a Sentence Using Recursion
Example: Reverse a sentence using recursion
/* 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);
}
}
Output
Enter a sentence: margorp emosewa awesome program
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 up different spaces 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.
example C program to reverse a sentence using recursion:
#include <stdio.h>
// Function to reverse a sentence using recursion
void reverseSentence() {
char c;
scanf("%c", &c);
if (c != '\n') { // Base case: when end of input is reached
reverseSentence(); // Recursive case
printf("%c", c); // Print the character after all recursive calls are finished
}
}
int main() {
printf("Enter a sentence: ");
reverseSentence();
return 0;
}
In this program, we define a function reverseSentence()
that uses recursion to reverse a sentence entered by the user.
The function first reads a character using scanf()
and stores it in the variable c
. If the character is not a newline character (\n
), the function enters the recursive case where it calls itself again to read the next character. This process continues until the end of the input is reached (i.e., when a newline character is encountered).
When the base case is reached, the function starts returning from the deepest call stack and prints the characters in reverse order.
In the main()
function, we ask the user to enter a sentence, and then call the reverseSentence()
function to print the sentence in reverse order.
Note: This program assumes that the sentence entered by the user does not contain any leading or trailing spaces. If the input sentence does contain leading or trailing spaces, the output may not be in the expected order. You may want to add additional input validation checks if necessary.