C++ Program to Reverse a String

Here you will get C++ program to reverse a string.

The user is asked to enter a string and then the reverse of the string is displayed.

For example:

Input String: hello

Output String: olleh

 C++ Program to Reverse a String


 

Output

C++ Program to reverse a string

Comment below if you are facing any difficulty to understand above program.

9 thoughts on “C++ Program to Reverse a String

  1. kalyan garimella

    I think this logic is good than using multiple for loops ……….

    #include
    #include
    #include

    using namespace std;

    int main(){
    char str1[20],str2[20];
    int i=0,len;

    cout<<"Enter a String : ";
    gets(str1);
    len = strlen(str1);

    while(len>=0){
    str2[i] = str1[–len];
    i++;
    }
    str2[i]='';

    cout<<"Reversed String : "<<str2;

    return 0;
    }

    Reply
  2. Dilip

    I think something is wrong in that code. You have never used a1 anywhere.

    Reply
    1. Arjun khapekar

      this will work for sure

      #include
      #include
      #include

      void reverse(char str[ ],int) ;

      void main()
      {
      char str[80];
      clrscr();
      cout<<"Enter the string : " ;
      cin.getline(str,80);
      int len=strlen(str);
      reverse(str,len);
      getch();
      }

      void reverse(char str1[ ] , int length)
      {
      int mid=length/2;
      length – – ;
      for(int i=0; i<mid; i++)
      {
      char temp=str1[i];
      str1[i]=str1[length];
      str1[length]=temp;
      length – – ;
      }
      cout<<"\t\t Reverse of the String is : " ;
      cout<<str1;
      }

      Reply
  3. Kishan

    #include
    #include
    #include
    void main()
    {
    char a[2100],a2[100],t;
    cout<<"enter the array :";
    gets(a);
    t=strlen(a);
    for(int i=0;a[i]!='\0';++i)
    {
    a2[t-i-1]=a[i];
    }
    for(i=0;i<t;++i)
    cout<<a2[i];
    }

    Reply
  4. Harikrishna D S

    #include
    #include
    #include
    using namespace std;

    int main()
    {
    char str[50];
    int str_len;
    cout<<"Enter the string"<<endl;
    gets(str);
    str_len=strlen(str);
    int start=0, end=str_len;

    for(int i=0;i<str_len;i++)
    {
    swap(str[i],str[str_len-1]);
    str_len–;
    }
    cout<<str;
    }

    Reply

Leave a Reply

Your email address will not be published. Required fields are marked *