Reversing a sentence using recursion is a common programming problem that can be easily solved using C++.
In this tutorial, we will discuss how to reverse a sentence using recursion in C++.
First, let’s define the problem statement. We have to reverse a given sentence using recursion.
For example, if the given sentence is “Hello World”, then the output should be “World Hello”. We will use a recursive approach to solve this problem.
To solve this problem, we can break down the sentence into words using space as a delimiter. We can then reverse each word and concatenate them to form the reversed sentence.
Let’s see how to implement this using C++ code:
#include <iostream>
using namespace std;
void reverseSentence(string sentence) {
if (sentence.length() == 0) {
return;
} else {
int i = sentence.find(" ");
if (i == string::npos) {
reverseSentence("");
cout << sentence << " ";
} else {
string word = sentence.substr(0, i);
sentence = sentence.substr(i + 1);
reverseSentence(sentence);
cout << word << " ";
}
}
}
int main() {
string sentence;
cout << "Enter a sentence: ";
getline(cin, sentence);
reverseSentence(sentence);
return 0;
}
In the code above, we have defined a function called reverseSentence which takes a string as an argument.
Inside the function, we first check if the length of the string is zero. If it is, we return.
Otherwise, we find the index of the first space in the sentence. If there is no space, we call the reverseSentence function recursively with an empty string and print the sentence.
If there is a space, we extract the first word from the sentence and call the reverseSentence function recursively with the remaining sentence. We then print the word.
In the main function, we get the input sentence from the user using the getline function and call the reverseSentence function to reverse the sentence.
In conclusion, we have seen how to reverse a sentence using recursion in C++.
This problem can be easily solved using a recursive approach by breaking down the sentence into words and reversing them.
The code above can be used to implement this approach in C++.




