I made a recursive function in C that prints whather entered string is palindrome or not.
It gives correct answers,but left and right pointers have weird values,and printf prints 4 times for string “ana” instead of 2.Can someone explain me what is going on.
Code:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
/*run this program using the console pauser or add your own getch, system("pause") or input loop */
int palindrome(int left, int right, char string[])
{
printf("stringleft:%c,stringright:%c,Left:%d,right:%dn", left, right, string[left], string[right]);
if (left == right)
{
return 1;
}
if (string[left] != string[right])
{
return 0;
}
left++;
right--;
palindrome(left, right, string);
}
int main(int argc, char *argv[])
{
char s[20];
int right = 0;
printf("Please input the string:");
scanf("%s", s);
while (s[right] != '')
{
right++;
}
right--;
printf("Right:%dn", right);
if (palindrome(0, right, s))
{
printf("nEntered string is palindrome! %d", palindrome(0, right, s));
}
else
{
printf("nEntered string is not palindrome. %d", palindrome(0, right, s));
}
}
I expected for string "ana"
left=0,right=2,string[left]=a,string[right]=a;
left=1,right=1,string[left]=n,string[right]=n;
4
The big issue with your code is that you don’t return in all cases from palindrome
. In this situation the behavior is undefined. Fortunately the solution is simple: return the value of the recursive call.
You’ve also not accounted for cases where the left index might be greater than the right. This can be accomplished by changing left == right
to left >= right
.
int palindrome(int left, int right, char string[])
{
if (left >= right) return 1;
if (string[left] != string[right]) return 0;
return palindrome(left+1, right-1, string);
}
Note there is no reason to use ++
and --
rather than simple adding or subtracting from the values passed to the recursive call, and recursion isn’t needed or desirable vs. a simple loop.
In main
it’s unclear why you’re manually calculating the length of the string rather than simply calling strlen
.
Without using recursion:
int palindrome(char *string) {
size_t length = strlen(string);
char *start = string;
char *end = &string[length - 1];
while (start <= end) {
if (*start != *end) return 0;
start++;
end--;
}
return 0;
}
2
The mistake is in your printf function
printf("stringleft:%c,stringright:%c,Left:%d,right:%dn", string[left], string[right], left, right);
You should be passing string[left]
and string[right]
first and only then left
and right
.
Also, you have a slight mistake in your if statement:
if(left >= right){
return 1;
}
Change it to this, so if you get an input with even length, like anna
You would still correctly finish your method
The reason why you get 4 outputs is because you call your palindrome
method twice in
if(palindrome(0,right,s))
and also inside if and else
Leonid Margulis is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.
4