Academic Integrity: tutoring, explanations, and feedback — we don’t complete graded work or submit on a student’s behalf.

Programming Practice Create a method: public static int[] productOfColumns(int[]

ID: 3718235 • Letter: P

Question

Programming Practice

Create a method: public static int[] productOfColumns(int[][] matrix)

Takes a rectangular matrix and produces an array containing the product of each column. The returned array must have length equal to the number of columns in the matrix and the ith entry must contain the product of the ith column. You may assume that if matrix is not null then it is nonempty and all rows are nonempty with the same length. Essentially if matrix is not null, then its no smaller (dimension wise) than {{1}}. If matrix is null, it should return null. E.g. If matrix = {{1, 2, 3}, {2, 2, 0}} this would return {2, 4, 0}; if matrix = {{1,2},{3,4},{5,6}}, this would return {15, 48}.

Parameters: matrix — A rectangular 2-d array of ints.

Returns: An array containing the product of each column.

Explanation / Answer

ProductOfMatrixCols.java

public class ProductOfMatrixCols {

public static void main(String[] args) {

//Declaring 2-D matrix

int matrix[][]= {{1, 2, 3}, {2, 2, 0}};

//calling the method by passing the 2-D array as argument

int matrixColProd[]=productOfColumns(matrix);

//Displaying the Resultant Matrix

System.out.println("Displaying the Result :");

for(int i=0;i<matrixColProd.length;i++)

{

System.out.print(matrixColProd[i]+" ");

}

System.out.println();

}

//This method will find the product of columns of 2-D matrix

private static int[] productOfColumns(int[][] matrix) {

int cols=matrix[0].length;

int res[]=null;

if(matrix==null)

{

return null;

}

else

{

res=new int[cols];

int prod;

for(int i=0;i<matrix[0].length;i++)

{

prod=1;

for(int j=0;j<matrix.length;j++)

{

prod*=matrix[j][i];

}

res[i]=prod;

}

}

return res;

}

}

_____________________

Output:

Displaying the Result :
2 4 0

______________

ProductOfMatrixCols.java

public class ProductOfMatrixCols {

public static void main(String[] args) {

//Declaring 2-D matrix

int matrix[][]={{1,2},{3,4},{5,6}};

//calling the method by passing the 2-D array as argument

int matrixColProd[]=productOfColumns(matrix);

//Displaying the Resultant Matrix

System.out.println("Displaying the Result :");

for(int i=0;i<matrixColProd.length;i++)

{

System.out.print(matrixColProd[i]+" ");

}

System.out.println();

}

//This method will find the product of columns of 2-D matrix

private static int[] productOfColumns(int[][] matrix) {

int cols=matrix[0].length;

int res[]=null;

if(matrix==null)

{

return null;

}

else

{

res=new int[cols];

int prod;

for(int i=0;i<matrix[0].length;i++)

{

prod=1;

for(int j=0;j<matrix.length;j++)

{

prod*=matrix[j][i];

}

res[i]=prod;

}

}

return res;

}

}

____________________

Output:

Displaying the Result :
15 48

______________Thank You