Answer:
1) Method calcTotal:
- public static long calcTotal(long [][] arr2D){
- long total = 0;
-
- for(int i = 0; i < arr2D.length; i++ )
- {
- for(int j = 0; j < arr2D[i].length; j++)
- {
- total = total + arr2D[i][j];
- }
- }
-
- return total;
- }
Explanation:
Line 1: Define a public method <em>calcTotal</em> and this method accept a two-dimensional array
Line 2: Declare a variable, total, and initialize it with zero.
Line 4: An outer for-loop to iterate through every rows of the two-dimensional array
Line 6: An inner for-loop to iterate though every columns within a particular row.
Line 8: Within the inner for-loop, use current row and column index, i and j, to repeatedly extract the value of each element in the array and add it to the variable total.
Line 12: Return the final total of all the element values as an output
Answer:
2) Method calcAverage:
- public static double calcAverage(long [][] arr2D){
- double total = 0;
- int count = 0;
-
- for(int i = 0; i < arr2D.length; i++ )
- {
- for(int j = 0; j < arr2D[i].length; j++)
- {
- total = total + arr2D[i][j];
- count++;
- }
-
- }
-
- double average = total / count;
-
- return average;
- }
Explanation:
The code in method <em>calcAverage</em> is quite similar to method <em>calcTotal</em>. We just need to add a counter and use that counter as a divisor of total values to obtain an average.
Line 4: Declare a variable, count, as an counter and initialize it to zero.
Line 11: Whenever an element of the 2D array is added to the total, the count is incremented by one. By doing so, we can get the total number of elements that exist in the array.
Line 16: Use the count as a divisor to the total to get average
Line 18: Return the average of all the values in the array as an output.
Answer:
3) calcRowAverage:
- public static double calcRowAverage(long [][] arr2D, int row){
- double total = 0;
- int count = 0;
-
- for(int i = 0; i < arr2D.length; i++ )
- {
- if(i == row)
- {
- for(int j = 0; j < arr2D[i].length; j++)
- {
- total = total + arr2D[i][j];
- count++;
- }
- }
-
- }
-
- double average = total / count;
-
- return average;
- }
Explanation:
By using method <em>calcAverage </em>as a foundation, add one more parameter, row, in the method <em>calcRowAverage</em>. The row number is used as an conditional checking criteria to ensure only that particular row of elements will be summed up and divided by the counter to get an average of that row.
Line 1: Add one more parameter, row,
Line 8-15: Check if current row index, i, is equal to the target row number, proceed to sum up the array element in that particular row and increment the counter.