pointers-memory · beginner · ~15 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.

Input format

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

Output format

The sum of the n elements, as a long.

Constraints

Iterate by advancing a pointer, not by indexing.

Starter code

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

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