Ask Question

Write a C+ + program that determines if a given string is a palindrome. A palindrome is a word or phrase that reads the same backward as forward. Blank, punctuation marks and capitalization do not count in determining palindromes. Here is some examples of palindromes:

Radar

Too hot to hoot

Madam! I'm adam

+2
Answers (1)
  1. 21 January, 09:51
    0
    The cpp program to determine if the given string is palindrome, is shown below.

    The program has comments at places to indicate the logic.

    #include

    #include

    using namespace std;

    int main () {

    / / string is taken as an array of characters of size 50

    char str1[50];

    int i, len, flag;

    cout<<"Enter any string to check for palindrome"<
    cin>>str1;

    / / length of input string is stored in variable len to be used in the loop

    len = strlen (str1) - 1;

    for (i=0; i<=len; i++)

    {

    / / if string is palindrome, value of flag variable is initialized to 0 else 1

    if (str1[i]==str1[len-i])

    flag = 0;

    else

    flag = 1;

    }

    if (flag = = 0)

    cout << str1 << " is a palindrome";

    else

    cout << str1 << " is not a palindrome";

    / / returns integer value since main has return type of integer

    return 0;

    }

    Explanation:

    The header files for input and output and string are imported.

    #include

    #include

    The string is taken as an array of type char having adequate size of 50.

    char str1[50];

    The length of the input string is calculated as

    len = strlen (str1) - 1;

    Within a single for loop using a single variable and the length of the string, we check whether the string is palindrome or not.

    for (i=0; i<=len; i++)

    {

    if (str1[i]==str1[len-i])

    flag = 0;

    else

    flag = 1;

    }

    The int flag is declared but not initialized.

    If the string is palindrome, the value of flag variable becomes 0. Otherwise, the value of flag variable will be initialized to 1.

    Depending on the value of flag variable, the message is displayed if the input string is palindrome or not.

    The above program works for all strings irrespective of special characters which may be included in the string.

    The above program also works for the examples of input string given in the question.
Know the Answer?
Not Sure About the Answer?
Find an answer to your question 👍 “Write a C+ + program that determines if a given string is a palindrome. A palindrome is a word or phrase that reads the same backward as ...” in 📗 Computers & Technology if the answers seem to be not correct or there’s no answer. Try a smart search to find answers to similar questions.
Search for Other Answers