C Program to check given number is PALINDROME or NOT
Objective
Write a C program to check if a given number is a Palindrome.
Algorithm / Approach
- Read an integer
nand store a copy of it intemp. - Initialize
rev = 0. - Use a
while(temp != 0)loop to reverse the number. - Extract the last digit:
temp % 10. - Append it to the reverse variable:
rev = (rev * 10) + (temp % 10). - Remove the last digit:
temp = temp / 10. - After the loop, if
rev == n, it is a Palindrome.
main.c
#include<stdio.h>
int main( ) {
int n, rev = 0, temp;
printf("Enter Value for N : ");
scanf("%d", &n);
temp = n;
while(temp!=0) {
rev = rev*10 + temp%10;
temp = temp/10;
}
if(rev == n) {
printf("N is PALINDROME\n");
}
else {
printf("N is NOT PALINDROME\n");
}
printf("\n");
return 0;
}
Expected Output
Enter Value for N: 1221 N is PALINDROME
Explanation of the Program
- A Palindrome number reads the same forwards and backwards (e.g., 1221, 12321).
- To reverse a number mathematically, we extract its last digit using Modulo (
% 10). We then push that digit onto our reversed number by multiplying the current reversed number by 10 (shifting it to the left) and adding the extracted digit.
Complexity
Time Complexity
O(log₁₀ n) - Proportional to the number of digits.
Space Complexity
O(1)