Placement Prep

Find Sum of Digits of a Number: C, C++, Java, Python

Programs to find the sum of digits of a number in C, C++, Java, and Python. Iterative and recursive approaches with step-by-step traced outputs.

By FACE Prep Team 6 min read
programs c-programming java python algorithms data-structures

The sum of digits of 719 is 17: extract each digit with the modulo operator, add it to a running total, divide the number by 10 to drop that digit, and repeat until nothing remains.

This is one of the most direct loop problems in any coding test. Two standard approaches exist: iterative (a while loop) and recursive. Both produce the same result; the iterative version uses O(1) extra space while the recursive version uses O(log n) call-stack frames. The digit sum operation also appears in number-theory proofs and checksum algorithms, though placement test questions focus strictly on the base-10 computation shown here.

How the Algorithm Works

The key insight is that n % 10 always returns the rightmost digit of n. Dividing by 10 (integer division) removes that digit. Doing this in a loop picks off digits from right to left.

Step-by-step for input 719:

  • Initial state: n = 719, sum = 0
  • Iteration 1: digit = 719 % 10 = 9, sum = 9, n = 71
  • Iteration 2: digit = 71 % 10 = 1, sum = 10, n = 7
  • Iteration 3: digit = 7 % 10 = 7, sum = 17, n = 0
  • Loop ends (n = 0). Return 17.

The same loop for 12345:

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

The loop condition is n > 0, which handles the termination naturally. For zero as input, the loop body never runs and the function returns 0.

For a related digit-manipulation pattern, see Armstrong number detection, which uses the same modulo-divide loop to check whether the sum of cubed digits equals the original number.

Iterative Approach

C

#include <stdio.h>

int sumOfDigits(int n) {
    int sum = 0;
    if (n < 0) n = -n;
    while (n > 0) {
        sum += n % 10;
        n /= 10;
    }
    return sum;
}

int main() {
    int num;
    printf("Enter a number: ");
    scanf("%d", &num);
    printf("Sum of digits of %d is %d\n", num, sumOfDigits(num));
    return 0;
}

Output for input 719: Sum of digits of 719 is 17

C++

#include <iostream>
using namespace std;

int sumOfDigits(int n) {
    int sum = 0;
    if (n < 0) n = -n;
    while (n > 0) {
        sum += n % 10;
        n /= 10;
    }
    return sum;
}

int main() {
    int num;
    cout << "Enter a number: ";
    cin >> num;
    cout << "Sum of digits of " << num << " is " << sumOfDigits(num) << endl;
    return 0;
}

Output for input 719: Sum of digits of 719 is 17

Java

import java.util.Scanner;

public class SumOfDigits {
    static int sumOfDigits(int n) {
        int sum = 0;
        if (n < 0) n = -n;
        while (n > 0) {
            sum += n % 10;
            n /= 10;
        }
        return sum;
    }

    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        System.out.print("Enter a number: ");
        int num = sc.nextInt();
        System.out.println("Sum of digits of " + num + " is " + sumOfDigits(num));
    }
}

Output for input 719: Sum of digits of 719 is 17

Python

def sum_of_digits(n):
    if n < 0:
        n = -n
    total = 0
    while n > 0:
        total += n % 10
        n //= 10
    return total

num = int(input("Enter a number: "))
print(f"Sum of digits of {num} is {sum_of_digits(num)}")

Output for input 719: Sum of digits of 719 is 17

Note: Python’s // operator is integer (floor) division. For positive numbers it behaves identically to C’s / on integers.

Recursive Approach

The recursive version expresses the same logic differently: the sum of digits of n equals its last digit plus the sum of digits of n // 10. The base case is any single-digit number (0 through 9), which is its own digit sum.

C

#include <stdio.h>

int sumOfDigitsRec(int n) {
    if (n < 0) n = -n;
    if (n < 10) return n;
    return (n % 10) + sumOfDigitsRec(n / 10);
}

int main() {
    int num;
    printf("Enter a number: ");
    scanf("%d", &num);
    printf("Sum of digits of %d is %d\n", num, sumOfDigitsRec(num));
    return 0;
}

Output for input 719: Sum of digits of 719 is 17

C++

#include <iostream>
using namespace std;

int sumOfDigitsRec(int n) {
    if (n < 0) n = -n;
    if (n < 10) return n;
    return (n % 10) + sumOfDigitsRec(n / 10);
}

int main() {
    int num;
    cout << "Enter a number: ";
    cin >> num;
    cout << "Sum of digits of " << num << " is " << sumOfDigitsRec(num) << endl;
    return 0;
}

Output for input 719: Sum of digits of 719 is 17

Java

import java.util.Scanner;

public class SumOfDigitsRec {
    static int sumOfDigitsRec(int n) {
        if (n < 0) n = -n;
        if (n < 10) return n;
        return (n % 10) + sumOfDigitsRec(n / 10);
    }

    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        System.out.print("Enter a number: ");
        int num = sc.nextInt();
        System.out.println("Sum of digits of " + num + " is " + sumOfDigitsRec(num));
    }
}

Output for input 719: Sum of digits of 719 is 17

Python

def sum_of_digits_rec(n):
    if n < 0:
        n = -n
    if n < 10:
        return n
    return (n % 10) + sum_of_digits_rec(n // 10)

num = int(input("Enter a number: "))
print(f"Sum of digits of {num} is {sum_of_digits_rec(num)}")

Output for input 719: Sum of digits of 719 is 17

Tracing the Recursive Output Step by Step

For input 719, the call stack unwinds like this:

  • sumOfDigitsRec(719) calls sumOfDigitsRec(71) and waits
  • sumOfDigitsRec(71) calls sumOfDigitsRec(7) and waits
  • sumOfDigitsRec(7) returns 7 (base case: 7 is a single digit)
  • sumOfDigitsRec(71) returns 1 + 7 = 8
  • sumOfDigitsRec(719) returns 9 + 8 = 17

The call stack depth equals the number of digits (3 for 719). For a 10-digit number the stack is 10 frames deep, well within any practical limit.

For input 12345, the recursive trace:

  • sumOfDigitsRec(12345) = 5 + sumOfDigitsRec(1234)
  • sumOfDigitsRec(1234) = 4 + sumOfDigitsRec(123)
  • sumOfDigitsRec(123) = 3 + sumOfDigitsRec(12)
  • sumOfDigitsRec(12) = 2 + sumOfDigitsRec(1)
  • sumOfDigitsRec(1) = 1 (base case)
  • Unwinding: 1 + 2 = 3, then 3 + 3 = 6, then 6 + 4 = 10, then 10 + 5 = 15

Edge Cases and Overflow

Input is zero

Both approaches return 0 correctly. The iterative loop’s condition n > 0 is false immediately. The recursive base case n < 10 returns 0 directly.

Input is negative

The if (n < 0) n = -n guard converts to the absolute value before processing. Without it, n % 10 in C and Java returns a negative remainder when the left operand is negative, producing wrong digit values and causing the loop to run indefinitely (since a negative n never reaches zero with n /= 10 toward positive values). The guard ensures the function works correctly on any integer input.

Integer overflow in C and Java

The int type in C and Java imposes a size limit on inputs. Key points:

  • Maximum int value (INT_MAX): 2,147,483,647 — if you need inputs beyond this, change the parameter type to long
  • The digit sum of INT_MAX itself (ten digits totalling at most 82) fits comfortably inside an int accumulator, so the sum variable never overflows
  • Passing a value larger than INT_MAX to an int parameter causes undefined behaviour in C and silent bit-wrapping in Java
  • Python integers have no fixed width, so sum_of_digits(10**100) works without any type changes

Python and arbitrary precision

Python integers have no fixed size limit. sum_of_digits(10**100) works without modification, making Python the natural choice when inputs can be very large.

For more programs that manipulate numbers using loops and accumulators, see the data structures programs collection in C, C++, Java, and Python and the insert, delete, and search in an array guide.

The modulo-divide loop in these programs is the same core pattern that appears in Armstrong number detection and palindrome checks. If you want to extend it to digital roots, happy numbers, or Kaprekar constants without setting up a local compiler, TinkerLLM has a Python sandbox at ₹299 where you can run and modify these programs directly in the browser.

Primary sources

Frequently asked questions

What is the sum of digits of 0?

The sum of digits of 0 is 0. The while loop condition `n > 0` is false from the start, so the accumulator stays at 0 and the function returns 0.

Does this program work for negative numbers?

Not by default. The while loop `n > 0` exits immediately for negative inputs. Add a guard at the start: `if (n < 0) n = -n;` in C/C++/Java or `if n < 0: n = -n` in Python. All four solutions above already include this guard.

What is the time complexity of the iterative sum-of-digits approach?

O(d), where d is the number of digits in the input. Since d = floor(log10(n)) + 1, this is O(log n) in terms of the input value n.

What happens if the input number is larger than INT_MAX?

In C and Java, int holds values up to 2,147,483,647. For larger inputs, change the parameter type to long (C/Java) or use Python, which handles arbitrarily large integers natively.

Can I find the sum of digits by converting the number to a string?

Yes. In Python: `sum(int(d) for d in str(abs(n)))`. In Java: iterate over `String.valueOf(Math.abs(n)).toCharArray()` and subtract '0' from each char. String conversion trades a little runtime overhead for readability.

What is a digital root, and how does it relate to sum of digits?

A digital root is the single-digit value obtained by repeatedly summing digits until one digit remains. For 719: sum=17, then 1+7=8. Digital roots are used in divisibility checks and checksum algorithms.

Build AI projects

A self-paced playground for building with LLMs.

TinkerLLM is FACE Prep's sister property. A guided environment for shipping real LLM applications, the kind of project that earns a paragraph on your resume, not a line.

Try TinkerLLM (₹299 launch)
Free AI Roadmap PDF