How to initialize a matrix with random characters in C++

1 Answer

0 votes
#include <iostream>
#include <iomanip> // setw()
#include <ctime>

#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++) {
            std::cout << std::setw(3) << matrix[i][j];
        }
        std::cout << "\n";
    }
}

// Function to generate a random character
char getRandomCharacters() {
    const std::string characters = "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ";
    
    return characters[std::rand() % characters.length()];
}
   
void initialize_matrix_with_random_characters(char matrix[][COLS], int rows, int cols) {
    std::srand(std::time(nullptr));
 
    for (int i = 0; i < rows; i++) {
        for (int j = 0; j < cols; j++) {
            matrix[i][j] = getRandomCharacters();
        }
    }
}
   
int main() {
    char matrix[ROWS][COLS] = {{""}};
   
    initialize_matrix_with_random_characters(matrix, ROWS, COLS);
      
    print_matrix(matrix, ROWS, COLS);
}
  
    
    
/*
run:
    
  f  R  f  S
  3  I  e  v
  j  i  B  4
    
*/

 



answered May 18, 2024 by avibootz
edited 16 hours ago by avibootz
...