basics · beginner · ~15 min

Sum 1..n recursively

Express an accumulation as a recurrence with a base case.

Challenge

Implement long sum_to_n(int n) returning 1+2+...+n using recursion (base case + smaller subproblem). Return 0 for n <= 0.

Starter code

long sum_to_n(int n) {
    /* TODO: base case, then recurse on n-1 */
    return 0;
}

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