basics · beginner · ~15 min

Sum 1..n recursively

Express an accumulation as a recurrence with a base case.

Challenge

Add up the integers from 1 to n using recursion rather than a loop.

Task

Implement long sum_to_n(int n) that returns 1 + 2 + ... + n. Use recursion: a base case plus a call on a smaller value. Return 0 when n <= 0.

Input

A single int n.

Output

Returns the sum 1..n as a long; returns 0 for non-positive n.

Example

sum_to_n(5)    ->   15    (1+2+3+4+5)
sum_to_n(1)    ->   1
sum_to_n(0)    ->   0
sum_to_n(10)   ->   55

Edge cases

  • n <= 0 returns 0 (this is also the recursion's base case).

Rules

  • Must be recursive.

Input format

A single int n.

Output format

The sum 1+2+...+n as a long, or 0 if n <= 0.

Constraints

Must be recursive; 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.