Detail Answer In this lab, you will create both recursive and non-recursive func
ID: 3546294 • Letter: D
Question
Detail Answer
In this lab, you will create both recursive and non-recursive function calls to recognize palindromes. A palindrorre is a string that reads the same forward and backward; that is, the letters are the same whether you read them from right to left or from left to right. For example, the one-word string "radar" is a palindrome. More complicated examples include: Straw? No, too stupid a fad. I put soot on warts. Able was I ere I saw Elba Your program takes an input line and decides if it is a palindrome using both recursive and non-recursive functions. Your functions ignore spaces, punctuations, and the difference between upper- and lowercase letters.Explanation / Answer
#include <iostream>
#include <string>
using namespace std;
bool palindrome_rec(string line)
{
int len = (int)line.length();
if (len == 0)
return true;
if (!isalnum(line[0]))
return palindrome_rec(line.substr(1));
if (!isalnum(line[len-1]))
return palindrome_rec(line.substr(0, len-1));
if (toupper(line[0]) != toupper(line[len-1]))
return false;
return palindrome_rec(line.substr(1, len-2));
}
bool palindrome(string line)
{
int i = 0;
int j = line.length() - 1;
while (i < j)
{
if (!isalnum(line[i])) // ignore spaces or punctualtions
i++;
else if (!isalnum(line[j]))
j--;
else
{
if (toupper(line[i]) != toupper(line[j]))
return false;
i++;
j--;
}
}
return true;
}
int main()
{
string line;
cout << "Enter a line: ";
getline(cin, line);
if (palindrome(line))
cout << "This is palindrome." << endl;
else
cout << "This is NOT palindrome." << endl;
if (palindrome_rec(line))
cout << "This is palindrome(recursive)." << endl;
else
cout << "This is NOT palindrome(recursive)." << endl;
return 0;
}
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.