Palindrome string program in C++
Written by
A palindrome is a number or a string, which is the same as its reverse. It will be the same when read from right to left and left to right.
We Use the following three methods
- Using predefined methods like strrev()
- Comparing string from start to end
- Palindrome in number
Method 1: Using predefined methods like strrev()
Logic:
In this method, we reverse the string, and compare the reversed string with original string.
Algorithm:
- Input the string
- Use strrev() to reverse the string
- Next, we compare both the strings using strcmp
- Based on the results, we output the result
Code:
#include<iostream.h>
#include<conio.h>
#include <string.h>
void main()
{
clrscr();
char str1[30], str2[30] ;
cout<<"Enter a string : \n";
cin>>str1
strcpy(str2,str1); //copying str1 in str 2
strrev(str2); //reversing string 2
if( strcmp(str1, str2) == 0 ) //compare the original and reversed string
cout<<"\n The string is a palindrome.\n";
else
cout<<"\n The string is not a palindrome.\n";
getch();
}
Output:
Enter a string:
Hello
The string is not a palindrome.
Method 2: Comparing string from start to end
Logic:
In this method, we compare the string from start to end, character by character.
Algorithm:
- Input the string
- Define i such that i=length of string -1
- Now, run a for loop, where the pointer j has starting index and i has ending index
- We then compare string[i] and string[j] characters, until i=j.
- We change the flag, if character is different
- In the end, we check the value of flag with predefined value, and accordingly output the result
Code:
#include <iostream>
#include<string>
using namespace std;
int main()
{
string str;
cout<<"Enter a string: ";
getline(cin,str);
int len=str.length();
int i=len-1;
int flag=0;
for (int j = 0; i<j; j++,i--)
{
if (str[i] != str[j])
{
flag=1;
cout<<"\n Entered string is not a Palindrome.\n";
break;
}
}
if (flag==0)
cout<<"\n Entered string is a Palindrome.\n";
return 0;
}
Output:
Enter a string: AABBBBAA
Entered string is a Palindrome.
Method-3 Palindrome with number
This method is already given in one of the examples previously.