Search⌘ K

Sum of Integers from 1 to n

Explore how to implement a recursive Java method that sums integers from 1 to a given number n. Understand the base case and recursive case clearly, and learn how the recursion stack helps solve this fundamental numerical problem.

What does the sum of integers from 1 to n mean?

Natural numbers are positive numbers starting from 1. These can be written as:

1,2,3,4,5,6,7,8,9,10......1,2,3,4,5,6,7,8,9,10......

We want to write a program that takes a particular number and sums up all the numbers from 1 up until that number.

The illustration below explains the concept to help you understand.

The sum of all numbers up to a particular number is equal to the sum of that number and the sum of all the numbers before it. It can be seen as follows:

i=15i\sum_{i=1} ^{5} i

== 55 ++ i=14i\sum_{i=1} ^{4} i

= ...