2D Arrays: Y o ur ta s k is t o w ri t e t w o m e t h o d s t h a t u s e a t w
ID: 3555413 • Letter: 2
Question
2D Arrays:
Your task is to write two methods that use a two-dimensional array as input and return a one-dimensional array that contains the row-by-row average or the column- by-column average, as directed. Name your class TwoDaverage, which shall contain the two methods described below. Include the usual comments for the class: source file name, and a brief description.
Row by Row Average Method
Name this method rowAverage. The input parameter for rowAverage() is a rectangular, two-dimensional array of doubles. rowAverage() returns a one-dimensional array of doubles whose length is the number of rows in the two-dimensional input array and whose values are the averages of each row. For example, the zeroth element of the one-dimensional array that is returned is the average of all the values in the zeroth row of the two-dimensional array.
Column by Column Average Method
Name this method columnAverage. The input parameter is the same as for rowAverage().
columnAverage() returns a one-dimensional array of doubles whose length is the number of columns in the two-dimensional input array and whose values are the averages of each column.
I need help. I cant figure out how to do this!!
Explanation / Answer
/* package whatever; // don't place package name! */
//Source File name : TwoDaverage.java
//Store input into the format of 2D array
//Pass it to rowAverage to get average of rows
//Pass it to columnAverage to get average of columns
import java.util.*;
import java.lang.*;
import java.io.*;
class TwoDaverage
{
public static double[] rowAverage(double[][] inputarray)
{
int n1=inputarray.length;//no of rows
double result[]=new double[n1];
for(int i=0;i<n1;i++)
{
int n2 =inputarray[i].length;//no of columns
double sum=0;
for(int j=0;j<n2;j++)
{
result[i]+=inputarray[i][j];
}
result[i]=result[i]/n2;
}
return result;
}
public static double[] columnAverage(double[][] inputarray)
{
int n1=inputarray.length;//no of rows
int n2=inputarray[0].length;//no of columns
double result[]=new double[n2];
for(int i=0;i<n2;i++)
{
for(int j=0;j<n1;j++)
{
result[i]+=inputarray[j][i];
}
result[i]=result[i]/n1;
}
return result;
}
public static void main (String[] args) throws java.lang.Exception
{
// your code goes here
double array[][]={{1,2},{2,3},{3,4}}; //Sample Input
double rowresult[]=rowAverage(array);
double columnresult[]=columnAverage(array);
for(int i=0;i<rowresult.length;i++)
System.out.println("Row Average "+i+": "+rowresult[i]);
for(int j=0;j<columnresult.length;j++)
System.out.println("Column Average "+j+": "+columnresult[j]);
}
}
//Link for ideone to verify: http://ideone.com/2F1lUp
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.