Create matrix of random numbers in Java

In this tutorial ,we will learn how to create matrix through using the  random numbers as input in java. By using this we can create our required matrix.

If you don’t know how to create a matrix of random numbers in java then you are at the right place. Because in this tutorial we gonna find how to create a matrix of random numbers in java.

Initialize the Matrix

we have to declare and initiate a  two-dimensional array (matrix) with the our required dimensions.

Format:

int[][] matrix = new int[m][n];

here m-number of desired rows

n-number of desired columns

Example:

if we want to create a 3×3 matrix then:

int[][] matrix = new int[3][3];

Fill the Matrix with Random Numbers

In this case we can use Random class to generate the random integers. We can use in different approaches like-

  • By using Random#ints (for integers)
import java.util.Random;

     // ...

     Random random = new Random();
     int[] sortedRandoms = random.ints(25, 1, 101).sorted().toArray();
     int index = 0;

     for (int i = 0; i < matrix.length; i++) {
         for (int j = 0; j < matrix[i].length; j++) {
             matrix[i][j] = sortedRandoms[index++];
         }
     }
     

  • By Using Math.random() (for double values)
for (int i = 0; i < matrix.length; i++) {
        for (int j = 0; j < matrix[i].length; j++) {
            matrix[i][j] = (int) (Math.random() * 100) + 1;
        }
    }
    

  • Let us understand how to create matrix of random numbers in Java through a program of 5×5 matrix-
    import java.util.Random;
    
    public class RandomMatrix {
        public static void main(String[] args) {
            int[][] matrix = new int[5][5];
            Random random = new Random();
    
            // Fill the matrix with random numbers between 0 and 99
            for (int i = 0; i < matrix.length; i++) {
                for (int j = 0; j < matrix[i].length; j++) {
                    matrix[i][j] = random.nextInt(100); // Generates a random number between 0 and 99
                }
            }
    
            // Print the matrix
            for (int i = 0; i < matrix.length; i++) {
                for (int j = 0; j < matrix[i].length; j++) {
                    System.out.printf("%-5d", matrix[i][j]);
                }
                System.out.println();
            }
        }
    }
    

     

    Output-

    23 45 12 78 90
    34 67 89 56 10
    87 32 54 76 98
    21 43 65 87 12
    76 98 10 32 54

 

 

Leave a Comment

Your email address will not be published. Required fields are marked *

Scroll to Top