Sunday, 23 September 2018

Checking whether a number is a palindrome or not in C++

Palindrome number

Palindrome numbers are those numbers which remain the same even after reversing.12321 is a palindrome number as the number remains the same even after reversing i.e.12321. This program uses the same idea used in finding the reverse of a number


Write a program in C++ to input a multi-digit number and check whether it is a palindrome or not.


We need to input a multi-digit number from the user and copy it to another variable. Then we extract the last digit of the multi-digit number by performing the mod operation with 10. The extracted value is added to a new variable which is multiplied by 10 every time. This increases one decimal place of each digit of the number in a new variable before adding the last digit to it. The last digit is then removed by using slash(/) operator and storing it in int data type. This process is continued until the multi-digit number is reduced to zero(0). Finally, after the while loop is terminated, we compare the reverse with the value copied initially. If the two value matches the number is a palindrome else it is not.




Program


#include<iostream.h>
#include<conio.h>
void main()
{
int a,b=0,rev=0,check;
clrscr();
cout<<"Enter a multidigit number=";
cin>>a;
check=a;
while(a!=0)
{
b=a%10;
rev=(rev*10)+b;
a=a/10;
}
if(check==rev)
cout<<"\nThe number is palindrome";
else
cout<<"\nThe number is not palindrome";
getch();
}



Output



Program to check palindrome numbers.
CHECKING OF PALINDROME NUMBER








Explanation


In the program, we entered a=565 which first is assigned to variable check. Since the value of a is not equal to zero(565!=0 is true), while loop will be executed as follows:

a                 b=a%10                  rev=(rev*10)+b                      a=a/10        
565             565%10=5              (0*10)+5=5                            565/10=56
56               56%10=6                (5*10)+6=56                          56/10=5
5                 5%10=5                  (56*10)+5=565                      5/10=0
0

The while loop will terminate since a=0. Now the if...else statement will check whether the value rev(reverse of a number) is equal to the value of check(input number). If they are equal then the number is palindrome message will be displayed on the screen.





No comments:

Post a Comment