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

Java is a popular programming language that is used to develop a wide range of applications. If you are a...
  • Java
  • March 6, 2023
Java is a programming language and computing platform that is used to create various types of applications. It is used...
  • Java
  • March 6, 2023
In this post, you’ll learn how to download and install JUnit in Eclipse so that you can use in your...
  • Java
  • October 9, 2022