C++ Program to Check Whether Given String is a Palindrome

Palindrome is a string, which when read in both forward and backward way is same.

Example:
Example: lol, pop, radar, rubber, madam etc.

Palindrome String Check Program in C++

 Example:
#include <iostream>
using namespace std;

int main(){
    char string1[20];
    int i, length;
    int flag = 0;
    
    cout << "Enter a string: "; cin >> string1;
    
    length = strlen(string1);
    
    for(i=0;i < length ;i++){
        if(string1[i] != string1[length-i-1]){
            flag = 1;
            break;
   }
}
    
    if (flag) {
        cout << string1 << " is not a palindrome" << endl; 
    }    
    else {
        cout << string1 << " is a palindrome" << endl; 
    }
    system("pause");
    return 0;
}
Program Output:

cplusplus-check-palindrome-string

Explanation:

To check if a string is a palindrome or not, a string needs to be compared with the reverse of itself.

Consider a palindrome string: lol,

---------------------------
index: 0 1 2

value: l o l
---------------------------

To compare it with the reverse of itself, the following logic is used:

  • 0th character in the char array, string1 is same as 2nd character in the same string.
    . . . .
  • ith character is same as 'length-i-1'th character.
  • If any one of the above condition fails, flag is set to true(1), which implies that the string is not a palindrome.
  • By default, the value of flag is false(0). Hence, if all the conditions are satisfied, the string is a palindrome.

Here are few other related articles for you to read:

Scroll Back to Top