Programming Examples

Java recursive function to find the sum of first n natural numbers


Write a Java Program using recursion to find the sum of first n natural numbers.

import java.util.*;
class NaturalSum
{
    
    int sum(int n)
    {
       if(n==0)
       {
           return 0;
       }
       else
       {           
           return (n+sum(n-1));
       }
       
    }    
    public static void main(String arr[])
    {
        Scanner sc=new Scanner(System.in);
        System.out.println("Enter the value of n : ");
        int n=sc.nextInt();
        NaturalSum obj=new NaturalSum();
        int ans=obj.sum(n);
        System.out.println("Sum first "+n+" natural numbers are: "+ans);
        
    }
}
Output

Enter the value of n : 

10

Sum first 10 natural numbers are: 55

CCC Online Test 2021 CCC Practice Test Hindi Python Programming Tutorials Best Computer Training Institute in Prayagraj (Allahabad) Best Java Training Institute in Prayagraj (Allahabad) Best Python Training Institute in Prayagraj (Allahabad) O Level Online Test in Hindi Bank SSC Railway TET UPTET Question Bank career counselling in allahabad Sarkari Naukari Notification Best Website and Software Company in Allahabad Sarkari Exam Quiz