Program to Reverse String C++

In this post we are going to create a program to reverse string in C++ programming language.

Reversing a number is quite easy task, see this to reverse a number

Program to reverse a number

Logic to Reverse a String:

To reverse a String we just exchange the first character with last character till we reach the mid of the string.

suppose we have a string ‘PROPROGRAMMING’, let’s see the steps:

  • We have 2 for loops, one from starting from 0 position and other starting from last position
  • Now we swap first value with last i.e. P will be swapped with G
  • Now first loop goes to position 0 + 1, and second loop goes to last – 1 position.
  • Now these values are swapped i.e. R with N
  • We continue to do this step till we reach the mid of the string.
  • Finally we have ‘GNIMMARGORPORP’

 

Program to Reverse String C++:

#include<iostream>
using namespace std;

int main( )
{
    int l,i,j;
    char str[80];
    int temp;
    cout<<"Enter string :";
    gets(str);

    for(l=0;str[l]!='';l++);    //finding length of string

    for(i=0,j=l-1;i<l/2;i++,j--)
    {
        temp=str[i];
        str[i]=str[j];
        str[j]=temp;
    }

    cout<<"Reverse String isn"<<str;

    return 0;
}

 

OUTPUT:

reverse string c++

Leave a Comment