121k views
1 vote
A palindrome is a string that reads the same forwards or backwards; for example dad, mom, deed (i.e., reversing a palindrome produces the same string). Write a recursive, bool-valued function, isPalindrome that accepts a string and returns whether the string is a palindrome. A string, s, is a palindrome if: s is the empty string or s consists of a single letter (which reads the same back or forward), or the first and last characters of s are the same, and the rest of the string (i.e., the second through next-to-last characters) form a palindrome.

User Digijay
by
7.1k points

2 Answers

3 votes

Final answer:

The function 'isPalindrome' recursively checks if a string is a palindrome by comparing the first and last characters and calling itself on the remaining substring. It returns true for empty strings or single characters and false if the characters don't match.

Step-by-step explanation:

A palindrome is a string that reads the same forwards and backwards. To write a recursive, bool-valued function, isPalindrome, that checks if a given string is a palindrome, we need to consider three cases: the string is empty, it has a single character, or its first and last characters are the same with the rest of the string being a palindrome as well. Here's a step-by-step explanation of how to create the isPalindrome function:

  • Base Case 1: If the string is empty or has a single character, return true, as by definition these are palindromes.
  • Base Case 2: If the first and last characters do not match, return false.
  • Recursive Step: If the first and last characters match, recursively call isPalindrome on the substring that excludes these two characters.

Here is a simple implementation of isPalindrome in a pseudo-code style:

def isPalindrome(s):
if len(s) <= 1:
return true
elif s[0] != s[-1]:
return false
else:
return isPalindrome(s[1:-1])

This function will systematically reduce the problem until it reaches a base case, and it will return either true or false based on whether the string is a palindrome or not.

User Timothy Miller
by
6.3k points
7 votes

Answer:

Explanation: Palindrom.c

#include <stdio.h>

#include <string.h>

int isPalindrome (char s[],int l);

int main()

{

char s[15];

printf("Enter a string: ");

scanf("%s", s);

int result = isPalindrome(s, strlen(s));

if(result){

printf("Palindrome\\");

}

else{

printf("Not a palindrome\\")

}

return 0;

}

int isPalindrome (char s[], int l)

{

if (l<=0)

return 1;

if (s[0] == s[l-1])

{

return isPalindrome (s+1, l-2);

}

else return 0;

}

User Menghan
by
7.0k points