In this code we will check the number is palindrome or not
#include <iostream>
using namespace std;
int main(){
int number,original,reverse = 0,remainder;
cout<<"Enter number"<<endl;
cin>>number;
original = number;
while(number !=0 ){
remainder = number % 10;
reverse = reverse*10+remainder;
number /= 10;
}
if(original == reverse)
cout<<original<<"=Number is palindrome"<<endl;
else
cout<<original<<"=Number is not palindrome"<<endl;
return 0;
}
Explanation of the Code:
- Input the Number:
- The program asks the user to input a number, which is stored in the variable
number
. - The variable
original
stores the original value ofnumber
to be used later for comparison.
- The program asks the user to input a number, which is stored in the variable
- Reverse the Number:
- The
while
loop runs as long asnumber
is not zero. In each iteration, it:- Extracts the last digit of the
number
using the modulus operator (% 10
) and stores it inremainder
. - Appends this digit to the
reverse
variable by multiplying the existing value ofreverse
by 10 and adding theremainder
. - Divides the
number
by 10 to remove the last digit (moving to the next digit).
- Extracts the last digit of the
- The
- Palindrome Check:
- After the loop ends, the program compares the
original
number with the reversednumber
. - If both are equal, it prints that the number is a palindrome.
- Otherwise, it prints that the number is not a palindrome.
- After the loop ends, the program compares the
Example :
User Input: 121
- Initial Values:
number = 121
reverse = 0
original = 121
- Steps to Reverse the Number:
- First iteration:
remainder = 121 % 10 = 1
reverse = 0 * 10 + 1 = 1
number = 121 / 10 = 12
- Second iteration:
remainder = 12 % 10 = 2
reverse = 1 * 10 + 2 = 12
number = 12 / 10 = 1
- Third iteration:
remainder = 1 % 10 = 1
reverse = 12 * 10 + 1 = 121
number = 1 / 10 = 0
(loop stops here)
- First iteration:
- Palindrome Check:
- Since
original (121)
is equal toreverse (121)
, the program prints:
- Since
Output:
121 = Number is palindrome