Generate random 2D array in C++

In this tutorial, we will learn how to generate a random 2D array in C++.

We use rand( ) and srand( ) functions in this tutorial. Please refer How to generate random numbers between 1 to 100 in C++, to understand how they work.

Code

#include <bits/stdc++.h>

using namespace std;

int main(){
    srand(time(0)); // to generate pseudo random numbers each time

    int rows = 1 + (rand() % 10); // lie b/w 1 to 10
    int cols = 1 + (rand() % 10); // lie b/w 1 to 10
    int arr[rows][cols];

    for (int i=0; i<rows; i++)
        for (int j=0; j<cols; j++)
            arr[i][j] = 1 + (rand() % 500); // lie b/w 1 to 500

    cout << "The rows of random 2d array are: " << rows << " and columns are: " << cols << endl;
    cout << "Random 2d array generated is:" << endl;

    for (int i=0; i<rows; i++){
        for (int j=0; j<cols; j++)
            cout << arr[i][j] << " ";
        cout << endl;
    }

    return 0;   
}

Output 1

The rows of random 2d array are: 8 and columns are: 10
Random 2d array generated is:
74 159 431 273 45 379 424 210 441 166 
493 43 488 4 328 230 341 113 304 170 
210 158 61 434 100 279 317 336 98 327 
13 268 311 134 480 150 80 322 468 173 
394 337 486 246 229 92 195 358 2 154 
209 445 169 491 125 197 31 404 223 167 
50 25 302 354 478 409 229 434 299 482 
136 14 366 315 64 37 426 170 116 95

Output 2

The rows of random 2d array are: 1 and columns are: 8
Random 2d array generated is:
99 93 441 129 111 305 439 185

Note: srand( ) is used to set the starting point with seed for producing the pseudo-random numbers. And don’t forget to import “#include <time.h>” header.

Note: If you want to generate a square matrix, then keep rows and cols the same.

Leave a Reply

Your email address will not be published. Required fields are marked *