OverIQ.com

C Program to check whether the number is a Palindrome

Last updated on September 23, 2020


What is a Palindrome Number? #

A number which remains the same when the digits are reversed is called a palindrome number. For example, 555, 10101, 45654 etc; are palindrome numbers. However, 123, 300 etc; are not.

The following is a C program to check whether the entered number is palindrome or not:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
/****************************************************
 Program to check whether the number is a palindrome
 ****************************************************/

#include<stdio.h> // include stdio.h library

int main(void)
{   
    int num, tmp_num, rev = 0, rem;

    printf("Enter a number: ");
    scanf("%d", &num);

    tmp_num = num;

    while(tmp_num != 0)
    {
        rem = tmp_num % 10;  // get the last digit from tmp_num
        rev = rev * 10 + rem;  
        tmp_num /= 10;  // remove the last digit from tmp_num
    }       

    if(num == rev)
    {
        printf("%d is a palindrome number.", num);
    }

    else
    {
        printf("%d is not palindrome number.", num);
    }

    return 0; // return 0 to operating system
}

Try it now

Expected Output: 1st run:

1
2
Enter a number: 1551
1551 is a palindrome number.

2nd run:

1
2
Enter a number: 123
123 is not palindrome number.

How it works #

The following table demonstrates what happens at each iteration of the while loop, assuming num = 1551.

Iteration rem rev tmp_num
After 1st iteration rem=1551%10=1 rev=0*10+1=1 tmp_num=1551/10=155
After 2nd iteration rem=155%10=5 rev=1*10+5=15 tmp_num=155/10=15
After 3rd iteration rem=15%10=5 rev=15*10+5=155 tmp_num=15/10=1
After 4th iteration rem=1%10=1 rev=155*10+1=1551 tmp_num=15/10=0

Recommended Reading: