In this Java program, you’ll learn how to Find the Sum of Natural Numbers using Recursion using the Java programming language.
How to Find the Sum of Natural Numbers using Recursion in JAVA?
Example 1:
RUN CODE SNIPPETpublic class Main { public static void main(String[] args) { int number = 50; 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; } }
OUTPUT
Sum = 1275
The sum of the numbers is to be stored in the variable number.
From the main function, the addnumbers is called and an argument 50 is passed.
Initially, the number is added to the results of addnumbers(49), and then the next function call from addnumbers to addnumbers continues.
The recursion is stopped when the number becomes 0.