92
Copyright 2003 Scott/Jones Publishing Alternate Version of Starting Out with C++, Third Edition Chapter 8 Arrays

Copyright 2003 Scott/Jones Publishing Alternate Version of Starting Out with C++, Third Edition Chapter 8 Arrays

Embed Size (px)

DESCRIPTION

Chapter 8 slide 3 Topics 8.7 The typedef Statement 8.8 Arrays as Function Arguments 8.9 Two-Dimensional Arrays 8.10 Vectors 8.13 Arrays of Structures 8.14 Arrays of Class Objects

Citation preview

Page 1: Copyright 2003 Scott/Jones Publishing Alternate Version of Starting Out with C++, Third Edition Chapter 8 Arrays

Copyright 2003 Scott/Jones Publishing

Alternate Version of Starting Out with C++, Third

Edition

Chapter 8Arrays

Page 2: Copyright 2003 Scott/Jones Publishing Alternate Version of Starting Out with C++, Third Edition Chapter 8 Arrays

Chapter 8 slide 2

Topics

8.1 Arrays Hold Multiple Values8.2 Accessing Array Elements8.3 Inputting and Displaying Array

Contents8.4 Array Initialization8.5 Processing Array Contents8.6 Using Parallel Arrays

Page 3: Copyright 2003 Scott/Jones Publishing Alternate Version of Starting Out with C++, Third Edition Chapter 8 Arrays

Chapter 8 slide 3

Topics

8.7 The typedef Statement8.8 Arrays as Function Arguments8.9 Two-Dimensional Arrays8.10 Vectors8.13 Arrays of Structures8.14 Arrays of Class Objects

Page 4: Copyright 2003 Scott/Jones Publishing Alternate Version of Starting Out with C++, Third Edition Chapter 8 Arrays

Chapter 8 slide 4

8.1 Arrays Hold Multiple Values

• Array: variable that can store multiple values of the same type

• Values are stored in adjacent memory locations

• Declared using [] operator:int tests[5];

Page 5: Copyright 2003 Scott/Jones Publishing Alternate Version of Starting Out with C++, Third Edition Chapter 8 Arrays

Chapter 8 slide 5

Array - Memory Layout

• The definition: int tests[5];

allocates the following memory:

first element

second element

third element

fourth element

fifth element

Page 6: Copyright 2003 Scott/Jones Publishing Alternate Version of Starting Out with C++, Third Edition Chapter 8 Arrays

Chapter 8 slide 6

Array Terminology

In the definition int tests[5];• int is the data type of the array elements• tests is the name of the array• 5, in [5], is the size declarator. It

shows the number of elements in the array.

• The size of an array is (number of elements) * (size of each element)

Page 7: Copyright 2003 Scott/Jones Publishing Alternate Version of Starting Out with C++, Third Edition Chapter 8 Arrays

Chapter 8 slide 7

Array Terminology

• The size of an array is:– the total number of bytes allocated for it– (number of elements) * (number of bytes for

each element)• Examples:

int tests[5] is an array of 20 bytes, assuming 4 bytes for an intlong double measures[10]is an array of 80 bytes, assuming 8 bytes for a long double

Page 8: Copyright 2003 Scott/Jones Publishing Alternate Version of Starting Out with C++, Third Edition Chapter 8 Arrays

Chapter 8 slide 8

8.2 Accessing Array Elements

• Each array element has a subscript, used to access the element.

• Subscripts start at 0

0 1 2 3 4subscripts:

Page 9: Copyright 2003 Scott/Jones Publishing Alternate Version of Starting Out with C++, Third Edition Chapter 8 Arrays

Chapter 8 slide 9

Accessing Array Elements

• Array elements can be used as regular variables:

tests[0] = 79;cout << tests[0];cin >> tests[1];tests[4] = tests[0] + tests[1];

• Arrays must be accessed via individual elements:

cout << tests; // not legal

Page 10: Copyright 2003 Scott/Jones Publishing Alternate Version of Starting Out with C++, Third Edition Chapter 8 Arrays

Chapter 8 slide 10

Global vs. Local Array

• Global array all elements initialized to 0 or NULL

• Local array all elements uninitialized by default

Page 11: Copyright 2003 Scott/Jones Publishing Alternate Version of Starting Out with C++, Third Edition Chapter 8 Arrays

Chapter 8 slide 11

8.3 Inputting and Displaying Array Contents

• Array elements can be used with cin, cout• If array represents a C-string or C++ string

object, can read in or display using just array name:char name[10]; // or 'string name;'cin >> name; cout << name << endl;

• Arrays of other types: element-by-element

Page 12: Copyright 2003 Scott/Jones Publishing Alternate Version of Starting Out with C++, Third Edition Chapter 8 Arrays

Chapter 8 slide 12

Inputting and Displaying Array Contents

• Can access element with constant subscript:cout << tests[3] << endl;

• Can use integer expression as subscript:for (i = 0; i < 5;i++)

cout << tests[i] << endl;• No checks that subscript is in range –

program may overwrite other memory

Page 13: Copyright 2003 Scott/Jones Publishing Alternate Version of Starting Out with C++, Third Edition Chapter 8 Arrays

Chapter 8 slide 13

8.4 Array Initialization

• Can be initialized during program execution with assignment statements:tests[0] = 79; tests[1] = 82; // etc.

• Can be initialized at array definition with an initialization list:int tests[5] = {79,82,91,77,84};

Page 14: Copyright 2003 Scott/Jones Publishing Alternate Version of Starting Out with C++, Third Edition Chapter 8 Arrays

Chapter 8 slide 14

Partial Array Initialization

• If array is initialized at definition with fewer initial values than the size declarator of the array, the remaining elements will be set to 0 or NULL:int tests[5] = {79, 82};

• Initial values used in order; cannot skip over elements to initialize noncontiguous range

79 82 0 0 0

Page 15: Copyright 2003 Scott/Jones Publishing Alternate Version of Starting Out with C++, Third Edition Chapter 8 Arrays

Chapter 8 slide 15

Implicit Array Sizing

• Can determine array size by the size of the initialization list:short quizzes[]={12,17,15,11};

• Must use either array size declarator or initialization list at array definition

12 17 15 11

Page 16: Copyright 2003 Scott/Jones Publishing Alternate Version of Starting Out with C++, Third Edition Chapter 8 Arrays

Chapter 8 slide 16

8.5 Processing Array Contents

• Array elements can be treated as ordinary variables of the same type as the array

• When using ++, -- operators, don’t confuse the element with the subscript:tests[i]++; // add 1 to tests[i]tests[i++]; // increment i, no // effect on tests

Page 17: Copyright 2003 Scott/Jones Publishing Alternate Version of Starting Out with C++, Third Edition Chapter 8 Arrays

Chapter 8 slide 17

Sum of Array Elements

• Use a simple loop to add together array elements:int tnum;float average, sum = 0;for(tnum = 0; tnum < 5; tnum++)

sum += tests[tnum];• Once summed, can compute average:

average = sum/5;

Page 18: Copyright 2003 Scott/Jones Publishing Alternate Version of Starting Out with C++, Third Edition Chapter 8 Arrays

Chapter 8 slide 18

Strings

• Can be processed using array name (entire string at once) or using subscripts(element at a time):string city;cout << "Enter city name: ";cin >> city;

'S' 'a' 'l' 'e' 'm'

city[0] city[1] city[2] city[3] city[4]

Page 19: Copyright 2003 Scott/Jones Publishing Alternate Version of Starting Out with C++, Third Edition Chapter 8 Arrays

Chapter 8 slide 19

8.6 Using Parallel Arrays

• Parallel arrays: two or more arrays that contain related data

• Subscript is used to relate arrays: elements at same subscript are related

• Arrays may be of different types

Page 20: Copyright 2003 Scott/Jones Publishing Alternate Version of Starting Out with C++, Third Edition Chapter 8 Arrays

Chapter 8 slide 20

Parallel Array Example

string name[5]; // student namefloat average[5];// course averagechar grade[5]; // course grade...for(int i = 0; i < 5; i++)

cout << "Student: " << name[i] << " average: " << average[i]

<< " grade: " << grade[i]<< endl;

Page 21: Copyright 2003 Scott/Jones Publishing Alternate Version of Starting Out with C++, Third Edition Chapter 8 Arrays

Chapter 8 slide 21

8.7 The typedef Statement

• Creates an alias for a simple or structured data type

• Format:typedef <existing type> <new name>;

• Example:typedef unsigned int uint;uint tests[5]; // array of unsigned // ints

Page 22: Copyright 2003 Scott/Jones Publishing Alternate Version of Starting Out with C++, Third Edition Chapter 8 Arrays

Chapter 8 slide 22

Uses of typedef

• Used to make code more readable• Can be used to create alias for array of

a particular type:typedef int program[8];// program now names a data type// that is an array of 8 intsprogram prog1, prog2;// 2 arrays

Page 23: Copyright 2003 Scott/Jones Publishing Alternate Version of Starting Out with C++, Third Edition Chapter 8 Arrays

Chapter 8 slide 23

8.8 Arrays as Function Arguments

• To pass an array to a function, just use the array name:showScores(tests);

• To define a function that takes an array parameter, use empty [] for array argument:void showScores(int []); // function prototypevoid showScores(int tests[]) // function header

Page 24: Copyright 2003 Scott/Jones Publishing Alternate Version of Starting Out with C++, Third Edition Chapter 8 Arrays

Chapter 8 slide 24

Arrays as Function Arguments• When passing an array to a function, it is

common to pass array size so that function knows how many elements to process:showScores(tests, 5);

• Array size must also be reflected in prototype, header:void showScores(int [], int); // function prototype

void showScores(int tests[], int size) // function header

Page 25: Copyright 2003 Scott/Jones Publishing Alternate Version of Starting Out with C++, Third Edition Chapter 8 Arrays

Chapter 8 slide 25

Arrays as Function Arguments

• Can use typedef to simplify function prototype, heading:typedef int intArray[]; // typedef

void showScores(intArray, int); // function prototype

void showScores(intArray tests, int size) // function header

Page 26: Copyright 2003 Scott/Jones Publishing Alternate Version of Starting Out with C++, Third Edition Chapter 8 Arrays

Chapter 8 slide 26

Modifying Arrays in Functions

• Array names in functions are similar to reference variables – changes made to array in a function are reflected in actual array in calling function

• Need to exercise caution that array is not inadvertantly changed by a function

Page 27: Copyright 2003 Scott/Jones Publishing Alternate Version of Starting Out with C++, Third Edition Chapter 8 Arrays

Chapter 8 slide 27

8.9 Two-Dimensional Arrays

• Can define one array for multiple sets of data

• Like a table in a spreadsheet• Use two size declarators in definition:

int exams[4][3];• First declarator is number of rows;

second is number of columns

Page 28: Copyright 2003 Scott/Jones Publishing Alternate Version of Starting Out with C++, Third Edition Chapter 8 Arrays

Chapter 8 slide 28

Two-Dimensional Array Representation

int exams[4][3];

• Use two subscripts to access element:exams[2][2] = 86;

exams[0][0] exams[0][1] exams[0][2]

exams[1][0] exams[1][1] exams[1][2]

exams[2][0] exams[2][1] exams[2][2]

exams[3][0] exams[3][1] exams[3][2]

columns

rows

Page 29: Copyright 2003 Scott/Jones Publishing Alternate Version of Starting Out with C++, Third Edition Chapter 8 Arrays

Chapter 8 slide 29

Initialization at Definition

• Two-dimensional arrays are initialized row-by-row:int exams[2][2] = { {84, 78}, {92, 97} };

• Can omit inner { }, some initial values in row – array elements without initial values will be set to 0 or NULL

84 78

92 97

Page 30: Copyright 2003 Scott/Jones Publishing Alternate Version of Starting Out with C++, Third Edition Chapter 8 Arrays

Chapter 8 slide 30

Two-Dimensional Array as Parameter, Argument

• Use array name as argument in function call:getExams(exams, 2);

• Use empty [] for row, size declarator for column in prototype, header:

void getExams(int [][2], int);// prototype

void getExams(int exams[][2], int rows)// header

Page 31: Copyright 2003 Scott/Jones Publishing Alternate Version of Starting Out with C++, Third Edition Chapter 8 Arrays

Chapter 8 slide 31

Two-Dimensional Array as Parameter, Argument

• Can use typedef for simpler notation:typedef int intExams[][2];...void getExams(intExams, int);// prototype

void getExams(intExams exams, int rows)// header

Page 32: Copyright 2003 Scott/Jones Publishing Alternate Version of Starting Out with C++, Third Edition Chapter 8 Arrays

Chapter 8 slide 32

Multi-Dimensional Arrays

• Can define arrays with any number of dimensions:short rectSolid(2,3,5);float timeGrid(3,4,3,4);

• When used as parameter, specify all but 1st dimension:void getRectSolid(short [][3][5]);

Page 33: Copyright 2003 Scott/Jones Publishing Alternate Version of Starting Out with C++, Third Edition Chapter 8 Arrays

Chapter 8 slide 33

8.10 Vectors

• Defined in the Standard Template Library (Chapter 15)

• Can hold values of any type:vector<int> scores;

• Automatically adds space as more is needed – no need to determine size at definition

• Can use [] to access elements

Page 34: Copyright 2003 Scott/Jones Publishing Alternate Version of Starting Out with C++, Third Edition Chapter 8 Arrays

Chapter 8 slide 34

Declaring Vectors• Vectors require vector header file• Declare a vector:

vector<int> scores;• Declare a vector with initial size 30:

vector<int> scores(30);• Declare a vector and initialize all elements to 0:

vector<int> scores(20, 0);• Declare a vector initialized to size and contents

of another vector:vector<int> scores(finals);

Page 35: Copyright 2003 Scott/Jones Publishing Alternate Version of Starting Out with C++, Third Edition Chapter 8 Arrays

Chapter 8 slide 35

Growing a Vector’s Size

• Use size member function to determine size of a vector:howbig = scores.size();

• Use push_back member function to add element to a full array or to an array that had no defined size:scores.push_back(75);

Page 36: Copyright 2003 Scott/Jones Publishing Alternate Version of Starting Out with C++, Third Edition Chapter 8 Arrays

Chapter 8 slide 36

Removing Vector Elements

• Use pop_back member function to remove last element from vector:scores.pop_back();

• To remove all contents of vector, use clear member function:scores.clear();

• To determine if vector is empty, use empty member function:while (!scores.empty()) ...

Page 37: Copyright 2003 Scott/Jones Publishing Alternate Version of Starting Out with C++, Third Edition Chapter 8 Arrays

Chapter 8 slide 37

8.13 Arrays of Structures

• Structures can be used as array elements: struct Student

{int studentID;string name;

short yearInSchool;float gpa;

};Student class[30];

Page 38: Copyright 2003 Scott/Jones Publishing Alternate Version of Starting Out with C++, Third Edition Chapter 8 Arrays

Chapter 8 slide 38

Arrays of Structures

• Use array subscript to access a specific structure in the array

• Then, use dot operator to access members of structure:cin >> class[25].studentID;cout << class[i].name << "has GPA " << class[i].gpa << endl;

Page 39: Copyright 2003 Scott/Jones Publishing Alternate Version of Starting Out with C++, Third Edition Chapter 8 Arrays

Chapter 8 slide 39

8.14 Arrays of Class Objects

• Classes can also be used as array elements:class square{ private:int side; public:void setSide(int s){ side = s; }int getSide(){ return side; }};square shapes[10];

Page 40: Copyright 2003 Scott/Jones Publishing Alternate Version of Starting Out with C++, Third Edition Chapter 8 Arrays

Chapter 8 slide 40

Arrays of Class Objects

• Use subscript to access a specific object in an object the array

• Use dot operator to access member functions of that object:shapes[4].setSide(12);for (i=0; i<10; i++) cout << shapes[i].getSide();

Page 41: Copyright 2003 Scott/Jones Publishing Alternate Version of Starting Out with C++, Third Edition Chapter 8 Arrays

Chapter 8 slide 41

Initialize Array of Objects

• Can use default constructor to perform same initialization for all objects

• Can use initialization list to supply specific initial values of objects:Square shapes[5] = {1,2,3,4,5};

• Default constructor used for remaining objects if initialization list is too short

• Must call constructor in initialization list if it takes > 1 argument

Page 42: Copyright 2003 Scott/Jones Publishing Alternate Version of Starting Out with C++, Third Edition Chapter 8 Arrays

Chapter 8 slide 42

Initialize Array of Objects

• If class has constructor that takes > 1 argument, then initialization list must include a call to the constructor:Rectangle spaces[3] = { Rectangle(2,5), Rectangle(1,3), Rectangle(7,7) };

Page 43: Copyright 2003 Scott/Jones Publishing Alternate Version of Starting Out with C++, Third Edition Chapter 8 Arrays

Copyright 2003 Scott/Jones Publishing

Alternate Version of Starting Out with C++, Third

Edition

Chapter 8Arrays

Page 44: Copyright 2003 Scott/Jones Publishing Alternate Version of Starting Out with C++, Third Edition Chapter 8 Arrays
Page 45: Copyright 2003 Scott/Jones Publishing Alternate Version of Starting Out with C++, Third Edition Chapter 8 Arrays

A First Book of C++: From Here To There, Third Edition

45

Objectives

You should be able to describe:• One-Dimensional Arrays• Array Initialization• Arrays as Arguments• Two-Dimensional Arrays• Common Programming Errors

Page 46: Copyright 2003 Scott/Jones Publishing Alternate Version of Starting Out with C++, Third Edition Chapter 8 Arrays

A First Book of C++: From Here To There, Third Edition

46

One-Dimension Arrays• One-Dimension Array(Single-Dimension

Array or Vector): a list of related values – All items in list have same data type– All list members stored using single group name

• Example: a list of grades98, 87, 92, 79, 85

– All grades are integers and must be declared• Can be declared as single unit under a common

name (the array name)

Page 47: Copyright 2003 Scott/Jones Publishing Alternate Version of Starting Out with C++, Third Edition Chapter 8 Arrays

A First Book of C++: From Here To There, Third Edition

47

One-Dimension Arrays (continued)

• Array declaration statement provides:– The array(list) name– The data type of array items– The number of items in array

• Syntax dataType arrayName[numberOfItems]

– Common programming practice requires defining number of array items as a constant before declaring the array

Page 48: Copyright 2003 Scott/Jones Publishing Alternate Version of Starting Out with C++, Third Edition Chapter 8 Arrays

A First Book of C++: From Here To There, Third Edition

48

One-Dimension Arrays (continued)

• Examples of array declaration statements:

const int NUMELS = 5; // define a constant // for the number of // items

int grade[NUMELS]; // declare the array

const int ARRAYSIZE = 4;char code[ARRAYSIZE];

const int NUMELS = 6;double prices[NUMELS];

Page 49: Copyright 2003 Scott/Jones Publishing Alternate Version of Starting Out with C++, Third Edition Chapter 8 Arrays

A First Book of C++: From Here To There, Third Edition

49

One-Dimension Arrays (continued)

• Each array allocates sufficient memory to hold the number of data items given in declaration

• Array element(component): an item of the array

• Individual array elements stored sequentially– A key feature of arrays that provides a simple

mechanism for easily locating single elements

Page 50: Copyright 2003 Scott/Jones Publishing Alternate Version of Starting Out with C++, Third Edition Chapter 8 Arrays

A First Book of C++: From Here To There, Third Edition

50

One-Dimension Arrays (continued)

Page 51: Copyright 2003 Scott/Jones Publishing Alternate Version of Starting Out with C++, Third Edition Chapter 8 Arrays

A First Book of C++: From Here To There, Third Edition

51

One-Dimension Arrays (continued)

• Index (subscript value): position of individual element in an array

• Accessing of array elements: done by giving array name and element’s index – grade[0] refers to first grade stored in grade

array• Subscripted variables can be used anywhere

that scalar variables are valid:– grade[0] = 95.75;– grade[1] = grade[0] - 11.0;

Page 52: Copyright 2003 Scott/Jones Publishing Alternate Version of Starting Out with C++, Third Edition Chapter 8 Arrays

A First Book of C++: From Here To There, Third Edition

52

One-Dimension Arrays (continued)

Page 53: Copyright 2003 Scott/Jones Publishing Alternate Version of Starting Out with C++, Third Edition Chapter 8 Arrays

A First Book of C++: From Here To There, Third Edition

53

One-Dimension Arrays (continued)

• Subscripts: do not have to be integers– Any expression that evaluates to an integer may

be used as a subscript– Subscript must be within the declared range

• Examples of valid subscripted variables (assumes i and j are int variables):

grade[i]grade[2*i]grade[j-i]

Page 54: Copyright 2003 Scott/Jones Publishing Alternate Version of Starting Out with C++, Third Edition Chapter 8 Arrays

A First Book of C++: From Here To There, Third Edition

54

Input and Output of Array Values

• Individual array elements can be assigned values interactively using a cin stream object

cin >> grade[0];cin >> grade[1] >> grade[2] >> grade[3];cin >> grade[4] >> prices[6];

• Instead, a for loop can be usedconst int NUMELS = 5;for (int i = 0; i < NUMELS; i++){cout << "Enter a grade: ";cin >> grade[i];

}

Page 55: Copyright 2003 Scott/Jones Publishing Alternate Version of Starting Out with C++, Third Edition Chapter 8 Arrays

A First Book of C++: From Here To There, Third Edition

55

Input and Output of Array Values (continued)

• Bounds checking: C++ does not check if value of an index is within declared bounds

• If an out-of-bounds index is used, C++ will not provide notification– Program will attempt to access out-of-bounds

element, causing program error or crash– Using symbolic constants helps avoid this

problem

Page 56: Copyright 2003 Scott/Jones Publishing Alternate Version of Starting Out with C++, Third Edition Chapter 8 Arrays

A First Book of C++: From Here To There, Third Edition

56

Input and Output of Array Values (continued)

• Using cout to display subscripted variables:– Example 1

cout << prices[5];

– Example 2cout << "The value of element " << i << " is " << grade[i];

– Example 3const int NUMELS = 20;for (int k = 5; k < NUMELS; k++)cout << k << " " << amount[k];

Page 57: Copyright 2003 Scott/Jones Publishing Alternate Version of Starting Out with C++, Third Edition Chapter 8 Arrays

A First Book of C++: From Here To There, Third Edition

57

Input and Output of Array Values (continued)Program example of array I/O (program 8.1):

#include <iostream>using namespace std;int main(){

const int NUMELS = 5;int i, grade[NUMELS];for (i = 0; i < NUMELS; i++) // Enter the grades{cout << "Enter a grade: ";cin >> grade[i];}cout << endl;for (i = 0; i < NUMELS; i++) // Print the gradescout << "grade [" << i << "] is " << grade[i] << endl;

return 0;}

Page 58: Copyright 2003 Scott/Jones Publishing Alternate Version of Starting Out with C++, Third Edition Chapter 8 Arrays

A First Book of C++: From Here To There, Third Edition

58

Input and Output of Array Values (continued)

• Sample run using Program 8.1:

Enter a grade: 85Enter a grade: 90Enter a grade: 78Enter a grade: 75Enter a grade: 92

grade[0] is 85grade[1] is 90grade[2] is 78grade[3] is 75grade[4] is 92

Page 59: Copyright 2003 Scott/Jones Publishing Alternate Version of Starting Out with C++, Third Edition Chapter 8 Arrays

A First Book of C++: From Here To There, Third Edition

59

Array Initialization• Array elements can be initialized within

declaration statements– Initializing elements must be included in braces– Example:const int NUMGALS = 20;int gallons[NUMGALS] = {19, 16, 14, 19, 20, 18, // initializing values

12, 10, 22, 15, 18, 17, // may extend across 16, 14, 23, 19, 15, 18, // multiple lines 21, 5};

Page 60: Copyright 2003 Scott/Jones Publishing Alternate Version of Starting Out with C++, Third Edition Chapter 8 Arrays

A First Book of C++: From Here To There, Third Edition

60

Array Initialization (continued)

• Size of array may be omitted when initializing values are included in declaration statement

• Example: the following are equivalentconst int NUMCODES = 6;char code[6] = {'s', 'a', 'm', 'p', 'l', 'e'};

char code[ ] = {'s', 'a', 'm', 'p', 'l', 'e'};

• Both declarations set aside 6 character locations for an array named code

Page 61: Copyright 2003 Scott/Jones Publishing Alternate Version of Starting Out with C++, Third Edition Chapter 8 Arrays

A First Book of C++: From Here To There, Third Edition

61

Array Initialization (continued)

• Simplified method for initializing character arrays char code[ ] = “sample”; //no braces or commas

• This statement uses the string “sample” to initialize the code array– The array is comprised of 7 characters– The first 6 characters are the letters: s, a, m, p, l, e

– The last character (the escape sequence \0) is called the Null character

Page 62: Copyright 2003 Scott/Jones Publishing Alternate Version of Starting Out with C++, Third Edition Chapter 8 Arrays

A First Book of C++: From Here To There, Third Edition

62

Array Initialization (continued)

Page 63: Copyright 2003 Scott/Jones Publishing Alternate Version of Starting Out with C++, Third Edition Chapter 8 Arrays

A First Book of C++: From Here To There, Third Edition

63

Arrays as Arguments• Array elements are passed to a called function

in same manner as individual scalar variables– Example:

findMax(grades[2], grades[6]);

• Passing a complete array to a function provides access to the actual array, not a copy– Making copies of large arrays is wasteful of storage

Page 64: Copyright 2003 Scott/Jones Publishing Alternate Version of Starting Out with C++, Third Edition Chapter 8 Arrays

A First Book of C++: From Here To There, Third Edition

64

Arrays as Arguments (continued)

• Examples of function calls that pass arrays

int nums[5]; // an array of five integerschar keys[256]; // an array of 256 charactersdouble units[500], grades[500];// two arrays of 500

//doubles

• The following function calls can then be made:

findMax(nums);findCharacter(keys);calcTotal(nums, units, grades);

Page 65: Copyright 2003 Scott/Jones Publishing Alternate Version of Starting Out with C++, Third Edition Chapter 8 Arrays

A First Book of C++: From Here To There, Third Edition

65

Arrays as Arguments (continued)

• Suitable receiving side function header lines:

int findMax(int vals[5])char findCharacter(char inKeys[256])void calcTotal(int arr1[5], double arr2[500], double arr3[500])

Page 66: Copyright 2003 Scott/Jones Publishing Alternate Version of Starting Out with C++, Third Edition Chapter 8 Arrays

A First Book of C++: From Here To There, Third Edition

66

Arrays as Arguments (continued)

• Example of passing arrays as arguments (program 8.4):– Constant MAXELS is declared globally– Prototype for findMax() uses constant MAXELS

to declare that findMax() expects an array of five integers as an argument

– As shown in Figure 8.7,only one array is created in Program 8.4

• In main() the array is known as nums• In findMax() it is known as vals

Page 67: Copyright 2003 Scott/Jones Publishing Alternate Version of Starting Out with C++, Third Edition Chapter 8 Arrays

A First Book of C++: From Here To There, Third Edition

67

Arrays as Arguments (continued)

• Example: Program 8.4#include <iostream>using namespace std;const int MAXELS = 5;int findMax(int [MAXELS]); // function prototypeint main(){

int nums[MAXELS] = {2, 18, 1, 27, 16};cout << "The maximum value is " << findMax(nums) << endl;return 0;

}// find the maximum valueint findMax(int vals[MAXELS]){

int i, max = vals[0];for (i = 1; i < MAXELS; i++) if (max < vals[i]) max = vals[i]; return max;

}

Page 68: Copyright 2003 Scott/Jones Publishing Alternate Version of Starting Out with C++, Third Edition Chapter 8 Arrays

A First Book of C++: From Here To There, Third Edition

68

Arrays as Arguments (continued)

Page 69: Copyright 2003 Scott/Jones Publishing Alternate Version of Starting Out with C++, Third Edition Chapter 8 Arrays

A First Book of C++: From Here To There, Third Edition

69

Two-Dimensional Arrays• Two-dimensional array (table): consists of

both rows and columns of elements• Example: two-dimensional array of integers

8 16 9 52 3 15 27 614 25 2 10

• Array declaration: names the array val and reserves storage for it

int val[3][4];

Page 70: Copyright 2003 Scott/Jones Publishing Alternate Version of Starting Out with C++, Third Edition Chapter 8 Arrays

A First Book of C++: From Here To There, Third Edition

70

Two-Dimensional Arrays (continued)• Locating array elements (Figure 8.9)

– val[1][3] uniquely identifies element in row 1, column 3

• Examples using elements of val array:price = val[2][3];val[0][0] = 62;newnum = 4 * (val[1][0] - 5);sumRow = val[0][0] + val[0][1] + val[0][2] + val[0][3];

– The last statement adds the elements in row 0 and sum is stored in sumRow

Page 71: Copyright 2003 Scott/Jones Publishing Alternate Version of Starting Out with C++, Third Edition Chapter 8 Arrays

A First Book of C++: From Here To There, Third Edition

71

Two-Dimensional Arrays (continued)

Page 72: Copyright 2003 Scott/Jones Publishing Alternate Version of Starting Out with C++, Third Edition Chapter 8 Arrays

A First Book of C++: From Here To There, Third Edition

72

Two-Dimensional Arrays (continued)

• Initialization: can be done within declaration statements (as with single-dimension arrays)

• Example:int val[3][4] = { {8,16,9,52}, {3,15,27,6}, {14,25,2,10} };

– First set of internal braces contains values for row 0, second set for row 1, and third set for row 2

– Commas in initialization braces are required; inner braces can be omitted

Page 73: Copyright 2003 Scott/Jones Publishing Alternate Version of Starting Out with C++, Third Edition Chapter 8 Arrays

A First Book of C++: From Here To There, Third Edition

73

Two-Dimensional Arrays (continued)• Processing two-dimensional arrays: nested

for loops typically used– Easy to cycle through each array element

• A pass through outer loop corresponds to a row• A pass through inner loop corresponds to a column

– Nested for loop in Program 8.7 used to multiply each val element by 10 and display results

• Output of Program 8.7Display of multiplied elements 80 160 90 520 30 150 270 60 140 250 20 100

Page 74: Copyright 2003 Scott/Jones Publishing Alternate Version of Starting Out with C++, Third Edition Chapter 8 Arrays

A First Book of C++: From Here To There, Third Edition

74

Two-Dimensional Arrays (continued)

• Prototypes for functions that pass two-dimensional arrays can omit the row size of the array– Example (program 8.8):

Display (int nums[ ][4]);– Row size is optional but column size is required

• The element val[1][3] is located 28 bytes from the start of the array (assuming 4 bytes for an int)

Page 75: Copyright 2003 Scott/Jones Publishing Alternate Version of Starting Out with C++, Third Edition Chapter 8 Arrays

A First Book of C++: From Here To There, Third Edition

75

Two-Dimensional Arrays (continued)• Determining offset of an array

– Computer uses row index, column index and column size to determine offset as shown below and in Figure 8.11

Page 76: Copyright 2003 Scott/Jones Publishing Alternate Version of Starting Out with C++, Third Edition Chapter 8 Arrays

A First Book of C++: From Here To There, Third Edition

76

Two-Dimensional Arrays (continued)

Page 77: Copyright 2003 Scott/Jones Publishing Alternate Version of Starting Out with C++, Third Edition Chapter 8 Arrays

A First Book of C++: From Here To There, Third Edition

77

Larger-Dimension Arrays• Arrays with more than two dimensions

allowed in C++ but not commonly used• Example: int response[4][10][6]

– First element is response[0][0][0]– Last element is response[3][9][5]

• A three-dimensional array can be viewed as a book of data tables (Figure 8.12)– First subscript (rank) is page number of table– Second subscript is row in table– Third subscript is desired column

Page 78: Copyright 2003 Scott/Jones Publishing Alternate Version of Starting Out with C++, Third Edition Chapter 8 Arrays

A First Book of C++: From Here To There, Third Edition

78

Larger-Dimension Arrays (continued)

Page 79: Copyright 2003 Scott/Jones Publishing Alternate Version of Starting Out with C++, Third Edition Chapter 8 Arrays

A First Book of C++: From Here To There, Third Edition

79

Common Programming Errors• Forgetting to declare an array

– Results in a compiler error message equivalent to “invalid indirection” each time a subscripted variable is encountered within a program

• Using a subscript that references a nonexistent array element– For example, declaring array to be of size 20

and using a subscript value of 25– Not detected by most C++ compilers and will

probably cause a runtime error

Page 80: Copyright 2003 Scott/Jones Publishing Alternate Version of Starting Out with C++, Third Edition Chapter 8 Arrays

A First Book of C++: From Here To There, Third Edition

80

Common Programming Errors (continued)

• Not using a large enough counter value in a for loop counter to cycle through all array elements

• Forgetting to initialize array elements– Don’t assume compiler does this

Page 81: Copyright 2003 Scott/Jones Publishing Alternate Version of Starting Out with C++, Third Edition Chapter 8 Arrays

A First Book of C++: From Here To There, Third Edition

81

Summary• Single-dimensional array: a data structure

that stores a list of values of same data type – Must specify data type and array size– int num[100]; creates an array of 100

integers• Array elements are stored in contiguous

locations in memory and referenced using the array name and a subscript– For example, num[22]

Page 82: Copyright 2003 Scott/Jones Publishing Alternate Version of Starting Out with C++, Third Edition Chapter 8 Arrays

A First Book of C++: From Here To There, Third Edition

82

Summary (continued)• Two-dimensional array is declared by listing both

a row and column size with data type and name of array

• Arrays may be initialized when they are declared– For two-dimensional arrays you list the initial values,

in a row-by-row manner, within braces and separating them with commas

• Arrays are passed to a function by passing name of array as an argument

Page 83: Copyright 2003 Scott/Jones Publishing Alternate Version of Starting Out with C++, Third Edition Chapter 8 Arrays

Array [6]

Chapter 8 slide 83

Page 84: Copyright 2003 Scott/Jones Publishing Alternate Version of Starting Out with C++, Third Edition Chapter 8 Arrays

Array [5]+adding

Chapter 8 slide 84

Page 85: Copyright 2003 Scott/Jones Publishing Alternate Version of Starting Out with C++, Third Edition Chapter 8 Arrays

Array [7] and max number

Chapter 8 slide 85

Page 86: Copyright 2003 Scott/Jones Publishing Alternate Version of Starting Out with C++, Third Edition Chapter 8 Arrays

Adding 5 for each

Chapter 8 slide 86

Page 87: Copyright 2003 Scott/Jones Publishing Alternate Version of Starting Out with C++, Third Edition Chapter 8 Arrays

Multi dimensional array

Chapter 8 slide 87

Page 88: Copyright 2003 Scott/Jones Publishing Alternate Version of Starting Out with C++, Third Edition Chapter 8 Arrays

Printing matrix

Chapter 8 slide 88

Page 89: Copyright 2003 Scott/Jones Publishing Alternate Version of Starting Out with C++, Third Edition Chapter 8 Arrays

Adding two matrix

Chapter 8 slide 89

Page 90: Copyright 2003 Scott/Jones Publishing Alternate Version of Starting Out with C++, Third Edition Chapter 8 Arrays

Chapter 8 slide 90

Page 91: Copyright 2003 Scott/Jones Publishing Alternate Version of Starting Out with C++, Third Edition Chapter 8 Arrays

Chapter 8 slide 91

Page 92: Copyright 2003 Scott/Jones Publishing Alternate Version of Starting Out with C++, Third Edition Chapter 8 Arrays

Chapter 8 slide 92