Program to Check String is Palindrome or not in C++


Palindrome String is a String that remains the same when its character are reversed. Like saas, for example: we take saas and reverse it, after revers it is same as original.

Steps to write program

  • Get the string from user.
  • Reverse it.
  • Compare it with the string entered by the user.
  • If both are same then print palindrome
  • Else print not a palindrome.

Program to Check String is Palindrome or not in C++

#include<iostream.h>
#include<conio.h>

void main()
{
int i,j,len,flag=1;
char a[20];
    
cout<<"Enter a string:";
cin>>a;
    
for(len=0;a[len]!='\0';++len);
   
for(i=0,j=len-1;i<len/2;++i,--j)
{
if(a[j]!=a[i])
flag=0;
}
   
if(flag==1)
{
cout<<"\nString is Palindrome";
}
else
{
cout<<"\nString is not Palindrome";
}
getch();
}

Output

Enter a String: saas
String is Palindrome

Check String is Palindrome or not in C++

#include<iostream.h>
#include<conio.h>
#include<string.h>
#include<stdio.h>

void main() 
{ 
char str[10]; 
int i,j,n,flag=0; 
cout<<"Enter any string:"<<endl; 
gets(str); 
n=strlen(str); 
for(i=0,j=n-1;i<=n/2;i++,j--) 
{ 
if(str[i]!=str[j]) 
flag=1; 
break; 
} 
if(flag==1) 
{
cout<<"String is not Palindrome"; 
}
else
{
cout<<"String is Palindrome"; 
}
getch(); 
}

Output

Enter any String: lol
String is Palindrome

0 comments: