pointers-memory · beginner · ~7 min
Iterate an array by moving a pointer.
Sum the elements of an array by walking a pointer across it rather than indexing.
Implement long sum_via_ptr(const int *a, int n) that returns the sum of the first n elements, advancing a pointer from a to a + n. No main — the grader calls it.
a — pointer to an int array. n — the element count (may be 0).
Returns the sum of the n elements as a long.
int a[] = {1,2,3,4,5};
sum_via_ptr(a, 5) -> 15
sum_via_ptr(a, 0) -> 0
n == 0: returns 0.Drill: practice one contract before combining it with other skills.
a — pointer to an int array. n — the element count (may be 0).
Returns the sum of the n elements as a long.
n is nonnegative. a points to a live array, including for n=0; at least n elements are readable. Every partial sum fits long. Do not mutate input.
long sum_via_ptr(const int *a, int n) {
/* TODO */
return 0;
}
Reading the exclusive end element; accumulating into int before returning long.
An empty range returns zero; one element, mixed signs, and a sum larger than INT_MAX but representable in long.
Solve this exercise in the browser editor — compile and run against the test harness, no setup required.