Advertisement
Home Data Structure Arrays Sum of Digits of All Elements in an Array

Sum of Digits of All Elements in an Array

0
Advertisement

Title: Sum of Digits of All Elements in an Array

Working with the individual digits of a number is a staple of beginner Java problems, and it shows up often in coding interviews because it combines basic looping, integer arithmetic, and careful handling of edge cases. In this guide, you will learn how to compute the sum of digits of every element in an integer array, step by step, with a complete Java program, a worked trace, examples, common pitfalls, and interview follow-ups.

Understanding the Problem

You are given an integer array. For every element, you must break it into its decimal digits and add those digits together. The answer is the total of all per-element digit sums across the whole array. For instance, for the array {12, 45, 7, 103}, the digits are 1, 2, 4, 5, 7, 1, 0, and 3, so the final result is 23.

The problem looks simple, but a careful solution has to handle negative numbers, zero elements, and multi-digit values uniformly. Pulling it apart into two small helpers, one that returns the digit sum of a single number and one that walks the array, keeps the logic easy to read and easy to test.

Approach

We use a classic modulo-and-divide loop to peel off each decimal digit, and an outer loop that walks the array and accumulates the running total. The steps below describe the algorithm end to end.

  1. Initialize a running total totalSum to 0.
  2. Iterate over every element of the input array using a for-each loop.
  3. For each element, take Math.abs so negative values are treated like their positive counterpart.
  4. Repeatedly take the last digit with number % 10 and add it to a per-element accumulator.
  5. Divide the element by 10 to drop the digit you just processed.
  6. Stop the digit-extraction loop when the element becomes 0.
  7. Add the per-element digit sum into totalSum and continue with the next element.
  8. After the array is fully traversed, return totalSum as the final answer.

Java Program

The full program below is self contained. You can paste it into a file called SumOfDigitsOfArray.java, compile it, and run it as is.

Java
public class SumOfDigitsOfArray {

    public static int sumOfDigits(int number) {
        int sum = 0;
        number = Math.abs(number);
        while (number > 0) {
            sum += number % 10;
            number /= 10;
        }
        return sum;
    }

    public static int sumOfDigitsOfAllElements(int[] numbers) {
        int totalSum = 0;
        for (int number : numbers) {
            totalSum += sumOfDigits(number);
        }
        return totalSum;
    }

    public static void main(String[] args) {
        int[] numbers = {12, 45, 7, 103};
        int result = sumOfDigitsOfAllElements(numbers);
        System.out.println("Sum of digits of all elements: " + result);
    }
}

Explanation of the Program

The sumOfDigits helper takes a single integer and returns the sum of its decimal digits. It first calls Math.abs so a value like -45 is treated as 45; without that step, the while (number > 0) loop would immediately exit for any negative input and silently return 0.

Inside the loop, number % 10 extracts the current last digit, we add it to sum, then number /= 10 shifts the remaining digits one place to the right by truncating the last one. The loop exits exactly when every digit has been consumed and number has become 0.

The sumOfDigitsOfAllElements method is a thin wrapper that calls sumOfDigits for every element of the array and accumulates the results into totalSum. The main method shows a tiny driver that constructs an array, invokes the method, and prints the result.

Step-by-Step Trace

Let us trace the algorithm on the input {13, 20, 7, 86, 101}. The expected final answer is 29 because the digits are 1, 3, 2, 0, 7, 8, 6, 1, 0, and 1.

Iterationelementdigit sum of elementtotalSum (before)totalSum (after)
113404
220246
377613
486141327
510122729

At the end of iteration i, totalSum holds the sum of digits across numbers[0..i]. Iteration 3 is worth a second look: the element 7 is a single-digit number, so the inner loop runs exactly once, which is the no-op branch for the outer accumulation length-wise. Iteration 4 shows the opposite case where a two-digit value adds the largest single contribution.

Examples

Example 1: Mixed one, two, and three digit values

Input: {12, 45, 7, 103}. The digits are 1, 2, 4, 5, 7, 1, 0, 3, which sum to 23.

Java
Sum of digits of all elements: 23

Example 2: Elements containing zero digits and negatives

Input: {99, -100, 50}. The Math.abs step treats -100 as 100. The digits are 9, 9, 1, 0, 0, 5, 0, which sum to 24.

Java
Sum of digits of all elements: 24

Common Mistakes to Avoid

Most bugs in this problem come from one of a handful of specific slips. The list below walks from the most frequent beginner slip to the most subtle one.

  • Skipping Math.abs – for an input like {-45, 12} the inner while (number > 0) loop never runs for -45, so the method silently returns 0 for that element. Apply Math.abs once at the top of sumOfDigits.
  • Taking only the last digit – writing sum = number % 10 once instead of looping until number is 0 gives wrong results for every multi-digit element. Always loop and divide by 10 each iteration.
  • Resetting totalSum inside the outer loop – declaring int totalSum = 0 inside the for-each body wipes out the running total on every element and leaves you with the digit sum of only the last element. Keep the accumulator outside the loop.
  • Using != 0 instead of > 0 without abs – combined with a missing Math.abs, this hides the sign bug: for -45 the condition -45 != 0 is true and the loop keeps running, but number % 10 yields -5 and the final sum is negative. Pair Math.abs with > 0.
  • Overflowing an int accumulator – for a very long array of near-Integer.MAX_VALUE values, totalSum can wrap around to a negative number without warning. Promote totalSum to long when inputs are known to be large.

Edge Cases to Test

Before you declare the program finished, run it mentally against each of the following inputs. These are the shapes an interviewer is most likely to probe for.

  • Empty array
  • Single-element array
  • Element equal to 0
  • Elements containing a zero digit, such as 2050
  • Negative elements, including -1
  • Mix of negative and positive values
  • Integer.MIN_VALUE present
  • Null array reference

Additional Considerations

The time complexity of the algorithm is O(n * d), where n is the length of the array and d is the maximum number of digits in any element. For 32-bit int values, d is bounded by 10, so in practice the running time is linear in n. The auxiliary space is O(1) because we only maintain a few scalar accumulators.

The Integer.MIN_VALUE case deserves special attention. In two’s complement arithmetic, Math.abs(Integer.MIN_VALUE) returns Integer.MIN_VALUE itself, because -Integer.MIN_VALUE cannot be represented as a positive int. If your inputs can reach that value, convert to long before taking the absolute value, or special-case the input explicitly.

Interview Follow-up Questions

The base problem is a warm-up. The questions below are the kind an interviewer uses to see how your solution bends when the constraints change.

  • What if you must return the per-element digit sums instead of a single total? – allocate an output int array of the same length and fill it in place; the outer loop body shrinks to one assignment.
  • What if the elements arrive as String objects to allow values beyond long range? – iterate over the characters directly and convert each one with Character.getNumericValue, skipping an optional leading sign character. No numeric parsing is needed.
  • What if the array is streamed in chunks that do not fit in memory? – keep a running long accumulator, process each chunk independently, and emit the final sum when the stream closes.
  • What if you must compute sumOfDigits recursively without any loops? – define sumOfDigits(n) = n == 0 ? 0 : n % 10 + sumOfDigits(n / 10) and apply Math.abs once at the entry point so each recursive step stays non-negative.
  • What if you need the digital root rather than the digit sum? – repeatedly apply sumOfDigits until the result is a single digit, or use the closed form 1 + (n - 1) % 9 for positive integers to get an O(1) answer.

Conclusion

Summing the digits of every element in an array is a tiny problem that packs most of the array-processing fundamentals you need in a Java interview: a nested loop structure, a guard for negative values, a careful treatment of zero, and an awareness of overflow at the boundaries. The two-helper design we built keeps each loop focused on a single concern, which makes the code easy to test and easy to adapt when the problem statement shifts.

Try adapting the program to return the digital root, or to work on a long[] array, and you will see how little of the structure has to change. You can learn more about array problems in Java here: Arrays.