149k views
5 votes
Write a program that uses the function isPalindrome given in Example 6-6 (Palindrome). Test your program on the following strings:

madam, abba, 22, 67876, 444244, trymeuemyrt

Modify the function isPalindrome of Example 6-6 so that when determining whether a string is a palindrome, cases are ignored, that is, uppercase and lowercase letters are considered the same.

The isPalindrome function from Example 6-6 has been included below for your convenience.

bool isPalindrome(string str)
{
int length = str.length();
for (int i = 0; i < length / 2; i++) {
if (str[i] != str[length – 1 – i]) {
return false;
} // if
} // for loop
return true;
}// isPalindrome

Your program should print a message indicating if a string is a palindrome:

madam is a palindrome

2 Answers

5 votes

Final answer:

The isPalindrome function is modified to test strings for being palindromes in a case-insensitive manner by converting them to lower case before comparison. The modified function is then tested with various strings to check for palindromes.

Step-by-step explanation:

A student is tasked with writing a program that can test if certain strings are palindromes. The provided isPalindrome function checks if a string reads the same forwards as backwards. To account for case insensitivity, we modify the function so that it compares characters in a case-insensitive manner by converting the string to a single case before the comparison loop.

Here is the modified version of the isPalindrome function:

bool isPalindrome(string str)
{
for (char &c : str) c = tolower(c); // Convert all characters to lowercase
int length = str.length();
for (int i = 0; i < length / 2; i++) {
if (str[i] != str[length – 1 – i]) {
return false;
}
}
return true;
}

When testing this function with strings such as 'madam', 'abba', '22', '67876', '444244', 'trymeuemyrt', it will now correctly identify palindromes regardless of the case of the letters.

User Cambium
by
5.2k points
4 votes

Answer:

Step-by-step explanation:

bool isPalindrome(string str)

{

int length = str.length();

for (int i = 0; i < length / 2; i++) {

if (str [i] != str [length – 1 – i]) {

return false;

}

}

cout << str << "is a palindrome";

return true;

}

User Pamba
by
5.9k points