42
Copyright © 2012 Pearson Education, Inc. Chapter 8 Two Dimensional Arrays

Copyright © 2012 Pearson Education, Inc. Chapter 8 Two Dimensional Arrays

Embed Size (px)

Citation preview

Copyright © 2012 Pearson Education, Inc.

Chapter 8

Two Dimensional Arrays

Copyright © 2012 Pearson Education, Inc.

OutlineObjectives

1.Two Dimensional Arrays

2.Problem Solving Applied: Terrain Navigation

3.Two Dimensional Arrays and the vector Class

4.Matrices

5.Numerical technique: Solution to Simultaneous Equations

6.Problem Solving Applied: Electrical-Circuit Analysis

7.Higher Dimensional Arrays

Copyright © 2012 Pearson Education, Inc.

ObjectivesDevelop problem solutions in C++

containing:• Matrix computations• Input from Data Files• Functions to Compute Sums and Averages• Techniques for solving a system of

simultaneous equations• Vectors to implement the concept of two-

dimensional arrays

Two Dimensional Arrays

Copyright © 2012 Pearson Education, Inc.

Two Dimensional Arrays

• Declaration and Initialization

• Computation and Output

• Function Arguments

Copyright © 2012 Pearson Education, Inc.

Two Dimensional Arrays

• A two dimensional array stores data as alogical collection of rows and columns.

• Each element of a two-dimensional array has a row position and a column position.

• To access an element in a two-dimensional array, you must specify the name of the array followed by:– a row offset– a column offset

Copyright © 2012 Pearson Education, Inc.

Declaration and Initialization

• The declaration of a two-dimensional array requires a row size and a column size.

• A consecutive block of (row size)*(column size) memory locations are allocated.

• All array elements must be of the same type.• Elements accessed by two offsets – a row offset

and a column offset.• The name of the array holds the address of the

first byte of memoryCopyright © 2012 Pearson Education, Inc.

Example

//Declaration int data[2][3];

Copyright © 2012 Pearson Education, Inc.

Memory Snapshot

?

?

?

?

?

?

data

Example

//Declaration int data[2][3];

Copyright © 2012 Pearson Education, Inc.

? ? ?? ? ?

row 0

row 1

col 0 col 1 col 2row/column form:

2D Array Definition Syntax

Copyright © 2012 Pearson Education, Inc.

Syntax:data_type identifier[ [row_size] ][column_size] [= initialization_list ]; //row_size and column_size must be integer constants

Examplesint data[2][5]; //allocates consecutive memory for 10 integer valuesdouble t[2][2] = {{3.0,5.0},{2.1,7.2}}; //allocates and initializes

Valid Referencescout << data[1][3];cout << t[1][0];

Invalid Referencescout << data[2][5]; //invalid offset.cout << t[-1][-1]; //invalid offset

Initialization Examplesint temp[4][3] = {50, 70, 60, 48, 75,62, 51, 69, 60, 52, 78, 63};

int temp[4][3] = {{50, 70, 60}, {48, 75, 62}, {51, 69, 60}, {52, 78, 63}};

int t2[7][4] = {{50, 70, 60}, {48, 75, 62}, {51, 69, 60}, {52, 78, 63}};

int temp[][3] = {{50, 70, 60}, {48, 75, 62}, {51, 69, 60}, {52, 78, 63}};

int temp[][3] = {50, 70, 60, 48, 75, 62, 51, 69, 60, 52, 78, 63};Copyright © 2012 Pearson Education, Inc.

Example: Input Using cin

• Nested for loops are often used wheninputting and assigning values to a two-dimensional array.– Nested loops are generally useful for getting around

the 2D arrays…

Copyright © 2012 Pearson Education, Inc.

//Declaration double table[RSIZE][CSIZE];

for (int i=0; i<RSIZE; ++i) //every row for (int j=0; j<CSIZE; ++j )//every col cin >> table[i][j];

Example: Assignment

Copyright © 2012 Pearson Education, Inc.

//Declaration const int RSIZE(3),CSIZE(2);double v[RSIZE][CSIZE];

for (int i=0; i<RSIZE; ++i) //every row for (int j=0; j<CSIZE; ++j )//every col v[i][j] = i+j;

0 1

1 2

2 3

V

Example: Computations

• Compute the average value of an arraywith n rows and m columns.

Copyright © 2012 Pearson Education, Inc.

double sum(0), average;for (int i=0; i<n; ++i) //every row for (int j=0; j<m; ++j )//every col sum += array[i][j];average = sum / (n*m);

Example: Computations

• Compute the average value of the nth rowof a 2D array with r rows and c columns.

Copyright © 2012 Pearson Education, Inc.

double sum(0), rowAverage;for (int j=0; j<c; ++j ) //every col sum += array[n][j];average = sum / c;

Modify!

• Modify the C++ statements on the previous slide to compute the average of the mth column.

Copyright © 2012 Pearson Education, Inc.

Outputting 2D Arrays

• Two dimensional arrays are often printed in a row by row format, using nested for statements.

• When printing the row values of an array, be sure to print:– whitespace between the values in a row.– a newline character at the end of each row.

Copyright © 2012 Pearson Education, Inc.

Example: Printing

Copyright © 2012 Pearson Education, Inc.

for (int i=0; i<n; ++i) {//every row for (int j=0; j<m; ++j )//every col cout << array[i][j] << ‘ ‘; cout << endl; //add end-of-line each row}

2D Arrays as Function Parameters

• 2-D arrays are always passed by reference. • The column dimension must be specified. The

leftmost dimension (row) may be empty [].• Function prototype example:

– int rowAverage(int Arr[][COLSIZE], int whichRow);

• Array declaration in main:– int table [ROWSIZE][COLSIZE];

• Function invocation example:avg = rowAverage(table, 3);

Copyright © 2012 Pearson Education, Inc.

Documentation Style

• Well-documented functions alwaysinclude pre-conditions and post-conditions in the function’s comment header block.– Pre-conditions describe the conditions assumed

to be true at the time the function is called.• If pre-conditions are not met, there is no guarantee

that the function will work correctly.

– Post-conditions describe the changes that will be made to the arguments during the execution of the function.

Copyright © 2012 Pearson Education, Inc.

Problem Solving Applied:Terrain Navigation

Copyright © 2012 Pearson Education, Inc.

Problem Solving Applied:Terrain Navigation

Copyright © 2012 Pearson Education, Inc.

Problem Solving Applied:Terrain Navigation

Copyright © 2012 Pearson Education, Inc.

Problem Solving Applied:Terrain Navigation

Copyright © 2012 Pearson Education, Inc.

Two Dimensional Arrays and the vector Class

Copyright © 2012 Pearson Education, Inc.

2D Arrays using theSTL vector Class

• Just as the vector may be used as a generic implementation of the array concept, the vector class may be used to provide an generic for 2D arrays.– Dynamic sizing of array.– Methods for determining and modifying size

and capacity dynamically.

Copyright © 2012 Pearson Education, Inc.

2D vector Definition Syntax

Copyright © 2012 Pearson Education, Inc.

Syntax:vector< vector< type_specifier > > identifier[(row_size,column_size)];

Examplesvector<vector<double> > temp(rows,cols);vector<vector<int> > table(10,4);vector<vector<char> > tags;vector<vector<Point> > image(height,width);

Passing vectorInstances to Functions

• Unlike 2D arrays, objects of vector types are passed by value to functions.– Thus a copy is made of the arguments to the function

call, and changes made to the formal parameter will NOT affect the argument value.

• Pass vector objects by reference to allow the function to alter the argument.

• Pass vector objects by const reference to avoid copying potentially large datasets.

Copyright © 2012 Pearson Education, Inc.

Matrices

Copyright © 2012 Pearson Education, Inc.

Matrix

• A matrix is a set of numbers arrangedin a rectangular grid with rows and columns.

• A square matrix has the same number of rows as columns.

• Row and Column offsets in Matrices are 1-based.

• 2D Arrays are useful for representing matrices.– Remember that C++ uses 0-based offsets!

Copyright © 2012 Pearson Education, Inc.

Matrix Computations and Operations

• The determinant of a matrix is a scalar value usedin computing matrix inverses and solving systems of simultaneous equations.

• The transpose of a matrix is a new matrix in which the rows of the original matrix are the columns of the transpose.

• Matrices of the same size may be added or subtracted element-by-element.

• Matrix multiplication (M * N) is defined only when the number of columns of M is equal to the number of rows in N.– Result has the size rows(M) x cols(N)

Copyright © 2012 Pearson Education, Inc.

Numerical Technique: Solution to Simultaneous Equations

Copyright © 2012 Pearson Education, Inc.

Graphical Interpretation

Copyright © 2012 Pearson Education, Inc.

• Solving two simultaneous (linear) equations is finding the point at which the lines intersect.

• Not all lines intersect, therefore there is not always a solution.

• In 2D, parallel lines do not intersect unless they are identical lines.

• When the lines are identical, there is no single point at which they intersect.

Graphical Interpretation

Copyright © 2012 Pearson Education, Inc.

• In high dimensional spaces, analogous situations may occur.

Solution Methods

• Simultaneous equations may besolved by a number of various methods, each of which has advantages and disadvantages.– Gauss elimination– Matrix Inverse– and others…

Copyright © 2012 Pearson Education, Inc.

Problem Solving Applied:Electrical-Circuit Analysis

Copyright © 2012 Pearson Education, Inc.

Problem Solving Applied:Electrical-Circuit Analysis

Copyright © 2012 Pearson Education, Inc.

Problem Solving Applied:Electrical-Circuit Analysis

Copyright © 2012 Pearson Education, Inc.

Problem Solving Applied:Electrical-Circuit Analysis

Copyright © 2012 Pearson Education, Inc.

Problem Solving Applied:Electrical-Circuit Analysis

Copyright © 2012 Pearson Education, Inc.

Higher Dimensional Arrays

Copyright © 2012 Pearson Education, Inc.

Higher Dimensional Arrays

• C++ allows arrays to be defined withmore than two dimensions.E.g.: int b[3][4][2]; //declare a 3-D array

• An offset must be specified for each dimension.

• Same ‘rules’ apply as for 1D and 2D arrays.

– Offsets are unchecked by C++.

• Only left-most dimension may be omitted when passing a multidimensional array to a function.

Copyright © 2012 Pearson Education, Inc.