This program checks whether a given number is a palindrome (reads the same forwards and backwards) using a while loop.
C Program
#include <stdio.h>
int main() {
int num, original, reversed = 0, remainder;
printf("Enter a number: ");
scanf("%d", &num);
original = num;
while (num != 0) {
remainder = num % 10;
reversed = reversed * 10 + remainder;
num = num / 10;
}
if (original == reversed) {
printf("%d is a palindrome.\n", original);
} else {
printf("%d is not a palindrome.\n", original);
}
return 0;
}
Explanation
- The original number is preserved in
originalsincenumgets modified during reversal. - Inside the
whileloop,num % 10extracts the last digit, which is appended toreversedbyreversed * 10 + remainder. num / 10removes the last digit (integer division), and the loop continues untilnumbecomes 0.- Finally, the reversed number is compared with the original — if they match, the number is a palindrome.
Sample Output
Enter a number: 12321
12321 is a palindrome.
Enter a number: 12345
12345 is not a palindrome.