Code Logo

Sum of Array

Published at10 Jan 2026
Easy 32 views
Like25

This problem asks for the total sum of all numbers in the array. Every element contributes to the result, so nothing is skipped.

Positive values increase the total, negative values reduce it, and zero leaves it unchanged. If the array is empty, the sum is simply 0 because there are no values to add.

For example, if nums = [1,2,3,4], the answer is 10. If nums = [10,-2,5], the answer is 13 because the negative value subtracts from the total. If all values are 0, the result stays 0.

So the task is to add every element in the array and return the final total.

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
Recommendation Algorithm Flow for Sum of Array

Solution Approach

A straightforward running total is all we need. We start from zero and add each number to that total as we scan the array.

Initialize the answer:

let total = 0;

Then process the numbers one by one:

for (const num of nums) {
  total += num;
}

Each step adds the current element into the running sum, so by the time the loop ends, total contains the sum of the whole array.

Then return it:

return total;

This solution runs in O(n) time and uses O(1) extra space.

Best Answers

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