basics · beginner · ~15 min
Iterate over an array with a size parameter.
Add up the elements of an int array given a pointer and a length.
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.
a: pointer to an array of int.n: how many elements to add (the array length). n may be 0.The sum of a[0..n-1] as a long (wider than int to avoid overflow when summing many values).
sum_array({1,2,3,4,5}, 5) -> 15
sum_array(a, 0) -> 0
sum_array({-1,-2,-3}, 3) -> -6
n = 0: return 0 (do not read a).Pointer a to an int array and a length n (n may be 0).
The sum of the first n elements as a long.
n = 0 returns 0 without reading a.
#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.