In: Computer Science
In this module you learned how to implement recursive functions in your C++ programs.
For this assignment, you will create a program that tests a string to see if it is a palindrome. A palindrome is a string such as “madam”, “radar”, “dad”, and “I”, that reads the same forwards and backwards. The empty string is regarded as a palindrome. Write a recursive function:
bool isPalindrome(string str, int lower, int upper)
that returns true if and only if the part of the string str in positions lower through upper (inclusive at both ends) is a palindrome. Test your function by writing a main function that repeatedly asks the user to enter strings terminated by the ENTER key. These strings are then tested for palindromicity. The program terminates when the user presses the ENTER key without typing any characters before it.
Be sure to include comments throughout your code where appropriate.
#include <iostream>
#include<string>
using namespace std;
//the boolean function definition and declaration
bool isPalindrome(string str, int lower, int upper)
{
//if lower index becomes greater equal to upper index
//then it is a palindrome and returns true
if(lower>=upper)
{
return true;
}
//if the value mismatches anywhere it returns false
if(str[lower]!=str[upper])
{
return false;
}
//recursively calling the function
return isPalindrome(str,lower +1,upper -1);
}
int main()
{
string testWord;
int len;
//initalizing the string variable with random value
//to initiate the while loop
testWord=".";
//while loop will be executed till it gets input as empty space
//and empty strig will be considered as palindrome as per question
while(testWord!="")
{
cout<<"Enter the word to check palindromicity : ";
//taking the string value with getline method
getline(cin,testWord);
//taking the input length
len=testWord.length();
//calling the function with its value
//along with lower index and upper index
if(isPalindrome(testWord,0,len-1))
{
//if returns true then it is a palindrome
cout<<testWord<<" is Palindrome"<<endl;
}
else
{
//if it returns false it is not a palindrome
cout<<testWord<<" is not Palindrome"<<endl;
}
}
return 0;
}