C++ program to reverse a given string using using length() function
codeaft.cpp
#include<iostream>
#include<cstring>usingnamespacestd;intmain(){cout<<"———————————————————————————————————————————";cout<<"\nProgram to reverse a given string";cout<<"\n———————————————————————————————————————————";strings,r="";cout<<"\nEnter the string ";getline(cin,s);for(inti=s.length()-1;i>=0;i--){r=r+s[i];}cout<<"\nThe reverse string is "<<r;cout<<"\n———————————————————————————————————————————\n";}
Output
codeaft@codeaft:~$ g++ codeaft.cpp codeaft@codeaft:~$ ./a.out
———————————————————————————————————————————
Program to reverse a given string
———————————————————————————————————————————
Enter the string CODEAFT
The reverse string is WODNIWGNIDOK
———————————————————————————————————————————
codeaft@codeaft:~$
C++ program to reverse a given string by swapping characters
codeaft.cpp
#include<iostream>
#include<cstring>usingnamespacestd;intmain(){cout<<"———————————————————————————————————————————";cout<<"\nProgram to reverse a given string";cout<<"\n———————————————————————————————————————————";chars[50],temp;cout<<"\nEnter the string ";cin>>s;inti=0,j=strlen(s)-1;for(i=0;i<j;i++,j--){temp=s[i];s[i]=s[j];s[j]=temp;}/* Another way, you can replace for loop with while loop
while(i<j)
{
temp=s[i];
s[i]=s[j];
s[j]=temp;
i++;
j--;
}
*/cout<<"\nThe reverse string is "<<s;cout<<"\n———————————————————————————————————————————\n";}
Output
codeaft@codeaft:~$ g++ codeaft.cpp codeaft@codeaft:~$ ./a.out
———————————————————————————————————————————
Program to reverse a given string
———————————————————————————————————————————
Enter the string CODEAFT
The reverse string is WODNIWGNIDOK
———————————————————————————————————————————
codeaft@codeaft:~$
Dear User, Thank you for visitng Codeaft. If you are interested in technical articles, latest technologies, and our journey further, please follow us on LinkedIn.