Write a Java method that takes an integer array as parameter and decides whether the array has an element such that the sum of all elements that are on the left side of that element equals that element, and the sum of all elements that are on the right side of that element also equals that element. If such an element exists in the array the method returns true. If such an element does not exist in the array the method returns false. Assume the array length is at least three. For example if the array is [3 -5 10

Respuesta :

Answer:

Here is the JAVA method:

  static boolean ElementEqualSum(int array[])  //definition of boolean type method that takes an array as argument

   {   int size;  //to store the size of the array

       size = array.length;  //assigns the length of the array to size variable

      int[] leftSum = new int[size];  // creates an array to store sum of left side

       leftSum[0] = array[0];  //sets the element at 0-th index (first element) of array to that of 0-th index of leftSum array

       for (int i = 1; i < size; i++)  //iterates through the array

           leftSum[i] = leftSum[i - 1] + array[i];  //sum of elements at left side of each element is taken at each iteration and the result is stored in leftSum array        

       int[] rightSum = new int[size];  //creates an array to store sum of right side

       rightSum[size - 1] = array[size - 1];  //sets the element at size - 1 index (last element) of array to that of size-1 index of rightSum array

       for (int i = size - 2; i >= 0; i--)   //iterates through the array backwards

           rightSum[i] = rightSum[i + 1] + array[i];  //sum of elements at right side of each element is taken at each iteration and the result is stored in rightSum array    

       for (int i = 1; i < size - 1; i++)  //iterates through the array till the end of the array is reached

           if (leftSum[i] == rightSum[i]) /*finds the element where leftSum and rightSum are same which means it finds the index of element such that the sum of all elements that are on the left side of that element equals that element, and the sum of all elements that are on the right side of that element also equals that element */

               return true;  //return true if such element exists and satisfied above if condition       

       return false;}  //returns false if no such element that satisfies the above if condition

   

Explanation:

In order to check the working of the above program, you can call this function in main passing it an array.

public static void main(String args[])     {  //start of main method

       int arr[] = {3,-5, 10, 1, 9, 3, 6} ;  //declare and initialize the arrays with elements

       System.out.println(ElementEqualSum(arr));     } } //calls method passing array to it

For detailed explanation of the program see the attached document.

Ver imagen mahamnasir
Ver imagen mahamnasir