Chapter 9 Data Structures: Arrays and Structs Lecture Notes Prepared By: Blaise W. Liffick, PhD Department of Computer Science Millersville University.

Slides:



Advertisements
Similar presentations
Copyright © 2014, 2008 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Starting Out with C++ Early Objects Eighth Edition by Tony Gaddis,
Advertisements

1 Arrays Chapter 9. 2 Outline  The array structure (Section 9.1)  Array declaration  Array initialization  Array subscripts  Sequential access to.
Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Chapter 9: Data Structures: Arrays and Structs Problem Solving, Abstraction,
Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Slide 7- 1 Overview 7.1 Introduction to Arrays 7.2 Arrays in Functions 7.3.
Chapter 9: Searching, Sorting, and Algorithm Analysis
Lecture 22: Arrays (cont). 2 Lecture Contents: t Searching in array: –linear search –binary search t Multidimensional arrays t Demo programs t Exercises.
Data Structures Arrays and Structs Chapter The Array Data Type t Array elements have a common name –The array as a whole is referenced through.
 2003 Prentice Hall, Inc. All rights reserved Introduction Arrays –Structures of related data items –Static entity (same size throughout program)
© Copyright 1992–2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved. 1 Chapter 6 - Arrays Outline 6.1Introduction 6.2Arrays.
Arrays Hanly - Chapter 7 Friedman-Koffman - Chapter 9.
 2006 Pearson Education, Inc. All rights reserved Arrays.
 2003 Prentice Hall, Inc. All rights reserved. 1 Arrays –Structures of related data items –Static entity (same size throughout program) A few types –Pointer-based.
Chapter 6 C Arrays Acknowledgment The notes are adapted from those provided by Deitel & Associates, Inc. and Pearson Education Inc. Arrays are data structures.
Chapter 5 - Arrays CSC 200 Matt Kayala 2/27/06. Learning Objectives  Introduction to Arrays  Declaring and referencing arrays  For-loops and arrays.
C++ for Engineers and Scientists Third Edition
Chapter 8 Arrays and Strings
1 CSCE 1030 Computer Science 1 Arrays Chapter 7 in Small Java.
 2007 Pearson Education, Inc. All rights reserved C Arrays.
Chapter 7: Arrays. In this chapter, you will learn about: One-dimensional arrays Array initialization Declaring and processing two-dimensional arrays.
Chapter 7 Arrays. Overview 7.1 Introduction to Arrays 7.2 Arrays in Functions 7.3 Programming with Arrays 7.4 Multidimensional Arrays.
© Copyright 1992–2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved. 1 Chapter 6 - Arrays Outline 6.1Introduction 6.2Arrays.
 2006 Pearson Education, Inc. All rights reserved Arrays.
Modular Programming Chapter Value and Reference Parameters computeSumAve (x, y, sum, mean) ACTUALFORMAL xnum1(input) ynum2(input) sumsum(output)
Chapter 8 Arrays and Strings
1 DATA STRUCTURES: LISTS. 2 LISTS ARE USED TO WORK WITH A GROUP OF VALUES IN AN ORGANIZED MANNER. A SERIES OF MEMORY LOCATIONS CAN BE DIRECTLY REFERENCED.
EGR 2261 Unit 8 One-dimensional Arrays  Read Malik, pages in Chapter 8.  Homework #8 and Lab #8 due next week.  Quiz next week.
(continue) © by Pearson Education, Inc. All Rights Reserved.
JAVA: An Introduction to Problem Solving & Programming, 5 th Ed. By Walter Savitch and Frank Carrano. ISBN © 2009 Pearson Education, Inc., Upper.
Arrays Module 6. Objectives Nature and purpose of an array Using arrays in Java programs Methods with array parameter Methods that return an array Array.
Object-Oriented Program Development Using Java: A Class-Centered Approach, Enhanced Edition.
C++ Programming: From Problem Analysis to Program Design, Fifth Edition Arrays.
Value and Reference Parameters. CSCE 1062 Outline  Summary of value parameters  Summary of reference parameters  Argument/Parameter list correspondence.
C++ for Engineers and Scientists Second Edition Chapter 11 Arrays.
Starting Out with C++ Early Objects Seventh Edition by Tony Gaddis, Judy Walters, and Godfrey Muganda Modified for use by MSU Dept. of Computer Science.
Lecture 26: Structures / struct s/. 2 Lecture Contents: t Basics of structs t Struct type definition ( struct reserved word) t Struct type definition.
Section 5 - Arrays. Problem solving often requires information be viewed as a “list” List may be one-dimensional or multidimensional List is implemented.
Copyright © 2012 Pearson Addison-Wesley. All rights reserved. Chapter 7 Arrays.
 2007 Pearson Education, Inc. All rights reserved C Arrays.
Slide 1 Chapter 5 Arrays. Slide 2 Learning Objectives  Introduction to Arrays  Declaring and referencing arrays  For-loops and arrays  Arrays in memory.
Chapter 5 Arrays. Copyright © 2006 Pearson Addison-Wesley. All rights reserved. 5-2 Learning Objectives  Introduction to Arrays  Declaring and referencing.
More Array Access Examples Here is an example showing array access logic: const int MAXSTUDENTS = 100; int Test[MAXSTUDENTS]; int numStudents = 0;... //
Chapter 7 Arrays. Introductions Declare 1 variable to store a test score of 1 student. int score; Declare 2 variables to store a test score of 2 students.
 2008 Pearson Education, Inc. All rights reserved. 1 Arrays and Vectors.
1 Chapter 12 Arrays. 2 C++ Data Types structured array struct union class address pointer reference simple integral enum char short int long bool floating.
Arrays.
JAVA: An Introduction to Problem Solving & Programming, 5 th Ed. By Walter Savitch and Frank Carrano. ISBN © 2008 Pearson Education, Inc., Upper.
Arrays Chapter 12. Overview Arrays and their properties Creating arrays Accessing array elements Modifying array elements Loops and arrays.
Module 1: Array ITEI222 - Advance Programming Language.
Arrays Chapter 7. MIS Object Oriented Systems Arrays UTD, SOM 2 Objectives Nature and purpose of an array Using arrays in Java programs Methods.
 2000 Prentice Hall, Inc. All rights reserved. 1 Chapter 4 - Arrays Outline 4.1Introduction 4.2Arrays 4.3Declaring Arrays 4.4Examples Using Arrays 4.5Passing.
Arrays Declaring arrays Passing arrays to functions Searching arrays with linear search Sorting arrays with insertion sort Multidimensional arrays Programming.
SEQUENTIAL AND OBJECT ORIENTED PROGRAMMING Arrays.
Lecture 21: Arrays. 2 Lecture Contents: t Declaring and referencing arrays t Array subscripts t Using for/while loops for sequential access t Demo programs.
Copyright © 2011 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Starting Out with C++ Early Objects Seventh Edition by Tony Gaddis, Judy.
Chapter 5 Arrays Copyright © 2016 Pearson, Inc. All rights reserved.
VISUAL C++ PROGRAMMING: CONCEPTS AND PROJECTS Chapter 7A Arrays (Concepts)
Arrays as Function Parameters. CSCE 1062 Outline  Passing an array argument (section 9.3)  Reading part of an array (section 9.4)  Searching and sorting.
Arrays An array is a grouping of elements of the same type that share a common base name Can have any number of elements in the array Individual elements.
Chapter 9: Data Structures: Arrays and Structs
7 Arrays.
Arrays Kingdom of Saudi Arabia
Arrays An array is a grouping of elements of the same type that share a common base name Can have any number of elements in the array Individual elements.
7 Arrays.
Chapter 9: Data Structures: Arrays
Arrays Arrays A few types Structures of related data items
Arrays An array is a grouping of elements of the same type that share a common base name Can have any number of elements in the array Individual elements.
Structure (i.e. struct) An structure creates a user defined data type
Data Structure(s) A way of storing and organizing data in a computer so that it can be used efficiently. e.g. Arrays Linked Lists stacks Queues Trees.
4.1 Introduction Arrays A few types Structures of related data items
Presentation transcript:

Chapter 9 Data Structures: Arrays and Structs Lecture Notes Prepared By: Blaise W. Liffick, PhD Department of Computer Science Millersville University Millersville, PA

© 2004 Pearson Addison-Wesley. All rights reserved 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

© 2004 Pearson Addison-Wesley. All rights reserved9-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

© 2004 Pearson Addison-Wesley. All rights reserved9-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

© 2004 Pearson Addison-Wesley. All rights reserved9-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};

© 2004 Pearson Addison-Wesley. All rights reserved9-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];

© 2004 Pearson Addison-Wesley. All rights reserved9-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];

© 2004 Pearson Addison-Wesley. All rights reserved9-8 Figure 9.3 Arrays onVacation, vacationDays, and dayOff

© 2004 Pearson Addison-Wesley. All rights reserved9-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 ([ ])

© 2004 Pearson Addison-Wesley. All rights reserved9-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

© 2004 Pearson Addison-Wesley. All rights reserved Sequential Access to Array Elements Random Access –Access elements is any order Sequential Access –Process elements in sequential order starting with the first

© 2004 Pearson Addison-Wesley. All rights reserved9-12 Example of Sequential Access int cube[10]; for (int i = 0; i < 10; i++) cube[i] = i * i * i;

© 2004 Pearson Addison-Wesley. All rights reserved9-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 )

© 2004 Pearson Addison-Wesley. All rights reserved Array Arguments Use, +, -, etc. to test and modify array elements individually Can pass array elements to functions exchange (s[3], s[5]);

© 2004 Pearson Addison-Wesley. All rights reserved9-15 Listing 9.3 Function to exchange the contents of two floating-point memory locations

© 2004 Pearson Addison-Wesley. All rights reserved9-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

© 2004 Pearson Addison-Wesley. All rights reserved9-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;

© 2004 Pearson Addison-Wesley. All rights reserved9-18 Listing 9.4 Function sameArray

© 2004 Pearson Addison-Wesley. All rights reserved9-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);

© 2004 Pearson Addison-Wesley. All rights reserved9-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]; }

© 2004 Pearson Addison-Wesley. All rights reserved 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

© 2004 Pearson Addison-Wesley. All rights reserved9-22 Listing 9.7 Function readScoresFile

© 2004 Pearson Addison-Wesley. All rights reserved9-23 Listing 9.7 Function readScoresFile (continued)

© 2004 Pearson Addison-Wesley. All rights reserved 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

© 2004 Pearson Addison-Wesley. All rights reserved9-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 Save the subscript of current element

© 2004 Pearson Addison-Wesley. All rights reserved9-26 Listing 9.8 Function findIndexOfMin

© 2004 Pearson Addison-Wesley. All rights reserved9-27 Listing 9.8 Function findIndexOfMin (continued)

© 2004 Pearson Addison-Wesley. All rights reserved9-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

© 2004 Pearson Addison-Wesley. All rights reserved9-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.

© 2004 Pearson Addison-Wesley. All rights reserved9-30 Listing 9.9 The function linSearch

© 2004 Pearson Addison-Wesley. All rights reserved9-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

© 2004 Pearson Addison-Wesley. All rights reserved9-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

© 2004 Pearson Addison-Wesley. All rights reserved9-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 Exchange the smallest item found in step 1.2 with item i

© 2004 Pearson Addison-Wesley. All rights reserved9-34 Listing 9.10 Function selSort

© 2004 Pearson Addison-Wesley. All rights reserved 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

© 2004 Pearson Addison-Wesley. All rights reserved9-36 Table 9.4 Table values of n and n 2

© 2004 Pearson Addison-Wesley. All rights reserved9-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

© 2004 Pearson Addison-Wesley. All rights reserved9-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 (n-2) + (n-1) which is n  (n-1) = n 2 /2 - n/2 2 or O(n 2 )

© 2004 Pearson Addison-Wesley. All rights reserved 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

© 2004 Pearson Addison-Wesley. All rights reserved9-40 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;

© 2004 Pearson Addison-Wesley. All rights reserved9-41 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);

© 2004 Pearson Addison-Wesley. All rights reserved structs as Operands and Arguments struct copy or assignment organist = janitor; // copy janitor to organist Copies each member from janitor struct to organist struct

© 2004 Pearson Addison-Wesley. All rights reserved9-43 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

© 2004 Pearson Addison-Wesley. All rights reserved9-44 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)

© 2004 Pearson Addison-Wesley. All rights reserved9-45 Listing 9.11 Function printStats

© 2004 Pearson Addison-Wesley. All rights reserved9-46 Listing 9.12 Function readEmployee

© 2004 Pearson Addison-Wesley. All rights reserved 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

© 2004 Pearson Addison-Wesley. All rights reserved9-48 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

© 2004 Pearson Addison-Wesley. All rights reserved Common Programming Errors Arrays –Out-of-range subscript references –Unsubscripted array references –Subscripted references to nonarray variables –Mixing types in passing arrays to functions structs –References to a struct member with no prefix –Reference to a struct member no incorrect prefix –Missing semicolon following a struct declaration