English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية

Java Basic Tutorial

Java Flow Control

Java Arrays

Java Object-Oriented (I)

Java Object-Oriented (II)

Java Object-Oriented (III)

Java Exception Handling

Java List (List)

Java Queue (Queue)

Java Map Collections

Java Set Collections

Java Input/Output (I/O)

Java Reader/Writer

Java Other Topics

Java program to find the sum of natural numbers using recursion

Comprehensive Java Examples

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.

Example: Sum of natural numbers using recursion

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.

Comprehensive Java Examples