2. (Recursion and Recurrence Relations) (a) (10 pts) Write a recursive function
ID: 3907080 • Letter: 2
Question
2. (Recursion and Recurrence Relations) (a) (10 pts) Write a recursive function that takes a string of length n and rctums I if the string is a palindrome, 0 if the string is not a palindrome. A palindrome is a string that is spelled the same forwards as it is backwards. E.g., "abba" and "aba" are both palindromes, but "abb" is not. The empty string. , is also a palindrome. For simplicity, you may assume the string passed to your function contains lowercase letters only, and no spaces. Do not call strlen _under any circumstances! The function signature is int is Palindrome (char *str, int n) iExplanation / Answer
#include <stdio.h>
// Funciton declaration for palindrome function
int palindrome (char *str, int n);
int main ()
{
int i, len = 0, result;
char string1[100];
// User input string
printf("Enter the string :: ");
scanf("%s", string1);
// Finding string length
for(i = 0; string1[i] != ''; i++) {
len++;
}
// Function call
result = palindrome(string1, len);
// Output message
if (result == 1)
printf("Entered String is palindrome ");
else
printf("Entered String is not a palindrome ");
return 0;
}
// Function definition for palindrome function
int palindrome (char *str, int n)
{
int middle, end, begin;
middle = n/2;
end = n-1;
for (begin = 0; begin < middle ; begin++) {
if (str[begin] != str[end]) {
return 0; // string is not palindrome
}
end--;
}
if (begin == middle)
return 1; // string is palindrome
}
/*************** OUTPUT OF PROGRAM ****************
Enter the string :: abba
Entered String is palindrome
Enter the string :: abc
Entered String is not a palindrome
Enter the string :: aba
Entered String is palindrome
****************************************************/
Related Questions
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.