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
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 |
#include<iostream.h> #include<stdio.h> #include<string.h> int main() { char a[50],temp; int i,j,len; cout<<"Enter any string:\n"; gets(a); len=strlen(a); cout<<"Reverse of the string is: "; for(i=0,j=len-1;i<len/2;++i,--j) { temp=a[i]; a[i]=a[j]; a[j]=temp; } cout<<a; return 0; } |
Output
Comment below if you are facing any difficulty to understand above program.
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;
}
I think something is wrong in that code. You have never used a1 anywhere.
this didnt work
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;
}
this is wrong programme
Wrong programme ….
#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];
}
#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;
}
if using for loop only ?