0

I am trying to create a matrix in C++. I am a beginner. Is there any other simple way to done this? I am refering to the for statement which uses cin (something like for (i,j=1; i,j<=n; i,j++) or cin >> a;)

int n=5;
int a[n][n];

for(int i=1; i<=n; i++) {
    for(int j=1; j<=n; j++) {
        cin >> a[i][j];
    }
}

Thanks!

MM PP
  • 4,050
  • 9
  • 35
  • 61
  • 6
    indices start from zero !! – Karoly Horvath Mar 31 '15 at 13:21
  • 2
    There is always other way to do this, but your is good. It is easier to read than a for(int i=0;i> a[i%n][i/n] } By the way, you have a bug : In computer science, start is often 0, not 1 (except for some obscur and strange language) – A.H Mar 31 '15 at 13:21
  • 3
    Arrays go from `0` to `n - 1`. Also, `int a[n][n]` is not standard C++ when `n` is not a constant expression (although this is supported on some compilers as an extension). – crashmstr Mar 31 '15 at 13:24
  • 1
    Simple for the user or simple to program? You could ask the user to provide a file with the desired contents (which you'd have to open/read/parse/validate/etc) and use the contents to populate the matrix. That might be easier for the user, though quite a bit more complicated for the programmer. – LawfulEvil Mar 31 '15 at 13:24
  • 1
    You can store the matrix in one dimension. http://stackoverflow.com/questions/14015556/how-to-map-the-indexes-of-a-matrix-to-a-1-dimensional-array-c – NathanOliver Mar 31 '15 at 13:25
  • Thank you for your comments! Thanks @A.H too! – MM PP Mar 31 '15 at 13:35
  • I learn C++ at highschool. I know, but my teacher said we must start from "1" because in a real matrix there doesn't exists a 0 line. – MM PP Mar 31 '15 at 13:38
  • 2
    Your teacher is wrong. If you access the value at position n, your program will misbehave. Indices in C++ arrays/matrices start from 0 and go to n-1, period. – Not a real meerkat Mar 31 '15 at 14:12
  • Thank you @CássioRenan ! I underestand. – MM PP Mar 31 '15 at 14:24
  • 1
    You can also pay attention to http://www.cplusplus.com/reference/array/array/ –  Mar 31 '15 at 15:38

0 Answers0