basics · beginner · ~15 min
Express an accumulation as a recurrence with a base case.
Implement long sum_to_n(int n) returning 1+2+...+n using recursion (base case + smaller subproblem). Return 0 for n <= 0.
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.