Download presentation
Presentation is loading. Please wait.
Published byCornelius Roderick Kennedy Modified over 9 years ago
1
Copyright © 2011 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Chapter 8: Arrays Starting Out with C++ Early Objects Seventh Edition by Tony Gaddis, Judy Walters, and Godfrey Muganda Revised 2015 Edward L. Jones, Ph.D., FAMU
2
Copyright © 2011 Pearson Education, Inc. Publishing as Pearson Addison-Wesley 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 8-2
3
Copyright © 2011 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Topics (continued) 8.7 The typedef Statement 8.8 Arrays as Function Arguments 8.9 Two-Dimensional Arrays 8.10 Arrays with Three or More Dimensions 8.12 Arrays of Class Objects 8-3
4
Copyright © 2011 Pearson Education, Inc. Publishing as Pearson Addison-Wesley 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 const int CAPACITY = 5; int T[CAPACITY]; … or int T[5]; 8-4
5
Copyright © 2011 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Array Storage in Memory This definition allocates the following memory: int T[5]; 8-5 Element 0Element 1Element 2Element 3Element 4 first second third fourth fifth
6
Copyright © 2011 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Array Terminology In the definition int T[5]; –int is the data type of the array elements –T is the name of the array –5, in [5], is the size declarator. It shows the maximum number of elements in the array (i.e., array capacity). –The allocated size of an array is the number of bytes required to store the array (number of elements) * (bytes needed for each element) 8-6
7
Copyright © 2011 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Array Terminology Examples // Assume int uses 4 bytes and double uses 8 bytes const int CAPACITY = 5, DSIZE = 10; int T[CAPACITY]; // holds 5 ints, array // occupies 20 bytes double volumes[DSIZE]; // holds 10 doubles // occupies 80 bytes 8-7
8
Copyright © 2011 Pearson Education, Inc. Publishing as Pearson Addison-Wesley 8.2 Accessing Array Elements Each array element is a variable whose “name” contains a subscript that uniquely identifies the element. Name of 3 rd element array T is T[2], ”T sub-two” Subscripts start at 0 8-8 subscripts 0 1 2 3 4
9
Copyright © 2011 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Accessing Array Elements Array elements are regular variables of the base data type. T[0] = 79; cout << T[0]; cin >> T[1]; T[4] = T[0] + T[1]; cout << T; // illegal due to ?? 8-9 0 1 2 3 4 T
10
Copyright © 2011 Pearson Education, Inc. Publishing as Pearson Addison-Wesley 8.3 Inputting and Displaying Array Contents cout and cin can be used to display values from and store values into an array element. int T[5]; // 5-element array cout << "Enter first T score "; cin >> T[0]; 8-10
11
Copyright © 2011 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Array Subscripts Array subscript can be an integer constant, integer variable, or integer expression Examples: Subscript is cin >> T[3]; int constant cout << T[i]; int variable cout << T[i+j]; int expression cin >> T[T[0]]; int expression 8-11
12
Copyright © 2011 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Inputting and Displaying All Array Elements To access each element of an array –Use a (for) loop –The loop control variable sequence must be valid subscripts, e.g., 0,1,2,… –A different array element will be referenced each time through the loop * for (i = 0; i < 5; i++) sum = sum + T[i]; 8-12
13
Copyright © 2011 Pearson Education, Inc. Publishing as Pearson Addison-Wesley WARNING!! No Bounds Checking C++ does not check that an array subscript is in range An invalid array subscript can cause program to overwrite other memory Example:* const int CAPACITY = 3; int num[CAPACITY]; num[4] = 25; C++ Segmentation error!! 8-13 num [0] [1] [2] 25
14
Copyright © 2011 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Off-By-One Errors Most often occur when a program accesses data one position beyond the end of an array, or misses the first or last element of an array. Don’t confuse the ordinal (order) number of an array element (first, second, third) with its subscript (0, 1, 2) 8-14
15
Copyright © 2011 Pearson Education, Inc. Publishing as Pearson Addison-Wesley 8.5 Processing Array Contents Array elements can be –treated as ordinary variables of the same type as the array –used in arithmetic operations, in relational expressions, etc. Example: if (principalAmt[3] >= 10000) interest = principalAmt[3] * intRate1; else interest = principalAmt[3] * intRate2; 8-15
16
Copyright © 2011 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Using Increment and Decrement Operators with Array Elements int T[15]; int Tsize; When using ++ and -- operators, don’t confuse the element with the subscript T[i]++; // increments T[i], but has // no effect on i. T[i++]; // increments i, but has // no effect on T array. 8-16
17
Copyright © 2011 Pearson Education, Inc. Publishing as Pearson Addison-Wesley 8.4 Array Initialization Can be initialized during program execution with assignment statements T[0] = 79; T[1] = 82; // etc. Can be initialized at array definition with an initialization list * int T[5] = {79,82,91,77,84}; 8-17
18
Copyright © 2011 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Partial Array Initialization If an array is initialized at definition with fewer values than the size declarator of the array, remaining elements will be set to 0. * int T[5] = {79, 82}; Initial values used in order; cannot skip over elements to initialize noncontiguous range. 8-18 7982000
19
Copyright © 2011 Pearson Education, Inc. Publishing as Pearson Addison-Wesley 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 when array is defined 8-19 12171511
20
Copyright © 2011 Pearson Education, Inc. Publishing as Pearson Addison-Wesley STOP / START HERE 8-20
21
Copyright © 2011 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Copying One Array to Another Assignment operator = not defined for arrays (but for int, float, etc.). int S[5], T[5]={1,5,3,2,7}; int Tsize = 5; // contains 5 vals. S = T; // won’t work Instead: use a loop to copy element-by- element: * for (int k=0; k<Tsize; k++) S[k] = T[k]; 8-21
22
Copyright © 2011 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Are Two Arrays Equal? Also, relational operators not defined for arrays: if (T2 == T1) cout << “EQUIVALENT”; //Invalid Instead: Sizes must match AND corresponding elements must match. Method 1: Use a flag and while loop: int k = 0; bool Equivalent = (T1size == T2size); while (Equivalent && k<T1size) { if(T1[k] != T2[k])Equivalent = false; k++; } if (Equivalent) cout << “EQUIVALENT”; 8-22
23
Copyright © 2011 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Are Two Arrays Equal? Also, cannot compare in a single expression: if (T2 == T1) Sizes AND corresponding elements must match. Method 1a: Use a flag and while loop: int k = 0; bool Equal = (T1size == T2size); while (Equal && k < CAPACITY) { Equal = (T1[k] == T2[k]); k++; } if (Equivalent) cout << “EQUIVALENT”; 8-23
24
Copyright © 2011 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Are Two Arrays Equal? Also, cannot compare in a single expression: if (T2 == T1) Instead: Sizes must match AND corresponding elements must match. Method 2: Use a flag and for loop: bool Equal = (T1size == T2size); for (int k=0; Equal && k<T1size; k++) { Equal = (T1[k] == T2[k]); } 8-24
25
Copyright © 2011 Pearson Education, Inc. Publishing as Pearson Addison-Wesley STOP / START HERE 8-25
26
Copyright © 2011 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Sum, Average of Array Elements Use a simple loop to add together array elements float average, sum = 0; for(int j=0; j<Tsize; j++) sum += T[j]; Once summed, average can be computed average = sum/Tsize; 8-26
27
Copyright © 2011 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Largest Array Element Use a loop to examine each element and find the largest element (i.e., one with the largest value) * int largest = T[0]; for (int m = 1; m < CAPACITY; m++) { if (T[m] > largest) largest = T[m]; } cout << "Highest score is " << largest; A similar algorithm exists to find smallest. 8-27
28
Copyright © 2011 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Partially-Filled Arrays The exact amount of data may not be known when a program is written. Programmer estimates maximum data capacity, and declares the array accordingly. Program must keep track of how many array elements are actually used – to avoid exceeding array capacity (segmentation error) * int T[CAPACITY]; int Tsize = 0; // Size of array T, initialized to empty. 8-28
29
Copyright © 2011 Pearson Education, Inc. Publishing as Pearson Addison-Wesley C-Strings and string Objects Both contain an array of characters. Both can be manipulated character by character. string city; cout << "Enter city name: "; cin >> city; cout << “Third letter is ‘” << city[2]; 8-29 'S''a''l''e''m' city[0]city[1]city[2]city[3]city[4]
30
Copyright © 2011 Pearson Education, Inc. Publishing as Pearson Addison-Wesley 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 The parallel arrays do not have to hold data of the same type Example: Each spreadsheet column is stored as a separate, parallel array. 8-30
31
Copyright © 2011 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Parallel Array Example const int CAPACITY = 5; string name[CAPACITY]; // student name float average[CAPACITY]; // course average char grade[CAPACITY]; // course grade 8-31 0123401234 0123401234 0123401234 name average grade
32
Copyright © 2011 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Displaying Parallel Array Contents int size = 0; *... //-| Processing to obtain size rows of data.... //-| Display size rows of data. for (int i = 0; i < size; i++) cout << " Student: " << name[i] << " Average: " << average[i] << " Grade: " << grade[i] << endl; 8-32
33
Copyright © 2011 Pearson Education, Inc. Publishing as Pearson Addison-Wesley 8-33 8.13 Arrays of Structured Variables Records can be used as array elements * struct Student { int studentID; string name; short year; double gpa; }; Student Class[30]; // Holds 30 // Student records.
34
Copyright © 2011 Pearson Education, Inc. Publishing as Pearson Addison-Wesley 8-34 Arrays of Structured Variables Use array subscript [ ] to access a specific record in the array Then use dot. operator to access a members of that record cin >> Class[25].studentID; cout << Class[i].name << " has GPA " << Class[i].gpa << endl;
35
Copyright © 2011 Pearson Education, Inc. Publishing as Pearson Addison-Wesley 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 exam[4][3]; 8-35 Number of rows Number of cols
36
Copyright © 2011 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Two-Dimensional Array Representation int exam[4][3]; Must use two subscripts to access element exam[2][2] = 86; 8-36 exam[0][0]exam[0][1]exam[0][2] exam[1][0]exam[1][1]exam[1][2] exam[2][0]exam[2][1]exam[2][2] exam[3][0]exam[3][1]exam[3][2] columns rowsrows
37
Copyright © 2011 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Initialization at Definition Two-dimensional arrays are initialized row- by-row int exam[2][2] = { {84, 78}, {92, 97} }; exam[0]is row 1, a 2-element int array. 8-37 8478 9297
38
Copyright © 2011 Pearson Education, Inc. Publishing as Pearson Addison-Wesley 2D Array Traversal Use nested loops, outer one for row and inner one for column, to visit each array element in a row-by-row fashion. for (int r=0; r<NROWS; r++) //outer for (int c=0; c<NCOLS; c++) //inner process exam[r][c] … 8-38
39
Copyright © 2011 Pearson Education, Inc. Publishing as Pearson Addison-Wesley 2D Array Traversal Use nested loops, outer one for column, and inner one for row, to visit each array element in a column-by-column fashion for (int c=0; c<NCOLS; c++) for (int r=0; r<NCOLS; r++) process exam[r][c] … 8-39
40
Copyright © 2011 Pearson Education, Inc. Publishing as Pearson Addison-Wesley STOP / START HERE 8-40
41
Copyright © 2011 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Array Element as Function Argument Passing a single array element (e.g., X[3]) to a function is no different than passing a regular variable. The receiving function does not need to know that the value it receives is coming from an array displayValue(score[i]); // function call void displayValue(int item) // function header { cout << item << endl; ) // function body } 8-41
42
Copyright © 2011 Pearson Education, Inc. Publishing as Pearson Addison-Wesley 8.8 Arrays as Function Arguments To declare a function with a one-dimensional array parameter, use empty [] to indicate the argument is a 1-D array. To pass an array argument to a function, just use the array name // Function prototype void showScores(int []); // Function header void showScores(int T[]) // Function call showScores(T); 8-42
43
Copyright © 2011 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Modifying Arrays in Functions Array parameters are passed by reference Changes made to array in a function are made to the actual array in the calling function Must be careful that an array is not inadvertently/mistakenly changed by a function 8-43
44
Copyright © 2011 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Passing an Entire 1-D Array Use the array name, without any brackets, as the argument Often necessary to also pass the array size so the function knows how many elements to process void showScores(int[], int); // function prototype. void showScores(int A[],int Asize) // function header. showScores(T, 5); // function call. 8-44
45
Copyright © 2011 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Passing a 2-Dimensional Array to a Function Use empty [] for row and a size declarator for col in the prototype and header // Prototype, where #cols is 2 void getExams(int[][2], int); // Header void getExams (int Ex[][2], int rows) Use array name as argument in function call getExams(exam, 2); 8-45
46
Copyright © 2011 Pearson Education, Inc. Publishing as Pearson Addison-Wesley 8.10 Arrays with Three or More Dimensions Can define arrays with any number of dimensions short rectSolid [2][3][5]; double timeGrid[3][4][3][4]; When used as parameter, specify size of all but first dimension void getRectSolid(short [][3][5]); 8-46
47
Copyright © 2011 Pearson Education, Inc. Publishing as Pearson Addison-Wesley 8.7 The typedef Statement Creates an alias for a data type. DOES NOT create a data type. Format: typedef existingType newTypeName; Example: typedef float Money; Money Paycheck[12]; // float array. 8-47
48
Copyright © 2011 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Uses of typedef Can make code more readable Creates alias (alternate name) for a data type Can give a name to an array-based data type (element type, capacity (specified or unspecified). // Define yearArray as a data type // that is an array of 12 ints typedef int yearArray[12]; // Create two 12-element int arrays. yearArray highTemps, lowTemps; 8-48
49
Copyright © 2011 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Using typedef for Array Parameter Can use typedef to simplify function prototype and heading // Make intArray an integer array // of unspecified size typedef int intArray[]; // Function prototype void showScores(intArray, int); // Function header void showScores(intArray T, int size) This aliased array type has unspecified capacity. 8-49
50
Copyright © 2011 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Using typedef with a Two-Dimensional Array Can use typedef for simpler notation typedef int intExamsARRAY[][2]; // Indefinite // Nx2 array. // Function prototype void getExams(intExamsARRAY, int); // Function header void getExams(intExamsARRAY exam, int rows) WARNING: Implementor/caller of function must remember that typedef refers to an array. 8-50
51
Copyright © 2011 Pearson Education, Inc. Publishing as Pearson Addison-Wesley STOP / START HERE 8-51
52
Copyright © 2011 Pearson Education, Inc. Publishing as Pearson Addison-Wesley 8.14 Arrays of Class Objects Class objects can also be used as array elements class SQUARE { private: int side; public: SQUARE(int s = 1) { side = s; } int getSide() { return side; } }; SQUARE shape[10]; // Create array of 10 // SQUARE objects 8-52
53
Copyright © 2011 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Arrays of Class Objects First, use an array subscript [ ] to access a specific object in the array Then, use dot. operator to access the member of that object for (i = 0; i < 10; i++) cout << shape[i].getSide() << endl; 8-53 member function object
54
Copyright © 2011 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Chapter 8: Arrays Starting Out with C++ Early Objects Seventh Edition by Tony Gaddis, Judy Walters, and Godfrey Muganda Revised 2015: Edward L. Jones, Ph.D., FAMU
Similar presentations
© 2024 SlidePlayer.com. Inc.
All rights reserved.