Pointer Assignment 26 — Sum of Digits of a Number Using Pointers
  • Twitter
  • Facebook
  • Snapchat
  • Instagram

C Program: Sum of Digits of a Number Using Pointers — Accumulating Digits Through a Read-Only Pointer

📑 On this page:
  • How Pointer-Based Digit Sum Works
  • The Three Steps of the Sum
  • 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 const int * so it's read-only
  • How to extract digits arithmetically with % 10 and / 10
  • Why the function makes a local copy and never touches the caller's variable
  • How to handle negative numbers, zero, and very large inputs safely
  • How the digit-extraction pattern is reused across reversal, palindrome, and digit-sum problems

How Pointer-Based Digit Sum Works

The sum of digits of a number is the total you get by adding all its digits. For 12345, that's 1 + 2 + 3 + 4 + 5 = 15. For 9009, that's 9 + 0 + 0 + 9 = 18. Because a number's digits aren't stored as separate memory cells — they're an interpretation of a single integer value — you have to extract them one at a time using arithmetic. n % 10 gives the last digit, and n / 10 drops it, so a loop that does both peels off the digits from right to left.

The pointer part of the assignment is about the function's interface. The function takes const int *num, reads the value through *num, and never writes back. Unlike the reversal problem, digit-summing doesn't need to modify the caller's variable — the result is a new value (the sum), which the function returns normally. So the pointer is const, which is a promise that the function will not modify the caller's data. This is the "read-only access" pattern, and it's the safest way to pass a value to a function that needs to inspect it but not change it.

Why use a pointer at all for this problem? The assignment asks for it, and there's a genuine benefit: passing by const int * documents at the call site (&num) that the function will read the number. It also matches the pattern used by many C library functions that take pointers to inputs they won't modify (e.g., const char * string parameters). The caller sees &num and knows the value is being handed off for inspection — and the const guarantees it won't be changed.

💡 In one line: Peel off each digit with n % 10, add it to a running sum, drop it with n /= 10, and repeat until n is 0 — then return the sum.

Diagram showing digits being extracted from a number one at a time and accumulated into a running sum, with the input provided to the function as a const pointer

The Three Steps of the Sum

Step Pointer / arithmetic operation Effect
1. Read and copylong n = *num; long sum = 0;A working copy of the value, plus a zeroed accumulator
2. Extract and addwhile (n > 0) { sum += n % 10; n /= 10; }Every digit is added to sum exactly once
3. Returnreturn sum;The total of the digits, as a non-negative value

The accumulation is the whole algorithm. Each iteration does two things: sum += n % 10 adds the current last digit, and n /= 10 shifts the number right by one decimal place so the next iteration sees a new last digit. When n reaches 0, there are no digits left to add, and sum holds the total. The loop runs exactly d times, where d is the number of digits — for a 32-bit int, at most 10.

Notice that this is the same digit-extraction loop used for reversing a number and for checking palindrome numbers. The only difference is what happens with each extracted digit: reversal appends it to a new number, palindrome-check compares the final result with the original, and digit-sum adds it to an accumulator. Learning this one pattern once unlocks all three problems.

Complete C Program

Program: sum of digits of a number using a pointer-based function

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

/* Return the sum of the digits of *num.
   The number is read through the pointer but never modified. */
long sum_of_digits(const int *num) {
    if (num == NULL) {
        return 0;
    }

    /* Work on a copy; negatives are summed by their absolute value. */
    long n = *num;
    if (n < 0) {
        n = -n;
    }

    long sum = 0;
    while (n > 0) {
        sum += n % 10;    /* add the last digit */
        n /= 10;          /* drop the last digit */
    }
    return sum;
}

int main(void) {
    int values[] = {12345, 0, 7, 9009, 100, -456, 2147483647};
    int n = (int)(sizeof(values) / sizeof(values[0]));

    printf("Sum of digits results:\n");
    printf("----------------------\n");
    for (int i = 0; i < n; i++) {
        printf("  %-12d -> %ld\n", values[i], sum_of_digits(&values[i]));
    }

    /* Interactive check */
    int input;
    printf("\nEnter a number: ");
    if (scanf("%d", &input) == 1) {
        printf("  sum of digits of %d = %ld\n", input, sum_of_digits(&input));
    }

    return 0;
}
                                    

Program Output

Sum of digits results:
----------------------
  12345        -> 15
  0            -> 0
  7            -> 7
  9009         -> 18
  100          -> 1
  -456         -> 15
  2147483647   -> 46

Enter a number: 987654
  sum of digits of 987654 = 39
                                

The output covers a range of cases: a normal multi-digit number (12345 → 15), zero (0 → 0), a single digit (7 → 7), a number with internal zeros (9009 → 18), a number with trailing zeros (100 → 1), a negative number (-456 → 15, because the sum uses the absolute value), and a large number near INT_MAX (2147483647 → 46). The interactive run with 987654 confirms the sum on a longer input: 9+8+7+6+5+4 = 39.

Step-by-Step Explanation

Let's walk through the pointer mechanics and the arithmetic.

1. The function signature

long sum_of_digits(const int *num) takes a pointer to a const int. The const is essential here: it signals that the function treats the input as read-only. Without it, callers would be unable to pass addresses of const variables, and the function's intent would be unclear. The return type is long rather than int so the sum can't overflow for 32-bit inputs: the maximum sum for a 10-digit number is 9·10 = 90, which fits easily in long — but using long is future-proof and makes the intent ("a possibly large accumulated total") explicit.

2. The null guard

if (num == NULL) return 0; prevents dereferencing a null pointer. Dereferencing NULL is undefined behaviour (usually a crash), so this guard makes the function robust against a mistaken caller. Returning 0 is a reasonable "no input → no sum" choice, though in production code you might return an error flag or use an out-parameter to indicate the failure. For this exercise, returning 0 is fine and it keeps the function total (defined for every input).

3. Working on a copy

long n = *num; reads the caller's value through the pointer into a local long. There are two reasons for using long instead of int here: (a) it avoids the edge case where INT_MIN can't be negated as an int (which is what the next line does for negatives), and (b) it leaves room for the accumulator to grow if the input range is expanded. The caller's variable is untouched: no *num = ... anywhere.

4. Handling negatives

if (n < 0) n = -n; takes the absolute value for negative inputs. The mathematical convention for "sum of digits" is usually the sum of the digits of the number's magnitude, ignoring the sign — the digits of -456 are 4, 5, 6, summing to 15. Working with the absolute value implements this. Doing the negation on a long rather than an int matters for INT_MIN: negating -2147483648 as an int is undefined behaviour (because 2147483648 exceeds INT_MAX), but negating it as a long (where it fits) is fine.

5. The extraction loop

while (n > 0) runs until n has no digits left. Each iteration does two things: sum += n % 10 extracts the current last digit and adds it to the accumulator, and n /= 10 removes that digit so the next iteration sees a new one. When n reaches 0, no digits remain and sum is complete.

6. Tracing 12345

Start: n = 12345, sum = 0.

  • Iteration 1: digit = 5, sum = 0 + 5 = 5, n = 1234.
  • Iteration 2: digit = 4, sum = 5 + 4 = 9, n = 123.
  • Iteration 3: digit = 3, sum = 9 + 3 = 12, n = 12.
  • Iteration 4: digit = 2, sum = 12 + 2 = 14, n = 1.
  • Iteration 5: digit = 1, sum = 14 + 1 = 15, n = 0. Loop exits.

Return 15. The digits were added in reverse order (5, 4, 3, 2, 1) — but addition is commutative, so the total is the same.

7. Tracing 9009

n = 9009: digit = 9, sum = 9, n = 900. Digit = 0, sum = 9, n = 90. Digit = 0, sum = 9, n = 9. Digit = 9, sum = 18, n = 0. Return 18. The internal zeros contribute 0 to the sum, which is correct — they're still digits, they just don't increase the total. This is a useful case to check, because it confirms the loop correctly handles zeros in the middle of the number.

8. Tracing 0

n = 0: the loop while (n > 0) doesn't run at all, and sum stays 0. Return 0. This is correct — the sum of the digits of 0 is 0. Some naive implementations special-case 0, but here the general logic handles it correctly. The while loop's condition is the key: it works for the empty case, not just the non-empty one.

9. Tracing -456

n = -456. The sign check makes n = 456. Then the loop produces 6 + 5 + 4 = 15. Return 15. The caller's variable -456 is unchanged (it was copied, not aliased through the pointer). This is exactly the behaviour you'd want: summing digits is a value operation, not a mutation, and it reports the same result for 456 and -456.

10. Why the pointer is const

The function reads *num exactly once, at the top, and never writes back. Marking the parameter as const int * documents this: the function promises not to modify the caller's data. This matters for two reasons. First, it lets callers pass addresses of const variables (and literals in some contexts) without a compiler warning. Second, it's a stronger contract than just "I won't write" — the compiler enforces it, catching any accidental assignment inside the function. Read-only functions are easier to test, easier to reason about, and safer to call from concurrent contexts.

11. Pointer version vs value version

Here's the same logic without a pointer parameter:

long sum_of_digits_value(int num) {
    if (num < 0) num = -num;
    long sum = 0;
    while (num > 0) {
        sum += num % 10;
        num /= 10;
    }
    return sum;
}
                                

Both versions work and produce the same results. For this particular problem, the value version is simpler — the function only reads the input once and computes a new value from it, so a pointer adds no functional benefit. The pointer version is required by the assignment, and it demonstrates the read-only access pattern, which is used everywhere in C for functions that inspect data without modifying it (think const char * string arguments, printf's format string, etc.). Learning both forms makes it easier to choose the right one for each problem.

12. Complexity

The loop runs once per digit, so 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 couple of local integer variables. This is optimal: each digit must be added exactly once to compute the sum, and no extra storage is needed. The same O(d) time / O(1) space pattern applies to reversal and palindrome checks, since all three problems examine each digit once.

🎯 Remember this: Sum of digits = sum += n % 10 and n /= 10, repeated until n is 0. Pass the number to the function as const int * so it can read but not modify the caller's variable. Handle negatives by taking the absolute value first, and use long for the accumulator so large inputs can't overflow it.

Frequently Asked Questions

1. Why is the parameter const int * instead of int *?

Because the function only reads the number — it never writes back. The const qualifier is a promise (enforced by the compiler) that the caller's variable won't be modified through the pointer. This matters in practice: it lets callers pass addresses of const variables without warnings, documents the function's intent at a glance, and catches accidental writes at compile time. Functions that inspect data without modifying it should always take const pointers.

2. Why does the function return long instead of int?

For a 32-bit int, the maximum sum of digits is 90 (for a 10-digit number of all 9s like 9,999,999,999, though that exceeds INT_MAX — realistic 32-bit inputs give sums up to about 82 for INT_MAX = 2147483647). That fits easily in int. But long is a better choice for three reasons: (a) it's future-proof if the input range is expanded, (b) it makes the type of the accumulator match the type of the working copy, keeping the arithmetic consistent, and (c) it avoids any doubt about overflow in intermediate computations. The cost is negligible, and the gain in clarity is real.

3. Why take the absolute value of negatives instead of rejecting them?

The mathematical "sum of digits" of a number is usually defined on its magnitude — the digits of -456 are 4, 5, 6, which sum to 15. This is the natural interpretation of the everyday phrase "add up the digits of this number." An alternative convention is to treat negative inputs as invalid and return an error, but that's less useful in practice. If you need to include the sign in the sum (subtracting the digits for negative numbers, giving -15 for -456), you'd adjust the accumulation — but that's a different problem, and most users expect the non-negative answer.

4. What happens if the input is 0?

The loop while (n > 0) doesn't run, so sum stays 0, and the function returns 0. This is correct: the sum of the digits of 0 is 0 (the only digit is 0, which contributes nothing). Some naive implementations special-case 0 with an extra check, but the general logic handles it correctly here — the loop's condition is the whole story. Testing 0 explicitly is a good habit, because it's an edge case that can break loops that use do...while or that assume at least one iteration.

5. Can I do this recursively?

Yes. A recursive version is elegant: sum(n) = (n % 10) + sum(n / 10), with base case sum(0) = 0. In code:

long sum_of_digits_rec(const int *num) {
    long n = *num;
    if (n < 0) n = -n;
    if (n == 0) return 0;
    return (n % 10) + sum_of_digits_rec(&(long){n / 10});
}

The recursion depth equals the number of digits — at most 10 for a 32-bit int, which is fine for the stack. The iterative version is generally preferred because it's slightly faster and doesn't risk stack overflow on very large numbers (though with int-sized inputs, this is a non-issue). Both are worth knowing; the iterative one is the standard answer.

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) — two local variables (n and sum). Both are optimal: each digit must be added exactly once to compute the sum, and no extra storage is needed. The same complexity analysis applies to reversal and palindrome checks, since all three iterate over the same digit sequence.

💡 Tip: Once this works, try "digital root" — the single-digit value obtained by repeatedly summing digits until one digit remains. For 12345, the sum is 15, whose digits sum to 6 — the digital root is 6. You can reuse sum_of_digits in a loop that repeats until the result is less than 10. That's a small extension of the same idea, and it's a common interview question.

📖 Related Tutorials

  • 27. Reverse a Number Using Pointers
  • 28. Check if a Number is Palindrome Using Pointers
  • 29. Factorial Using Pointers
  • 19. Reverse a String Using Pointers
  • 2. Swap Two Numbers Using Pointers
  • All 30 Pointer Assignments

Previous Topic: -->> 25. Delete an Element from an Array Using Pointers   ||   Next Topic: -->> 27. Reverse a Number 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.