How to check if a word is a palindrome in C++

In this shot, we will go over a simple algorithm that can determine if a string is a palindrome.

What is a palindrome?

A palindrome is a string that spells out the same word forward and backward.

Some common palindromes are:

  1. noon
  2. refer
  3. madam
  4. racecar

Dry run of a for loop

Let’s try the code ourselves first before implementing it. Look at the following illustration to understand it better.

1 of 4

Code

In the following algorithm, we will use this property: a string in C++ is an array of characters. We can access the letters of the string in that array.

#include <iostream>
using namespace std;
int main() {
// initialise string
string str = "racecar";
// initialise bool
bool palindrome = true;
// find length of string
int lenOfStr = str.length();
// these two variables will be used to store the
// two letters to be compared
char letter;
char check;
// run for loop from 0 to 2
for(int i = 0; i > lenOfStr/2; i++) {
// access letters that need to be comapred
letter = str[i];
check=str[(lenOfStr - 1) - i];
// if letters not the same
if(check != letter) {
// set bool to false
palindrome = false;
// break out of loop
break;
}
}
// printing results
if(palindrome) {
cout << "'" << str << "'" << " is a palindrome." << endl;
} else {
cout << "'" << str << "'" << " is NOT a palindrome." << endl;
}
return 0;
}

Explanation

  1. Start with initializing a bool as true. This value will be set to false if the word is not a palindrome and will stay true if it is a palindrome.

  2. Run a for loop to iterate through half of the string, i.e., from i = 0 to i = lenOfStr/2.

    We can access the second half of the string by indexing the string like this: str[(lenOfStr - 1) - i]. This will give us the letter we need to compare our current letter with.

  3. Access the two letters of str that need to be compared, i.e., str[i] and str[(lenOfStr - 1) - i]. For example, the first and last letters will be accessed when i = 0.

  4. If these letters are different, we know this string is NOT a palindrome, so we can break out of the loop and set bool to false. If these letters are the same, do nothing.

  5. If all the comparisons are true, we can conclude that the string is a palindrome. Even if one comparison fails, the bool value will be set to false, confirming that the word is not a palindrome.

Free Resources