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

1 Answer

0 votes
#include <stdio.h>
#include <stdlib.h> // For rand() and srand()
#include <time.h>   // For time()

#define ROWS 5
#define COLS 4

void fillMatrixWithRandom0and1(int matrix[ROWS][COLS], int rows, int cols) {
    // Seed the random number generator
    srand(time(0));

    // Fill the matrix with random 0s and 1s
    for (int i = 0; i < rows; ++i) {
        for (int j = 0; j < cols; ++j) {
            matrix[i][j] = rand() % 2; // Generates either 0 or 1
        }
    }
}

int main() {
    int matrix[ROWS][COLS];

    fillMatrixWithRandom0and1(matrix, ROWS, COLS);

    // Print the matrix
    for (int i = 0; i < ROWS; ++i) {
        for (int j = 0; j < COLS; ++j) {
            printf("%d ", matrix[i][j]);
        }
        printf("\n");
    }

    return 0;
}


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

 



answered Jan 24, 2025 by avibootz

Related questions

1 answer 92 views
1 answer 103 views
1 answer 93 views
1 answer 88 views
1 answer 92 views
1 answer 79 views
...