Recursion

Hey people, I have a problem with recursion that I can't seem to solve. The code I've written so far is below:

18 int main(void) {
19 int temp, i, start, end, size =0, count =0, num[MAX_SIZE] = {0};
20
21 printf("Enter start and end: ");
22 scanf("%d %d", &start, &end);
23
24 while(start <= end) {
25 temp = start;
26 for(i=0;temp>0;i++) {
27 num[i] = temp % 10;
28 temp /= 10;
29 size++;
30 }
31 count += isPalindrome(num, size);
32 start++;
33 }
34
35 printf("Number of palindrome numbers = %d\n", count);
36
37 return 0;
38 }
39
40 // Return 1 if arr is a palindrome, or 0 otherwise.
41 // Driver function to call recursive function palindromeRecur()
42 int isPalindrome(int arr[], int size) {
43 int i=0;
44 return palindromeRecur(arr, i, size);
45 }
46
47 // Return 1 if arr is a palindrome, or 0 otherwise.
48 // Recursive function
49 int palindromeRecur(int arr[], int i, int size) {
50 if(size <= i)
51 return 1;
52
53 if(arr[i] != arr[size])
54 return 0;
55 else return palindromeRecur(arr, i+1, size-1);
56 }
Remove the line numbers and add code tags, the code is unreadable otherwise.

I have a problem

...such as?
int main(void) {
int temp, i, start, end, size =0, count =0, num[MAX_SIZE] = {0};

printf("Enter start and end: ");
scanf("%d %d", &start, &end);

// From start to end, numbers are passed into isPalindrome function to
// determine whether it is a palindrome. The 'count' of palindrome within
// this range is then printed.
while(start <= end) {
temp = start;
for(i=0;temp>0;i++) {
num[i] = temp % 10;
temp /= 10;
size++;
}
count += isPalindrome(num, size);
start++;
}

printf("Number of palindrome numbers = %d\n", count);

return 0;
}

// Return 1 if arr is a palindrome, or 0 otherwise.
// Driver function to call recursive function palindromeRecur()
int isPalindrome(int arr[], int size) {
int i=0;
return palindromeRecur(arr, i, size);
}

// Return 1 if arr is a palindrome, or 0 otherwise.
// Recursive function
int palindromeRecur(int arr[], int i, int size) {
if(size <= i)
return 1;

if(arr[i] != arr[size])
return 0;
else return palindromeRecur(arr, i+1, size-1);
}

My isPalindrome and palindromeRecur are unable to correctly determine a positive case. Every case is return 0. Thank you for your time.
Two problems with size values..

1. Line 53. Array size starts from 0 to (size-1). You are taking the ending index as size, instead of size-1. It should be:
if(arr[i] != arr[size-1])

2. size value should be reset to 0 before calculating for the next number.
Insert size=0; after line 25.
That should work.

Also, while posting code, please use the Source code format (in the formats section on the right) or use code tags.

Hope this helps.
Last edited on
Thank you, didn't realize I forgotten to re-initialize size after the first recursion is over.
Topic archived. No new replies allowed.