This is a program which finds the reverse of a string entered by a user and tell whether its a palindrome or not.... now the issue is this that it is correctly reversing the string when in for loop i initilize with size()-1... but it misses one character when i initialize with size(). why is this so?
//palindromee
#include <iostream>
using namespace std;
int main()
{
string s;
string s1;
cout<<"Enter something: ";
cin>>s;
s1.assign(s);
int k=0;
for(int i = s.size()-1 ; i>=0 ; i--)
//why correct ans reversing on size()-1?
{ // and wrong ans on size()
s1[k]=s[i];
k++;
}
cout<<"string s= "<<s;
cout<<"\nstring s1= "<<s1<<'\n';
int checker=s.compare(s1);
if(checker == 0)
{
cout<<"\n\npalindrome";
}
else cout<<"\n NOT A PALINDROME";
return 0;
}
That's because in c & c++ array indexes are 0 based. The same goes true for the string class, where accessing individual characters using the [] operator the index is 0 based. The length of an array (or the size of a string) is ALWAYS outside it's bounds.