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:%d\n", 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] != '\0')
{
right++;
}
right--;
printf("Right:%d\n", 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;
The mistake is in your printf function
printf("stringleft:%c,stringright:%c,Left:%d,right:%d\n", 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