Multidimensional Arrays
Array Conceptual: What if we want more than one index??? List of objects indexed by a number What if we want more than one index??? Row / Col
Two-Dimensional Arrays Logical matrix Declare: type identifier[rows][cols]; Rows then columns int scores[5][3]; 1 2 76 82 83 84 94 88 93 3 91 98 4
Initialization Initialize as list of lists: Zero out entire array: int nums[3][4] = {{19,22,31,42}, {50,61,32,83}, {93,47,15,66}}; Zero out entire array: int nums[3][4] = {{0}};
2D Access Access: scores[row][col] scores[4][0] = 10; cout << scores[2][1]; //outputs 93 1 2 76 82 83 84 94 88 93 3 91 98 4 10
Storage 2D arrays stored internally in row major order scores[1][??] First dimension is start address of row scores[1][??] 1 2 76 82 83 84 94 88 93 1 2 3 4 5 6 7 8 76 82 83 84 94 88 93
Traversals Traverse with nested loops Row index/col index Loop order matters
Loop Samples i, j aren't great, but get used to them Use constants for loop conditions
Single Dimension Traversals Traversing one row or column requires one loop, one hardcoded index
Sum all columns Sum all columns: Column is main loop, rows second:
Sum Rows And Columns Use arrays of row totals / col totals to build all sums 1 4 2 5 9 7 1 2 1
Sum Rows And Columns Use arrays of row totals / col totals to build all sums 1 4 2 5 9 7 1 2 4 1 4
Sum Rows And Columns Use arrays of row totals / col totals to build all sums 1 4 2 5 9 7 1 2 6 1 4 2
Sum Rows And Columns Use arrays of row totals / col totals to build all sums 1 4 2 5 9 7 1 2 6 5 1 9 2
Sum Rows And Columns Use arrays of row totals / col totals to build all sums
Passing Arrays Must specify each dimension after first when passed as parameter
Storage 2D arrays stored internally in row major order scores[1][??] First dimension is start address of row scores[1][??] 1 2 76 82 83 84 94 88 93 1 2 3 4 5 6 7 8 76 82 83 84 94 88 93
Passing Arrays Compiles, but BAD
Passing Arrays Specify columns using global constant:
Passing Arrays Same using defined global constants: Don't need to pass number rows Still need to specify array second dimension
Faking 2D Can fake 2D with a 1D array scores[1][2] scores[3*1 + 2] [row][col] [colwidth*row][col] 1 2 76 82 83 84 94 88 93 scores[1][2] scores[3*1 + 2] 3*0 + 0 3*0 + 1 3*0 + 2 3*1 + 0 3*1 + 1 3*1 + 2 3*2 + 0 3*2 + 1 3*2 + 2 1 2 3 4 5 6 7 8 76 82 83 84 94 88 93
Multidimensional Arrays Can have an arbitrary number of dimensions: