How to initialize a matrix with random characters in C

1 Answer

0 votes
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
 
#define ROWS 3
#define COLS 4

void print_matrix(char matrix[][COLS], int rows, int cols) {
    for (int i = 0; i < rows; i++) {
        for (int j = 0; j < cols; j++) {
            printf("%3c", matrix[i][j]);
        }
        printf("\n");
    }
}
 
void initialize_matrix_with_random_characters(char matrix[][COLS], int rows, int cols) {
    const char characters[] = "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ";
    int characters_count = sizeof characters;
     
    srand(time(NULL));
        
    for (int i = 0; i < rows; i++) {
        for (int j = 0; j < cols; j++) {
            matrix[i][j] = characters[rand() % characters_count];
        }
    }
}
 
int main() {
    char matrix[ROWS][COLS] = {{""}};
 
    initialize_matrix_with_random_characters(matrix, ROWS, COLS);
    
    print_matrix(matrix, ROWS, COLS);

    return 0;
}
 
  
  
  
/*
run:
  
  H  1  d  l
  0  1  n  i
  j  6  5  2
  
*/

 



answered May 18, 2024 by avibootz
...