JAVA – Write a recursive method that takes a positive integer nand find the sum of all the integers from 0 to n. Then test yourmethod with a few values. Your solution must be recursive.
Answer
Solution:
import java.util.*;
class Main
{
public static void main(String[] args)
{
int n;
Scanner sc = new Scanner(System.in);
System.out.print(“Enter positive integer n: “);
n = sc.nextInt();
int sum = addNumbers(n);
System.out.println(“Sum of all the integers from 0 to ” +n+ ” =” + sum);
}
//recursive method to find sum of all the integers from 0 ton
public static int addNumbers(int num)
{
if (num != 0)
return num + addNumbers(num – 1);
else
return num;
}
}
Output:
Please
OR
OR