Please explan and show commented C++ Code. /* Palindrome Detector Write a bool f
ID: 3692576 • Letter: P
Question
Please explan and show commented C++ Code.
/* Palindrome Detector
Write a bool function that uses recursion to determine if a string argument is a palindrome.
The function should return true if the argument reads the same forward and backward.Demonstrate the function in a program.
*/
#include <iostream>
#include <string>
using namespace std;
bool palindrome(string x);
int main()
{
string expression;
cout << "Enter a word expression: " << endl;
getline (cin, expression);
expression.length;
if (palindrome(expression) == true)
cout << "Your expression is a palindrome.";
else
cout << "Your expression is not a palindrome.";
return 0;
}
bool palindrome(string x)
{
if (x.length == 1)
return true;
else if (x[0] == x[x.length - 1])
{
string word;
for (int i = 1; i < x.length - 1; i++) //start at index 1
word = word + x[i];
return palindrome(word);
}
}
Explanation / Answer
#include <iostream>
#include <string>
using namespace std;
bool palindrome(string x);
int main()
{
string expression;
cout << "Enter a word/ expression: ";
getline (cin, expression);
if (palindrome(expression) == true)
cout << "Your expression is a palindrome.";
else
cout << "Your expression is not a palindrome.";
cout<<endl;
return 0;
}
bool palindrome(string sentence)
{
int length = sentence.length();
string firstWord = sentence.substr(0,1);
string lastWord = sentence.substr((length - 1), 1);
if (firstWord == lastWord)
{
sentence = sentence.substr((0 + 1), (length - 2));
if (sentence.length() <= 1) return true;
return palindrome(sentence);
}
else
return false;
}