ℹ️ Select 'Choose Exercise', or randomize 'Next Random Exercise' in selected language.

Choose Exercise:
Timer 00:00
WPM --
Score --
Acc --
Correct chars --

Sum of Array Elements

Java

Goal -- WPM

Ready
Exercise Algorithm Area
1public class ArraySum {
2
3/**
4* Calculates the sum of all elements in an integer array.
5* This is a basic practice exercise for loop accumulation.
6*
7* @param arr The integer array whose elements are to be summed.
8* @return The total sum of the array elements.
9*/
10public static int sumArray(int[] arr) {
11// Handle null or empty array edge case.
12if (arr == null || arr.length == 0) {
13return 0; // Sum of an empty or null array is 0.
14}
15
16int sum = 0;
17// Iterate through each element and add it to the sum.
18for (int element : arr) {
19sum += element;
20}
21return sum;
22}
23
24public static void main(String[] args) {
25int[] numbers1 = {1, 2, 3, 4, 5};
26int[] numbers2 = {10, -5, 20};
27int[] emptyArray = {};
28int[] nullArray = null;
29
30System.out.println("Sum of numbers1: " + sumArray(numbers1)); // Expected: 15
31System.out.println("Sum of numbers2: " + sumArray(numbers2)); // Expected: 25
32System.out.println("Sum of emptyArray: " + sumArray(emptyArray)); // Expected: 0
33System.out.println("Sum of nullArray: " + sumArray(nullArray)); // Expected: 0
34}
35}
Algorithm description viewbox

Sum of Array Elements

Algorithm description:

This Java code calculates the sum of all elements within an integer array. It iterates through each number in the array and adds it to a running total. This is a fundamental programming task often used as an introductory exercise for loops and variable accumulation, applicable in scenarios like calculating total sales, scores, or any aggregate numerical data.

Algorithm explanation:

The `sumArray` function has a time complexity of O(n), where n is the number of elements in the array, because it iterates through each element exactly once. The space complexity is O(1) as it only uses a single variable (`sum`) to store the running total, regardless of the array size. Edge cases handled include null or empty arrays, for which the function correctly returns 0. The logic is straightforward: initialize a sum variable to zero, then for each element in the array, add its value to the sum. Finally, return the accumulated sum.

Pseudocode:

function sumArray(array):
  if array is null or empty:
    return 0
  sum = 0
  for each element in array:
    sum = sum + element
  return sum