Last active
December 18, 2025 15:25
-
-
Save neps-in/19fb0c91f045794eaee0dea2a461650d to your computer and use it in GitHub Desktop.
Check if a given integer is palindrome or not in C
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| /** | |
| * @file palindrome.c | |
| * @brief Palindrome number checker using arithmetic digit reversal. | |
| * | |
| * This program checks whether a given integer is a palindrome. | |
| * A palindrome number reads the same forwards and backwards | |
| * (e.g., 121, 1331, 7). | |
| * | |
| * @details | |
| * The algorithm reverses the digits of the input number using | |
| * modulus and division operations, then compares the reversed | |
| * value with the original number. | |
| * | |
| * Negative numbers are not considered palindromes. | |
| * | |
| * @input Integer value from standard input | |
| * @output Indicates whether the number is a palindrome | |
| * | |
| * @complexity | |
| * Time Complexity : O(d), where d is the number of digits | |
| * Space Complexity : O(1) | |
| * | |
| * @author Napoleon Arouldas S. | |
| * @website https://neps.in | |
| * @linkedin https://www.linkedin.com/in/meetneps | |
| * | |
| * @date 13-07-2000 | |
| */ | |
| #include <stdio.h> | |
| #include <stdbool.h> | |
| bool isPalindrome(int n) | |
| { | |
| if (n < 0) { | |
| return false; // Negative numbers are not palindromes | |
| } | |
| // Preserve the n because, n becomes zero inside the loop. | |
| int original = n; | |
| // initialise the reversed number to zero. otherwise it | |
| // can contain random , unpredictable number | |
| int reversed = 0; | |
| // Lets test with n = 127 | |
| while (n > 0) { | |
| n = n % 10; // Extract last digit of n, 7 | |
| // in the first pass reversed = 0 + lastnumber reversed = 0 * 10 + 7 is 7 | |
| reversed = reversed * 10 + n; | |
| n = n / 10; // end of the first pass n = 12 | |
| } | |
| return original == reversed; | |
| } | |
| int main(void) | |
| { | |
| int number; | |
| printf("Enter a number: "); | |
| scanf("%d", &number); | |
| if (isPalindrome(number)) { | |
| printf("%d is a palindrome\n", number); | |
| } else { | |
| printf("%d is not a palindrome\n", number); | |
| } | |
| return 0; | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment