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
Here is the solution. Please do upvote thank you.
import java.util.*;
import java.lang.Math;
public class Main
{
public static void main(String args[])
{
int max=1;
int min=0;
int range=max-min+1;
int rows;
int columns;
int count=0;
Scanner sc=new Scanner(System.in);
rows=sc.nextInt();
columns=sc.nextInt();
int matrix[][]=new int[rows][columns];
for(int i=0;i<rows;i++)
{
for(int j=0;j<columns;j++)
{
int r=(int)(Math.random()*range)+min;
matrix[i][j]=r;
}
}
for(int i=0;i<rows;i++)
{
for(int j=0;j<columns;j++)
{
System.out.print(matrix[i][j]);
System.out.print(" ");
}
System.out.println();
}
System.out.println();
for(int j=0;j<columns;j++)
{
if(j%2==0)
{
count=0;
for(int y=0;y<rows;y++)
{
if(matrix[y][j]==1)
count+=1;
}
System.out.print(count);
System.out.print(" ");
}
}
System.out.println();
}
}