How to randomly place a random value in each row of an 8x8 int array with zero values in C

1 Answer

0 votes
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <time.h>

/*
 * initializeBoard:
 *   - Sets all values in the 8x8 array to zero
 *   - For each row:
 *       * randomly selects one column (0–7)
 *       * places a random integer (1–100) in that column
 *
 *   Uses:
 *     - memset for efficient zeroing
 *     - rand() for random column and value
 */
void initializeBoard(int board[8][8]) {
    // Seed the random number generator once per program run
    srand((unsigned)time(NULL));

    for (int row = 0; row < 8; row++) {
        // Efficiently set all 8 integers in this row to zero
        memset(board[row], 0, sizeof(board[row]));

        // Choose a random column index
        int col = rand() % 8;

        // Choose a random value between 1 and 100
        int value = (rand() % 100) + 1;

        board[row][col] = value;
    }
}

/*
 * printBoard:
 *   - Prints the 8x8 board in a readable grid format
 */
void printBoard(const int board[8][8]) {
    for (int row = 0; row < 8; row++) {
        for (int col = 0; col < 8; col++) {
            printf("%d ", board[row][col]);
        }
        printf("\n");
    }
}

int main(void) {
    int board[8][8] = {{0}};  // Uninitialized; will be filled by initializeBoard()

    initializeBoard(board);
    printBoard(board);

    return 0;
}


/*
run:

0 0 0 0 0 0 75 0 
0 0 0 0 0 0 66 0 
0 0 0 0 76 0 0 0 
0 0 0 81 0 0 0 0 
0 0 45 0 0 0 0 0 
0 0 0 0 27 0 0 0 
0 84 0 0 0 0 0 0 
92 0 0 0 0 0 0 0 

*/

 



answered 2 days ago by avibootz

Related questions

...