In: Computer Science
***JAVA PROGRAM
Write a method called shrink that accepts an array of integers (that the user inputs) as a parameter and returns a new array containing the result of replacing each pair of integers with the sum of that pair. For example, if an array called list stores the values {7, 2, 8, 9, 4, 15, 7, 1, 9, 10}, then the call of shrink(list) should return a new array containing {9, 17, 19, 8, 19}.
The first pair from the original list is shrunken into 9 (7 + 2),
the second pair is shrunken into 17 (8 + 9), and so on.
If the list stores an odd number of elements, the final element is not collapsed. For example, if the list had been {1, 2, 3, 4, 5}, then the call would return {3, 7, 5}. Your method should not change the array that is passed as a parameter.
Be sure to have a shrink() method
*All variable names are completely up to you, as long as they’re descriptive
*Use the correct data types
*Use comments to explain what you’re coding
*Put your name in a comment
import java.util.Arrays;
public class ArrayShrinkExample {
public static void main(String[] args) {
int arr[]={7, 2,
8, 9, 4, 15, 7, 1, 9, 10};
System.out.println(Arrays.toString(shrink(arr)));
int arr2[]={1,
2, 3, 4, 5};
System.out.println(Arrays.toString(shrink(arr2)));
}
public static int [] shrink(int arr[]) {
int size;
if(arr.length%2==0)
size=arr.length/2;
else
size=arr.length/2+1;
int res[]= new int[size];
for(int
i=0,j=0;i<arr.length-1;i+=2,j++) {
res[j]=arr[i]+arr[i+1];
}
if(arr.length%2==1) {
res[res.length-1]=arr[arr.length-1];
}
return res;
}
}
Note : Please comment below if you have concerns. I am here to help you
If you like my answer please rate and help me it is very Imp for me