Create an integer 1D array \"arrayId\" with size 8 and initialize the array with
ID: 3773318 • Letter: C
Question
Create an integer 1D array "arrayId" with size 8 and initialize the array with the following numbers -4, 6, -15, 21. 29, 54, -23, -2 There are four positive numbers and four negative numbers in array 1d Create an integer 2D array called *array2d" with size of 2 Times 4. Write a method separateNumbers (array 1d, array2d) and does the following task Access the 1D array, copy positive numbers into the first row of the 2D array negative numbers into the 2^nd row of the 2D array Write a separate method calcLargerRow(array2d) which takes the 2D array as the argument and print out the row index with a larger absolute sumExplanation / Answer
package com.example.se;
/**
* @author Srinivas Palli
*
*/
public class ArrayLargerSum {
/**
* @param args
*/
public static void main(String[] args) {
try {
int array1d[] = { -4, 6, -15, 21, 29, 54, -23, -2 };
int array2d[][] = new int[2][4];
array2d = separateNumbers(array1d);
System.out.println("array2d elements:");
for (int i = 0; i < array2d.length; i++) {
for (int j = 0; j < array2d[i].length; j++) {
System.out.print(array2d[i][j] + " ");
}
System.out.println();
}
calcLargerRow(array2d);
} catch (Exception e) {
// TODO: handle exception
}
}
public static int[][] separateNumbers(int[] array1d) {
int array2d[][] = new int[2][4];
int positiveCount = 0, negativeCount = 0;
for (int i = 0; i < array1d.length; i++) {
if (array1d[i] > 0) {
array2d[0][positiveCount++] = array1d[i];
} else {
array2d[1][negativeCount++] = array1d[i];
}
}
return array2d;
}
public static void calcLargerRow(int array2d[][]) {
int firstRowSum = 0, secondRowSum = 0;
for (int i = 0; i < 4; i++) {
firstRowSum += array2d[0][i];
secondRowSum += Math.abs(array2d[1][i]);
}
if (firstRowSum > secondRowSum) {
System.out.println("First row sum is greater:" + firstRowSum);
} else {
System.out.println("second row absolute sum is greater :"
+ secondRowSum);
}
}
}
OUTPUT:
array2d elements:
6 21 29 54
-4 -15 -23 -2
First row sum is greater:110
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.