140k views
4 votes
C++

a. Write a program that uses the function isPalindrome given in example 6-6 (Palindrome). Test your program on the followinng strings: "madam", "abba", "22", "67876", "444244", and "trymeuemyrt"

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

Example 6-6:
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;
return true;
}

User Farskeptic
by
6.1k points

1 Answer

6 votes

Answer:

a) # include <iostream>

# include <conio.h>

# include <stdio.h>

# include <string.h>

using namespace::std;

bool IsPalindrome(const string& str)

{

if (str.empty())

return false;

int i = 0; // first characters

int j = str.length() - 1; // last character

while (i < j)

{

if (str[i] != str[j])

{

return false;

}

i++;

j--;

}

return true;

}

int main()

{

string str;

cout<<"Enter the string";

getline(cin, str);

bool a= IsPalindrome(str);

if(a)

{

cout<<"Is in palindrome";

}

else

{

cout<<"Is not in palindrome";

}

}

b) Modified version of function with full program to discard uppercase or lowercase is as below:

# include <iostream>

# include <conio.h>

# include <stdio.h>

# include <string.h>

using namespace::std;

bool IsPalindrome(const string& str)

{

if (str.empty())

return false;

int i = 0; // first characters

int j = str.length() - 1; // last character

while (i < j)

{

char a= tolower(str[i]);

char b= tolower(str[j]);

if (a != b)

{

return false;

}

i++;

j--;

}

return true;

}

int main()

{

string str;

cout<<"Enter the string";

getline(cin, str);

bool a= IsPalindrome(str);

if(a)

{

cout<<"Is in palindrome";

}

else

{

cout<<"Is not in palindrome";

}

}

Step-by-step explanation:

Please check the answer section.

User Yevgeniy Gendelman
by
6.6k points