Palindrome in C++ Modify the program so it takes a WORD and a PHRASE and returns
ID: 3880688 • Letter: P
Question
Palindrome in C++
Modify the program so it takes a WORD and a PHRASE and returns the correct feedback. You entered a WORD or you ENTERED a PHRASE.
#include <iostream>
#include <string>
using namespace std;
// Function prototype
bool isPalindrome(string);
int main()
{
const int SIZE = 6;
// Create an array of strings to test.
string testStrings[SIZE] =
{ "ABLE WAS I ERE I SAW ELBA",
"FOUR SCORE AND SEVEN YEARS AGO",
"NOW IS THE TIME FOR ALL GOOD MEN",
"DESSERTS I STRESSED",
"AKS NOT WHAT YOUR COUNTRY CAN DO FOR YOU",
"KAYAK" };
// Test the strings.
for (int i = 0; i < SIZE; i++)
{
cout << """ << testStrings[i] << """;
if (isPalindrome(testStrings[i]))
cout << " is a palindrome. ";
else
cout << " is NOT a palindrome. ";
}
return 0;
}
//*******************************************
// The isPalindrome function returns true *
// the argument is a palindrome, false *
// otherwise. *
//*******************************************
bool isPalindrome(string str)
{
bool status = false;
if (str.length() <= 1)
status = true;
else if (str.at(0) == str.at(str.length()-1))
status = isPalindrome (str.substr(1, str.length()-2));
return status;
}
Explanation / Answer
#include <iostream>
#include <string>
using namespace std;
// Function prototype
bool isPalindrome(string);
int main()
{
const int SIZE = 6;
string s;
cout<<"Enter the WORD or PHRASE: "<<endl;
getline(cin, s);
if (isPalindrome(s))
cout << s<<" is a palindrome. ";
else
cout << s<<" is NOT a palindrome. ";
return 0;
}
//*******************************************
// The isPalindrome function returns true *
// the argument is a palindrome, false *
// otherwise. *
//*******************************************
bool isPalindrome(string str)
{
bool status = false;
if (str.length() <= 1)
status = true;
else if (str.at(0) == str.at(str.length()-1))
status = isPalindrome (str.substr(1, str.length()-2));
return status;
}
Output:
Related Questions
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.