### C++ - Help with matrix!

Hello! So I have this code which displays a 3 by 3 matrix and outputs each element as a 0 or 1, using rand.

 ``123456789101112131415161718192021222324`` `````` #include using namespace std; void printMatrix(int matrix[], int r, int c) { for(int i=0;i

My question is, how can I ask the user to enter a positive integer which sets the matrix. For example if the user enters "2" the matrix will be 2 by 2 and will output as:

 ``1234`` `````` 1 0 0 1 ``````

If the user enters "7" the matrix will by 7 by 7 and will output as:

 ``123456789`` `````` 0 1 1 0 1 0 0 1 1 1 1 0 0 0 0 0 1 0 0 0 0 1 1 0 0 1 1 1 1 1 1 1 0 0 1 0 0 0 1 0 1 1 0 1 0 1 0 1 0 ``````

And so forth...

How can I do this?
I'm so lost here, thanks for help.
Last edited on
Your issue is a common one. Arrays sizes have to be compile-time constants in C++. Allocating an array based on user input size requires dynamic allocation. This can be done by using new[]/delete[], or by using an std::vector (or other dynamic container).

I suggest using an std::vector in this regard. The syntax is similar enough to regular arrays, you still access elements like my_vector[i].

 ``123456789101112131415161718192021222324252627282930313233343536373839404142`` `````` #include #include #include #include using namespace std; void printMatrix(const std::vector& matrix, int r, int c) { for(int i=0;i> n; if (n <= 0) { return 1; } vector matrix(n*n); for (int i = 0; i < n * n; i++) { matrix[i] = rand() % 2; } printMatrix(matrix, n, n); return 0; }``````
Last edited on
Appreciate it man, thanks for clearing it up.