Program for Palindrome

#include <iostream.h>
#include<string.h>
void main()
{
char str[80];
int len,i,j,flag=0;
cout<<"\nEnter String: ";
cin.getline(str,80);
len=strlen(str);
for(len=0;str[len]!='\0';++len)
{ for(i=0,j=len-1;i<=(len/2);++i,--j)
{
if(str[i]!=str[j])
{
flag=0;
break;
}
}
}
if(flag)
cout<<"\nIt is Palindrome!";
else
cout<<"\nIt is not Palindrome!";
}



What is wrong in the above program to check if a string is palindrome???
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
#include <iostream.h>
#include<string.h>
void main()
{
   char str[80];
   int len,i,j,flag=0;
   cout<<"\nEnter String: ";
   cin.getline(str,80);
   len=strlen(str);
   for(len=0;str[len]!='\0';++len)
   {
      for(i=0,j=len-1;i<=(len/2);++i,--j)
      {
         if(str[i]!=str[j])
         {
            flag=0;
            break;
         }
      }
   }
   if(flag)
      cout<<"\nIt is Palindrome!";
   else
      cout<<"\nIt is not Palindrome!";
   }


Please use code tabs (the <> symbol next to the text box) next time.

And I'd've done it this way:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
i=0;
j=strlen(str)-1;
while(i<j)
{
   if(str[i]!=str[j])
   {
      cout << "Not a palindrome!";
      break;
   }
   i++;
   j=strlen(str)-1-i;
}
if(i<j)
   cout << "Palindrome!";
<iostream.h> is not standard, use <iostream> and <cstring>.
Avoid using c-strings, they are error prone and hard to use. Use std::string instead. http://www.cplusplus.com/reference/string/string/
Using strings, the whole procedure boils down to one function call :
1
2
3
4
5
6
7
8
9
10
#include <string>
#include <iostream>
#include <algorithm>
//...
std::string str = "some texttxet emos";
if (std::equal(str.begin(), str.end(), str.rbegin())) {
    std::cout << "palindrome" << std::endl;
} else {
    std::cout << "not a palindrome" << std::endl;
}

Last edited on
Topic archived. No new replies allowed.