Title: Chapter 10 MultiDimensional Numeric Arrays
1Chapter 10 Multi-Dimensional Numeric Arrays
2Multidimensional Arrays
- Visual image of matrix or table for
two-dimensional array - Subscript for each dimension
- Declared with value for each dimension
int b2 3
Number of elements 23 6
Lesson 10.1
3Initializing
- Initialized by row
- Example int b2 3 51, 52, 53, 54, 55, 56
- Elements would beb0 0 51 b0 1
52 b0 2 53b1 0 54 b1 1
55 b1 2 56
Remember subscripts begin at zero!
Lesson 10.1
4Initializing
- Can use braces to separate rows
int c 4 3 1, 2, 3,
4, 5, 6, 7,
8, 9, 10, 11, 12
Advantage is visual table!
Lesson 10.1
5Initializing
int c4 3 1,2,
4, 5, 6, 7,
10,11,12
If values left outof row, implicitly
initialized to zero. c2 2 0
Lesson 10.1
6Printing
for (j 0 j lt 2 j) for
(k 0 k lt 3 k)
cout ltlt bj k
cout ltlt endl
- Usually use nested for loop
- Two dimensions, two loops
- First loop controls rows
- Second loop controls columns
Lesson 10.1
7Reading Array From File
infile gtgt num_rows gtgt num_cols for (j 0 j lt
num_rows j) for (k 0 k lt
num_cols k)
infile gtgt aj k
Lesson 10.2
8Storage of Two-Dimensional Arrays
- Fills row by row
- If have fewer elements, then storage to the right
of those filled un-initialized elements - Three and greater dimensions
- Far right subscript increments first
- Other subscripts increment in order from right to
left
Lesson 10.2
9Storage
If file gave number of rows as 3 and number of
columns as 4 then have non-contiguous storage.
array5 9
1 2 3 4 2 4 6 8 3 5 7 9
Lesson 10.2
10Storage Location
- Formula to locate arrays element's position in
memory
sequence location x (J K) y (K) z 1
sequence location 0 (3 4) 1 (4) 21
7
Lesson 10.2
11Passing Array to Function
Declaration
void funcName (type, type, type max_cols)
Call
funcName (rows, cols, arrayName)
void funcName (type r, type c, type array
max_cols)
Header
Lesson 10.2
12const Qualifier
- Place in front of array name in function
declaration and header - Assures that array is not modified in function
void funcName (type, type, const type col
)
Declaration
Lesson 10.2
13Summary
Learned how to
- Initialize multidimensional arrays
- Print multidimensional arrays
- Read a file for array element values
- Visualize storage
- Pass an array to a function