How to fill a matrix with 1 and 0 in random locations with C#

1 Answer

0 votes
using System;

public class FillMatrixWith1And0InRandomLocations
{
    const int ROWS = 5;
    const int COLS = 4;

    public static void Main(string[] args)
    {
        int[,] matrix = new int[ROWS, COLS];

        FillMatrixWithRandom0and1(matrix, ROWS, COLS);

        PrintMatrix(matrix, ROWS, COLS);
    }

    static void FillMatrixWithRandom0and1(int[,] matrix, int rows, int cols) {
        Random rand = new Random();

        for (int i = 0; i < rows; i++) {
            for (int j = 0; j < cols; j++) {
                matrix[i, j] = rand.Next(2); // Generates either 0 or 1
            }
        }
    }

    static void PrintMatrix(int[,] matrix, int rows, int cols)
    {
        for (int i = 0; i < rows; ++i) {
            for (int j = 0; j < cols; ++j) {
                Console.Write(matrix[i, j] + " ");
            }
            Console.WriteLine();
        }
    }
}

 
  
/*
run:
    
1 0 0 0 
0 1 1 1 
0 0 1 0 
0 0 0 1 
1 1 0 1 
     
*/

 



answered Jan 25, 2025 by avibootz

Related questions

1 answer 63 views
1 answer 99 views
1 answer 90 views
1 answer 86 views
1 answer 88 views
1 answer 76 views
...