Question
Print sum of first N th natural number using recursion
ENTER Nth TERM 10
Sum of first 10 NATURAL NUMBER: 55
Share code with your friends
Share on whatsapp
Share on facebook
Share on twitter
Share on telegram
Code
import java.util.Scanner;
public class AddFirstNNaturalNumber
{
public static int Sum(int num)
{
if(num==0)
{
return 0;
}
else
{
return num+Sum(num-1);
}
}
public static void main(String args[])
{
int num=0,sum=0;
Scanner sc=new Scanner(System.in);
System.out.print("ENTER Nth TERM ");
num=sc.nextInt();
sum=Sum(num);
System.out.println("Sum of first "+num+" NATURAL NUMBER: "+sum);
}
}