Download presentation
Presentation is loading. Please wait.
1
Multidimensional Arrays
2
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
3
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
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}};
5
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
6
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
7
Traversals Traverse with nested loops Row index/col index
Loop order matters
8
Loop Samples i, j aren't great, but get used to them
Use constants for loop conditions
9
Single Dimension Traversals
Traversing one row or column requires one loop, one hardcoded index
10
Sum all columns Sum all columns: Column is main loop, rows second:
11
Sum Rows And Columns Use arrays of row totals / col totals to build all sums 1 4 2 5 9 7 1 2 1
12
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
13
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
14
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
15
Sum Rows And Columns Use arrays of row totals / col totals to build all sums
16
Passing Arrays Must specify each dimension after first when passed as parameter
17
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
18
Passing Arrays Compiles, but BAD
19
Passing Arrays Specify columns using global constant:
20
Passing Arrays Same using defined global constants:
Don't need to pass number rows Still need to specify array second dimension
21
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
22
Multidimensional Arrays
Can have an arbitrary number of dimensions:
Similar presentations
© 2025 SlidePlayer.com. Inc.
All rights reserved.