250 likes | 282 Views
Multidimensional Arrays. Array. Conceptual: List of objects indexed by a number What if we want more than one index??? Row / Col. Two-Dimensional Arrays. Two-Dimensional Array Logical matrix Declare: t ype identifier[ rows ][ cols ]; Rows then columns int scores[ 5 ][ 3 ];.
E N D
Array • Conceptual: • List of objects indexed by a number • What if we want more than one index??? • Row / Col
Two-Dimensional Arrays • Two-Dimensional Array • Logical matrix • Declare: type identifier[rows][cols]; • Rows then columns int scores[5][3];
Initialization • Initialize as list of lists: intnums[3][4] = {{19,22,31,42}, {50,61,32,83}, {93,47,15,66}}; • Zero out entire array: intnums[3][4] = {{0}};
2D Access • Access: scores[row][col] scores[4][0] = 10; cout << scores[2][1]; //outputs 93
Storage • 2D arrays stored internally in row major order • First dimension is start address of row scores[1][??]
Traversals • Traverse with nested loops • Row index/col index • Loop order matters
Order: 0 0 0 1 0 2 1 0 1 1 1 2
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
Sum Rows And Columns • Use arrays of row totals / col totals to build all sums
Sum Rows And Columns • Use arrays of row totals / col totals to build all sums
Sum Rows And Columns • Use arrays of row totals / col totals to build all sums
Sum Rows And Columns • Use arrays of row totals / col totals to build all sums
Passing Arrays • Must specify each dimension after first whenpassed as parameter
Storage • 2D arrays stored internally in row major order • First dimension is start address of row scores[1][??]
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 • [row][col] [colwidth*row][col] scores[1][2] scores[3*1 + 2]
Multidimensional Arrays • Can have an arbitrary number of dimensions: