w3resource

C++ Exercises: Reverse a string

C++ For Loop: Exercise-85 with Solution

Write a program in C++ to reverse a string.

Visual Presentation:

C++ Exercises: Reverse a string

Sample Solution:-

C++ Code :

#include <iostream> // Including the input-output stream library
using namespace std; // Using standard namespace

// Function declaration to reverse the string recursively
void revOfString(const string& a);

int main() // Main function
{
    string str; // Declaring a string variable 'str'

    // Displaying a message to reverse a string
    cout << "\n\n Reverse a string:\n";
	cout << "----------------------\n";

	// Asking the user to enter a string
	cout << " Enter a string: ";
    getline(cin, str); // Taking the entire line as input and storing it in 'str'

    // Displaying a message before printing the reversed string
    cout << " The string in reverse are: ";

    // Calling the reverse string function
    revOfString(str);

    return 0; // Returning 0 to indicate successful execution
}

// Function definition to reverse the string recursively
void revOfString(const string& str)
{
    size_t lengthOfString = str.size(); // Getting the length of the string

    // Checking if the length of the string is 1, then simply print the character and end the line
    if (lengthOfString == 1)
       cout << str << endl;
    else
    {
        // Print the last character of the string
        cout << str[lengthOfString - 1];

        // Recursively call the function by passing the substring from 0 to length - 1
        revOfString(str.substr(0, lengthOfString - 1));
    }
}

Sample Output:

 Reverse a string:                                                     
----------------------                                                 
 Enter a string: w3resource                                            
 The string in reverse are: ecruoser3w  

Flowchart:

Flowchart: Reverse a string

C++ Code Editor:

Contribute your code and comments through Disqus.

Previous: Write a program in C++ to compute the sum of the digits of an integer using function.
Next: Write a program in C++ to count the letters, spaces, numbers and other characters of an input string.

What is the difficulty level of this exercise?



Become a Patron!

Follow us on Facebook and Twitter for latest update.

It will be nice if you may share this link in any developer community or anywhere else, from where other developers may find this content. Thanks.

https://www.w3resource.com/cpp-exercises/for-loop/cpp-for-loop-exercise-85.php