basics · beginner · ~15 min

Sum an array

Iterate an array by index.

Challenge

Add up the elements of an integer array.

Task

Implement long array_sum(const int *a, int n) that returns the sum of the first n elements of a. Accumulate into a long so large totals don't overflow. No main — the grader calls it.

Input

A pointer a to at least n ints, and the count int n (n >= 0).

Output

Returns the sum of the n elements as a long.

Example

array_sum({1,2,3,4,5}, 5)   ->   15
array_sum({-3,3}, 2)        ->   0
array_sum({7}, 1)           ->   7

Edge cases

  • n == 0 returns 0 (empty range).

Input format

A pointer a to n ints, and the count int n (n >= 0).

Output format

The sum of the n elements, as a long.

Constraints

n may be 0 (returns 0).

Starter code

long array_sum(const int *a, int n) {
    /* TODO */
    return 0;
}

Common mistakes

Array index out-of-bounds (i <= len); failing to initialize accumulators or counters; treating array parameter as whole array instead of pointer.

Edge cases to handle

Array of length 0; array of length 1; negative numbers; all identical elements; extreme min/max integer values.

Solve this exercise in the browser editor — compile and run against the test harness, no setup required.