C++ program to check if a sentence is a Palindrome or not

Wikipedia defines Palindrome as, “A palindrome is a word, phrase, number or other sequence of units that can be read the same way in either direction (the adjustment of punctuation and spaces between words is generally permitted).”

There are two different kinds of Palindrome. One is on a character by character basis while the other is on a word by word basis. Examples of these two type of palindromes are “Was it a rat I saw?” and “Fall leaves after leaves fall” respectively.

I have written a program in C++ which can check a word, phrase or sentence if it is a palindrome on a character by character basis. It is capable of handling complex sentences with punctuation marks such as “Dammit, I’m mad!”.

The logic I used in this program is almost self evident but still I have written a short explanation of how it works in the following lines.

Explanation

The sentence is stored in a character array named “sentence”. Then the number of characters entered by user is calculated using the first one-line for loop and stored in a variable called “rcntr” (short for reverse counter). This variable is used to determine how many times the next for loop should run and also it cycles through the characters of sentence in reverse order. In next for loop, actual processing takes place. If a non-alphabet character is countered at the position i then “rcntr” is incremented back so that the i+1th character could be compared with the “rcntr”th character. Similarly if such a character is encountered at “rcntr”th position then i is decremented back so that (“rcntr”-1)th could be compared with the ith character. If, at any position ith character and “rcntr”th character don’t match while they are alphabetic characters than it means that the sentence entered is not a palindrome. So, the loop execution is breaked after reversing the value of a boolean variable “decider”. And that’s it!!

If you have any suggestions about improving this program then please let me know. I shall be very thankful to you!

5 thoughts on “C++ program to check if a sentence is a Palindrome or not”

  1. Fun post! I’m not a C++ programmer by any stretch of the imagination, but I came up with this:

    #include
    #include
    #include

    using namespace std;

    bool is_palindrome(string line)
    {
    deque characters;

    // push each alphabetic character onto the deque lowercased
    for (string::iterator i = line.begin(); i != line.end(); i++)
    if (isalpha(*i))
    characters.push_back(tolower(*i));

    while (!characters.empty())
    {
    // take something off the front
    char left = characters.front();
    characters.pop_front();

    // if we’re out of things, then we’re a palindrome because this is
    // the odd character that was left over.
    if (characters.empty())
    return true;

    // take something off the end
    char right = characters.back();
    characters.pop_back();

    // if the thing from the front and the thing from the end are the same,
    // we still may be a palindrome
    if (left != right)
    return false;
    }

    // if we make it here without more stuff on the end, we are a palindrome
    return characters.empty();
    }

    int main()
    {
    string line;

    // read in a line
    cout << "Enter a line to check: ";
    getline(cin, line);

    // so, is it a palindrome?
    bool palindrome = is_palindrome(line);

    // display different messages depending
    if (palindrome)
    cout << "Palindrome!" << endl;
    else
    cout << "Not a palindrome. :(" << endl;

    // make this state our UNIX return status, depending
    return (int)!palindrome;
    }

    This could probably be improved by just running a forward and a backward iterator in parallel instead of copying the string into a deque, but this made more sense to me.

  2. Use the string class (#include ). You can do an infinite length input, don’t need to calculate the length of it (it is a member function call), and you can access it like a char array.

    Also, ! the if statement when checking for tolower, that way you can put the cout not a palindrome logic in there without an if-else statement, only need an if statement.

  3. Little bug on my program above, I actually had this in a function so the cout statements were return statements (originally true and false). So the code doesn’t precisely work as I just posted, (it will post NOT A PALINDROME and PALINDROME HELL YEAH for failures and PALINDROME HELL YEAH for successes)

  4. I tried to write my own… I noted that you were going for case insensitive so I included this as well, though it would be simpler without it…

    This one doesn’t care about the length beyond the fact that the character array is given a limit on length, and calculates it as it inputs instead of needing to input it and then reiterate to calculate the length.

    Also I decided to go with pointers over the array notation.

    Though this solution could be wrong, I’m only in an intro C++ course and saw this post on reddit.

    #include
    using namespace std;

    int main()
    {
    // Wouldn’t this be an easier way to input the characters?

    const int SIZE = 50;
    char* charArray = new char[SIZE];
    char* tempStartPointer = charArray;
    char* tempEndPointer = charArray;

    int length = 0;
    char c = cin.get();
    while(c != ‘n’ && length < SIZE – 1) // SIZE 1 for null char
    {
    *(tempEndPointer++) = c;
    length++;
    c = cin.get();
    }

    // for debugging give it the extra null char
    *tempEndPointer = '';

    // move tempEndPointer back one so it is at the end of the string
    tempEndPointer–;

    while(tempStartPointer < tempEndPointer)
    {
    if(!isalpha(*tempStartPointer))
    {
    tempStartPointer++;
    continue;
    }

    if(!isalpha(*tempEndPointer))
    {
    tempEndPointer–;
    continue;
    }

    if(toupper(*tempStartPointer++) != toupper(*tempEndPointer–))
    {
    cout << "NOT A PALINDROME";
    break;
    }
    }

    cout << "PALINDROME HELL YEAH";

    delete[] charArray;

    return 0;
    }

Leave a Reply