Sum Natural Numbers using Recursion in Java

Exercise:

Write a Java Program to find the sum of natural numbers using recursion.

Click Here to View the Solution!
public class RecursiveAddition{
 
    public static void main(String[] args) {
        int number = 30;
        int sum = addNumbers(number);
        System.out.println("Sum = " + sum);
    }
 
    public static int addNumbers(int num) {
        if (num != 0)
            return num + addNumbers(num - 1);
        else
            return num;
    }
} 
Click Here to View the Output!
Sum = 465
Click Here to View the Explanation!
  • This program in used to calculate the sum of the natural numbers till a given number through the process of recursion.
  • An integer number 30 is initialized in the program. All the natural numbers up to 30 will be added into the variable sum using the user-defined function addNumbers that is called from main().
  • In the first step, the number 30 will be added into the output of addNumbers(29)
  • As a recursive function, addNumbers() will be called by addNumbers() and 29 will be passed and added to the output of addNumbers(28). This recursive process will continue until the number reaches 0.
  • After the number becomes equal to 0, the recursive call will end and the sum of all the natural numbers will be stored in the variable sum and returned to the main() function to be printed.