C Program to Check Whether a Number is Palindrome or Not

A palindrome number is a number whose reverse is the original number. Some examples of palindrome number are: 121, 12321, 515, etc. C program to check whether the number is palindrome or not is shown below.

Example 1: Check Palindrome Using while Loop and if…else Statement

#include<stdio.h>
int main()
{
    int num,res=0,chk,c;
    printf("Enter a number n");
    scanf("%d",&num);
    chk=num;

    while (num>0)
    {
        c = num % 10;
        res = res*10+c;
        num = num/10;
    }

    if (chk == res)
        printf("n The entered number is PALINDROME.");
    else
        printf ("n The entered number is NOT PALINDROME.");
   
    return 0;

}

Here the user is asked to enter a number. The entered number is assigned to variable num. Another variable chk is assigned the same value as num to check the result at the end of the program. The loop begins and continues to loop as along as num>0. When num>0 the c variable stores the last digit of the number. The variable res is initially 0 so res*10 = 0 + c which is equal to res=c. Then the statement num=num / 10 removes the last digit of the digit as for example, 129/10 equals to 12.

On the second loop, c again stores the last digit of the number. Then the value currently being stored at res is multiplied by 10 and c is added to res. The statement num=num/10 again removes the last digit and the loop continues as long as n>0. When n is < or = 0 then the loop stops.

Example 2: Check Palindrome for 3 Digit Number

Another method, to check whether a number is palindrome or not in C programming is by comparing the first and last digit of the number. If the first and last digits are the same then the number of palindrome

#include<stdio.h>
int main()
{
   int a,b,c,x;

    printf("Enter a three digit number n");
    scanf("%d",&a);

    x=a%10;
    a=a/10;
    b=a%10;
    c=a/10;

    if (x==c)
       printf("n It is PALINDROME. ");
    else
       printf("n It is NOT PALINDROME. ");

    return 0;

}

Here, variable x holds the last digit of the number. The statement a=a/10 removes the last digit. The variable b holds the middle digit of the three digit number. And the variable c holds the first digit of the number. If the last digit is equal to the first digit then the number is palindrome, otherwise not.

Output

Enter a number
121
It is PALINDROME.
Enter a number
300
It is NOT PALINDROME.