Write a recursive function that returns the sum of the integers from 1 to
n. If n is 0 or negative, the sum is 0.
sumTo(n)
sumTo(3) // → 6 (1 + 2 + 3)
sumTo(1) // → 1
sumTo(0) // → 0
Summing 1 through n is usually a loop-and-accumulator exercise. Recursion reframes it as self-similarity: the sum from 1 to n is one new piece (the number n) plus a smaller version of the same problem — the sum from 1 to n-1.
What's the simplest input with an immediate answer? Once n drops to 0 or below, there's nothing left to add, so the sum is 0. Each call passes n-1 to the next, so the sequence n, n-1, n-2, ... always reaches that floor.
Trust that sumTo(n-1) correctly returns the sum from 1 to n-1. Then the sum from 1 to n is just n plus that trusted result — you don't re-derive the smaller sum, you combine your current number with it.
Calling sumTo(3) triggers sumTo(2), then sumTo(1), then sumTo(0). sumTo(0) is the base case — it returns 0 immediately, the bottom of the stack. From there the calls resolve in reverse: sumTo(1) computes 1 + 0 = 1. sumTo(2) computes 2 + 1 = 3. sumTo(3) computes 3 + 3 = 6, the final answer. No addition happens until the base case is hit — each pending call waits, holding its own value of n, until the call below it resolves.
"Current value combined with the recursive result of a smaller problem" is the backbone of far more interesting recursion — tree traversals, divide-and-conquer, problems on nested or branching data. The arithmetic here is trivial on purpose, so you can focus on the mechanics: base case, trusting the recursive call, and tracing how values accumulate as the stack unwinds. Also worth noting: this uses O(n) stack depth to do work a loop could do in O(1) extra space — a tradeoff to stay aware of once recursion gets deeper.
def sum_to(n):
if n <= 0:
return 0
return n + sum_to(n - 1)
Sign in to join the discussion.
No comments yet. Be the first to ask a question.
Press Run to execute your code, or Submit to test and complete this problem.