Write a method named collapse that accepts an array of integers as a parameter and returns a new array where each pair of integers from the original array has been replaced by the sum of that pair. For example, if an array called a stores {7, 2, 8, 9, 4, 13, 7, 1, 9, 10}, then the call of collapse(a) should return a new array containing {9, 17, 17, 8, 19}. The first pair from the original list is collapsed into 9 (7 2), the second pair is collapsed into 17 (8 9), and so on.

Respuesta :

Answer:

The method in Java is as follows:

public static void collapse(int [] myarr) {  

       int [] arr = new int[myarr.length/2];

       int k = 0;

       for (int i = 0;i<myarr.length;i+=2){

           arr[k] = myarr[i]+myarr[i+1];

           k++;

       }

       for (int i = 0;i<myarr.length/2;i++){

           System.out.print(arr[i]+" ");

       }

   }  

Explanation:

This defines the collapse method

public static void collapse(int [] myarr) {  

This declares a new array

       int [] arr = new int[myarr.length/2];

This declares and initializes k to 0

       int k = 0;

This iterates through the array passed as argument

       for (int i = 0;i<myarr.length;i+=2){

This calculates the elements of the new array

           arr[k] = myarr[i]+myarr[i+1];

           k++;

       }

The following iteration returns and prints the elements of the new array

       for (int i = 0;i<myarr.length/2;i++){

           System.out.print(arr[i]+" ");

       }

   

See attachment for complete program which includes the main

Ver imagen MrRoyal
ACCESS MORE
EDU ACCESS