Problem: Write a C++ program to check whether a given string is a palindrome or not.

Example:

Input:  mom
Output: Palindrome

Input:  Malayalam
Output: Palindrome

A palindrome string is that string which in reverse is equal to the original string.

Palindrome string

To check palindrome string in C++:

  1. Input the string.
  2. Reverse the string.
  3. Check whether the reverse of the string is equal to the input string.
  4. If yes, then the string is a palindrome, or else it is not.

Here is the implementation of the steps in C++:

#include <iostream>
using namespace std;
 
int main()
{
    string str, rev="";
        
    //Input String 
    cout<<"Enter a string: ";
    cin >> str;
    
    //Reverse String
    for(int i=str.length()-1; i>=0; i--){
        //If character is in upper case convert it to lower case
        if(str[i]>=65 && str[i]<=90)
            str[i] = str[i]+32;
            
        //assign the character to reverse string variable
        rev +=str[i];
    }
    
    //Output result
    if(rev == str)
        cout << "Palindrome";
    else
        cout << "Not Palindrome";
        
    return 0;
}

Output:

Enter a string: mom
Palindrome


Strings such as Mom (first letter as upper case) do not match up with its reverse despite being a palindrome. So in the program, we lower the case of the characters before assigning them to the rev variable.

In this programming example, we learned to check a palindrome string in C++.

Leave a Reply

17 − 9 =