Untitled
unknown
plain_text
10 months ago
1.3 kB
5
Indexable
import java.util.Scanner; public class RandomMatrix { public static void main(String[] args) { Scanner scanner = new Scanner(System.in); System.out.print("Enter number of rows: "); int rows = scanner.nextInt(); System.out.print("Enter number of columns: "); int cols = scanner.nextInt(); int[][] matrix = new int[rows][cols]; int zeroCount = 0; int oneCount = 0; // Fill the matrix with random 0s and 1s for (int i = 0; i < rows; i++) { for (int j = 0; j < cols; j++) { int randomValue = (int) (Math.random() * 2); // 0 or 1 matrix[i][j] = randomValue; if (randomValue == 0) { zeroCount++; } else { oneCount++; } } } // Display the matrix System.out.println("Matrix:"); for (int i = 0; i < rows; i++) { for (int j = 0; j < cols; j++) { System.out.print(matrix[i][j] + " "); } System.out.println(); } // Display the counts System.out.println("Number of 0s: " + zeroCount); System.out.println("Number of 1s: " + oneCount); } }
Editor is loading...
Leave a Comment