Question
C++ Programming Palindrome Detector: A palindrome is any word, phrase, or sentence that reads the same...
C++ Programming
Palindrome Detector:
A palindrome is any word, phrase, or sentence that reads the same forward and backward. Here are some well-known palindromes:
Able was I, ere I saw Elba
A man,a plan, a canal, Panama
Desserts, I stressed
Kayak
Write a book 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, which continues to ask the user to type a text, and then print out the text is palindrome or not, until the user wants to quit the program. (Note: you might delete any punctuation signs firstly, only need to consider the letters)
(C++ Programming)
Answers
#include <iostream>
#include <cctype>
using namespace std;
//function declarations
bool testPalindrome(string str);
string upperCaseIt(string s);
int main()
{
//Declaring variables
string str,str1;
char ch;
/* This while loop continues to execute
* until the user enters other than 'y' or 'Y'
*/
while(true)
{
str1="";
//Getting the input entered by the user
cout<<"\nEnter a string :";
getline(cin,str);
//eliminating spaces,commas..etc
for(int i=0;i<str.length();i++)
{
if(isalpha(str[i]))
str1+=str[i];
}
//calling the function
str1=upperCaseIt(str1);
//calling the function
if(testPalindrome(str1))
cout<<"This is a Palindrome"<<endl;
else
cout<<"This is not a Palindrome"<<endl;
cout<<"\nDo you Want to continue(Y/N):";
cin>>ch;
if(ch=='y'||ch=='Y')
{
cin.ignore();
continue;
}else
{
break;
}
}
return 0;
}
/* This is a recursive function which calculates
* whether the String is Palindrome or not using recursive method
* Param:string
* return: boolean
*/
bool testPalindrome(string str) {
if(str.length() == 0 || str.length() == 1)
return true;
else if(str[0] == str[str.length()-1])
return testPalindrome(str.substr(1, str.length()-2));
return false;
}
// This function will convert the lower case to upper case
string upperCaseIt(string s)
{
for (int i = 0; i < s.size(); i++)
{
if (s.at(i) >= 97 && s.at(i) <= 122)
{
s.at(i) = s.at(i) - 32;
}
}
return s;
}
_____________________
Output:
______________Thank You
ב c:\ CAProgram Files (x86) Dev-CpplMinGW641bin\PlaindromelrrespectiveOfSpacesCommaR Files Enter a string Able was I. ere I saw Elba his is a Pali Do you Want to continue CY/N>:y Enter a string A man a plan. a canal. Panama his is a Pali Do you Want to continue CY/N>:y Enter a string Desserts. I stressed This is a Pal Do you want to continue(Y/N);y Enter a string Kayak This is a Pal Do you want to continue(Y/N):n Process exited after 54.7 seconds with return value 0 Press any key to continue . - .