pointers-memory · beginner · ~7 min

Sum an array with a pointer

Iterate an array by moving a pointer.

Challenge

Sum the elements of an array by walking a pointer across it rather than indexing.

Task

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.

Input

a — pointer to an int array. n — the element count (may be 0).

Output

Returns the sum of the n elements as a long.

Example

int a[] = {1,2,3,4,5};
sum_via_ptr(a, 5)   ->   15
sum_via_ptr(a, 0)   ->   0

Edge cases

  • n == 0: returns 0.

Why this matters

Drill: practice one contract before combining it with other skills.

Input format

a — pointer to an int array. n — the element count (may be 0).

Output format

Returns the sum of the n elements as a long.

Constraints

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.

Starter code

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

Common mistakes

Reading the exclusive end element; accumulating into int before returning long.

Edge cases to handle

An empty range returns zero; one element, mixed signs, and a sum larger than INT_MAX but representable in long.

Up next

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