Reverse a String (Iterative) C++

There are many ways defined to reverse a string in the C++ code including stack, In-place, and iteration. In this sample, a simple string will be reversed iteratively with the following algorithm;


   Step-1: Input the string
   Step-2: Get the length of the string using length() method
   Step-3: Swap the last character to first using for loop
   Step-4: Print

Incompatibility of the above calculation, the accompanying code in c++ language tried as following;


 Live Demo

#include <bits/stdc++.h>
using namespace std;
void strReverse(string& str){
   int n = str.length();
   // Swap character starting from two
   cout<<"interative reverse (Tomhanks)::";
   for (int i = 0; i < n / 2; i++)
      swap(str[i], str[n - i - 1]);
int main(){
   string str = "Tomhanks";
   cout << str;
   return 0;


As the above code compiled, the given string “Tomhanks” will be printed in reverse order as follows;

Iterative reverse (Tomhanks):: sknahmoT