How to create an M x N matrix with random numbers in C#

2 Answers

0 votes
using System;
 
public class Program
{
    public static void PrintMatrix(int[,] matrix) {
        for (int i = 0; i < matrix.GetLength(0); i++) {
            for (int j = 0; j < matrix.GetLength(1); j++) {
                Console.Write(matrix[i, j].ToString().PadLeft(4) + " ");
            }
            Console.WriteLine();
        }
    }
     
    private static int[,] CreateMatrixWithRandomNumbers(int rows, int columns) {
        Random random = new Random();
 
        int[,] matrix = new int[rows, columns];
 
        for (int i = 0; i < rows; i++) {
            for (int j = 0; j < columns; j++) {
                matrix[i, j] = random.Next(1, 101); 
            }
        }
 
        return matrix;
    }
 
    static void Main(string[] args)
    {
        int[,] matrix = CreateMatrixWithRandomNumbers(4, 5);
 
        PrintMatrix(matrix);
    }
}



/*
run:

  74   91   40   46   15 
  96   21    3   49   69 
  15   12   40   25   56 
  69    6   56    2   70 
  
*/

 



answered May 14, 2024 by avibootz
0 votes
using System;

public class Example
{
    public static void PrintMatrix(double[,] matrix) {
        for (int i = 0; i < matrix.GetLength(0); i++) {
            for (int j = 0; j < matrix.GetLength(1); j++) {
                Console.Write(matrix[i, j].ToString().PadLeft(4) + " ");
            }
            Console.WriteLine();
        }
    }
    
    private static double[,] CreateMatrixWithRandomNumbers(int rows, int cols) {
        double[,] randomMatrix = new double[rows, cols];
        Random rand = new Random();

        for (int i = 0; i < rows; i++) {
            for (int j = 0; j < cols; j++) {
                int num = rand.Next() % 100;
                randomMatrix[i, j] = Math.Abs(num);
            }
        }

        return randomMatrix;
    }

    public static void Main(string[] args)
    {
        double[,] matrix = CreateMatrixWithRandomNumbers(4, 5);
 
        PrintMatrix(matrix);
    }
}


/*
run:

  56   42   85   38   55 
  78   93   48   65   57 
  83   70   85   83   51 
  87   96   79   79    4 
  
*/

 



answered May 14, 2024 by avibootz
...