# Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Chapter 9: Data Structures: Arrays and Structs Problem Solving, Abstraction,

## Presentation on theme: "Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Chapter 9: Data Structures: Arrays and Structs Problem Solving, Abstraction,"— Presentation transcript:

Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Chapter 9: Data Structures: Arrays and Structs Problem Solving, Abstraction, and Design using C++ 6e by Frank L. Friedman and Elliot B. Koffman

Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley 2 9.1 The Array Data Type Array elements have a common name –The array as a whole is referenced through the common name Array elements are of the same type — the base type Individual elements of the array are referenced by sub-scripting the group name –element’s relative position used, beginning with 0 Array stored in consecutive memory locations

Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley 3 Additional Array Details Subscripts are denoted as expressions within brackets: [ ] Base type can be any fundamental, library- defined, or programmer -defined type The index type is integer and the index range must be 0... n -1, for array of size n

Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley 4 Array Declaration element-type array-name [array-size]; Type of all the values in the array Name of the entire collection of values Integer expression indicating number of elements in the array

Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley 5 Example 1 element-type array-name [array-size] = {initialization-list}; float x[8] = {16.0, 12.0, 6.0, 8.0, 2.5, 12.0, 14.0, -54.5}; 16.012.06.08.02.512.014.0-54.5

Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley 6 Example 1 (con’t) cout << x[0]; x[3] = 25.0; sum = x[0] + x[1]; sum += x[2]; x[3] += 1.0; x[2] = x[0] + x[1];

Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley 7 Example 2 const int NUM_EMP = 10; bool onVacation[NUM_EMP]; int vacationDays[NUM_EMP]; enum day {sunday, monday, tuesday, wednesday, thursday, friday, saturday}; day dayOff[NUM_EMP]; float plantHours[7];

Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley 8 Figure 9.3 Arrays onVacation, vacationDays, and dayOff

Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley 9 Array Initialization List of initial values enclosed in braces ({ }) following assignment operator (=) Values from initialization list are assigned in order to array elements Length of initialization list cannot exceed size of the array If too few values, value assigned is system dependent Size of array can be automatically set to number of initializing values using empty brackets ([ ])

Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley 10 Array Subscripts Enclosed in brackets ([ ]) Indicates which element is referenced by position Array subscript value is different than array element value Subscript can be an expression of any integral type To be valid, subscript must be a value between 0 and one less than the array size

Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley 11 9.2 Sequential Access to Array Elements Random Access –Access elements is any order Sequential Access –Process elements in sequential order starting with the first

Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley 12 Example of Sequential Access int cube[10]; for (int i = 0; i < 10; i++) cube[i] = i * i * i;

Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley 13 Strings and Arrays of Characters string object uses an array of char Can reference individual character of a string object in different ways –name[ i ] –name.at( i ) Other member functions of string class –message.length( i )

Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley 14 9.3 Array Arguments Use, +, -, etc. to test and modify array elements individually Can pass array elements to functions exchange (s[3], s[5]);

Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley 15 Listing 9.3 Function to exchange the contents of two floating-point memory locations

Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley 16 Passing an Array Argument Arrays are always passed by reference Pass entire array to a function by writing just its name (no subscripts or brackets) in the argument list of the function call In function definition and prototype, user empty brackets ([ ]) to identify array Use keyword const to indicate that array argument cannot be changed by function

Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley 17 Example 1 const int MAX_SIZE = 5; float x[MAX_SIZE ]; float y[MAX_SIZE ];... if (sameArray(x, y, MAX_SIZE)) cout << “Arrays are identical.” << endl; else cout << “Arrays are different.” << endl;

Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley 19 Example 2 const int MAX_SIZE = 5; float x[MAX_SIZE ] = {1.8, 2.2, 3.4, 5.1, 6.7}; float y[MAX_SIZE ] = {2.0, 4.5, 1.3, 4.0, 5.5}; float z[MAX_SIZE];... addArray(MAX_SIZE, x, y, z);

Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley 20 Listing 9.5 Function addArray // File: addArray.cpp // Stores the sum of a[i] and b[i] in c[i] // Sums pairs of array elements with subscripts ranging from 0 //to size – 1 // Pre: a[i] and b[i] are defined (0 <= i <= size-1) // Post: c[i] = a[i] + b[i] (0 <= i <= size-1) void addArray (int size,// IN: the size of the arrays const float a[],// IN: the first array const float b[],// IN: the second array float c[])// OUT: result array { // Add corresponding elements of a and b and store in c for (int i = 0; i < size; i++) c[i] = a[i] + c[i]; }

Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley 21 9.4 Reading Part of an Array Sometimes it is difficult to know how many elements will be in an array –150 students in one section –200 students in another section Always allocate enough space for largest possible amount needed Remember to start reading with index [0] Must keep track of how many elements used

Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley 24 9.5 Searching and Sorting Arrays Two common array processing problems –Searching –Sorting E.g. –look for a particular score, highest score, etc. –rearrange an array of scores in increasing order

Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley 25 Finding the Smallest Value 1. Assume the first element is smallest so far and save its subscript 2. For each array element after the first one 2.1 If the current element < the smallest so far 2.1.1 Save the subscript of current element

Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley 28 Array Search - Interface Input arguments –int items[ ]// array to search –int size// number of items in array –int target// item to find Output arguments –none Returns –if found, subscript of first location in array –if not found, -1

Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley 29 Array Search - Algorithm 1. For each array element 1.1 If the current element contains the target 1.2 Return the subscript of the current element 2. Return -1.

Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley 31 Sorting an Array in Ascending Order Many programs execute more efficiently if data is in order before processing starts Possible to order in either ascending or descending arrangement Selection sort just one of many ways to do this –reuses previous components of search and swap operations

Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley 32 Selection Sort Input arguments float items[ ]// array to sort int n// number of items to sort Output arguments int items [ ]// original array sorted Local variables int i// subscript of first element int minSub// subscript of smallest item

Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley 33 Selection Sort - Algorithm 1. Starting with the first item in the array (subscript 0) and ending with the next-to-last-item: 1.1 Set i equal to the subscript of the first item in the subarray to be processed in the next steps 1.2 Find the subscript (minSub) of the smallest item in the subarray with subscripts ranging from i through n-1 1.3 Exchange the smallest item found in step 1.2 with item i

Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley 35 9.6 Analyzing Algorithms: Big-O Notation Need to estimate efficiency of algorithms in order to compare Approximate the effect on an algorithm of a change in the number of items, n, that the algorithm processes Look at how an algorithm’s execution time increases with n (i.e. its growth rate). –Expressed in terms of largest contributing factor of polynomial describing processing time

Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley 36 Table 9.4 Table values of n and n 2

Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley 37 Analysis of a Search Algorithm Search an array of n elements using linear search method Target can be anywhere in the array For random data, it’s equally likely target is at end of array as at beginning On average, must search n/2 array elements Linear search is O(n) process

Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley 38 Analysis of Sort Algorithm Focus on the number of array element comparisons and exchanges required For selection sort, requires n-1 comparisons for 1st pass, n-2 for 2nd, etc. Total number of comparisons is 1 + 2 + 3 +... + (n-2) + (n-1) which is n  (n-1) = n 2 /2 - n/2 2 or O(n 2 )

Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley 39 9.7 Multidimensional Arrays Allows for complex arrangement of data Can have many dimensions Syntax element-type arrayName [size 1 ] [size 2 ]…[size n ]; E.g. double table[NROWS] [NCOLS];

Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley 40 Declaring Two- Dimensional Arrays Most common multidimensional array Represents a table E.g. char ticTacTie[3][3]; Access ticTacTie[1][2] Row Column

Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley 41 Figure 9.10 A tic-tac-toe board stored as array ticTacToe

Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley 42 Example const int NUM_ROWS = 11; const int SEATS_IN_ROW = 9; string seatPlan [NUM_ROWS][SEATS_IN_ROW];... seatPlan[0][8] = “Gerry”;

Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley 43 Figure 9.11 A classroom seating plan

Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley 44 Initialization Each inner pair of braces contains initial values for one row of the array matrix const int NUM_ROWS = 2; const int NUM_COLS = 3; float matrix[NUM_ROWS][NUM_COLS] ={{5.0, 4.5, 3.0}, {-16.0, -5.9, 0.0}};

Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley 45 Nested Loops for Two-D Arrays Row order –use row subscript as outer loop control variable Column order –use column subscript as outer loop control variable

Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley 46 Two-Dimensional Arrays as Function Arguments Row dimension can be anonymous, but column dimension must be specified C++ must know the number of elements in each row in order to access a particular array element

Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley 47 Function sumMatrix float sumMatrix (float table[][NUM_COLS], int rows) { float sum = 0.0; // Add each array element value to sum. for (int r = 0; r < rows; r++) for (int c = 0; c < NUM_COLS; c++) sum += table[r][c]; return sum; }

Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley 48 Arrays with Several Dimensions const int PEOPLE = 10; const int YEARS = 5; money sales[PEOPLE][YEARS][12];

Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley 49 9.8 The struct Data Type struct used to store related data items Individual components of the struct are called its members Each member can contain different types of data Three parts –declaration of structure –use of structure to define a new variable –access of members of the structured variable Typically declare struct as global

Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley 50 struct Type Declaration struct struct-type { type 1 id-list 1 ; type 2 id-list 2 ;... type n id-list n ; }; struct employee { int id; string name; char gender; int numDepend; float rate; float totWages; };... employee organist, janitor;

Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley 51 Accessing Members of a struct organist.id = 1234; organist.name = “Noel Goddard”; organist.gender = ‘F’; organist.numDepend = 0; organist.rate = 12.00; organist.totWages = 480.0;... organist.totWages += (organist.rate * 40.0);

Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley 52 9.9 structs as Operands and Arguments struct copy or assignment organist = janitor; // copy janitor to organist Copies each member from janitor struct to organist struct

Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley 53 Passing a struct as an Argument Actual and formal parameters must be same type struct Using structs as arguments can shorten argument list Passing structs by value can be inefficient, since it duplicates values of all members

Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley 54 Passing struct by Reference Same as other reference parameters –use & to identify in parameter list Can also use constant reference –precede parameter with reserved word const –E.g. void printStats(const examStats& stuExams)

Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley 57 9.10 Array of Structs Declaration of an array of structs employee company [10]; Storage for 10 employee structs Can pass to a function readEmployee (company[i]);

Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley 58 Figure 9.14 Sketch of array company

Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley 59 Function readCompany // File: readCompany.cpp // READS 10 EMPLOYEE RECORDS INTO ARRAY company void readCompany (employee company[]) { // Read 10 employees. for (int i = 0; i < 10; i++) { cout << "Enter data for employee " << (i+1) << ":" << endl; readEmployee (company[i]); }

Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley 60 9.11 String as Arrays of Characters Declaring and initializing char name[ ] = “Jackson”; // array size 8 or char name[8] = “Jackson”; // 7 characters Last character stored is ‘\0’ to denote the end of the string in a character array

Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley 61 Reading and Writing Character Arrays Can read or write entire character array at once cin >> name; cout << name << endl; Can read or write each character of of array –must account for null character at end of array

Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley 62 9.12 Graphics with Arrays To draw a triangle or a closed figure that has more than 4 sides, use drawpoly and fillpoly Both functions require an array argument that stores the points to be displayed. The coordinates of each point are stored in consecutive elements of the array. For drawpoly, the polygon must be closed; that is, the first point should be repeated as the last point.

Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley 63 Listing 9.15 #include int main() { // (x, y) int poly[12] = { 100, 200, // top-left corner 300, 100, // roof peak 500, 200, // top-right corner 500, 400, // bottom-right corner 100, 400, // bottom-left corner 100, 200 // top-left corner }; char message[] = "Press a key to repaint house - press Q to quit"; initwindow(640, 500, "House"); outtextxy(100, 450, message);

Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley 64 Listing 9.15 cont’d srand(time(NULL)); char ch = '*'; while (toupper(ch) != 'Q') { int color = rand() % 16; int fill = rand() % 12; setfillstyle(fill, color); fillpoly(6, poly); ch = getch(); } closegraph(); // close the window }

Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley 66 Drawing a grid Listing 9.16 is a program that draws the grid shown in Fig. 9.18. In function main, the two-dimensional array gridArray stores the color values to be displayed in each cell, starting with row 0 which has all black cells (color value is 0). This array is passed to function drawGrid. The body of function drawGrid contains a pair of nested loops to access each element of gridArray.

Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley 67 Drawing a grid cont’d For element gridArray[r][c], the statements rectangle(c*CELL_SIZE, r*CELL_SIZE, // top-left corner c*CELL_SIZE + CELL_SIZE, // bottom-right r*CELL_SIZE + CELL_SIZE); // corner draw a rectangle associated with row r, column c of the array. The statements color = gridArray[r][c] % 16; setfillstyle(SOLID_FILL, color); floodfill(c*CELL_SIZE + 1, r*CELL_SIZE + 1, WHITE); fill the rectangle just drawn with the color value stored in grid[r][c]. After the grid is drawn, the main function prompts the user to select a cell by clicking in it.

Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley 68 Drawing a grid cont’d Method reportResult processes the mouse click and stores in (x, y) the coordinates of the pixel clicked. The statements row = y / CELL_SIZE; column = x / CELL_SIZE; convert the pixel coordinates to a row and column value which are returned to the main function. The graphics function getpixel returns an integer representing the color value of the cell that was selected. color = getpixel(x, y); // return color of pixel at (x, y)

Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley 69 Listing 9.16 #include using namespace std; const int NUM_ROWS = 5; const int NUM_COLS = 6; const int CELL_SIZE = 50; // dimensions of a square cell void drawGrid(int[][NUM_COLS]); void reportResult(int&, int&, int&); void recolor(int, int, int, int); int main() { int gridArray[NUM_ROWS][NUM_COLS] = { {0, 0, 0, 0, 0, 0}, {2, 4, 2, 4, 2, 4}, {1, 2, 3, 4, 5, 6}, {2, 3, 4, 15, 6, 7}, {5, 5, 5, 5, 5, 5} };

Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley 70 Listing 9.16 cont’d int width = CELL_SIZE * NUM_COLS; int height = CELL_SIZE * NUM_ROWS + 100; int row, column; // row and column of cell clicked int color; // color of cell clicked initwindow(width, height, "Grid - Press a key to close"); drawGrid(gridArray); char message[100] = "Select a cell by clicking it"; outtextxy(100, height - 50, message); reportResult(row, column, color); cout << "You clicked the cell in row " << (row + 1) << ", column " << (column + 1) << endl; recolor(row, column, color, HATCH_FILL); getch(); closegraph(); }

Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley 71 Listing 9.16 cont’d // Draw the grid corresponding to the color values in gridArray void drawGrid(int gridArray[][NUM_COLS]) { int color; // color of cell // Draw a grid cell for each array element for (int r = 0; r < NUM_ROWS; r++) { for (int c = 0; c < NUM_COLS; c++) { setcolor(WHITE); // border color // Draw cell border rectangle(c*CELL_SIZE, r*CELL_SIZE, // top-left corner c*CELL_SIZE + CELL_SIZE, // bottom-right r*CELL_SIZE + CELL_SIZE); // corner // Fill the cell color = gridArray[r][c] % 16; setfillstyle(SOLID_FILL, color); floodfill(c*CELL_SIZE + 1, r*CELL_SIZE + 1, WHITE); }

Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley 72 Listing 9.16 cont’d // Report the results of a mouse click by the user. // Pre: The grid is displayed // Post: The row, column, and color of the cell selected // are returned through row and column. void reportResult(int& row, int& column, int& color) { int x, y; // (x, y) position of mouse click clearmouseclick(WM_LBUTTONDOWN); while (!ismouseclick(WM_LBUTTONDOWN)) { delay(100); } getmouseclick(WM_LBUTTONDOWN, x, y); // Convert x (y) pixel position to row (column) row = y / CELL_SIZE; column = x / CELL_SIZE; color = getpixel(x, y); // get pixel color }

Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley 73 Listing 9.16 cont’d // Recolors a selected grid cell with a new color and // pattern. // Pre: The cell row and column and new color // and pattern are are defined. // Post: The selected cell is refilled. void recolor(int row, int column, int newColor, int pattern) { setfillstyle(pattern, newColor); floodfill(column*CELL_SIZE + 1, row*CELL_SIZE + 1, WHITE); }