In: Computer Science
JAVA
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
CODE -
import java.util.Scanner;
import java.util.Random;
public class matrix {
// FUNCTION TO FIND AND DISPLAY SUM OF EACH COLUMN OF THE MATRIX AT EVEN INDEX
static void sumColumns(int[][] matrix)
{
// FINDING THE NUMBER OF ROWS IN THE MATRIX
int row = matrix.length;
// FINDING THE NUMBER OF COLUMNS IN THE MATRIX
int column = matrix[0].length;
// LOOP TO FIND AND PRINT SUM OF EACH COLUMNS AT EVEN INDEX
for(int i=0; i<column; i = i+2)
{
int sum_column = 0;
for(int j=0; j<row; j++)
sum_column += matrix[j][i];
System.out.print(sum_column + " ");
}
}
// MAIN FUNCTION
public static void main(String[] args)
{
int row, column;
Scanner keyboard = new Scanner(System.in);
Random rand = new Random();
// TAKING NUMBER OF ROW AND NUMBER OF COLUMN AS INPUT FROM THE USER
System.out.print("Enter number of rows and columns ");
row = keyboard.nextInt();
column = keyboard.nextInt();
// CREATING A MATRIX OF SIZE ENTERED BY THE USER
int[][] matrix = new int[row][column];
// FILLING THE MATRIX RANDOMLY WITH 0 AND 1
for(int i=0; i<row; i++)
for(int j=0; j<column; j++)
matrix[i][j] = rand.nextInt(2);
// DISPLAYING THE MATRIX
for(int i=0; i<row; i++)
{
for(int j=0; j<column; j++)
System.out.print(matrix[i][j] + " ");
System.out.println();
}
// CALLING THE sumColumns FUNCTION.
sumColumns(matrix);
keyboard.close();
}
}
SCREENSHOTS -
CODE -
OUTPUT -
If you have any doubt regarding the solution, then do
comment.
Do upvote.