Java Program to Find the Sum of Natural Numbers using Recursion

In this Java program, you’ll learn how to Find the Sum of Natural Numbers using Recursion using the Java programming language.  

How to Find the Sum of Natural Numbers using Recursion in JAVA? 

Example 1: 

RUN CODE SNIPPET
public class Main  
{ 
    public static void main(String[] args)  
    { 
        int number = 50; 
        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; 
    } 
}

OUTPUT 

Sum = 1275

The sum of the numbers is to be stored in the variable number. 

From the main function, the addnumbers is called and an argument 50 is passed. 

Initially, the number is added to the results of addnumbers(49), and then the next function call from addnumbers to addnumbers continues. 

The recursion is stopped when the number becomes 0. 

Share:

Leave A Reply

Your email address will not be published. Required fields are marked *

You May Also Like

In this Java program, we will learn how to find the GCD of two numbers using Java.  GCD (Greatest Common...
  • Java
  • December 3, 2024
In this Java Program, you’ll learn how to swap two numbers using the Java programming language.  How to Swap Two...
  • Java
  • December 2, 2024
In this Java program , we will learn how to Find Largest Element in an Array in your Java program.   How to Find Largest Element...
  • Java
  • December 2, 2024