C++ String Exercises: Reverse a given string

C++ String: Exercise-1 with Solution

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

Visual Presentation:

C++ Exercises: Reverse a given string

Sample Solution:

C++ Code :

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

// Function to reverse a string
string reverse_string(string str) {
	string temp_str = str; // Creating a temporary string to store the original string
	int index_pos = 0; // Initializing index position to start from the beginning

	// Loop to reverse the string
	for (int x = temp_str.length()-1; x >= 0; x--) // Iterating through the string in reverse order
		str[index_pos] = temp_str[x]; // Reversing the characters and storing in the original string
		index_pos++; // Moving to the next index position
	return str; // Returning the reversed string

int main() 
	cout << "Original string: w3resource"; // Displaying the original string
	cout << "\nReverse string: " << reverse_string("w3resource"); // Displaying the reversed string

	cout << "\n\nOriginal string: Python"; // Displaying the original string
	cout << "\nReverse string: " << reverse_string("Python"); // Displaying the reversed string

	return 0; // Returning 0 to indicate successful execution

Sample Output:

Original string: w3resource
Reverse string: ecruoser3w

Original string: Python
Reverse string: nohtyP


Flowchart: Reverse a given string.

C++ Code Editor:

Contribute your code and comments through Disqus.

Previous C++ Exercise: C++ String Exercises Home
Next C++ Exercise: Change every letter in a string with the next one.

What is the difficulty level of this exercise?

Follow us on Facebook and Twitter for latest update.