Use recursion to find whether a string is a palindrome or not. A palindrome is a
ID: 3806233 • Letter: U
Question
Use recursion to find whether a string is a palindrome or not. A palindrome is a sentence or word that is spelled the same forwards as backwards. Make sure you identify both the base case (what is an easy palindrome to solve?) along with the recursive step (how can you solve a palindrome in terms of palindromes?) before coding. You have to ignore all punctuation and whitespace, and also ignore case differences (i.e., upper and lowercase letters should be treated the same) when testing for a palindrome. A onlyLowercaseLetters() function is provided in palindrome.cpp that returns a string without only the letters from the input string (all in lower case). This should help make this problem easier. Here is an example of program input/output: Example 1 (user input is underlined): Enter a sentence: cat NOT a palindrome Example 2 (user input is underlined): Enter a sentence: lol Palindrome Example 3 (user input is underlined): Enter a sentence: race car Palindrome Example 4 (user input is underlined): Enter a sentence: Madam, I'm adam. Palindrome Example 5 (user input is underlined): Enter a sentence: .4 Palindrome
Explanation / Answer
#include<iostream>
using namespace std;
int main()
{
int i,j,len,flag=1;
char a[20];
cout<<"Enter a string:";
cin>>a;
for(len=0;a[len]!='';++len);
for(i=0,j=len-1;i<len/2;++i,--j)
{
if(a[j]!=a[i])
flag=0;
}
if(flag==1)
cout<<"The string is Palindrome";
else
cout<<"The string is not Palindrome";
return 0;
}
Related Questions
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.