// CS2310 Exercise 21 // Chapter 18 // // Name ____________________________ SSN _______________________ // // Chapter 18. p1052 - 1 // Use recursion to solve the following problem. // A palindrome is a string of characters that reads the same forward // and backward. Write a program that reads in strings of characters // and determines if each string is a palindrome. Each string is on // a separate input line. Echo print each string, followed by "Is a // palindrome" if the string is a palindrome or "Is not a palindrome" // if the string is not a palindrome. For example, given the input // string // // Able was I ere I saw Elba // the program would print "Is a palindrome." In determining whether // a string is a palindrome, consider uppercase and lowercase letters // to be the same. #include #include #include #define MAXLEN 30 using namespace std; bool Palindrome(string str) { // PRE: // str is assigned and its length >= 1 // POST: // Return true if str is a palindrome // false otherwise int len = str.length(); char ch1, ch2; // Get the first character of the string // and convert it to uppercase if necessary ch1 = str.c_str()[0]; if (islower(ch1)) ch1 = toupper(ch1); // Get the last character of the string // and convert it to uppercase if necessary ch2 = str.c_str()[len-1]; if (islower(ch2)) ch2 = toupper(ch2); if (len <= 1) // Base case: If the length of the string // is less than or equal to 1, then ... return // Write the return value here else // Write the code for general case: It // compares the first half of the string // to the second half of the string in // flip order -- fold the string at the // middle and compare two halves // pairwisely. // If the first character is not equal to // the last character, then return false; // otherwise, compare the remaining pairs // in the string using resursive call. // Hint: We can use function // substr(fst, lst) to get the substring of // a given string from index fst to lst, // e.g., the substring from index 1 to // index len-2 of string str is: // str.substr(1, len-2); } int main() { string str; char cstr[MAXLEN]; cout << "Enter the string (* to quit):"; cin.getline(cstr, MAXLEN, '\n'); str = (string) cstr; while (strcmp(str.c_str(), "*")) { if (Palindrome(str)) cout << "This is a palindrome" << endl << endl; else cout << "This is not a palindrome" << endl << endl; cout << "Enter the string (* to quit):"; cin.getline(cstr, MAXLEN, '\n'); str = (string) cstr; } }