Sum of Integers from 1 to n
Explore how to use recursion to find the sum of integers from 1 to n. This lesson breaks down the problem into base and recursive cases, helping you understand how recursion operates with numeric sequences.
What does the sum of integers from 1 to mean?
Natural numbers are all positive numbers starting with . These can be written as follows:
We want to write a program that takes a specific number and adds all the numbers from until that number.
For example, if , the sum of numbers from to is: .
Mathematical Notation
Let’s write it down mathematically:
.
.
.
Generic Mathematical Notation
.
.
.
$ … +2+1$
Implementation
Explanation
Let’s begin by breaking down the solution into subtasks:
.
.
The last statement is where execution halts, therefore it will become the base case. The rest will be mapped to the recursive case:
Let’s take a look at another example in the next lesson.