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 if...else
conditions, and java recursion methods.
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
number
.addNumbers()
is a recursive method which is called from the main() function and we take 55 as input and pass it as an argument.number
(55) is added to the result of addNumbers(19)
.addNumbers()
to addNumbers()
, 54 is passed which is added to the result of addNumbers(53)
. This process continues until num is equal to 0.num
is equal to 0, there is no recursive call and this returns the sum of integers to the main()
function.
Comments