Task 2: Test for Palindrome (recursive)
Write a function isPalindrom() that takes as input a C string and its size, and recursively tests whether it is a palindrome (a word or phrase which remains the same if reversed. e.g. radar, kayak etc). The function returns the Boolean data type which is either true or false. The required header “stdbool.h” has already been included in tasks.h.
The function has the following prototype:
bool isPalindrom(char * ptr_array, int size);
The recursive definition of a palindrome is:
The string is a palindrome if it has only one character or is an empty string.
The string is a palindrome if the first and the last characters are the same and the characters in between form a palindrome.
#include <stdio.h>
#include <string.h>
#include <stdbool.h>
// A recursive function that
// check a str[s..e] is
// palindrome or not.
bool isPalindrom(char *ptr_array, int s, int size)
{
int e = size - 1;
if (size==0)
return true;
else
{
if (s == e)
return true;
if (ptr_array[s] != ptr_array[e])
return false;
if (s < e + 1)
return isPalindrom(ptr_array, s+1 , size - 1);
}
return true;
}
// Driver Code
int main()
{
char str[100];
printf("Enter a string : ");
scanf("%s",str);
int n=strlen(str);
char *ptr_array=str;
if (isPalindrom(ptr_array,0,n))
printf("Yes");
else
printf("No");
return 0;
}
Comments
Leave a comment