C Program to Check Palindrome Number

A String or Number is Palindrome if the reverse of the number/String is same as original, e.g 121, madam.

We are going to create a simple program to check if a given Number is Palindrome or not in C Language.

Note: You must have a Knowledge of Basics C Language.
#include <stdio.h>
#include <conio.h>

int main()
{
    int n, reversedNumber = 0, remainder, originalNumber;

    printf("Enter a Number: ");
    scanf("%d", &n);

    //We have stored the Original number to check later if the reverse number is same as original
    originalNumber = n;

    while( n>0 )
    {
        remainder = n%10;
        reversedNumber = reversedNumber*10 + remainder;
        n = n/10;
    }

    // palindrome if orignalNumber and reversedNumber is equal
    if(originalNumber == reversedNumber)
        printf("%d is a palindrome.", originalNumber);
    else
        printf("%d is not a palindrome.", originalNumber);

    getch();
    return 0;
}

Output will be:

Enter a Number: 121
121 is a palindrome.

Logic

So, What’s the logic behind the above code?

We have created 4 variables i.e noriginalNumber, reversedNumber and remainder.

  • n – To get the Input Number from the user
  • originalNumber – Storing the value of to check later if Original Number is equals to Reversed number or not
  • reversedNumber – Storing the Reverse Number
  • remainder – Storing the Remainder after dividing the remaining numbers i.e n by 10.

Now, we have to ask the user to enter a Number and Let’s say user has entered 2353.

We Store this number in variable.

Now, we have created a while loop which will run till n is greater than 0.

We are using while loop to generate the reverse of the number entered by the user.

We have to first find out the remainder and then multiply 10 with the reversed number and then add the remainder to it and then divide the variable by 10.

In our case, When the while loop runs:

LoopVariables Value
1st Loop
  • remainder = 2353%10 = 3
  • reversedNumber = 0*10 + remainder = 0+3 = 3
  • n = 2353/10 = 235 (n is integer)
2nd Loop
  • remainder = 235%10 = 5
  • reversedNumber = 3*10 + remainder = 30+5 = 35
  • n = 235/10 = 23 (n is integer)
3rd Loop
  • remainder = 23%10 = 3
  • reversedNumber = 35*10 + remainder = 350+3 = 353
  • n = 23/10 = 2 (n is integer)
4th Loop
  • remainder = 2%10 = 2
  • reversedNumber = 353*10 + remainder = 3530+2 = 3532
  • n = 2/10 = 0 (n is integer)

 
Loop Ends. (n==0)

Then we check if the reversedNumber==originalNumber and print if it’s palindrome or not.

Please don’t forget to share this Page.

Shubham Kumar

Hey, I am Shubham and i love Blogging, Coding and exploring new things and obviously sharing my experience with you.

You may also like...

1 Response

  1. Thank you for sharing shubham

Leave a Reply

Your email address will not be published. Required fields are marked *