Skip to main content

10.2) 2D Arrays


double x[6][10];                     // 6 row, 10 columns, uninitialized
int y[3][5] = { {1, 2, 3, 4, 5},     // 3 rows, 5 columns
                {6, 7, 8, 7, 6},     // note how {} are nested
                {5, 4, 3, 2, 1} };
x[0][0] = 3.14159;                   // assigns to top-left element of x
cout << y[2][4] << endl;             // prints bottom-right element of y
  • 2D array x can be thought of as a matrix with 6 rows and 10 columns, or as 6-element array, each element of which is a 10-element array of double values
  • Initialization syntax works for 2D arrays also, by providing values in { } for each row and then enclosing these inside { }
  • We can define arrays with three or more dimensions in a similar fashion - although initialization syntax becomes unwieldy and difficult to visualize in more than two dimensions