Google News
logo
C++ program to Reverse a Sentence Using Recursion
In the following example of C++ program to reverse a sentence using recursion :
Program :
#include <iostream>
using namespace std;

// function prototype
void reverse(const string& a);

int main() {
  string str;

  cout << " Please enter a string " << endl;
  getline(cin, str);
    
  // function call
  reverse(str);

  return 0;    
}

// function definition
void reverse(const string& str) {

  // store the size of the string
  size_t numOfChars = str.size();

  if(numOfChars == 1) {
    cout << str << endl;
  }
  else {
    cout << str[numOfChars - 1];

    // function recursion
    reverse(str.substr(0, numOfChars - 1));
  }
}
Output :
Please enter a string 

gninraeL emiT eerF

Free Time Learning
In this program, the user is asked to enter a string which is stored in the string object str.

Then, the reverse() function is called which is a recursive function.

Inside this function, we store the size of the input string in the numOfChars variable.

In the first function call, reverse() prints the last character of the string with the code:
cout << str[numOfChars - 1];​
Remember that strings are actually character arrays, so each individual character of a string can be represented as an index of the string array str[].

In the next line, the recursive function is called:
reverse(str.substr(0, numOfChars - 1));​
Here, substr() gives the string upto the 2nd last character, which is passed again to the reverse() function.

In the next reverse() call, the 2nd last character is printed because the string contains one less character from the last. After this, one character from the last is cut-off from the string again and passed to the reverse() function.