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.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
 
#include<iostream>
using namespace std;

void printMatrix(int matrix[], int r, int c)
{
    for(int i=0;i<r;i++)
    {
         for(int j=0;j<c;j++)
         {
              cout<<matrix[i*c+j]<<" ";   
         }   
         
         cout << endl;
    }   
}

int main()
{
    srand((unsigned)time(0)); 
    int matrix[9] = {rand()%2,rand()%2,rand()%2,rand()%2,rand()%2,rand()%2,rand()%2,rand()%2,rand()%2};
    printMatrix(matrix, 3, 3);
    return 0;
}


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:

1
2
3
4

1 0
0 1


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

1
2
3
4
5
6
7
8
9

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].

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
 
 
#include<iostream>
#include <vector>
#include <cstdlib>
#include <ctime>
using namespace std;

void printMatrix(const std::vector<int>& matrix, int r, int c)
{
    for(int i=0;i<r;i++)
    {
         for(int j=0;j<c;j++)
         {
              cout<<matrix[i*c+j]<<" ";   
         }   
         
         cout << endl;
    }   
}

int main()
{
    srand((unsigned)time(0)); 
    
    std::cout << "Enter size: ";
    int n;
    std::cin >> n;

    if (n <= 0)
    {
        return 1;
    }
    
    vector<int> 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.
Topic archived. No new replies allowed.