In this Java program, you’ll learn how to find the sum of natural numbers using recursion. In this program, we used the following Java basics such as

conditions, and java recursion methods.**if...else**

The positive numbers 1, 2, 3, 4... are known as **natural numbers**. This program below takes a positive integer from the user as input and calculates the sum up to the given number.

Here is the code of the program to find the sum of natural numbers using recursion.

```
//Java Program to Find the Sum of Natural Numbers using Recursion
import java.util.Scanner;
public class JavaPrograms {
public static void main(String[] args) {
int number;
// create an object of Scanner class
Scanner sc = new Scanner(System.in);
// ask users to enter numbers
System.out.println("Enter a number: ");
number = sc.nextInt();
int sum = addNumbers(number);
System.out.println("Sum = " + sum);
sc.close();
}
public static int addNumbers(int num) {
if (num != 0)
return num + addNumbers(num - 1);
else
return num;
}
}
```

Enter a number:

55

Sum = 1540

- First, we take the input from the user and the number whose sum is to be found is stored in a variable

.**number** - Initially, the

is a recursive method which is called from the main() function and we take 55 as input and pass it as an argument.**addNumbers()** - The

(55) is added to the result of**number**

.**addNumbers(19)** - In the next function call from

to**addNumbers()**

, 54 is passed which is added to the result of**addNumbers()**

. This process continues until**addNumbers(53)****num**is equal to 0. - When

is equal to**num****0**, there is no recursive call and this returns the sum of integers to the

function.**main()**

## Comments