In this tutorial, you will learn how to check a number is a palindrome or not using a C program.
C Program to Check Whether a Number is Palindrome or Not
#include <stdio.h>
int main()
{
// variables to store the number and its reverse
int num, reversed_num=0;
// variable to store the remainder when the number is divided by 10
int remainder;
// variable to store a copy of the original number
int original_num;
printf("Enter an integer: ");
scanf("%d", &num);
original_num = num; // store the original number
// reverse the number
while(num != 0)
{
remainder = num % 10; // get the remainder when the number is divided by 10
// append the remainder to the reversed number
reversed_num = reversed_num * 10 + remainder;
num /= 10; // divide the number by 10 to remove the last digit
}
// check if the original number is equal to its reverse
if(original_num == reversed_num)
printf("%d is a palindrome.", original_num);
else
printf("%d is not a palindrome.", original_num);
return 0;
}
Output
Enter an integer: 565
565 is a palindrome.
Explanation
This program first reads in an integer from the user and stores it in the variable num
. It then stores a copy of the original number in the variable original_num
.
Next, the program enters a while loop that continues until num
is equal to 0. Inside the loop, it calculates the remainder when num
is divided by 10 and stores it in the variable remainder
. It then appends the remainder to the reversed number, which is stored in the variable reversed_num
. Finally, it divides num
by 10 to remove the last digit.
After the while loop completes, the program checks if the original number is equal to its reverse. If they are equal, it prints that the number is a palindrome. If they are not equal, it prints that the number is not a palindrome.
You can find more C Programming Examples here.
Follow us on Facebook, YouTube, Instagram, and Twitter for more exciting content and the latest updates.