Recursive functions call themselves. Write a recursive function that determines
ID: 3692146 • Letter: R
Question
Recursive functions call themselves. Write a recursive function that determines if an input string is a palindrome in C++. Keep in mind the following rules:
1. Punctuation and spaces don’t count, and capital letters are the same as lower-case, so you’ll have to deal with that one way or another. For example, “A man, a plan, a canal. Panama” is a palindrome. So are “kayak” and “12421”.
2. Use the “string” class for your input parameter. That lets you use all of the string functions.
Consider carefully the base case for returning from recursive calls. Your function declaration is: bool isPalindrome(string); Write a driver program that asks for a string and prints whether it is a palindrome or not. The program should stop if the length of the string is zero.
Hand in your C++ file(s). You can probably do this in a single .CPP file.
Explanation / Answer
Hi below i have written the sample function and hope so this helps you for your reference:)
#include <iostream>
#include <string>
#include <vector>
#include <cctype>
#include <algorithm>
bool check_palindrome(std::string input) {
std::string line(20 ,'*');
std::cout << line << std::endl;
std::string stripped_input;
for(std::size_t i = 0; i < input.size(); i++)
{
if(std::isalpha(input[i]))
stripped_input += std::tolower((char)input[i]);
}
std::string reverse = stripped_input;
std::reverse(reverse.begin(), reverse.end());
std::size_t j = 0;
while( j < stripped_input.size() )
{
if ( j == stripped_input.size() - 1)
return true;
else {
if(reverse[j] == stripped_input[j])
j++;
else break; } }
return false; }
int main() {
std::cout << "Enter input" << std::endl; std::string input;
std::getline(std::cin, input, '#');
if (check_palindrome(input)){
std::cout << "Palindrome"; }
else{
std::cout << "Not a Palindrome"; }
return 0;
}
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.