CS157 MultiDArrays
int val[3][4]; // 3 rows, 4 columns
Column 0 | Column 1 | Column 2 | Column 3 | |
---|---|---|---|---|
Row 0 | 8 | 16 | 9 | 52 |
Row 1 | 3 | 15 | 28 | 6 |
Row 2 | 14 | 25 | 2 | 10 |
val[1][3]
means row 1, column 3. There’s a 6 there.
val[1][3]
, not val[1,3]
.
Initialization:
#define NUMROWS 3 #define NUMCOLS 4 int val[NUMROWS][NUMCOLS] = { { 8, 16, 9, 52}, { 3, 15, 27, 6}, {14, 25, 2, 10} };
First row is an array containing {8, 16, 9, 52}
.
The inner braces can be omitted, if you have no soul:
int val[NUMROWS][NUMCOLS] = {8,16,9,52,3,15,27,6,14,25,2,10};
Column 0 | Column 1 | Column 2 | Column 3 | |
---|---|---|---|---|
Row 0 | first | second | third | fourth |
Row 1 | fifth | sixth | seventh | eighth |
Row 2 | ninth | tenth | eleventh | twelfth |
#define NUMROWS 3 #define NUMCOLS 4 int val[NUMROWS][NUMCOLS] = {{8,16,9,52}, {3,15,27,6}, {14,25,2,10}}; printf("The hard way:\n"); printf(" %2d %2d %2d %2d\n", val[0][0], val[0][1], val[0][2], val[0][3]); printf(" %2d %2d %2d %2d\n", val[1][0], val[1][1], val[1][2], val[1][3]); printf(" %2d %2d %2d %2d\n", val[2][0], val[2][1], val[2][2], val[2][3]); printf("The easy way:\n"); for (int i=0; i<NUMROWS; i++) { for (int j=0; j<NUMCOLS; j++) printf(" %2d", val[i][j]); printf("\n"); }
The hard way: 8 16 9 52 3 15 27 6 14 25 2 10 The easy way: 8 16 9 52 3 15 27 6 14 25 2 10
#define NUMROWS 3 #define NUMCOLS 4 int val[NUMROWS][NUMCOLS] = {{8,16,9,52}, {3,15,27,6}, {14,25,2,10}}; /* Multiply each element by 10 and display it */ for (int i=0; i<NUMROWS; i++) { for (int j=0; j<NUMCOLS; j++) { val[i][j] *= 10; printf(" %3d", val[i][j]); } printf("\n"); }
80 160 90 520 30 150 270 60 140 250 20 100
#define NUMROWS 3 #define NUMCOLS 4 void display(int array[NUMROWS][NUMCOLS]); int main() { int val[NUMROWS][NUMCOLS] = {{8,16,9,52}, {3,15,27,6}, {14,25,2,10}}; display(val); return 0; } void display(int nums[NUMROWS][NUMCOLS]) { /* Multiply each element by 10 and display it */ for (int i=0; i<NUMROWS; i++) { for (int j=0; j<NUMCOLS; j++) { nums[i][j] *= 10; printf(" %3d", nums[i][j]); } printf("\n"); } }
80 160 90 520 30 150 270 60 140 250 20 100
for
loop counter
to cycle through all the array elements