C++ Program to Reverse a String with Output and Explanation
for (int i = 0; i < n / 2; ++i) std::swap(str[i], str[n - i - 1]); where n is the string length.Examples
How to Think About It
Algorithm
Code
#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; }
Dry Run
Let's trace the string "hello" through the code to see how it reverses.
Initial string
str = "hello", n = 5
First iteration (i=0)
Swap str[0] ('h') and str[4] ('o') -> str = "oellh"
Second iteration (i=1)
Swap str[1] ('e') and str[3] ('l') -> str = "olleh"
Loop ends
i reaches n/2, string reversed as "olleh"
| Iteration | String state |
|---|---|
| 0 (start) | hello |
| 1 | oellh |
| 2 | olleh |
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
#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; }
#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; }
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.
| Approach | Time | Space | Best For |
|---|---|---|---|
| Manual swap loop | O(n) | O(1) | In-place reversal without extra memory |
| std::reverse function | O(n) | O(1) | Clean, standard, and efficient |
| New reversed string | O(n) | O(n) | When original string must stay unchanged |
std::reverse from <algorithm> for a clean and efficient solution.