basics · beginner · ~15 min

Sum of array

Iterate over an array with a size parameter.

Challenge

Add up the elements of an int array given a pointer and a length.

Task

Implement long sum_array(const int *a, size_t n) returning the sum of the first n ints in a. No main — the grader calls it.

Input

  • a: pointer to an array of int.
  • n: how many elements to add (the array length). n may be 0.

Output

The sum of a[0..n-1] as a long (wider than int to avoid overflow when summing many values).

Example

sum_array({1,2,3,4,5}, 5)   ->   15
sum_array(a, 0)             ->   0
sum_array({-1,-2,-3}, 3)    ->   -6

Edge cases

  • n = 0: return 0 (do not read a).

Input format

Pointer a to an int array and a length n (n may be 0).

Output format

The sum of the first n elements as a long.

Constraints

n = 0 returns 0 without reading a.

Starter code

#include <stddef.h>

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

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