(in c++, without using #include <iostream.h> or <stdio.h>) Write a recursive fun
ID: 3676163 • Letter: #
Question
(in c++, without using #include <iostream.h> or <stdio.h>)
Write a recursive function that returns true if an input string is a palindrome and false if it is not. You can do this by checking if the first character equals the last character, and if so, make a recursive call with the input string minus the first and last characters. You will have to define a suitable stopping condition. Then write a program that takes in a string as user input, then calls the above function and outputs the result. Input string may have characters and numbers. Ignore case when comparing two chracters.
The program should print a string of text to the terminal before getting the inputs from the user. A session should look like one of the following examples (including whitespace and formatting):
The strings printed by the program should include a newline at the end, but no other trailing whitespace (whitespace at the end of the line).
Explanation / Answer
#include<iostream>
#include<string>
#include <assert.h>
using namespace std;
bool is_palindrome(string);
int main(void) {
cout << "Starting tests..." << endl;
const int num_tests = 5;
string strings[num_tests] = {
"aibohphobia", "detartrated", "aba", "abba", "wassamassaw"
};
string not_strings[num_tests] = {
"ab", "abc", "abcbba", "redivide", "ccccdecccc"
};
for (int i = 0; i < num_tests; i++) {
assert (is_palindrome(strings[i]));
assert(!is_palindrome(not_strings[i]));
cout << strings[i] << (is_palindrome(strings[i])
? " is a palindrome"
: " is not a palindrome" )
<< endl;
cout << not_strings[i] << (is_palindrome(not_strings[i])
? " is a palindrome"
: " is not a palindrome" )
<< endl;
}
cout << "All tests passed." << endl;
string user_input;
cout << "Enter string to recursively check for palindrome-ness" << endl;
cin >> user_input;
cout << (is_palindrome(user_input)
? "Word is a palindrome"
: "Word is not a palindrome" )
<< endl;
return 0;
}
bool is_palindrome(string s) {
if (s.size() <= 1)
return true;
if (s.front() != s.back()) {
return false;
} else {
return true && is_palindrome(s.substr(1, s.size() - 2));
}
}
Related Questions
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.