C++ Program to Reverse a String

Write a c++ program to reverse a string. Reverse a string in c++.

C++ program to reverse a string

  1. Accept a string or sentence from user.
  2. Calculate Length of string by using strlen() function.
  3. Use for loop to replace last and first characters. Then second and second last characters and so on.
  4. Resultant string is the reverse string of original given string.
  5. Print the reverse string to the screen.
Here is the source code of C++ program to reverse a string.
/* C++ program to reverse a string */

#include<iostream>
#include<string.h>
using namespace std;

int main ()
{
    char temp, str[100];
    int i, n;

    cout << "Enter a string : ";
    cin >> str;

    n = strlen(str) - 1;

    for (i = 0; i < n; i++,n--)
    {
        temp = str[i];
        str[i] = str[n];
        str[n] = temp;
    }

    cout << "\n Reverse String : " << str;

    return 0;
}

Output:

 Enter a string : computer

 Reverse String : retupmoc

Comments