In: Computer Science
To the TwoDArray class, add a method called sumCols() that sums the elements in each column and displays the sum for each column. Add appropriate code in main() of the TwoDArrayApp class to execute the sumCols() method.
/**
* TwoDArray.java
*/
public class TwoDArray
{
private int a[][];
private int nRows;
public TwoDArray(int maxRows, int maxCols) //constructor
{
a = new int[maxRows][maxCols];
nRows = 0;
}
//******************************************************************
public void insert (int[] row)
{
a[nRows] = row;
nRows++;
}
//******************************************************************
public void display()
{
for (int i = 0; i < nRows; i++)
{
for (int j = 0; j < a[0].length; j++)
System.out.format("%5d", a[i][j]);
System.out.println(" ");
}
}
}
/**
* TwoDArrayApp.java
*/
public class TwoDArrayApp
{
public static void main(String[] args)
{
int maxRows = 20;
int maxCols = 20;
TwoDArray arr = new TwoDArray(maxRows, maxCols);
int b[][] = {{1, 2, 3, 4}, {11, 22, 33, 44}, {2, 4, 6, 8},{100, 200, 300,
400}};
arr.insert(b[0]); arr.insert(b[1]); arr.insert(b[2]); arr.insert(b[3]);
System.out.println("The original matrix: ");
arr.display();
}
}
/** * TwoDArray.java */ public class TwoDArray { private int a[][]; private int nRows; public TwoDArray(int maxRows, int maxCols) //constructor { a = new int[maxRows][maxCols]; nRows = 0; } //****************************************************************** public void insert(int[] row) { a[nRows] = row; nRows++; } public void sumCols() { for (int i = 0; i < a[0].length; i++) { int sum = 0; for (int j = 0; j < nRows; j++) { sum += a[j][i]; } System.out.println("Sum of all elements of column " + i + " is " + sum); } } //****************************************************************** public void display() { for (int i = 0; i < nRows; i++) { for (int j = 0; j < a[0].length; j++) System.out.format("%5d", a[i][j]); System.out.println(" "); } } }
/** * TwoDArrayApp.java */ public class TwoDArrayApp { public static void main(String[] args) { int maxRows = 20; int maxCols = 20; TwoDArray arr = new TwoDArray(maxRows, maxCols); int b[][] = {{1, 2, 3, 4}, {11, 22, 33, 44}, {2, 4, 6, 8}, {100, 200, 300, 400}}; arr.insert(b[0]); arr.insert(b[1]); arr.insert(b[2]); arr.insert(b[3]); System.out.println("The original matrix: "); arr.display(); arr.sumCols(); } }