palindrome program....

#include <iostream.h>
#include <conio.h>
#include <string.h>
int main()
{
char strn[80];
int i,j,flag=0,len;
cout<<"Enter the string:";
cin.getline(strn,80);
len=strlen(strn);
for(i=0,j=len-1;i<=(len/2);++i,--j)
{
if(strn[i]==strn[j])
flag=1;
}

if(flag)
cout<<"Palindrome";

else cout<<"Not a palindrome";

getch();
}


The objective is to check whether a string is a palindrome or not.........

Why doesnt the above program work...
Please give me a similar logic ......i only know arrays,iteration statements and related topics........
Last edited on
The logic for mine (that works for me) is:
get string
get length of string
loop for half the length of string
if the character at position "c" & position of length-c are the same, keep looping, otherwise it's not a 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
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
#include<iostream>
#include<string>
using namespace std; // the namespace for cout<< & such functions
int main()
{
char strn[80];
cout<<"Enter the string: ";
cin.getline(strn,80);
int len=strlen(strn);

bool flag=true; // create a Boolean value, "flag" to be used in our loop

for(int c=0;c!=len/2;c++) // do a loop from 0 to half the length of the string
{
if(flag) // if it is a palindrome so far
{
if(strn[c]!=strn[len-c-1]) // check the characters match
{
flag=false; // if they don't set the indicator to false
}

}
else
{
break; // if it is not a palindrome, exit the for loop
}
}

// if flag is true cout "Palindrome" otherwise output "Not Palindrome"

if(flag)
{
cout<<"Palindrome";
}
else
{
cout<<"Not Palindrome";
}

cin.get();
return 0;
}


Hope this helps.
1
2
3
4
5
for(i=0,j=len-1;i<=(len/2);++i,--j)
{
if(strn[i]==strn[j])
flag=1;
}


I think the loop checks only if (strn[40]==strn[41])

You can use a counter to count the true flags- using or not using nested loops.
But still the best solution is using break, as chris said .



Last edited on

or something like

1
2
3
4
5
6
7
8
9

  char *s = strn; // point to first char
  char *e = strn + strlen(strn) - 1; // point to last char

  while ( *s == *e && s != e ) ++s, --e; // move towards each other
  bool flag = ( s == e ); 
  if ( !flag ) cout << " Not a ";
  cout << "Palindrome" << endl;


Last edited on
Topic archived. No new replies allowed.