Function Assignment 14 โ€” Check Whether a Number Is a Palindrome Using a Function
  • Twitter
  • Facebook
  • Snapchat
  • Instagram

C Program: Check Whether a Number Is a Palindrome Using a Function

๐Ÿ“‘ On this page:
  • What is a palindrome?
  • Designing the isPalindrome function
  • Complete C Program
  • Program Output
  • Step-by-Step Explanation
  • Frequently Asked Questions
๐Ÿ“š In this program, you will learn:
  • What a palindrome is โ€” as a number and as a string
  • How to reverse an integer by extracting digits with % 10 and / 10
  • How to write a predicate function that returns 1 or 0
  • How to handle negative numbers in palindrome checking
  • How this same technique generalizes to reversing strings and other sequences

What is a palindrome?

A palindrome reads the same forwards as backwards. For strings, "racecar", "madam", "level", and "noon" are all palindromes. For numbers, the same rule applies: 121, 1221, 12321, 9009, 7, and 0 are palindromes. 123, 100, and 1234 are not.

There's something satisfying about palindromes โ€” they're a kind of symmetry that feels like a puzzle. But beyond the puzzle aspect, checking whether something is a palindrome is a small exercise in a common programming pattern: reversing a sequence and comparing it to the original. That pattern shows up in many places โ€” reversing strings, reversing linked lists, comparing sequences in general. Mastering it here gives you a tool you'll use over and over.

The integer version is arguably simpler than the string version, because you don't need to worry about case, punctuation, or spaces. Just extract the digits and build the reverse. For 12321, the reverse is also 12321 โ€” they match, so it's a palindrome. For 123, the reverse is 321 โ€” they don't match, so it's not.

There's one edge case worth handling explicitly: negative numbers. -121 reversed is 121- (sort of), which isn't a valid number, and certainly doesn't equal -121. So negative numbers are not palindromes by the standard definition โ€” the minus sign breaks the symmetry. Our function handles this by returning 0 for negative inputs before doing any digit extraction.

๐Ÿ’ก In one line: save the original number, reverse it by repeatedly extracting the last digit (n % 10) and appending to the reversed value (rev = rev * 10 + digit), then compare the reversed number to the original. If they match, it's a palindrome.

A number like 12321 shown symmetrically around a vertical axis, illustrating that reading it forwards and backwards gives the same number.

Designing the isPalindrome function

Same pattern as isPrime and isEven โ€” one integer in, one integer out (1 for palindrome, 0 for not):

Part Choice Why
Function nameisPalindromeReads naturally at the call site: if (isPalindrome(n)). Same convention as isPrime, isEven, isLeapYear.
Parameterint nThe number to check. Using int covers the typical range; for larger numbers, use long or long long.
Return typeint1 for palindrome, 0 for not. The C convention for boolean-valued functions. Could also be bool with <stdbool.h>.

That gives us the prototype:

int isPalindrome(int n);
                                

And the definition:

int isPalindrome(int n) {
    if (n < 0) return 0;         /* negatives aren't palindromes */

    int original = n;
    int reversed = 0;

    while (n > 0) {
        int digit = n % 10;
        reversed = reversed * 10 + digit;
        n /= 10;
    }

    return reversed == original;
}
                                

The loop is the key. Let's trace it for n = 12321:

  1. Original = 12321, reversed = 0, n = 12321.
  2. digit = 12321 % 10 = 1. reversed = 0 ร— 10 + 1 = 1. n = 1232.
  3. digit = 1232 % 10 = 2. reversed = 1 ร— 10 + 2 = 12. n = 123.
  4. digit = 123 % 10 = 3. reversed = 12 ร— 10 + 3 = 123. n = 12.
  5. digit = 12 % 10 = 2. reversed = 123 ร— 10 + 2 = 1232. n = 1.
  6. digit = 1 % 10 = 1. reversed = 1232 ร— 10 + 1 = 12321. n = 0.
  7. Loop ends. reversed = 12321, original = 12321, they match โ†’ return 1. โœ“

The pattern is: each iteration peels off the last digit of n and pushes it onto the end of reversed. After all digits are processed, reversed is the digit-reverse of the original. Comparing it to the original (which we saved at the start, before the loop destroys it) tells us whether the number is a palindrome.

The return reversed == original; line is idiomatic C โ€” the comparison produces 1 (true) or 0 (false), which is exactly the return value we want. No need for an if statement.

๐ŸŽฏ Key idea: you must save the original n before the loop, because the loop destroys it (by dividing it down to 0). The saved copy is what you compare against the reversed result.

Complete C Program

Program: check whether an integer is a palindrome

#include <stdio.h>

/* Function prototype */
int isPalindrome(int n);

int main(void) {
    int n;

    printf("Enter an integer: ");
    scanf("%d", &n);

    if (isPalindrome(n)) {
        printf("%d is a palindrome.\n", n);
    } else {
        printf("%d is not a palindrome.\n", n);
    }

    return 0;
}

/* Palindrome check โ€” reverse the digits and compare */
int isPalindrome(int n) {
    if (n < 0) return 0;

    int original = n;
    int reversed = 0;

    while (n > 0) {
        int digit = n % 10;
        reversed = reversed * 10 + digit;
        n /= 10;
    }

    return reversed == original;
}
                                    

And a version that prints the reverse alongside the original, so you can see why the comparison succeeds or fails:

Variant: print the reversal for transparency

#include <stdio.h>

int reverseNumber(int n) {
    int reversed = 0;
    while (n > 0) {
        reversed = reversed * 10 + (n % 10);
        n /= 10;
    }
    return reversed;
}

int main(void) {
    int n;
    printf("Enter an integer: ");
    scanf("%d", &n);

    int rev = reverseNumber(n);
    printf("Original: %d\n", n);
    printf("Reversed: %d\n", rev);
    printf("%d is %s palindrome.\n",
           n, (rev == n) ? "a" : "not a");

    return 0;
}
                                    

This version is a bit more informative โ€” it shows the original and the reversed number, so you can see exactly why 12321 is a palindrome and 123 is not. For teaching purposes, this is a nice intermediate step: it exposes the mechanism of the check, rather than just reporting a boolean.

And a test harness that checks a range of numbers:

Variant: list all palindromes up to 500

#include <stdio.h>

int isPalindrome(int n) {
    if (n < 0) return 0;
    int original = n, reversed = 0;
    while (n > 0) {
        reversed = reversed * 10 + (n % 10);
        n /= 10;
    }
    return reversed == original;
}

int main(void) {
    int count = 0;
    printf("Palindromes from 0 to 500:\n");
    for (int n = 0; n <= 500; n++) {
        if (isPalindrome(n)) {
            printf("%4d ", n);
            if (++count % 15 == 0) printf("\n");
        }
    }
    printf("\nTotal: %d\n", count);
    return 0;
}
                                    

The inner if (++count % 15 == 0) breaks the output into lines of 15 numbers each, which makes a long list more readable. This is a small formatting convenience โ€” worth knowing for any time you're printing a long sequence. The %4d right-aligns each number in a 4-character field, so they line up in columns.

Program Output

A typical run with a palindrome:

Enter an integer: 12321
12321 is a palindrome.
                                

With a non-palindrome:

Enter an integer: 123
123 is not a palindrome.
                                

With a single-digit number:

Enter an integer: 7
7 is a palindrome.
                                

With a negative number:

Enter an integer: -121
-121 is not a palindrome.
                                

And the transparency variant with 12321:

Enter an integer: 12321
Original: 12321
Reversed: 12321
12321 is a palindrome.
                                

And with 1234:

Enter an integer: 1234
Original: 1234
Reversed: 4321
1234 is not a palindrome.
                                

And the range-listing variant:

Palindromes from 0 to 500:
   0    1    2    3    4    5    6    7    8    9   11   22   33   44   55
  66   77   88   99  101  111  121  131  141  151  161  171  181  191  202
 212  222  232  242  252  262  272  282  292  303  313  323  333  343  353
 363  373  383  393  404  414  424  434  444  454  464  474  484  494
Total: 60
                                

Sixty palindromes under 500 โ€” the count is correct. The pattern is clear: all single digits, all double digits where both digits match (11, 22, 33, ...), and three-digit numbers where the first and last digit match. The list makes the structure of palindrome numbers visible.

Step-by-Step Explanation

Let's walk through the function and trace what happens in memory.

1. The negative check

if (n < 0) return 0; โ€” the minus sign is not a digit, so it breaks the palindrome property. -121 reads as "121-" when reversed, which doesn't equal "-121". More importantly, the arithmetic doesn't work: -121 % 10 is -1 in C (since modulo preserves the sign of the dividend), so the digit extraction would produce a nonsensical result. The early return avoids all that.

2. Saving the original

int original = n; โ€” we're about to destroy n by dividing it down to 0, so we save a copy. Without this, we'd have nothing to compare the reversed value against. This is a common pattern: whenever you're going to modify a value, save the original if you'll need it later.

3. The reversed accumulator

int reversed = 0; โ€” starts at 0 and accumulates digits. Each iteration multiplies by 10 (shifting existing digits left) and adds the new digit (which lands in the units place). This is the standard "reverse a number" idiom in C.

4. The digit extraction loop

int digit = n % 10; gets the last digit. reversed = reversed * 10 + digit; appends it to the reversed number. n /= 10; drops the last digit from n. The loop continues while n > 0, so it runs once per digit. For 12321 (5 digits), the loop runs 5 times.

5. Tracing isPalindrome(1234)

  1. original = 1234, reversed = 0, n = 1234.
  2. digit = 4, reversed = 4, n = 123.
  3. digit = 3, reversed = 43, n = 12.
  4. digit = 2, reversed = 432, n = 1.
  5. digit = 1, reversed = 4321, n = 0.
  6. Loop ends. reversed = 4321, original = 1234. 4321 โ‰  1234 โ†’ return 0. โœ“

6. Tracing isPalindrome(0)

original = 0, reversed = 0, n = 0. The loop condition n > 0 is immediately false, so the loop doesn't run. reversed = 0, original = 0, they match โ†’ return 1. Is 0 a palindrome? By the standard definition, yes โ€” "0" reads the same forwards and backwards. Some implementations might argue it shouldn't count, but the answer of 1 is at least consistent with the definition.

7. What about numbers with trailing zeros?

Consider 100. The reverse is 001, which as an integer is 1. Since 1 โ‰  100, the function correctly returns 0. The leading zeros of the reversed representation are lost, but that doesn't affect the comparison โ€” 100 and 1 are different numbers, so it's not a palindrome. Consider 1001: reversed is 1001, so it IS a palindrome. The zeros are preserved because they're in the middle, not at the end. Only trailing zeros are lost, and any number ending in 0 (except 0 itself) can't be a palindrome, since its leading digit would have to be 0.

8. Complexity

The loop runs once per digit of n. For a 32-bit int, that's at most 10 iterations (since INT_MAX โ‰ˆ 2.1 billion, which has 10 digits). For a long long, at most 19. So the function runs in O(log n) time โ€” very fast. For comparison, checking whether a string is a palindrome also runs in O(n) time (where n is the length), which is equivalent since there are O(log n) digits in a number.

9. The comparison reversed == original

This is the final check. The result of == is either 1 (if they're equal) or 0 (if not). Returning that directly is exactly what we want for a int isPalindrome function. It's a clean way to express "the answer is whether the two things match." No if, no ternary โ€” just the comparison itself as the return value.

10. Palindromes and strings

The same technique works for strings. To check if a string is a palindrome, you'd compare the first character to the last, the second to the second-to-last, etc. A cleaner version uses two pointers moving inward. The integer version we've written here uses digit extraction instead of character access, but the underlying idea is the same: reverse and compare. Once you've internalized the integer version, the string version is a small adjustment.

๐Ÿ” Try this: run the transparency variant with 12321, then 1234, then 100. For each, observe the reversed value and how the comparison plays out. Then run the range-listing variant and find the palindromes under 1000 โ€” there should be 99 total (9 single-digit, 9 two-digit, 90 three-digit, plus 0 = 99? Actually 0 to 999 gives 108: 10 single-digit including 0, 9 two-digit, 90 three-digit, minus overlap โ€” count it yourself). Verifying the exact count is a good exercise.

Frequently Asked Questions

1. Are negative numbers palindromes?

No, by the standard definition. -121 reversed is 121-, which is not the same as -121. The minus sign breaks the symmetry. Our function returns 0 for negative inputs. Some non-standard definitions might say -121 is a palindrome "ignoring the sign," but that's a variant, not the standard. If you want to support that variant, take abs(n) at the start and then check the absolute value.

2. What's the maximum number this can handle?

With int, it's about 2.1 billion (INT_MAX). For larger numbers, use long (about 9.2 ร— 10ยนโธ on 64-bit systems) or long long. The reversal itself can overflow โ€” reversing 1,000,000,009 gives 9,000,000,001, which exceeds INT_MAX. If you need to handle such numbers, use a larger type or compare digits from both ends (rather than reversing the whole number), which avoids the overflow entirely.

3. Is 0 a palindrome?

By the standard definition, yes. "0" reads the same forwards and backwards. Our function returns 1 for 0. If you want to exclude 0 (some problem statements do), add if (n == 0) return 0; or if (n <= 0) return 0; at the top. The definition is a matter of convention โ€” pick whichever your problem statement specifies.

4. How is this different from checking a string palindrome?

Conceptually the same โ€” reverse and compare. But the mechanics differ. For a string, you'd compare characters using array indexing (or pointer arithmetic). For an integer, you use % 10 and / 10 to extract digits. The string version is more flexible (it can handle letters, punctuation, spaces, mixed case) but requires more care around what to compare (should "A man, a plan, a canal: Panama" count as a palindrome? The classic answer is yes, after stripping non-letters and lowercasing). The integer version is simpler because there's no ambiguity about what a "digit" is.

5. Can I check palindromes without reversing?

Yes โ€” by comparing digits from the outside in. You'd extract the first and last digits, compare them, then strip both and repeat. In practice, this requires knowing the number of digits (to compute powers of 10), so it's more code than the reversal approach. The reversal approach is simpler and standard. For strings, the "two pointers from outside in" approach is standard and efficient โ€” but for numbers, reversal is easier.

6. How many palindromes are there under 1000?

There are 108 palindromes from 0 to 999 inclusive. Let's count: single digits (0โ€“9): 10 numbers. Two-digit: 11, 22, 33, ..., 99 โ€” 9 numbers. Three-digit: first and last digit match, middle is any digit. First digit is 1โ€“9 (9 choices), middle is 0โ€“9 (10 choices), last is determined by first โ€” so 9 ร— 10 = 90 numbers. Total: 10 + 9 + 90 = 109. Wait โ€” but 0 is counted as a single digit, and that might not count as a "positive" number. Excluding 0: 108. The exact count depends on whether you include 0. Either way, the enumeration is a good sanity check for the function.

๐Ÿ’ก Tip: Once this works, try the string version โ€” write isStringPalindrome(const char *s) that checks whether a string reads the same forwards and backwards. The mechanics differ (character access vs. digit extraction), but the underlying idea is the same. Then try a version that ignores case and punctuation. That's the version that handles "A man, a plan, a canal: Panama" โ€” the famous palindrome sentence attributed to Leigh Mercer.

๐Ÿ“– Related Tutorials

  • Introduction to Functions in C
  • Recursion in C
  • Function Definition
  • Function Declaration
  • Types of Functions
  • Previous: Generate a Multiplication Table Using a Function
  • Next: Reverse a String Using a Function
  • All 33 Function Assignments

Previous Topic: -->> 13. Generate a Multiplication Table Using a Function   ||   Next Topic: -->> 15. Reverse a String Using a Function


C Language

  • Home
  • Why C Language
  • History of C Language
  • Applications of C Language
  • Introduction To C
    • What is Program?
    • Structure of C Program
    • Working Of C Program
    • CHARACTER SET
    • VARIABLES AND IDENTIFIERS
    • BUILT-IN DATA TYPES
    • OPERATORS AND EXPRESSIONS
    • CONSTANTS AND LITERALS
    • SIMPLE ASSIGNMENT STATEMENT
    • BASIC INPUT/OUTPUT STATEMENT
    • SIMPLE 'C' PROGRAMS
    • Assignments
  • Operators in C Programming
    • Arithmetic Operators
    • Assignment Operators
    • Increment and Decrement Operators
    • Relational Operators
    • Logical Operators
    • Bitwise Operators
    • Other Operators
    • Assignments
  • CONDITIONAL STATEMENTS
    • DECISION MAKING WITHIN A PROGRAM
    • CONDITIONS
    • IF STATEMENT
    • IF-ELSE STATEMENT
    • IF-ELSE LADDER
    • NESTED IF-ELSE
    • SWITCH CASE
    • Assignments
  • LOOPS STATEMENTS
    • Introduction to Loops
    • GO TO Statement
    • Do while Loop
    • While Loop
    • Nested While Loop
    • Difference Between While and Do while
    • Difference Between Goto and loop
    • while loop assignments
    • C FOR Loop
    • C For loop examples
    • Nested for loop
    • Nested for loop examples
    • Infinite while Loops
    • Infinite for Loops
    • Continue in Loops
    • break in Loops
    • difference while do..while & for
    • Assignments
  • Arrays
    • One Dimensional Array
    • Declaring 1D Arrays
    • Initilization of 1D arrays
    • Accessing element of one 1D Array
    • Read and Display 1D Arrays
    • Two Dimensional Arrays
    • Declare 2D Arrays
    • Read and Display 2D Arrays
    • Assignments/Examples
  • Functions
    • Introduction
    • Need For User-Defined Function
    • Multiple Function Program
    • Modular Programming
    • Elements Of User Defined Function
    • Function Definition
    • Function Declaration
    • Types of functions
    • Nesting of Function
    • Recursion
    • Passing Array To Functions
    • Scope,Visibility and Lifetime of Variables
    • Assignments
  • Structure
    • Introduction
    • Array vs Structure
    • Defining Structure
    • Declaring Structure Variables
    • Type Defined Structure
    • Accessing Structure Members
    • Structure Initilization
    • Copying & Comparing Structure Variables
    • Array of Structure
    • Arrays Within Structure
    • Structures Within Structures
    • Structures and Functions
    • Structure Examples/Assignments
  • Union
    • Define Union
    • Create and use Union
    • Difference Between Structure and Union
    • Union Examples
    • Union FAQ
  • Pointers
    • What Are Pointers In C?
    • How Do We Use Pointers In C?
    • Declaration Of A Pointer
    • The Initialization Of A Pointer
    • Syntax Of Pointer Initialization
    • Use Of Pointers In C
    • The Pointer To An Array
    • The Pointer To A Function
    • The Pointer To A Structure
    • Types Of Pointers
    • The Null Pointer
    • The Void Pointer
    • The Wild Pointer
    • The Near Pointer
    • The Huge Pointer
    • The far Pointer
    • dangling pointer
    • Accessing Pointers- Indirectly And Directly
    • Pros Of Using Pointers In C
    • Cons Of Pointers In C
    • Applications Of Pointers In C
    • The & Address Of Operator In C
    • How To Read The Complex Pointers In C?
    • Practice Problems On Pointers
  • File Processiong
    • File Handling In C
    • Types Of Files In C
    • Operations Done In File Handling
    • File Examples
    • Binary Files
    • count words,lines in a file
    • Copy files
    • Update File
    • count vowels in a file
  • Preprocessor
    • Macro substitution division
    • File Inclusion
    • Conditional Compilation
    • Other directives
    • Examples
  • Dynamic Memory Allocation
    • malloc
    • calloc
    • free
    • realloc
    • Examples
  • Storage Classes
  • Graphics
  • Frequently Asked Interview Questions (FAQ)
    • Introduction To C FAQ
    • Operators FAQ
    • Conditional Statements FAQ
    • Loops FAQ
    • Arrays FAQ
    • Function FAQ
    • Structure FAQ
    • Pointers FAQ
    • Files FAQ
    • Storage classes FAQ
    • Dynamic Memory FAQ
  • Programs/Assignments
    • Introduction To C
    • Operators
    • Conditional Statements
    • Loops
    • Arrays
    • Function
    • Structure
    • Pointers
    • Files
    • Storage classes
    • Dynamic Memory
  • Case Studies
  • Multiple Choice Questions
    • Introduction To C MCQ
    • Operators MCQ
    • Conditional Statements MCQ
    • Loops MCQ
    • Arrays MCQ
    • Function MCQ
    • Structure MCQ
    • Pointers MCQ
    • Files MCQ
    • Storage classes MCQ
    • Dynamic Memory MCQ
    • More MCQ

Get in touch

  • tech2dsm@gmail.com

© Sankalan Data Tech. All rights reserved.