C++ for Beginners: C++ program to Reverse a Sentence Using Recursion

(C++ programming Example for Beginners)

C++ program to Reverse a Sentence Using Recursion

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.

 


Example: Reverse a sentence using recursion.


#include <iostream>
using namespace std;

void reverse(const string& a);

int main(){
    string str;
    cout << " Please enter a string " << endl;
    getline(cin, str);
    reverse(str);
    return 0;    
}

void reverse(const string& str){
    size_t numOfChars = str.size();

    if(numOfChars == 1)
       cout << str << endl;
    else
    {
       cout << str[numOfChars - 1];
       reverse(str.substr(0, numOfChars - 1));
    }
}

Output

Enter a sentence: margorp emosewa
awesome program

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. In the first function call, reverse() prints the last character of the string (numOfChars – 1), -1 because array starts with 0.

Then, 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.

This goes until the length of the string equals 1, when the final character (or the first character) is printed and the loop ends.

 

C++ for Beginners: C++ program to Reverse a Sentence Using Recursion

Sign up to get end-to-end “Learn By Coding” example.



Disclaimer: The information and code presented within this recipe/tutorial is only for educational and coaching purposes for beginners and developers. Anyone can practice and apply the recipe/tutorial presented here, but the reader is taking full responsibility for his/her actions. The author (content curator) of this recipe (code / program) has made every effort to ensure the accuracy of the information was correct at time of publication. The author (content curator) does not assume and hereby disclaims any liability to any party for any loss, damage, or disruption caused by errors or omissions, whether such errors or omissions result from accident, negligence, or any other cause. The information presented here could also be found in public knowledge domains.