So I have this problem with arrays. I have to make a program that makes the user input two numbers - one for the number of rows, and one for the columns in a 2d array and then the program has to fill the array with random numbers. The main problem is how do I make the program take variables for the number and rows and columns? Aren't they supposed to the a constant value?
To do this at run time you have several options.
1. Use of variant length arrays if you use GCC, though it's not recommended.
2. Use of dynamic memory
3. Use of nested vectors
4. Use of a single vector - mapping row and col to a index
Options 2-4 could easily be inside a class.
I would recommend option 3
#include <iostream>
#include <vector>
#include <ctime>
#include <cstdlib>
usingnamespace std;
using matrix = vector< vector<int> >; // Saves typing this long type declaration every time
//======================================================================
matrix genMatrix( int rows, int cols )
{
matrix M( rows, vector<int>( cols, 0 ) ); // Declare container with specified number of rows and columns
for ( int i = 0; i < rows; i++ )
{
for ( int j = 0; j < cols; j++ ) M[i][j] = rand() % 100;
}
return M;
}
//======================================================================
void print( const matrix &M )
{
for ( auto row : M )
{
for ( auto e : row ) cout << e << '\t';
cout << '\n';
}
}
//======================================================================
int main()
{
srand( time( 0 ) );
int rows, cols;
cout << "Enter the number of rows: " ; cin >> rows;
cout << "Enter the number of columns: "; cin >> cols;
matrix M = genMatrix( rows, cols );
print( M );
}
//======================================================================
Enter the number of rows: 5
Enter the number of columns: 10
39 84 37 95 34 71 7 59 42 40
54 59 80 27 99 12 0 45 37 83
61 59 15 43 30 16 48 63 22 14
43 99 30 80 95 43 21 86 17 13
61 17 31 29 8 96 27 81 37 59