data-structures · beginner · ~15 min

Recursive array sum

Sum an array by shrinking its length.

Challenge

Implement:

long long array_sum(const int *a, int n);

Return the sum of a[0..n-1], computed recursively.

Input format

Array a, length n.

Output format

Sum of elements.

Constraints

Reduce n by 1 each call.

Starter code

#include <stddef.h>
/* Sum of a[0..n-1], computed recursively. */
long long array_sum(const int *a,int n){ (void)a;(void)n; return 0; }

Common mistakes

Off-by-one indexing (use a[n-1] with the n-1 subproblem).

Edge cases to handle

n==0 returns 0.

Background lessons

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