Write a JAVA program that contains a recursive method that c

Write a JAVA program that contains a recursive method that computes the sum of all elements of an array of integers by using recursion. Include testing of the recursive method in the main method of the class.

Solution

SumOfArrayElementsUsingRecursion.java

public class SumOfArrayElementsUsingRecursion {

   public static void main(String[] args) {
      
       //Declaring and initializing the integer type array
       int arr[] = { 2, 3, 4, 5, 6, 7, 8, 9, 11, 22, 33, 44, 55, 66, 77, 88,99,43,56,72,34 };
      
       //finding the size of the array
       int size = arr.length;
      
       //calling the recursive function by passing the array and size as arguments
       int sum = recursiveFun(arr, size - 1);
      
       //Displaying the sum of elements in the array
       System.out.println(\"The Sum of Array Elements are :\" + sum);

   }

   /* This is a recursive function which calculates the sum of array elements
   * params :integer array ,size of the array-1
   * Return : sum of array elements
   */
   private static int recursiveFun(int[] arr, int size) {
       if (size < 0) {
           return 0;
       } else {
           return (arr[size] + recursiveFun(arr, size - 1));
       }

   }

}

_____________________________________________

output:

The Sum of Array Elements are :744

_____________Thank You.

Write a JAVA program that contains a recursive method that computes the sum of all elements of an array of integers by using recursion. Include testing of the r

Get Help Now

Submit a Take Down Notice

Tutor
Tutor: Dr Jack
Most rated tutor on our site