In: Computer Science
JAVA posted multiple times
Write a program that prompts the user to enter a matrix number
of rows and number of columns.
In main method create 2D matrix based on the number of rows and
columns input by the user; randomly fills the matrix with 0s and 1s
and prints it.
Create method sumColumns that takes only the matrix you created in
main method and find the sum of each column with even index and
prints it. Do not use global variables.
Here is a sample run of the program:
Enter number of rows and columns 4 6
1 0 0 0 1 0
0 0 0 0 1 0
1 0 1 0 1 1
1 1 1 1 0 1
3 2 3
Process finished with exit code 0
Please find the answer below.
Please do comments in case of any issue. Also, don't forget to rate
the question. Thank You So Much.
Matrix.java
package staticclasses;
import java.util.Random;
import java.util.Scanner;
public class Matrix {
static void sumColumns(int matrix[][]) {
for (int j = 0; j <
matrix[0].length; j++) {
if(j%2==0)
{
int sum=0;
for (int i = 0; i < matrix.length; i++)
{
sum +=matrix[i][j];
}
System.out.print(sum+" ");
}
}
}
public static void main(String[] args) {
Scanner sc = new
Scanner(System.in);
System.out.print("Enter number of
rows and columns ");
int row,column;
row = sc.nextInt();
column = sc.nextInt();
int matrix[][] = new
int[row][column];
Random rand = new Random();
for (int i = 0; i < row; i++)
{
for (int j = 0;
j < column; j++) {
matrix[i][j]= rand.nextInt(2);
System.out.print(matrix[i][j]+" ");
}
System.out.println();
}
sumColumns(matrix);
}
}