Presentation is loading. Please wait.

Presentation is loading. Please wait.

Alternate Version of Starting Out with C++, Third Edition

Similar presentations


Presentation on theme: "Alternate Version of Starting Out with C++, Third Edition"— Presentation transcript:

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

2 Topics 8.1 Arrays Hold Multiple Values 8.2 Accessing Array Elements
8.3 Inputting and Displaying Array Contents 8.4 Array Initialization 8.5 Processing Array Contents 8.6 Using Parallel Arrays Chapter 8 slide 2

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 Chapter 8 slide 3

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]; Chapter 8 slide 4

5 Array - Memory Layout The definition: allocates the following memory:
int tests[5]; allocates the following memory: first element second element third element fourth element fifth element Chapter 8 slide 5

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) Chapter 8 slide 6

7 Array Terminology The size of an array is: Examples:
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 int long double measures[10]is an array of 80 bytes, assuming 8 bytes for a long double Chapter 8 slide 7

8 8.2 Accessing Array Elements
Each array element has a subscript, used to access the element. Subscripts start at 0 subscripts: 1 2 3 4 Chapter 8 slide 8

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 Chapter 8 slide 9

10 Global vs. Local Array Global array  all elements initialized to 0 or NULL Local array  all elements uninitialized by default Chapter 8 slide 10

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 pr8-01.cpp Chapter 8 slide 11

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 pr8-02.cpp, pr8-03.cpp, pr8-04.cpp Chapter 8 slide 12

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}; pr8-05.cpp, pr8-06.cpp, pr8-07.cpp Chapter 8 slide 13

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 pr8-08.cpp Chapter 8 slide 14

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 Chapter 8 slide 15

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 pr8-09.cpp Chapter 8 slide 16

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; pr8-10.cpp, pr8-11.cpp Chapter 8 slide 17

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; pr8-12.cpp 'S' 'a' 'l' 'e' 'm' city[0] city[1] city[2] city[3] city[4] Chapter 8 slide 18

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 pr8-13.cpp Chapter 8 slide 19

20 Parallel Array Example
string name[5]; // student name float average[5];// course average char grade[5]; // course grade ... for(int i = 0; i < 5; i++) cout << "Student: " << name[i] << " average: " << average[i] << " grade: " << grade[i] << endl; Chapter 8 slide 20

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 Chapter 8 slide 21

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 ints program prog1, prog2;// 2 arrays Chapter 8 slide 22

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 prototype void showScores(int tests[]) // function header pr8-14.cpp, pr8-15.cpp, pr8-16.cpp, pr8-17.cpp Chapter 8 slide 23

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 Chapter 8 slide 24

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 Chapter 8 slide 25

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 pr8-18.cpp Chapter 8 slide 26

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 Chapter 8 slide 27

28 Two-Dimensional Array Representation
int exams[4][3]; Use two subscripts to access element: exams[2][2] = 86; columns 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] r o w s pr8-19.cpp Chapter 8 slide 28

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 Chapter 8 slide 29

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 pr8-20.cpp Chapter 8 slide 30

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 pr8-21.cpp Chapter 8 slide 31

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]); pr8-22.cpp Chapter 8 slide 32

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 pr8-23.cpp Chapter 8 slide 33

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); Chapter 8 slide 34

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); pr8-24.cpp, pr8-25.cpp Chapter 8 slide 35

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()) ... pr8-26.cpp, pr8-27.cpp, pr8-28.cpp Chapter 8 slide 36

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]; pr8-31.cpp Chapter 8 slide 37

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; Chapter 8 slide 38

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]; pr8-32.cpp Chapter 8 slide 39

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(); pr8-33.cpp Chapter 8 slide 40

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 pr8-34.cpp, pr8-35.cpp Chapter 8 slide 41

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) }; Chapter 8 slide 42

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

44

45 Objectives You should be able to describe: One-Dimensional Arrays
Array Initialization Arrays as Arguments Two-Dimensional Arrays Common Programming Errors 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 grades 98, 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) 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 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]; 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 A First Book of C++: From Here To There, Third Edition

50 One-Dimension Arrays (continued)
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] ; A First Book of C++: From Here To There, Third Edition

52 One-Dimension Arrays (continued)
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] 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 used const int NUMELS = 5; for (int i = 0; i < NUMELS; i++) { cout << "Enter a grade: "; cin >> grade[i]; } 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 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 2 cout << "The value of element " << i << " is " << grade[i]; Example 3 const int NUMELS = 20; for (int k = 5; k < NUMELS; k++) cout << k << " " << amount[k]; 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 grades cout << "grade [" << i << "] is " << grade[i] << endl; return 0; 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: 85 Enter a grade: 90 Enter a grade: 78 Enter a grade: 75 Enter a grade: 92 grade[0] is 85 grade[1] is 90 grade[2] is 78 grade[3] is 75 grade[4] is 92 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}; 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 equivalent const 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 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 A First Book of C++: From Here To There, Third Edition

62 Array Initialization (continued)
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 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 integers char keys[256]; // an array of 256 characters double units[500], grades[500];// two arrays of //doubles The following function calls can then be made: findMax(nums); findCharacter(keys); calcTotal(nums, units, grades); 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]) 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 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 prototype int main() { int nums[MAXELS] = {2, 18, 1, 27, 16}; cout << "The maximum value is " << findMax(nums) << endl; return 0; } // find the maximum value int findMax(int vals[MAXELS]) int i, max = vals[0]; for (i = 1; i < MAXELS; i++) if (max < vals[i]) max = vals[i]; return max; A First Book of C++: From Here To There, Third Edition

68 Arrays as Arguments (continued)
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 Array declaration: names the array val and reserves storage for it int val[3][4]; 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 A First Book of C++: From Here To There, Third Edition

71 Two-Dimensional Arrays (continued)
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 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.7 Display of multiplied elements 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) 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 A First Book of C++: From Here To There, Third Edition

76 Two-Dimensional Arrays (continued)
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 A First Book of C++: From Here To There, Third Edition

78 Larger-Dimension Arrays (continued)
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 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 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] 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 A First Book of C++: From Here To There, Third Edition

83 Array [6] Chapter 8 slide 83

84 Array [5]+adding Chapter 8 slide 84

85 Array [7] and max number Chapter 8 slide 85

86 Adding 5 for each Chapter 8 slide 86

87 Multi dimensional array
Chapter 8 slide 87

88 Printing matrix Chapter 8 slide 88

89 Adding two matrix Chapter 8 slide 89

90 Chapter 8 slide 90

91 Chapter 8 slide 91

92 Chapter 8 slide 92


Download ppt "Alternate Version of Starting Out with C++, Third Edition"

Similar presentations


Ads by Google