English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية
In this program, you will learn to find the sum of natural numbers using Java recursion. This is done with the help of a recursive function.
Positive numbers1,2,3 ...are called natural numbers. The following program takes a positive integer from the user and calculates the sum of the given number.
You can alsoSum of natural numbers using a loop But, you will learn to solve this problem using recursion here.
public class AddNumbers { public static void main(String[] args) { int number = 20; 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; } }
When running the program, the output is:
Sum = 210
The summing numbers are stored in the variable number.
Initially, addNumbers() is called from the main() function, with20 is passed as a parameter.
number(2) is added to addNumbers(19) result.
In the next function call from addNumbers() to addNumbers(), the following will be passed19, this value will be added to addNumbers(18. This process continues until num equals 0.
No recursive call is made when num equals 0, and then the sum of the integer is returned to the main() function.