Extra 5% OFF Use Code: OL05
Free Shipping over ₹999

Check number is palindrome or not

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:

  1. 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 of number to be used later for comparison.
  2. Reverse the Number:
    • The while loop runs as long as number is not zero. In each iteration, it:
      • Extracts the last digit of the number using the modulus operator (% 10) and stores it in remainder.
      • Appends this digit to the reverse variable by multiplying the existing value of reverse by 10 and adding the remainder.
      • Divides the number by 10 to remove the last digit (moving to the next digit).
  3. Palindrome Check:
    • After the loop ends, the program compares the original number with the reversed number.
    • If both are equal, it prints that the number is a palindrome.
    • Otherwise, it prints that the number is not a palindrome.

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)
  • Palindrome Check:
    • Since original (121) is equal to reverse (121), the program prints:

Output:

121 = Number is palindrome

    Leave a Reply

    Your email address will not be published.

    Need Help?