Java Program to Find the Sum of Natural Numbers using Recursion

In this java program, we will learn about how to calculate the sum of natural numbers using recursion.
The natural numbers are the numbers that include all integers from 1 to infinity. To find the sum of all natural number till N, we have to add all numbers between 1 to N.

Let sumNumbers(N) be a method to calculate sum of natural numbers from 1 to N. Then

sumNumbers(N) = 1 + 2 + 3 + ... + N
sumNumbers(N) = [1 + 2 + 3 + ... +(N-1)]+ N
sumNumbers(N) = sumNumbers(N-1)+ N

From above recursion equation, to calculate natural number sum till N, we have to first calculate sum of natural numbers till (N-1) and then add N.
For Example:

sumNumbers(10) = sumNumbers(9) + 10

To understand this java program, you should have understanding of the following Java programming concepts:


Java program to find the sum of natural numbers using recursion

public class NumbersSumRecursion {
  static int sumNumbers(int N) {
    if (N == 1) {
      return 1;
    } else {
      return sumNumbers(N - 1) + N;
    }
  }

  public static void main(String[] args) {
    int sum = sumNumbers(15);
    System.out.println("Sum of Numbers till 15 : "+sum);
  }
}
Output
Sum of Numbers till 15 : 120