Reputation:
Need your help in finding a palindrome.
The problem in my palindrome is: when I put a sentence the test is not performed well because my program checks only the first letter and the last letter So this causes problems With the first letter of sentences is worth to last letter but the second letter is not worth to the one before last letter.
If you can help me solve this I appreciate it Thanks.
my code -
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
char recursive_palindrome(const char st[], int first, int last )
{
if(st[first] != st[last])
{
return(0);
}
if(last-first<=1)
{
return(1);
return(recursive_palindrome(st, first+1,last+1));
}
}
int main()
{
char st[255];
printf("enter a string: \n");
gets(st);
if ( recursive_palindrome(st,0,strlen(st)-1))
{
puts("yes\n");
}
else
{
puts("No");
}
}
Upvotes: 0
Views: 73
Reputation: 2907
Can you please try this code, I solved the issues which were:
1) This if(first > last)
before if(st[first] != st[last])
so you save extra call.
2) This fix:
if(st[first] != st[last])
{
return(0);
}
3) This calling was adding last+1 which is wrong!
return(recursive_palindrome(st, first+1,last-1));
The Code:
char recursive_palindrome(const char st[], int first, int last )
{
if(first > last)
{
return(1);
}
if(st[first] != st[last])
{
return(0);
}
return(recursive_palindrome(st, first+1,last-1));
}
int main()
{
char st[255];
printf("enter a string: \n");
gets(st);
if ( recursive_palindrome(st,0,strlen(st)-1))
{
puts("yes\n");
}
else
{
puts("No");
}
return 0;
}
Upvotes: 0
Reputation: 67772
The line
return(recursive_palindrome(st, first+1,last+1))
should not be in the conditional block
if(last-first<=1) {
because you want to recurse if that branch is not taken. Also, it should be:
return(recursive_palindrome(st, first+1,last-1))
(first moves forwards, last moves backwards).
Upvotes: 0
Reputation: 23058
if(last-first<=1)
{
return(1);
return(recursive_palindrome(st, first+1,last+1));
}
Should be modified into
if(last-first<=1)
{
return(1);
}
return(recursive_palindrome(st, first+1,last-1));
Please note that your original recursive_palindrome()
does not reach any return statement if st[first] == st[last] && last-first > 1
. Compiler should have issued a warning about it.
Upvotes: 2