0
0
CppProgramBeginner · 2 min read

C++ Program to Reverse a String with Output and Explanation

You can reverse a string in C++ by using a loop to swap characters from the start and end, like for (int i = 0; i < n / 2; ++i) std::swap(str[i], str[n - i - 1]); where n is the string length.
📋

Examples

Inputhello
Outputolleh
Inputworld
Outputdlrow
Input
Output
🧠

How to Think About It

To reverse a string, think of it like flipping a row of books: swap the first with the last, the second with the second last, and so on until you reach the middle. This way, the string is reversed in place without needing extra space.
📐

Algorithm

1
Get the input string.
2
Find the length of the string.
3
Loop from the start to the middle of the string.
4
Swap the character at the current position with the character at the corresponding position from the end.
5
After the loop ends, the string is reversed.
6
Print the reversed string.
💻

Code

cpp
#include <iostream>
#include <string>

int main() {
    std::string str;
    std::cout << "Enter a string: ";
    std::getline(std::cin, str);
    int n = str.length();
    for (int i = 0; i < n / 2; ++i) {
        std::swap(str[i], str[n - i - 1]);
    }
    std::cout << "Reversed string: " << str << std::endl;
    return 0;
}
Output
Enter a string: hello Reversed string: olleh
🔍

Dry Run

Let's trace the string "hello" through the code to see how it reverses.

1

Initial string

str = "hello", n = 5

2

First iteration (i=0)

Swap str[0] ('h') and str[4] ('o') -> str = "oellh"

3

Second iteration (i=1)

Swap str[1] ('e') and str[3] ('l') -> str = "olleh"

4

Loop ends

i reaches n/2, string reversed as "olleh"

IterationString state
0 (start)hello
1oellh
2olleh
💡

Why This Works

Step 1: Calculate string length

We find the length n to know how many swaps are needed, only up to half the string.

Step 2: Swap characters

Swapping characters at positions i and n - i - 1 flips the string from both ends towards the center.

Step 3: Stop at the middle

We stop swapping at the middle because after that, characters would be swapped back to original places.

🔄

Alternative Approaches

Using std::reverse function
cpp
#include <iostream>
#include <string>
#include <algorithm>

int main() {
    std::string str;
    std::cout << "Enter a string: ";
    std::getline(std::cin, str);
    std::reverse(str.begin(), str.end());
    std::cout << "Reversed string: " << str << std::endl;
    return 0;
}
This uses the built-in <code>std::reverse</code> function for simplicity and readability.
Creating a new reversed string
cpp
#include <iostream>
#include <string>

int main() {
    std::string str, rev;
    std::cout << "Enter a string: ";
    std::getline(std::cin, str);
    for (int i = str.length() - 1; i >= 0; --i) {
        rev += str[i];
    }
    std::cout << "Reversed string: " << rev << std::endl;
    return 0;
}
This method builds a new string by adding characters from the end to the start, using extra memory.

Complexity: O(n) time, O(1) space

Time Complexity

The loop runs half the string length, so time grows linearly with input size, making it O(n).

Space Complexity

Swapping in place uses no extra space beyond variables, so space complexity is O(1).

Which Approach is Fastest?

Using std::reverse is fastest and simplest; manual swapping is similar but more code; building a new string uses extra space and is slower.

ApproachTimeSpaceBest For
Manual swap loopO(n)O(1)In-place reversal without extra memory
std::reverse functionO(n)O(1)Clean, standard, and efficient
New reversed stringO(n)O(n)When original string must stay unchanged
💡
Use std::reverse from <algorithm> for a clean and efficient solution.
⚠️
Forgetting to stop swapping at the middle causes characters to swap back, leaving the string unchanged.