basics · beginner · ~15 min
Express an accumulation as a recurrence with a base case.
Add up the integers from 1 to n using recursion rather than a loop.
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.
A single int n.
Returns the sum 1..n as a long; returns 0 for non-positive n.
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
n <= 0 returns 0 (this is also the recursion's base case).A single int n.
The sum 1+2+...+n as a long, or 0 if n <= 0.
n is an integer representing upper limit of summation.
long sum_to_n(int n) {
/* TODO: base case, then recurse on n-1 */
return 0;
}
Missing the base case causing infinite recursion and stack overflow.
n = 0, n < 0, n = 1, large n testing recursion depth.
Solve this exercise in the browser editor — compile and run against the test harness, no setup required.