Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations IamaSherpa on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

palindrome problem in C

Status
Not open for further replies.

dgboult

Programmer
Apr 29, 2001
7
US
Hello,
This is what I have so far. It reads in a message than prints the message in reverse. How do I compare the array's in order to find out if the message is a palindrome or not?
If there is a easier way, please show me. Can you do it with out using strings?


#include <stdio.h>
#define N 10

main()
{
int i, a[N];

printf(&quot;Enter a message: &quot;);
for (i = 0; i < N; i++)
scanf(&quot;%c&quot;, &a);

printf(&quot;In reverse order: &quot;);
for (i = N - 1; i >= 0; i--)
printf(&quot;%c&quot;, a);
printf(&quot;\n&quot;);

return 0;
}

Thanks,
Doug
 
See as you are checking the palindrome the first thing is your array should be a character type. And there is nothing as string in 'C' its a character array or you can take a character pointer to denote the derived data type string.
Take the reverse of the string in another one and run the following loop.

for(i=0,j=strlen(rev_str)-1; str!='\0'; i++,j--)
{
//Compare the characters of srings herein.....

}


If the chars donot match at any point.terminate the string and display &quot;Not a palindrome&quot; else print its a palindrome.
I know that this has to be a home assignment so I am not giving you the code and deprive you of a learning experience.Hope you get the logic and solve it on your own.



Happy Learning.
SwapSawe
 
Well, strings in C /are/ character arrays, so string is a valid term :)

To the OP:

Another way is to do it with pointers by starting one pointer at the end of the &quot;string&quot; and one pointer at the beginning while maintaining a pointer to the beginning of the string. Loop through the string, incrementing the beginning pointer and decrementing the end pointer. If the characters don't match at any point, terminate the loop. Compare the pointer that started at the end to the pointer that points to the beginning of the string. If they match, it's a palindrome.

int isPalindrome(const char *s)
{
const char *const start=s; /* bookmark the start of the
* string
*/
const char *end=strchr(s,'\0')-1; /* Get pointer to end */

while (start!=end) {
/* You fill in the rest */

/* ... */

return start==end;
}

Generalize it further by ignoring spaces and punctuation marks, so that a phrase like:

A man a plan a canal panama!

is flagged as a palindrome.

Russ
bobbitts@hotmail.com
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top