Monday, 11 February 2013

Two-Dimensional Arrays


Two-Dimensional Arrays

A two-dimensional (2D) array is a \grid" of elements. While there is very little that a 2D
array can do that an ordinary array cannot, sometimes information is conceptually easier to

represent as a 2D array. For example, the NXT display in Figure 3.1 is naturally suited to
a 2D array representation. The syntax for declaring a 2D array is
 
[ datatype ] [ variable name ][[ SIZE1 ]][[ SIZE2 ]];
 
More speci cally, an array that might represent the NXT display would be
 
bool screen [100][64];
 
Elements that are true indicate pixels that that are on. Elements that are false indicate
pixels that are o . To represent a blank screen, we set all of the elements to false
 
bool screen [100][64];
for (i =0;i <100; i ++) {
for (j =0;j <64; j ++) {
screen [i][j]= false ;
}
}
 
To represent a display with a horizontal line across the middle of the display
 
bool screen [100][64];
for (i =0;i <100; i ++) {
screen [i ][32]= true ;
}
 
Notice that indices start at zero, just like with ordinary arrays. We see a nice correspondence
between the pixel coordinate, (i,j), and the 2D array element [i][j]. A programmer can
make a whole assortment of changes to the screen array and then use it to \paint" the screen
all at once by \visiting" every array element and, if true, turning on the corresponding pixel.
 
for (i =0;i <100; i ++) {
for (j =0;j <64; j ++) {
if( screen [i][j]) { nxtSetPixel (i,j); }
}
}


No comments:

Post a Comment