Write a complete Java program to recursively find the SUM from 0 to N for a non-negative integer N.
Also, design an exception class to handle the negative number entered by the user.
Java code pasted below.
import java.util.Scanner;
public class AddN {
public static void main(String[] args) {
//scanner object for reading the number
Scanner sc=new Scanner(System.in);
System.out.println("Enter N:");
int number=sc.nextInt();
int sum;
try{
//calling recursive function
sum = addN(number);
System.out.println("Sum = " + sum);
}catch(Exception e){System.out.println(e);}
}
//recursive function with exception is thrown with negative
number
public static int addN(int num)throws Exception {
if(num<0)
throw new Exception("Number is negative,Enter a positive
number!");
if (num != 0)
return num + addN(num - 1);
else
return num;
}
}
Output Screen - Test case 1
Output Screen - Test case 2
Get Answers For Free
Most questions answered within 1 hours.