In this article, you’ll learn how to get the sum of n numbers using a recursion function. Recursion function is said to be calling itself over and over again in the application. By using recursive functions, we can remove the side effects of the looping structures. It is essential to define the base case or the terminating condition correctly in a recursive function. Otherwise, it will lead to an infinite loop.

Sum of N Numbers Using Recursion in Java

In most of the cases, base condition checks whether the number is equal to zero or not. But this will change based on the logic that we are trying to express in the method. The structure of the recursive function is always the same. There should be a condition which calls the same function over and over again, and the other is the base condition. Base condition still takes the else part in the if and else conditional statement.

Below is the function to get the sum of N Number using Recursion in Java.

public static void main(String[] args) {
	int number;
	//get the input from the user
	System.out.println("Enter the number: ");
	Scanner input = new Scanner(System.in);
	//convert string into an integer
	number = input.nextInt();
	      
	//call the method
	int total = getTotal(number);
	System.out.println("Sum = " + total);
	//close the scanner instance
	 input.close();
}

Now call the function from the main menu

public static int getTotal(int number) {
	//check whether the number not equals to zero
	if (number != 0) {
	//recursively calling the function
	    return number + getTotal(number - 1);
	}
	//return the total when the number becomes zero
	else {
	      return number;
	}
}

Code Explanation

In the example above, the getTotal() method is the recursive function, and it takes one integer number as the argument. This method will call itself again and again after checking whether the number is not equivalent to zero. When the base condition (number == 0) is not met, we will be recursively calling the function until the base condition is met. When the base condition is satisfied, all the values will be added together and returned as one value through the else block.

Example

For example: If the user enters 5; recursive function will add 5+4+3+2+1 and return the total.

As we are calling this method from the main method, we have made this method a static method. When we use a static method, there is no requirement to create an instance of the class and calling that method. Also, we are taking the input number from the user and convert it to integer from string format before passing it into the recursive function.

Output:

Enter the number:

90

Sum = 4095

 

Enter the number:

20

Sum = 210

Recommended Reading

Last modified: March 17, 2019

Comments

Write a Reply or Comment

Your email address will not be published.