char s[100];
//char t[100];
int count = 1;
int j=0;
int x,i;
cin >>s;
x=strlen(s);
//cout <<x <<endl;
cout <<s[j] <<endl;
i=x-1;
cout <<s[i] <<endl;
for (int i = x-1; i <= 0; i--)
{
if (s[j] != s[i])
{
count = 0;
}
j++;
}
if ( count )
{
cout <<"YES";
}
else
{
cout <<"NO";
}
return 0;
I Want to whether a given string is palindrome or not. Whats wrong with this code? i am expecting it to print YES if a palindrome is being input and NO if the string is not a palindrome. But it always prints YES. There are no errors.
Your code is never entering that for loop
since the condition i = x-1 and i <=0
wont be true well assuming your string is not empty
, then there is no need to keep a count variable since as soon as the strings are not matching you can print NO and exit the code.
You can implement it like:
#include <iostream>
using namespace std;
int main() {
char s[100];
int x,i,j=0;
cin >>s;
x=strlen(s);
i = x-1;
cout <<s[0] <<endl;
cout <<s[i] <<endl;
for (int i = x-1; i >= 0; i--)
{
if (s[j] != s[i])
{
cout <<"NO";
return 0;
}
j ++;
}
cout <<"YES";
return 0;
}