More Dimensions
> Click or hit Control-Enter to run the code above
Arrays Can Have Multiple Dimensions
// This is a single-dimensional array of ints of size 4
int[] samples = new int[4];
// This is a two-dimensional array of of chars of
// size 4 in the first dimension and 8 in the second
char[][] board = new char[4][8];
// This is a three-dimensional array of of doubles of
// size 6 in the first dimension, 8 in the second,
// and 10 in the third
double[][][] temperature = new double[6][8][10];
Understanding Multi-Dimensional Arrays
// This is a two-dimensional array
int[][] samples = new int[4][8];
// This is a one-dimensional array
int[] samplesSlice = samples[0];
> Click or hit Control-Enter to run the code above
Multi-Dimensional Array Initialization
We can also initialize multi-dimensional arrays:
int[][] measurements = {
{ 1, 2 },
{ 3, 4 }
};
// This is equivalent to
int measurements = new int[2][2];
measurements[0][0] = 1;
measurements[0][1] = 2;
measurements[1][0] = 3;
measurements[1][1] = 4;
(The ordering can be confusing, but you won’t see this often.)
> Click or hit Control-Enter to run the code above
Forget About Rows and Columns
(These aren’t spreadsheets—you’re not in business school.)
You’re In Charge
The first, second, third, or Nth index of an array mean whatever you want.
This is particularly important when representing certain kinds of data using multi-dimensional arrays.
Multi-Dimensional Data
What kind of data would work well in a multi-dimensional array?
Multi-Dimensional Data
What kind of data would work well in a multi-dimensional array?
-
Pictures and images: each pixel is stored in a 2-dimensional grid
-
Higher-dimensional data: our world is 3D—4D, actually—so our data should be as well.
-
Sound: even data that might seem one dimensional often turns out to be more complicated than we expected
Multi-Level Loops
A frequent use of nested for
loops is to iterate over multi-dimensional
arrays:
for (int i = 0; i < array.length; i++) {
for (int j = 0; j < array[i].length; j++) {
System.out.println(array[i][j]);
}
}
> Click or hit Control-Enter to run the code above
Announcements
-
MP2 is out and due on Friday. Please get started! Today is the best day to come to office hours.
-
EMP (Even More Practice) continues tonight from 5–7PM in Siebel 1404. This is where it will be held for the rest of the semester. If you struggled on MP1, Quiz 2, the last couple TC, be there.
-
The current set of Turing’s Craft exercises (TC5) are due tonight at midnight.
-
The next set of Turing’s Craft exercises (TC6) are due tomorrow at midnight.