Please login

Prime

Prepinsta Prime

Video courses for company/skill based Preparation

(Check all courses)
Get Prime Video
Prime

Prepinsta Prime

Purchase mock tests for company/skill building

(Check all mocks)
Get Prime mock

C++ program to check if the given string is palindrome or not

Checking if the given string is palindrome or not.

In this article, we will learn how to code a C++ program to find if the given string is palindrome or not. The strings that read the same forward as well as backward are said to be a palindrome. In this C++ program to check a string is a palindrome or not we will iterate first half of the string through a for loop and will compare it with remaining half as we need to find if first and last, second and second last, and so in the string are equal or not. If these characters are equal then the string is palindrome else it is not.

C++ program to check if the given string is palindrome or not

Algorithm:

  • Initialize the variable.
  • Accept the input.
  • Initialize for loop.
  • Check if string is palindrome or not.
  • Terminate for loop.
  • Print result.

C++ programming code to check if a given string is palindrome or not

#include <iostream>
#include <string.h>
using namespace std;

int main()
{
    //Initializing variable.
    char str[100];  
    int i,length=0,flag=0;

    //Accepting input.
    cout<<"Enter  the string : "<<endl;
    gets(str);
    length=strlen(str);

    //Initializing for loop.
    for(i=0;i<length/2;i++)  
    {
      //Checking if string is palindrome or not.
      if(str[i]==str[length-i-1])
      flag++;

    }
      //Printing result.
      if(flag==i)
 	cout<<"String entered is palindrome";
      else
        cout<<"String entered is not palindrome";

      return 0;
}
Output 1:
Enter the string : PREPSTER
String entered is not palindrome

Output 2:
Enter the string : MAM
String entered is palindrome