-
Is it a Palindrome?
Hi, I'm writing a program that will identify whether or not the user's input string is a palindrome or not. However, the program keeps the inputed string is a palindrome eventhough it is not. It will say that the string is not a palindrome if the inputed string is a little bit longer. Please, help me!
Code:
#include <stdio.h>
#include <string.h>
#define MAX 50
int palindrome(char[]);
int main()
{
char str[MAX];
printf("Enter a string : ");
scanf("%s",str);
if(palindrome(str)==1)
{
printf("\nThe string is palindrome.\n");
}
else
{
printf("\nThe string is not palindrome.\n");
}
return 0;
}
int palindrome(char str[])
{
int flag = 0;
int start, end;
char rev[MAX];
// Create another string for checking.
for(start=0;str[start]!='\0';start++)
{
rev[start] = str[start];
}
// Check whether the string is palindrome.
// Using the user's input to check with the new string.
for(start=0, end=strlen(str)-1; start<=end; start++, end--)
{
if(str[start] == rev[end])
{
flag = 1;
return(flag);
}
}
flag = 0;
return (flag);
}
-
Your function doesn't test the whole string - look where you return.
-
WOW! thank you, i didn't see that!
-
There's no need for you to create a duplicate string internally to compare against the input argument. You aren't even creating a properly terminated string (you stop copying characters right before you get to the NULL) even though it doesn't matter that much in this case since you are using strlen on the original string and not this copy.
Just do something like this:
Code:
int palindrome(char str[])
{
int flag = 1;
int start, end;
for(start=0, end=strlen(str)-1; flag && start<end; start++, end--)
{
if(str[start] != str[end])
flag = 0;
}
return flag;
}