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.
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!
using namespace std;
const int sentencesize = 50;
int rcntr = 0;//reverse counter ... circles through sentence from end to beginning
bool decider = true;
cout << "Please enter the sentence or phrase that you want to check:n";
//calculate the number of characters entered
for (rcntr = 0; sentence[rcntr] != ''; rcntr++);
int loopvar = rcntr/2;
for (int i = 0; i <= loopvar; i++)
if (isalpha(sentence[i]) && isalpha(sentence[rcntr]))
if ( tolower(sentence[i]) == tolower(sentence[rcntr]) )
cout << "It is not a palindrome.n";
decider = false;
else if (!(isalpha(sentence[rcntr])))
cout << "It is a palindrome.n";