C++ program to check palindrome number or string
In this C++ programs guide we will learn to write:
-
c++ program to check palindrome number
-
c++ program to check palindrome string
What is Palindrome?
A word/sequence/number which read the same in both forward and backward.
Example of palindrome:
Number = 121 (when reversed also gives 121). More examples - 1221, 13331, etc.
String = madam (when reversed it also reads madam), More examples - RADAR, WOW
C++ program to check palindrome number
A variable is assigned to store the input, let say input is n and variable is v1 there after n is reversed through while loop and stored in another variable, let say v2.
Now v1 and v2 is compared. If original and reverse of the number match then its Palindrome number otherwise not.
Given below is code snippet to write a c++ program to check whether a number is palindrome or not.
#include <iostream>
using namespace std;
int main()
{
int n,r,sum=0,num;
cout<<"Enter the No.";
cin>>n;
num=n;
while(n>0)
{
r=n%10;
sum=(sum*10)+r;
n=n/10;
}
if(num==sum)
cout<<"Palindrome :)";
else
cout<<"Not Palindrome :(";
return 0;
}
Output
265
Not Palindrome :(
C++ program to check palindrome string
Two character arrays of size 100 is taken.
One is to store the original string and another for reversed string, now they are compared. If original and reversed string match then its Palindrome, otherwise not.
Given below is a c++ program to check palindrome string.
#include<iostream>
#include<string>
using namespace std;
int main()
{
char x[100],y[100];
cin>>x;
strcpy(y,x); // x string copied to y
strrev(y); // y string reversed
if(strcmp(x,y)==0) // compare x and y string
cout<<"Palindrome :)"
else
cout<<"Not Palindrome :(";
return 0;
}
Output
wow
Palindrome :)
Would you like to see your article here on tutorialsinhand.
Join
Write4Us program by tutorialsinhand.com
About the Author
Page Views :
Published Date :
Jan 23,2021