;

Java Program to Find the Sum of Natural Numbers using Recursion


Tutorialsrack 06/11/2021 Java

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.

Example - Java 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;
	}

}
Output

Enter a number: 

55

Sum = 1540

Working of Program

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


Related Posts



Comments

Recent Posts
Tags