Check if a number is palindrome or not
In this article, we will look at a C program that checks if a number is palindrome or not with example and explanation.
The number to be tested will be taken as input from the user.
A palindrome number is a number which reads the same backward as forward. Examples of palindrome numbers are 11, 22, 33, 121, 343, 88788 etc.
Algorithm
To check if a number is palindrome or not, first reverse its digits and then compare the reversed number with the original number.
If both the numbers are equal, the number is palindrome, otherwise not.
To reverse a number with C program, check this article.
C program
Below is a C program to check if a number is palindrome.
#include <stdio.h> void main() { // declare variables int num, reversedNumber = 0, remainder, originalNumber; printf("Enter a number: "); // read number scanf("%d", &num); // copy original number originalNumber = num; // loop till all digits are removed while( num != 0 ) { remainder = n % 10; reversedNumber = reversedNumber*10 + remainder; num /= 10; } // compare orignal and reversed numbers if (originalNumber == reversedNumber) printf("%d is palindrome.", originalNumber); else printf("%d is not palindrome.", originalNumber); }
Note that /=
is a shorthand operator for division and assignment. So, the statement num /= 10
is equivalent to num = num/10
.
Output of this program is
Enter a number: 7564
7564 is not palindrome.
Enter a number: 777
777 is palindrome.