3D Array Summation
Problem Statement
Write a Java program that initializes a 3D array of integers and computes the sum of all elements using nested loops. The program should return the total sum and test the implementation with 3D arrays of different dimensions, including edge cases like single-element arrays and arrays with varying sizes for each dimension. You can visualize this as calculating the total value of items stored in a 3D grid, such as boxes stacked in a warehouse with layers, rows, and columns, by adding up every item’s value.
Input: A 3D array of integers with dimensions d × r × c (e.g., array = {{{1, 2}, {3, 4}}, {{5, 6}, {7, 8}}}).
Output: A long integer representing the sum of all elements in the 3D array (e.g., 36 for the example above).
Constraints:
- 1 ≤ d, r, c ≤ 100 (where d is depth, r is rows, c is columns).
- Elements are integers between -10^4 and 10^4.
- The array is guaranteed to be non-empty and well-formed (all sub-arrays have consistent dimensions). Example:
- Input:
array = {{{1, 2}, {3, 4}}, {{5, 6}, {7, 8}}} - Output: 36
- Explanation: Sum = 1 + 2 + 3 + 4 + 5 + 6 + 7 + 8 = 36.
- Input:
array = {{{1}}} - Output: 1
- Explanation: The single-element 3D array has sum 1.
Pseudocode
FUNCTION sum3DArray(array)
IF array is null OR array is empty OR array[0] is empty OR array[0][0] is empty THEN
RETURN 0
ENDIF
SET depth to number of layers in array
SET rows to number of rows in array[0]
SET cols to number of columns in array[0][0]
SET sum to 0
FOR i from 0 to depth - 1
FOR j from 0 to rows - 1
FOR k from 0 to cols - 1
SET sum to sum + array[i][j][k]
ENDFOR
ENDFOR
ENDFOR
RETURN sum
ENDFUNCTION
FUNCTION main()
SET testArrays to 3D arrays with different dimensions
FOR each array in testArrays
CALL sum3DArray(array)
PRINT result
ENDFOR
ENDFUNCTION
Algorithm Steps
- Check if the input 3D array is null, empty, or has empty sub-arrays. If so, return 0.
- Determine the dimensions:
depth(d),rows(r), andcolumns(c) of the 3D array. - Initialize a variable
sumto 0. - Use three nested loops to iterate through each element
array[i][j][k]: a. Add the element tosum. - Return the final
sum. - In the
mainmethod, create test 3D arrays with different dimensions and callsum3DArrayto verify correctness.
Java Implementation
public class ThreeDArraySummation {
// Computes the sum of all elements in a 3D array
public long sum3DArray(int[][][] array) {
// Check for null or empty array
if (array == null || array.length == 0 || array[0].length == 0 || array[0][0].length == 0) {
return 0;
}
// Get dimensions
int depth = array.length;
int rows = array[0].length;
int cols = array[0][0].length;
// Initialize sum
long sum = 0;
// Iterate through all elements
for (int i = 0; i < depth; i++) {
for (int j = 0; j < rows; j++) {
for (int k = 0; k < cols; k++) {
sum += array[i][j][k];
}
}
}
return sum;
}
// Main method to test sum3DArray with various inputs
public static void main(String[] args) {
ThreeDArraySummation summer = new ThreeDArraySummation();
// Test case 1: 2x2x2 3D array
int[][][] array1 = {{{1, 2}, {3, 4}}, {{5, 6}, {7, 8}}};
System.out.println("Test case 1:");
System.out.println("Array:");
print3DArray(array1);
System.out.println("Sum: " + summer.sum3DArray(array1));
// Test case 2: 1x1x1 single-element array
int[][][] array2 = {{{1}}};
System.out.println("Test case 2:");
System.out.println("Array:");
print3DArray(array2);
System.out.println("Sum: " + summer.sum3DArray(array2));
// Test case 3: 2x3x2 non-uniform dimensions
int[][][] array3 = {{{1, 2}, {3, 4}, {5, 6}}, {{7, 8}, {9, 10}, {11, 12}}};
System.out.println("Test case 3:");
System.out.println("Array:");
print3DArray(array3);
System.out.println("Sum: " + summer.sum3DArray(array3));
// Test case 4: 1x2x3 array with negative numbers
int[][][] array4 = {{{-1, -2, -3}, {-4, -5, -6}}};
System.out.println("Test case 4:");
System.out.println("Array:");
print3DArray(array4);
System.out.println("Sum: " + summer.sum3DArray(array4));
// Test case 5: Empty array
int[][][] array5 = {};
System.out.println("Test case 5:");
System.out.println("Array:");
print3DArray(array5);
System.out.println("Sum: " + summer.sum3DArray(array5));
}
// Helper method to print 3D array
private static void print3DArray(int[][][] array) {
if (array == null || array.length == 0) {
System.out.println("null");
return;
}
System.out.println("[");
for (int i = 0; i < array.length; i++) {
System.out.println(" [");
for (int j = 0; j < array[i].length; j++) {
System.out.print(" [");
for (int k = 0; k < array[i][j].length; k++) {
System.out.print(array[i][j][k]);
if (k < array[i][j].length - 1) {
System.out.print(", ");
}
}
System.out.println("]");
}
System.out.println(" ]");
}
System.out.println("]");
}
}
Output
Running the main method produces:
Test case 1:
Array:
[
[
[1, 2]
[3, 4]
]
[
[5, 6]
[7, 8]
]
]
Sum: 36
Test case 2:
Array:
[
[
[1]
]
]
Sum: 1
Test case 3:
Array:
[
[
[1, 2]
[3, 4]
[5, 6]
]
[
[7, 8]
[9, 10]
[11, 12]
]
]
Sum: 78
Test case 4:
Array:
[
[
[-1, -2, -3]
[-4, -5, -6]
]
]
Sum: -21
Test case 5:
Array:
null
Sum: 0
Explanation:
- Test case 1: Sums a 2×2×2 array: 1 + 2 + 3 + 4 + 5 + 6 + 7 + 8 = 36.
- Test case 2: Sums a 1×1×1 array: 1 = 1.
- Test case 3: Sums a 2×3×2 array: 1 + 2 + 3 + 4 + 5 + 6 + 7 + 8 + 9 + 10 + 11 + 12 = 78.
- Test case 4: Sums a 1×2×3 array with negatives: -1 + (-2) + (-3) + (-4) + (-5) + (-6) = -21.
- Test case 5: Returns 0 for an empty array.
How It Works
- Step 1: The
sum3DArraymethod checks for null or empty arrays. For{{{1, 2}, {3, 4}}, {{5, 6}, {7, 8}}}, it proceeds. - Step 2: Get dimensions:
depth = 2,rows = 2,cols = 2. - Step 3: Initialize
sum = 0. - Step 4: Iterate through all elements:
- Layer 0:
[1, 2]→ sum = 0 + 1 + 2 = 3;[3, 4]→ sum = 3 + 3 + 4 = 10. - Layer 1:
[5, 6]→ sum = 10 + 5 + 6 = 21;[7, 8]→ sum = 21 + 7 + 8 = 36.
- Layer 0:
- Example Trace: For test case 1, accumulates: 1 + 2 + 3 + 4 + 5 + 6 + 7 + 8 = 36.
- Main Method: Tests with different dimensions (2×2×2, 1×1×1, 2×3×2, 1×2×3) and an empty array, printing inputs and sums.
- Summation Property: Uses nested loops to access each element, ensuring all are included in the sum.
Complexity Analysis Table
| Operation | Time Complexity | Space Complexity |
|---|---|---|
| Summation | O(drc) | O(1) |
| Full Algorithm | O(drc) | O(1) |
Note:
- d is the depth, r is the number of rows, c is the number of columns.
- Time complexity: O(drc), as the algorithm iterates through each element once.
- Space complexity: O(1), as only a single
sumvariable is used (excluding input/output). - Best, average, and worst cases are O(drc).
✅ Tip: Use nested loops for straightforward 3D array traversal. Test with varying dimensions and negative numbers to ensure correctness, especially for edge cases like single-element arrays.
⚠ Warning: Ensure the 3D array is well-formed (consistent dimensions across layers, rows, and columns) to avoid
NullPointerExceptionorArrayIndexOutOfBoundsException. Use alongfor the sum to handle large arrays within the given constraints.