Pointer Assignment 28 — Check if a Number is Palindrome Using Pointers
  • Twitter
  • Facebook
  • Snapchat
  • Instagram

C Program: Check if a Number is Palindrome Using Pointers — Digit Reversal Through a Function

📑 On this page:
  • How Pointer-Based Palindrome Check Works
  • The Three Steps of the Check
  • Complete C Program
  • Program Output
  • Step-by-Step Explanation
  • Frequently Asked Questions
📚 In this program, you will learn:
  • How to pass a number to a function by pointer (int *)
  • How to reverse the digits of an integer using only arithmetic and a pointer
  • Why the function makes a local copy and never modifies the caller's variable
  • How to handle negative numbers, zero, and single-digit edge cases
  • Why this differs from palindrome checking on a string

How Pointer-Based Palindrome Check Works

A number is a palindrome if it reads the same forwards and backwards — like 12321, 45654, or 7. Checking a number is different from checking a string: you can't walk a pointer character by character, because the "digits" are not stored as separate characters in memory. Instead, you extract digits one at a time using % 10 and / 10, and rebuild the reversed number arithmetically. Then you compare the reversed number with the original.

Where do pointers come in? The assignment specifically asks for a function that takes the number by pointer. This is partly an exercise in writing clean function interfaces: the caller passes &num, the function receives int *, and it reads *num to get the value. It never modifies *num — the pointer is used for access, not for output. That makes the function self-contained and easy to test: it takes a pointer to an int and returns an int (1 or 0), with no side effects on the caller's data.

The reversal is done on a local copy, not on the caller's variable. If the function worked directly on *num, it would destroy the original value while reversing it — and then there would be nothing left to compare against. So the function first copies *num into original, then reverses a second copy, n, and compares rev with original. The caller's variable is completely untouched.

💡 In one line: Extract each digit with % 10, append it to a reversed number with rev = rev * 10 + digit, drop the digit with / 10, then compare rev with the original.

Diagram showing a number's digits being extracted and appended in reverse order to build the reversed number, then compared with the original

The Three Steps of the Check

Step Pointer / arithmetic operation Effect
1. Copy the originalint original = *num; int n = original;A working copy to reverse, and a preserved original to compare with
2. Reverse the digitswhile (n > 0) { int d = n % 10; rev = rev * 10 + d; n /= 10; }rev holds the digits of original in reverse order
3. Comparereturn rev == original;1 if palindrome, 0 otherwise

The reversal step is the core. On each iteration, n % 10 peels off the last digit, and rev = rev * 10 + digit appends it to the right end of rev. Because the digits are extracted from right to left, appending them to the right of rev effectively reverses their order. After the loop, rev has exactly the same digits as original, in the opposite order.

The comparison rev == original is the whole test. If the reversed number equals the original, the digits read the same both ways, and the number is a palindrome. Note that comparing integers is O(1), whereas comparing strings would require walking pointers — this is the key simplification that number-based palindrome checking offers over string-based checking.

Complete C Program

Program: check if a number is palindrome using a pointer-based function

#include <stdio.h>
#include <limits.h>

/* Reverse the digits of a non-negative integer. */
static int reverse_digits(int n) {
    int rev = 0;
    while (n > 0) {
        int digit = n % 10;
        rev = rev * 10 + digit;
        n /= 10;
    }
    return rev;
}

/* Return 1 if *num is a palindrome, 0 otherwise.
   The function never modifies *num. */
int is_palindrome_number(const int *num) {
    if (num == NULL) {
        return 0;
    }

    int original = *num;

    /* Negative numbers are not palindromes in the usual sense. */
    if (original < 0) {
        return 0;
    }

    /* 0 through 9 are single-digit palindromes. */
    if (original < 10) {
        return 1;
    }

    int rev = reverse_digits(original);
    return rev == original;
}

int main(void) {
    int values[] = {121, 12321, 12345, 7, 1001, 1231, 0, -121, 45654};
    int n = (int)(sizeof(values) / sizeof(values[0]));

    printf("Palindrome check results:\n");
    printf("-------------------------\n");
    for (int i = 0; i < n; i++) {
        printf("  %-8d -> %s\n",
               values[i],
               is_palindrome_number(&values[i]) ? "palindrome" : "not a palindrome");
    }

    /* Interactive check */
    int input;
    printf("\nEnter a number to check: ");
    if (scanf("%d", &input) == 1) {
        printf("  %d -> %s\n",
               input,
               is_palindrome_number(&input) ? "palindrome" : "not a palindrome");
    }

    return 0;
}
                                    

Program Output

Palindrome check results:
-------------------------
  121      -> palindrome
  12321    -> palindrome
  12345    -> not a palindrome
  7        -> palindrome
  1001     -> palindrome
  1231     -> not a palindrome
  0        -> palindrome
  -121     -> not a palindrome
  45654    -> palindrome

Enter a number to check: 1234321
  1234321 -> palindrome
                                

The output covers a wide range of cases: simple palindromes (121, 12321), non-palindromes (12345, 1231), single-digit numbers (7), zero (which is a palindrome), negative numbers (-121 is not considered a palindrome in the usual definition), and even-length palindromes (1001). The interactive check with 1234321 shows the function works for longer numbers without any change.

Step-by-Step Explanation

Let's walk through the logic carefully.

1. The function signature

int is_palindrome_number(const int *num) takes a pointer to a const int. The const is a promise that the function will not modify the caller's variable through the pointer. This is correct and intentional: the function only reads *num, copies its value into a local variable, and never writes back. The pointer is there to satisfy the assignment's requirement of passing the number by pointer — not because the function needs to modify the caller's value.

2. The null guard

if (num == NULL) return 0; is a defensive check. If a caller passes NULL by mistake, dereferencing it would be undefined behaviour (usually a crash). Returning 0 (not a palindrome) is a safe, deterministic response. In production code, you might instead assert or return an error code, but for a simple teaching example, returning 0 is fine and it avoids the crash.

3. Copy the original value

int original = *num; dereferences the pointer to get the integer value and stores it in a local variable. This is the value the caller passed in — the one we need to check and to compare against at the end. Since we're about to destroy a working copy, we need to keep this original safe.

4. Handle negative numbers

By convention, negative numbers are not palindromes. -121 has a minus sign on the left but nothing on the right, so it doesn't read the same forwards and backwards. Returning 0 for original < 0 is the standard behaviour. Some programs handle negative palindromes by comparing absolute values, but that's unusual and arguably a different problem. The simplest and most widely expected answer is that negative numbers are never palindromes.

5. Handle single-digit numbers

Any single digit — 0 through 9 — is trivially a palindrome: it has exactly one digit, so it reads the same both ways. The guard if (original < 10) return 1; handles this case. Note that this includes 0, which is conventionally a palindrome. Without the guard, the reversal logic would still work for single digits, but the guard makes the intent explicit and short-circuits the reversal for a common, trivial case.

6. The reverse_digits helper

reverse_digits(int n) is a small, focused function that takes a non-negative integer and returns its digits in reverse order. It uses three steps per iteration: digit = n % 10 to peel off the last digit, rev = rev * 10 + digit to append it to rev, and n /= 10 to drop the digit. When n reaches 0, every digit has been processed. The function is used elsewhere in the chapter (e.g., "reverse a number using pointers"), so factoring it out here avoids duplication.

7. Tracing 12321

Start: n = 12321, rev = 0.

  • Iteration 1: digit = 1, rev = 0·10 + 1 = 1, n = 1232.
  • Iteration 2: digit = 2, rev = 1·10 + 2 = 12, n = 123.
  • Iteration 3: digit = 3, rev = 12·10 + 3 = 123, n = 12.
  • Iteration 4: digit = 2, rev = 123·10 + 2 = 1232, n = 1.
  • Iteration 5: digit = 1, rev = 1232·10 + 1 = 12321, n = 0. Loop exits.

rev = 12321, which equals the original. Return 1 — palindrome.

8. Tracing 12345

The same loop produces rev = 54321, which does not equal 12345. Return 0 — not a palindrome. The reversal was done fully; there was no early exit. This is different from the string-based check, which can bail out on the first mismatched pair. For numbers, you have to build the full reversed value before comparing, because you can't peek at the "last digit" of the reversed number until it's built.

9. Why the function doesn't modify *num

The parameter is const int *num, and the function only reads through it: int original = *num;. There's no *num = ... anywhere. This is important for two reasons. First, it allows the caller to pass a const value (including a literal in some contexts), because the function never writes through the pointer. Second, it preserves the caller's variable — a caller who calls is_palindrome_number(&x) can be confident that x is the same after the call as before it. Side-effect-free functions are easier to test and reason about.

10. Pointer version vs direct value version

Here is the same logic without a pointer parameter:

int is_palindrome_value(int n) {
    if (n < 0) return 0;
    if (n < 10) return 1;
    return reverse_digits(n) == n;
}
                                

Both versions work and produce the same results. The pointer version is required by the assignment, but it doesn't actually need the pointer for anything — the function reads the value once and works entirely on locals. This is a common pattern in C exercises: pass by pointer to satisfy a requirement or to be consistent with other functions in the same chapter, even when a value parameter would suffice. It's harmless, and it reinforces the habit of thinking about whether to pass by value or by pointer.

11. Why number-palindrome checking differs from string-palindrome checking

A string palindrome check compares mirror characters directly: s[i] against s[n-1-i]. That works because characters are stored individually and can be indexed. For a number, the digits are not stored as separate elements in memory — the number is a single int, and the digits are an interpretation. So you can't "walk" the digits with a pointer; you have to extract them arithmetically. This is why the number version is fundamentally different from the string version, even though both check the same abstract property ("reads the same forwards and backwards").

12. Complexity

The time complexity is O(d), where d is the number of digits in the number. For a 32-bit int, d is at most 10, so the loop runs at most 10 times — effectively O(1) in practice. Space is O(1) — just a few local integer variables. This is essentially optimal: you have to examine every digit at least once to be sure the number is a palindrome, and O(d) time with O(1) space is the best possible.

🎯 Remember this: Reverse the digits with rev = rev * 10 + n % 10 and n /= 10, then compare rev with the original. Preserve the original in a local copy, handle negatives and single digits explicitly, and pass the number by const int * so the function can read it but never modify the caller's variable.

Frequently Asked Questions

1. Why does the function take a pointer if it doesn't modify the number?

The assignment explicitly asks for a pointer-based solution, so passing const int * satisfies that requirement. Beyond the requirement, passing a pointer makes the intent clear: the caller sees &num at the call site, and the function sees const int *, which is a common C idiom for "this function reads an int but doesn't own or modify it." For this particular problem, passing int by value would be simpler and equally correct — but both work, and the pointer version is the one assigned.

2. Why is 0 considered a palindrome?

By convention, single-digit numbers are palindromes because they have only one digit and therefore read the same in both directions. 0 fits this definition: the string "0" reversed is "0". The program handles this explicitly with if (original < 10) return 1;, which covers 0 through 9. Some sources debate whether 0 should be considered a palindrome, but the standard mathematical convention is that it is — it's a single-digit string that reads the same way forwards and backwards.

3. Why are negative numbers not considered palindromes?

A negative number like -121 has a minus sign on the left but not on the right, so it doesn't read the same forwards and backwards. This is the standard convention in mathematics and programming. You could argue that the digits 1, 2, 1 form a palindrome and the sign is just a prefix, but most definitions and most interview questions treat negative numbers as not palindromes. The function implements this convention with if (original < 0) return 0;. If you wanted to treat negatives as palindromes based on their digit sequence, you'd compare reverse_digits(-n) == -n or compare reverse_digits(abs(n)) == abs(n).

4. Why doesn't the loop exit early on a mismatch, like the string version does?

Because a number's digits aren't individually addressable. For a string, you can compare s[0] with s[n-1] and exit on the first mismatch. For a number, you have to build the entire reversed value before you can compare it with the original — the digit that would "correspond" to s[0] is the last digit of rev, and rev isn't complete until the loop finishes. So the number version always does the full O(d) work, even for numbers that fail the check on the first digit. This is not a bug — it's a consequence of how integers are stored.

5. What happens on integer overflow during reversal?

If the reversed number exceeds INT_MAX (or the type of rev), signed overflow is undefined behaviour in C. For example, reversing 1000000009 produces 9000000001, which exceeds a 32-bit int. The safest fix is to declare rev as long long so it can hold the reversed value for any 32-bit input. A more robust check is to detect overflow before it happens: if rev > (INT_MAX - digit) / 10, the reversal would overflow. For the inputs in this program (all well within int range and small), overflow doesn't occur, but production code should be careful.

6. What is the time and space complexity?

Time is O(d), where d is the number of digits. For a 32-bit int, d is at most 10, so it's effectively constant time. Space is O(1) — a few local variables. This is optimal: you can't determine palindromicity without examining all the digits in the worst case, and you don't need any extra storage. The function is a standard example of an arithmetic algorithm with linear-in-digits complexity and constant extra space.

💡 Tip: Once this works, try the follow-up: "Find the next palindrome greater than a given number." You'll use the same reversal logic, but wrap it in a loop that increments the candidate and checks each one. Or try the "palindrome number without converting to string" variant, which is exactly what this program does — a common interview question precisely because it tests whether you can manipulate digits arithmetically.

📖 Related Tutorials

  • 27. Reverse a Number Using Pointers
  • 26. Sum of Digits Using Pointers
  • 29. Factorial Using Pointers
  • 30. Swap Two Strings Using Pointers
  • 19. Reverse a String Using Pointers
  • All 30 Pointer Assignments

Previous Topic: -->> 27. Reverse a Number Using Pointers   ||   Next Topic: -->> 29. Factorial Using Pointers


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.