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.
- Initialize a running total
totalSumto0. - Iterate over every element of the input array using a for-each loop.
- For each element, take
Math.absso negative values are treated like their positive counterpart. - Repeatedly take the last digit with
number % 10and add it to a per-element accumulator. - Divide the element by
10to drop the digit you just processed. - Stop the digit-extraction loop when the element becomes
0. - Add the per-element digit sum into
totalSumand continue with the next element. - After the array is fully traversed, return
totalSumas 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.
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.
| Iteration | element | digit sum of element | totalSum (before) | totalSum (after) |
|---|---|---|---|---|
| 1 | 13 | 4 | 0 | 4 |
| 2 | 20 | 2 | 4 | 6 |
| 3 | 7 | 7 | 6 | 13 |
| 4 | 86 | 14 | 13 | 27 |
| 5 | 101 | 2 | 27 | 29 |
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.
Sum of digits of all elements: 23Example 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.
Sum of digits of all elements: 24Common 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 innerwhile (number > 0)loop never runs for-45, so the method silently returns0for that element. ApplyMath.absonce at the top ofsumOfDigits. - Taking only the last digit – writing
sum = number % 10once instead of looping untilnumberis0gives wrong results for every multi-digit element. Always loop and divide by10each iteration. - Resetting totalSum inside the outer loop – declaring
int totalSum = 0inside 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-45the condition-45 != 0is true and the loop keeps running, butnumber % 10yields-5and the final sum is negative. PairMath.abswith> 0. - Overflowing an int accumulator – for a very long array of near-
Integer.MAX_VALUEvalues,totalSumcan wrap around to a negative number without warning. PromotetotalSumtolongwhen 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_VALUEpresent- 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
intarray 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
longaccumulator, 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 applyMath.absonce 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
sumOfDigitsuntil the result is a single digit, or use the closed form1 + (n - 1) % 9for 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.



