#include<iostream>
usingnamespace 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:
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].