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

A palindrome is a string, which when read in both forward and backward ways is the same.

Example:

Example: lol, pop, radar, 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 the same as 2nd character in the same string.
    . . . .
  • ith character is the same as 'length-i-1'th character.
  • If anyone of the above condition fails, the flag is set to true(1), which implies that the string is not a palindrome.
  • By default, the value of the flag is false(0). Hence, if all the conditions are satisfied, the string is a palindrome.


Found This Page Useful? Share It!
Get the Latest Tutorials and Updates
Join us on Telegram

Notifications

Updates are enabled for this browser.

Receive new tutorials, articles and learning resources. You can turn updates off anytime.

Test browser code

Use this code in admin to send a test notification to this browser.