Search code examples
c++palindrome

I have tried to write a code to find if a word is a palindrome or not but it is not working. Whats's wrong with it?


#include <iostream>
#include <string.h>

using namespace std;

int main()
{
    int len;
    char char1[100],char2[100];
    cout << "Enter a word:" << endl;

    cin >> char1;
    len = strlen(char1);

    for(int i=0;i<len;i++)
    {
        char2[i] = char1[len-i-1];
    }
    if(strcmp(char1,char2))
    {
        cout << "It is not a palindrome." << endl;
    }
    else
    {
        cout << "It is a palindrome" << endl;
    }
}

I have tried to write a code to find if a word is a palindrome or not. When I enter "madam" as input the output is "It is a palindrome". But when I enter "dad" as input the output is "It is not a palindrome". Why is it?


Solution

  • Because character arrays are used here to represent strings and also strcmp is used to compare theses arrays, You need to remember that the last value of a text has to be '\0' (also called a null character / null terminator).

    So after the loop, which copies the string in reverse, the following needs to be added;

    char2[len] = '\0';
    

    When using strcmp the condition should be explicitly shown what it is checking. The reason is that strcmp returns 3 results (-1, 0 ,1) and from Your code it should be directly visible if the API is used correctly. (Even though C and C++ have an implicit conversion of a value to bool)

    Also contrary to intuition the result of strcmp will be converted to true when the compared strings are different (-1 and 1) and converted to false when they are the same (0).

    The condition should be, for example:

    if (strcmp(char1, char2) == 0)    // checking if strings are equal
    

    or

    if (strcmp(char1, char2) != 0)    // checking if strings are different
    

    In an ambiguous case of a function result like it is here, it is even suggested to create a temporary (constant) boolean variable to make the code easier to understand. Like this:

    const bool is_palindrome = (strcmp(char1, char2) == 0);
    if (is_palindrome)
        // ...
    

    Here is another proposal, how to implement this algorithm:

    #include <iostream>
    #include <string>
    
    int main()
    {
        using namespace std;
    
        cout << "Enter a word:" << endl;
    
        string input_str;    
        getline(cin, input_str);
    
        const string reversed_str(input_str.rbegin(), input_str.rend());
    
        const bool is_palindrome = (input_str == reversed_str);
    
        if (is_palindrome)
        {
            cout << "It is a palindrome" << endl;
        }
        else
        {
            cout << "It is not a palindrome." << endl;
        }
    }