Use Recursion to Reverse Sentences in C++

Write a C++ program that reverses a sentence with the help of a recursive function.

Click Here to View the Solution:
#include <iostream>
using namespace std;
// function prototype
void Rev(const string& x);
int main() 
{
    string str;
    cout << "Insert a sentence to be reversed: " << endl;
    getline(cin, str);
    cout<< "\nAfter Reversal:\n";
    Rev(str);           // function call
    return 0;    
}
void Rev(const string& str)
{
    size_t chars = str.size();    // store the size of the string
    if(chars == 1)
    {
        cout << str << endl;
    }
    else
    {
        cout << str[chars - 1];
        Rev(str.substr(0, chars - 1));     // function recursion
    }
}
Click Here to View the Output:
Insert a sentence to be reversed:
 edoc fo edoc
 After Reversal:
 code of code
Click Here to View the Explanation:
  • The user is requested to enter a string object. It is stored as a variable in str.
  • A recursive function is created and called in the main () function. This recursive function is Rev ().
  • String length is stored in chars variable. This is the size of the string that has been entered by the user.
  • Since strings are character arrays, every string character is an index of the string array. The function is called in the main () function and the last character of the string is stored. Rev () returns to second last function.
  • The function is called again and the character on second last is printed this time. Now the function returns to the character before the second last character and the process goes on.
  • When the value of string equals 1, the value of str is printed on the screen. The loop is terminated.
%d bloggers like this: