Recursion

Example #2: Another common recursive function is the sum of all positive integers up to \( n \), defined as \( \sum n = 1 + 2 + \dots + n \).

Like factorial, this can be defined recursively: \( \sum n = n + \sum (n - 1) \), with the base case \( \sum 0 = 0 \).

For example, $\sum 3 \;$$= 3 + \sum 2 \;$$= 3 + 2 + \sum 1 \;$$= 3 + 2 + 1 + \sum 0 \;$$= 3 + 2 + 1 + 0 \;$$= 6$.

While this can be computed quickly using formula \( \frac{n(n + 1)}{2} \) which we've already learned, the recursive version is useful pedagogically to understand recursion's mechanism.

Here is the definition: \( \sum n = \begin{cases} 0 & \text{if } n = 0 \\ n + \sum(n - 1) & \text{if } n > 0 \end{cases} \).

$$\sum n = \begin{cases} 0 & \text{if } n = 0 \\ n + \sum(n - 1) & \text{if } n > 0 \end{cases}$$