C Program to Check Palindrome Number
while and if statements; if both are equal, it prints the number is palindrome.Examples
How to Think About It
Algorithm
Code
#include <stdio.h> int main() { int num, original, reversed = 0, digit; printf("Enter an integer: "); scanf("%d", &num); original = num; while (num != 0) { digit = num % 10; reversed = reversed * 10 + digit; num /= 10; } if (original == reversed) printf("%d is a palindrome number.\n", original); else printf("%d is not a palindrome number.\n", original); return 0; }
Dry Run
Let's trace the input 121 through the code
Input and Initialization
num = 121, original = 121, reversed = 0
First loop iteration
digit = 121 % 10 = 1; reversed = 0 * 10 + 1 = 1; num = 121 / 10 = 12
Second loop iteration
digit = 12 % 10 = 2; reversed = 1 * 10 + 2 = 12; num = 12 / 10 = 1
Third loop iteration
digit = 1 % 10 = 1; reversed = 12 * 10 + 1 = 121; num = 1 / 10 = 0
Comparison
original = 121, reversed = 121; they are equal
| num | digit | reversed |
|---|---|---|
| 121 | 1 | 1 |
| 12 | 2 | 12 |
| 1 | 1 | 121 |
Why This Works
Step 1: Extract digits
The code uses num % 10 to get the last digit of the number.
Step 2: Build reversed number
It multiplies the current reversed number by 10 and adds the extracted digit to shift digits left and append the new digit.
Step 3: Compare original and reversed
If the reversed number equals the original, the number is a palindrome.
Alternative Approaches
#include <stdio.h> #include <string.h> int main() { char str[20]; int len, i, flag = 1; printf("Enter an integer: "); scanf("%s", str); len = strlen(str); for (i = 0; i < len / 2; i++) { if (str[i] != str[len - i - 1]) { flag = 0; break; } } if (flag) printf("%s is a palindrome number.\n", str); else printf("%s is not a palindrome number.\n", str); return 0; }
#include <stdio.h> int reverse(int num, int rev) { if (num == 0) return rev; return reverse(num / 10, rev * 10 + num % 10); } int main() { int num, rev; printf("Enter an integer: "); scanf("%d", &num); rev = reverse(num, 0); if (num == rev) printf("%d is a palindrome number.\n", num); else printf("%d is not a palindrome number.\n", num); return 0; }
Complexity: O(d) time, O(1) space
Time Complexity
The program loops through each digit once, so time depends on the number of digits d, making it O(d).
Space Complexity
It uses a fixed number of variables regardless of input size, so space complexity is O(1).
Which Approach is Fastest?
The numeric reversal method is fastest and uses least memory compared to string conversion or recursion.
| Approach | Time | Space | Best For |
|---|---|---|---|
| Numeric reversal | O(d) | O(1) | Fast and memory efficient |
| String conversion | O(d) | O(d) | Simple code, uses extra memory |
| Recursive reversal | O(d) | O(d) | Elegant but uses stack space |