Java Write Recursive Method Takes Positive Integer N Find Sum Integers 0 N Test Method Val Q37191189

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:

@anonymous/DeadlyUpsetQuadrants share + new repl languages talk Sign up No description saved java version 1.8.0 31 Java (TM

Please

OR
OR

Leave a Comment

This site uses Akismet to reduce spam. Learn how your comment data is processed.