Java Program to Find the Sum of Natural Numbers Using Recursion

In this post, we will learn to code the Java Program to Find the Sum of Natural Numbers Using Recursion. Let’s see the Sum of Natural Numbers using recursion in Java Programming Language.

What are Natural Numbers?

Natural Numbers are a part of the number system. They include all the positive numbers from 1 to infinity.
For example, 1, 2, 3, 4, 5, . . . . , ∞ (infinity) These are Natural Number

let’s see the Sum of N Natural Numbers where N is 10.

1 + 2 + 3 + 4 + 5 + 6 + 7 + 8 + 9 + 10 = 55

Now, let’s see the Sum of Natural Numbers Using Recursion in Java Programming Language.

Java Program to Find the Sum of Natural Numbers Using Recursion

import java.util.*;

public class Main{
    
    public static int sumOfNaturalNumbers(int N){
        if(N == 1){
            return 1;
        }
        return N + sumOfNaturalNumbers(N-1);
    }
    
    public static void main(String[] args){
        
        Scanner sc = new Scanner(System.in);
        System.out.println("Enter the value of N :");
        int N = sc.nextInt();
        
        int sum = sumOfNaturalNumbers(N);
        System.out.println("Sum of N Natural Numbers are "+sum);
        
    }
    
}

Output

Enter the value of N : 10
Sum of N Natural Numbers are 55

How Does This Program Work?

        Scanner sc = new Scanner(System.in);
        System.out.println("Enter the value of N :");
        int N = sc.nextInt();

In this program, we take the input of N from the user using the Scanner Class in Java.

        int sum = sumOfNaturalNumbers(N);

Then, we call the recursive function sumOfNaturalNumbers() which gives the sum of N natural numbers.

    public static int sumOfNaturalNumbers(int N){
        if(N == 1){
            return 1;
        }
        return N + sumOfNaturalNumbers(N-1);
    }

In this recursive function, we put the base case as return 1 if N is 1. i.e. Sum of Natural numbers till 1 is 1.

We return the sum of N and call the same function for value N-1. At last, we get the sum of the natural numbers till N in the sum variable in the main function.

        System.out.println("Sum of N Natural Numbers are "+sum);

Then, we display the sum of N natural numbers. This is the Java Program to Find the Sum of Natural Numbers Using Recursion.

Conclusion

I hope after going through this post, you understand Java Program to Find the Sum of Natural Numbers Using Recursion.
If you have any doubt regarding the topic, feel free to contact us in the comment section. We will be delighted to help you.

Also Read:

Leave a Comment

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