C++ Program to Check Palindrome String

programming

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 pallandrome string is the string that equals the original string in reverse.

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 palindrome otherwise not.

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

#include <iostream>
using namespace std;
 
int main()
{
    string str, rev="";
        
    //1. Input String 
    cout<<"Enter a string: ";
    cin >> str;
    
    //2. Reverse String
    for(int i=str.length()-1; i>=0; i--){
        //if the character is in upper case, transform 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];
    }
    
    //3. Compare the reverse with the input string
    if(rev == str)
        cout << "Palindrome";
    else
        cout << "Not Palindrome";
        
    return 0;
}

Output:

Enter a string: mom
Palindrome


Strings such as Mom, despite being palindrome would not match with its reverse because its first letter is in the upper case.

For true comparison, we have to transform all the upper case letters into lower case.

Leave a Reply

Your email address will not be published. Required fields are marked *