A palindrome is a word, number, phrase, or other sequences of characters which reads the same backward as forward. Words such as madam or racecar or the number 10801 are a palindrome.
For a given string if reversing the string gives the same string then we can say that the given string is a palindrome. Which means to check for the palindrome, we need to find whether the first and last, second and last-1, and so on elements are equal or not.
Input − naman
Output − string is a palindrome
Input − tutorials point
Output − string is not a palindrome
In C++ Program to Check if a Given String is a Palindrome. The entered string is copied to a new string, and then we compare the first letter with the last letter of string and second letter with second last letter and so on till the end of the string. If both of the letters have the same sequence of characters, i.e., they are identical then the string is a palindrome otherwise not.
Example
#include <iostream> #include<string.h> using namespace std; { int main(){ char string1[]={"naman"}; int i, length; int flag = 0; length = strlen(string1); for(i=0;i < length ;i++){ if(string1[i] != string1[length-i-1]) { flag = 1; break; } } if (flag==1){ printf(" string is not a palindrome"); } else { printf(" string is a palindrome"); } return 0; } }
Output
string is a palindrome
Note - The program is case sensitive.