### Printing an array

Hello, I am trying to get this very simple program to work and I can't figure it out. The program is supposed to have the user input values of a matrix and then simply print the matrix. Here's the code:

 ``123456789101112131415161718192021222324252627282930`` ``````#include using namespace std; int main () { int a,b; // matrix dimensions int n_input,m_input; cout << "Please enter the number of rows in the matrix: "; cin >> a; a--; cout << "Please enter the number of columns in the matrix: "; cin >> b; b--; int array [a][b]; for (m_input=0; m_input<=b;m_input++) { for (n_input=0; n_input<=a; n_input++) { cout << "Please input "<< (n_input+1) << "x" << (m_input+1)<< ":"; cin >> array[n_input][m_input]; } } // print the matrix int n, m; for (m=0; m<=b; m++) { for (n=0; n<=a; n++) { cout << array [n][m] << " "; } cout<

The print array section works if I put in the values of the array when I declare it, so that leads me to believe that I'm making a mistake in the input of the values section. Any help is greatly appreciated!
Why do you subtract one from the sizes of the array?

Also, you cannot declare an array like you are on line 14 - it is not valid C++ code. If your compiler supports that then it is probably an extension and there is no telling how it works or how reliable it is.

What exactly doesn't work about it?
Last edited on
I subtract one from a and b because if someone puts in they want a 3X3 matrix, according to the program that's a 2X2, (0,1,2), right?

What's wrong with how I declare the array. Is it the use of variables?

And yes, I should have shown what's wrong with it. If I input
1 2 3
1 2 3
1 2 3

The program spits out:

1 1 2
1 2 3
1 2 2085812496

not sure why it does this...
Marius wrote:
I subtract one from a and b because if someone puts in they want a 3X3 matrix, according to the program that's a 2X2, (0,1,2), right?
This is wrong. 3x3 is 3x3, not 2x2. (0, 1, 2) is three indices, not two.

Marius11 wrote:
What's wrong with how I declare the array. Is it the use of variables?
In C++, you cannot declare an array using variables for its size, the size has to be known at compile time, not runtime.

As for what your program is doing wrong, again it is because 1. your array size is too small and 2. you can't make an array dynamically like that.
Topic archived. No new replies allowed.