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:

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
#include <iostream>
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<<endl;
    }
    return 0;
}



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.