Google Add

Search

Program to Find Sum of N Natural Numbers using Recursion in Java

Write a program to find sum of N natural numbers using recursion in Java. In this program user will input any positive number (n) and we find sum of n  number.

For example - If user has input 9. Then their sum is

9 + 8 + 7 + 6 + 5 + 4 + 3 + 2 + 1 = 45

If you are not familiar with the concept of recursion then check below posts which help you to understand this concept.

Recursion concept.

Difference between recursion and iteration

MCQ on recursion

Program to find sum of n natural numbers in C, C++

Logic to Find Sum of N Natural Numbers using Recursion

i) Take input from user.

ii) Define base case and recursively call method.

public static int Summation (int n) {
        
        /* Base case */

        if ( n <= 0) {
            
            return 0;
            
        } else {
            
            /* Recursive call */

            return n + Summation (n-1); 
        }

Suppose if user has input 9. Then the method will call like this.

9 + Summation (8)
9 + 8 + Summation (7)
9 + 8 + 7 + Summation (6)
9 + 8 + 7 + 6 + Summation (5)
9 + 8 + 7 + 6 + 5 + Summation (4)
9 + 8 + 7 + 6 + 5 + 4 + Summation (3)
9 + 8 + 7 + 6 + 5 + 4 + 3 + Summation (2)
9 + 8 + 7 + 6 + 5 + 4 + 3 +  2 + Summation (1)

After this step the base condition is reached so the value is returned.

Java Programs

Program to Find Sum of N Natural Numbers using Recursion in Java


import java.util.*;

public class Recursionp {

    
    public static int Summation (int n) {
        
        // Base case
        
        if ( n <= 0) {
            
            return 0;
            
        } else {
            
            // Recursive call
            
            return n + Summation (n-1); 
        }
    }
    /**
     * @param args the command line arguments
     */
    public static void main(String[] args) {

        int  num;
        
        Scanner inp = new Scanner(System.in);
        System.out.println("\n Please enter number ");
        
        num = inp.nextInt();
        
        System.out.println ("\n The summation of number is "+Summation(num));
        
    }
    
}

No comments:

Post a Comment