Palindrome is a number or sequence of characters which reads same backward and forward. If we reverse a palindrome number, the reversed and original number will be same. The first C program checks whether a number is palindrome by reversing the number. The second program does the same thing without reversing the number.
By reversing the number:
#include <stdio.h> int reverse(int n) { int r = 0; while(n) { r = r * 10 + n % 10; n = n / 10; } return r; } void main() { int num = 0; printf("Enter an integer: "); scanf("%d", &num); if(num == reverse(num)) printf("%d is palindrome\n", num); else printf("%d is not palindrome.\n", num); }
Without reversing the number
#include <stdio.h> #include <math.h> int getdigit(int num, int n) { int r, t1, t2; t1 = pow(10, n+1); r = num % t1; if (n > 0) { t2 = pow(10, n); r = r / t2; } return r; } int number_len(int n) { int len = 0; while(n) { len++; n /= 10; } return len; } void main() { int num = 0, i, len, flag = 1; printf("Enter an integer: "); scanf("%d", &num); len = number_len(num); for (i = 0; i < len/2; i++) { if(getdigit(num, i) != getdigit(num, len - i - 1)) { flag = 0; break; } } if(flag) printf("%d is palindrome.\n", num); else printf("%d is not palindrome.\n", num); }
Outout:
Enter an integer: 4232 4232 is not palindrome. Enter an integer: 65756 65756 is palindrome.
The post C Program to Check Whether a Number is Palindrome appeared first on QnA Plus.