Code Logo

Sum of Array

Published at10 Jan 2026
1D Array Easy 44 views
Like25

Given an array of integers, compute the sum of all elements. Return the total as an integer.

For example, the sum of [1, 2, 3, 4, 5] is 15. The sum of [-5, 10, -3] is 2. An empty array returns 0. A single-element array [7] returns 7.

Summation is the most fundamental aggregation operation. It is used in calculating totals, averages, financial balances, and statistical measures. The pattern of accumulating a running total by iterating through a collection is essential for all data processing work.

The solution initializes a sum variable to 0 and adds each element during iteration. After the loop, return the sum.

Edge cases include an empty array (return 0), a single element (return that element), negative values (correctly reduce the total), and large arrays where the sum might exceed typical integer ranges.

Example Input & Output

Example 1
Input
nums = [1, 2, 3, 4]
Output
10
Explanation

Example 1: Sum of [1, 2, 3, 4] is 10

Example 2
Input
nums = [10, -2, 5]
Output
13
Explanation

Example 2: Sum of [10, -2, 5] is 13

Example 3
Input
nums = [0, 0, 0]
Output
0
Explanation

Example 3: Sum of [0, 0, 0] is 0

Algorithm Flow

Recommendation Algorithm Flow for Sum of Array

Solution Approach

Iterate through the array and accumulate the sum of all elements into a running total.

function arraySum(arr)
  sum = 0
  for i = 0 to length(arr) - 1
    sum = sum + arr[i]
  return sum

Initialize sum to 0. Loop through each element and add it to the running total using the addition operator. After all elements are processed, return the accumulated sum. For an empty array, the loop never executes and sum remains 0.

Time complexity is O(n), space complexity is O(1).

Best Answers

java
class Solution {
    public int sum_array(int[] nums) {
        int sum = 0;
        for (int num : nums) sum += num;
        return sum;
    }
}