Data Structures Arrays and Structs Chapter 9. 2 9.1 The Array Data Type t Array elements have a common name –The array as a whole is referenced through.

Slides:



Advertisements
Similar presentations
Introduction to C Programming
Advertisements

1 Arrays Chapter 9. 2 Outline  The array structure (Section 9.1)  Array declaration  Array initialization  Array subscripts  Sequential access to.
Chapter 9 Data Structures: Arrays and Structs Lecture Notes Prepared By: Blaise W. Liffick, PhD Department of Computer Science Millersville University.
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.
Lecture 22: Arrays (cont). 2 Lecture Contents: t Searching in array: –linear search –binary search t Multidimensional arrays t Demo programs t Exercises.
Chapter 10.
Topic 9 – Introduction To Arrays. CISC105 – Topic 9 Introduction to Data Structures Thus far, we have seen “simple” data types. These refers to a single.
Simple Arrays COMP104 Lecture 11 / Slide 2 Arrays * An array is a collection of data elements that are of the same type (e.g., a collection of integers,characters,
 2003 Prentice Hall, Inc. All rights reserved Introduction Arrays –Structures of related data items –Static entity (same size throughout program)
Computer programming1 Arrays. Computer programming2 ARRAYS Motivation Introduction to Arrays Static arrays Arrays and Functions Arrays, Classes, and typedef.
1 11/27/06CS150 Introduction to Computer Science 1 Searching Arrays.
Arrays Hanly - Chapter 7 Friedman-Koffman - Chapter 9.
Chapter 8. 2 Objectives You should be able to describe: One-Dimensional Arrays Array Initialization Arrays as Arguments Two-Dimensional Arrays Common.
 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.
Computer Science 1620 Arrays. Problem: Given a list of 5 student grades, adjust the grades so that the average is 70%. Program design: 1. read in the.
C++ for Engineers and Scientists Third Edition
Chapter 8 Arrays and Strings
Simple Arrays Programming COMP104 Lecture 12 / Slide 2 Arrays l An array is a collection of data elements that are of the same type (e.g., a collection.
Basic Elements of C++ Chapter 2.
Modular Programming Chapter Value and Reference Parameters t Function declaration: void computesumave(float num1, float num2, float& sum, float&
Chapter 7: Arrays. In this chapter, you will learn about: One-dimensional arrays Array initialization Declaring and processing two-dimensional arrays.
Programming Languages -1 (Introduction to C) arrays Instructor: M.Fatih AMASYALI
Chapter 7 Arrays. Overview 7.1 Introduction to Arrays 7.2 Arrays in Functions 7.3 Programming with Arrays 7.4 Multidimensional Arrays.
Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Chapter 12: Recursion Problem Solving, Abstraction, and Design using C++
Modular Programming Chapter Value and Reference Parameters computeSumAve (x, y, sum, mean) ACTUALFORMAL xnum1(input) ynum2(input) sumsum(output)
CHAPTER 07 Arrays and Vectors (part I). OBJECTIVES 2 In this part you will learn:  To use the array data structure to represent a set of related data.
Chapter 8 Arrays and Strings
EGR 2261 Unit 8 One-dimensional Arrays  Read Malik, pages in Chapter 8.  Homework #8 and Lab #8 due next week.  Quiz next week.
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.
Prof. amr Goneid, AUC1 CSCE 110 PROGRAMMING FUNDAMENTALS WITH C++ Prof. Amr Goneid AUC Part 11. The Struct Data Type.
C++ Programming: From Problem Analysis to Program Design, Fifth Edition Arrays.
Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Extended Prelude to Programming Concepts & Design, 3/e by Stewart Venit and.
Value and Reference Parameters. CSCE 1062 Outline  Summary of value parameters  Summary of reference parameters  Argument/Parameter list correspondence.
CS Midterm Study Guide Fall General topics Definitions and rules Technical names of things Syntax of C++ constructs Meaning of C++ constructs.
C++ for Engineers and Scientists Second Edition Chapter 11 Arrays.
Lecture 26: Structures / struct s/. 2 Lecture Contents: t Basics of structs t Struct type definition ( struct reserved word) t Struct type definition.
Review Binary Numbers Bit : 0 or 1 Byte: 8 bites 256 different values 2 8 KB : 1024 bytes 2 10 bytes MB : 1024 * 1024 bytes 2 10 * 2 10 (2 20 ) bytes GB.
Section 5 - Arrays. Problem solving often requires information be viewed as a “list” List may be one-dimensional or multidimensional List is implemented.
A First Book of C++: From Here To There, Third Edition2 Objectives You should be able to describe: One-Dimensional Arrays Array Initialization Arrays.
Copyright © 2012 Pearson Addison-Wesley. All rights reserved. Chapter 7 Arrays.
 2007 Pearson Education, Inc. All rights reserved C Arrays.
1 One Dimensional Arrays Chapter 11 2 "All students to receive arrays!" reports Dr. Austin. Declaring arrays scores :
Chapter 7: Arrays. Outline Array Definition Access Array Array Initialization Array Processing 2D Array.
Copyright © 2002 W. A. Tucker1 Chapter 9 Lecture Notes Bill Tucker Austin Community College COSC 1315.
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.
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.
Arrays Chapter 7. MIS Object Oriented Systems Arrays UTD, SOM 2 Objectives Nature and purpose of an array Using arrays in Java programs Methods.
Extra Recitations Wednesday 19:40-22:30 FENS L055 (tomorrow!) Friday 13:40-16:30 FENS L063 Friday 17: :30 FENS L045 Friday 19:40-22:30 FENS G032.
1 11/12/04CS150 Introduction to Computer Science 1 More 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.
1 Lecture 4: Part1 Arrays Introduction Arrays  Structures of related data items  Static entity (same size throughout program)
Array. Array is a group of data of the same type. Array elements have a common name –The array as a whole is referenced through the common name Individual.
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.
Prof. Amr Goneid, AUC1 CSCE 110 PROGRAMMING FUNDAMENTALS WITH C++ Prof. Amr Goneid AUC Part 7. 1-D & 2-D Arrays.
Objectives You should be able to describe: One-Dimensional Arrays
A FIRST BOOK OF C++ CHAPTER 7 ARRAYS. OBJECTIVES In this chapter, you will learn about: One-Dimensional Arrays Array Initialization Arrays as Arguments.
Chapter Topics The Basics of a C++ Program Data Types
Basic Elements of C++.
Basic Array Definition
Chapter 7 Arrays.
Basic Elements of C++ Chapter 2.
Arrays Kingdom of Saudi Arabia
COMS 261 Computer Science I
Chapter 9: Data Structures: Arrays
COMS 261 Computer Science I
4.1 Introduction Arrays A few types Structures of related data items
Presentation transcript:

Data Structures Arrays and Structs Chapter 9

2 9.1 The Array Data Type t Array elements have a common name –The array as a whole is referenced through the common name t Array elements are of the same type — the base type t Individual elements of the array are referenced by sub_scripting the group name

3 Arrays t Analogies –Egg carton –Apartments –Cassette carrier t More terminology –Ability to refer to a particular element Indexing or sub_scripting –Ability to look inside an element Accessing value

4 Arrays t Language restrictions –Subscripts are denoted as expressions within brackets: [ ] –Base type can be any fundamental, library-defined, or programmer -defined type

5 Arrays –The index type is integer and the index range must be 0... n -1 where n is a programmer-defined constant expression. –Parameter passing style Always call by reference (no indication necessary)

6 Array Declaration

7 Sample Declarations  Suppose const int N = 20; const int M = 40; const int MaxStringSize = 80; const int MaxListSize = 1000 ;

8 Sample Declarations t Then the following are all correct array declarations. int A[10]; char B[MaxStringSize]; float C[M*N]; int Values[MaxListSize]; Rational D[N-15];

9 Subscripting t Suppose int A[10]; // array of 10 ints  To access an individual element we must apply a subscript to array name A –A subscript is a bracketed expression The expression in the brackets is known as the index –First element of A has index 0 A[0]

10 Subscripting –Second element of A has index 1, and so on A[1] –Last element has an index one less than the size of the array A[9] t Incorrect indexing is a common error

11 Array Elements t Suppose int A[10]; // array of 10 uninitialized ints  To access an individual element we must apply a subscript to array name A

12 Array Element Manipulation t Given the following: int i = 7, j = 2, k = 4; A[0] = 1; A[i] = 5; A[j] = A[i] + 3; A[j+1] = A[i] + A[0]; A[A[j]] = 12;

13 Array Element Manipulation cin >> A[k]; // where the next input value is 3

14 Inputting Into An Array int A[MaxListSize]; int n = 0; int CurrentInput; while((n > CurrentInput)) { A[n] = CurrentInput; ++n; }

15 Displaying An Array // List A of n elements has // already been set for (int i = 0; i < n; ++i) { cout << A[i] << " "; } cout << endl;

16 Remember t Arrays are always passed by reference –Artifact of C  Can use const if array elements are not to be modified t You do not need to include the array size within the brackets when defining an array parameter t Initialize array with 0 or some other known value

Sequential Access to Array Elements t Random Access –Access elements is random order t Sequential Access –Process elements in sequential order starting with the first –ShowDiff.cpp a program that looks at values and calculates a difference between the element and the average

18 ShowDiff.cpp #include using namespace std; int main() { const int MAX_ITEMS = 8; float x[MAX_ITEMS]; float average; float sum;

19 ShowDiff.cpp // Enter the data. cout << "Enter " << MAX_ITEMS << " numbers: "; for (int i = 0; i < MAX_ITEMS; i++) cin >> x[i]; // Compute the average value. sum = 0.0; for (int i = 0; i < MAX_ITEMS; i++) sum += x[i]; average = sum / MAX_ITEMS;

20 ShowDiff.cpp cout << "The average value is " << average << endl << endl; // Display the difference between each item // and the average. cout << "Table of differences between x[i] and the average." << endl; cout << setw (4) << "i" << setw (8) << "x[i]" << setw (14) << "difference" << endl;

21 ShowDiff.cpp for (int i = 0; i < MAX_ITEMS; i++) cout << setw (4) << i << setw (8) << x[i] << setw (14) << (x[i] - average) << endl; return 0; }

22 ShowDiff.cpp Program Output Enter 8 numbers: The average value is 2.0 Table of differences between x[i] and the average Ix[I]difference etc

Array Arguments t Use, +, - to test and modify array elements t At times it might benefit you to pass an entire array to a function t Can pass array elements to functions –actual function call exchange (s[3], s[5]); t Examples follow

24 Exchange.cpp // FILE: Exchange.cpp // Exchanges two type float values void exchange (float& a1, float& a2) { float temp; temp = a1; a1 = a2; a2 = temp; }

25 Arrays as Function Arguments t Remember arrays are pass by reference –Passing the array address t Remember these points when passing arrays to functions –The formal array argument in a function is not itself an array but rather is a name that represents an actual array argument. Therefore in the function definition, you need only inform the compiler with [] that the actual argument will be an array

26 Arrays as Function Arguments t Remember these points when passing arrays to functions –Formal array arguments that are not to be altered by a function should be specified using the reserved word const. When this specification is used, any attempt to alter the contents will cause the compiler generate an error message t SameArray.cpp example

27 SameArray.cpp // FILE: SameArray.cpp // COMPARES TWO FLOAT ARRAYS FOR EQUALITY BY // COMPARING CORRESPONDING ELEMENTS // Pre: a[i] and b[i] (0 <= i <= size-1) are // assigned values. // Post: Returns true if a[i] == b[i] for all I // in range 0 through size - 1; otherwise, // returns false. bool sameArray (float a[], float b[], const int size)

28 SameArray.cpp { // Local data... int i; i = 0; while ((i < size-1) && (a[i] == b[i])) i++; return (a[i] == b[i]); }

29 AddArray.cpp // Array elements with subscripts ranging from // 0 to size-1 are summed element by element. // 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, const float a[], const float b[], float c[]) { // Add corresponding elements of a and b and store in c. for (int i = 0; i < size; i++) c[i] = a[i] + b[i]; } // end addArray

Reading Part of an Array t Sometimes it is difficult to know how many elements will be in an array t Scores example –150 students –200 students t Always allocate enough space at compile time t Remember to start with index [0]

31 ReadScoresFile.cpp // File: ReadScoresFile.cpp // Reads an array of exam scores for a lecture // section of up to max_size students. #include using namespace std; #define inFile "Scores.txt"

32 ReadScoresFile.cpp void readScoresFile (ifstream& ins,int scores[], const int MAX_SIZE, int& sectionSize); int main() { int scores[100]; int size; ifstream ins; ins.open(inFile);

33 ReadScoresFile.cpp if (ins.fail()) { cout << "Error" << endl; return 1; } readScoresFile(ins, scores, 5, size); for (int i = 0; i < size; i++) cout << scores[i] << " " ; cout << endl; return 0; }

34 ReadScoresFile.cpp // File: ReadScoresFile.cpp // Reads an array of exam scores for a lecture // section of up to MAX_SIZE students from a // file. // Pre: None // Post: The data values are read from a file // and stored in array scores. // The number of values read is stored in // sectionSize.(0 <= sectionSize < MAX_SIZE).

35 ReadScoresFile.cpp void readScoresFile (ifstream& ins, int scores[], const int MAX_SIZE, int& sectionSize) { // Local data... int tempScore; // Read each array element until done. sectionSize = 0; ins >> tempScore; while (!ins.eof() && (sectionSize < MAX_SIZE)) { scores[sectionSize] = tempScore;

36 ReadScoresFile.cpp sectionSize++; ins >> tempScore; } // end while // End of file reached or array is filled. if (!ins.eof()) { cout << "Array is filled!" << endl; cout << tempScore << " not stored" << endl; }

Searching and Sorting Arrays t Look at 2 common array problems –Searching –Sorting t How do we go about finding the smallest number in an array? –Assume 1st is smallest and save its position –Look for one smaller –If you locate one smaller save its position

38 ArrayOperations.cpp // File: arrayOperations.cpp // Finds the subscript of the smallest value in a // subarray. // Returns the subscript of the smallest value // in the subarray consisting of elements // x[startindex] through x[endindex] // Returns -1 if the subarray bounds are invalid. // Pre: The subarray is defined and 0 <= // startIndex <= endIndex. // Post: x[minIndex] is the smallest value in // the array.

39 ArrayOperations.cpp int findIndexOfMin(const float x[], int startIndex, int endIndex) { // Local data... int minIndex; int i; // Validate subarray bounds if ((startIndex endIndex)) {

40 ArrayOperations.cpp cerr << "Error in subarray bounds" << endl; return -1; } // Assume the first element of subarray is // smallest and check the rest. // minIndex will contain subscript of smallest // examined so far. minIndex = startIndex; for (i = startIndex + 1; i <= endIndex; i++) if (x[i] < x[minIndex]) minIndex = i;

41 ArrayOperations.cpp // All elements are examined and minIndex is // the index of the smallest element. return minIndex; } // end findIndexOfMin

42 Strings and Arrays of Characters t String object uses an array whose elements are type char t First position of a string object is 0 –example string find function ret of position 0 t Can use the find function to locate or search an array t We will study some various search functions

43 Linear Search t The idea of a linear search is to walk through the entire until a target value is located t If the target is not located some type of indicator needs to be returned

44 ArrayOperations.cpp // Searches an integer array for a given element // (the target) // Array elements ranging from 0 to size - 1 are // searched for an element equal to target. // Pre: The target and array are defined. // Post: Returns the subscript of target if // found; otherwise, returns -1. int linSearch (const int items[], int target, int size) { for (int i = 0, i < size, i++)

45 ArrayOperations.cpp if (items[next] == target) return next; // All elements were tested without success. return -1; } // end linSearch

46 Sorting in Ascending Order Selection Sort t Idea of the selection sort is to locate the smallest value in the array t Then switch positions of this value and that in position [0] t We then increment the index and look again for the next smallest value and swap t Continue until sorted

47 ArrayOperations.cpp // Sorts an array (ascending order) using // selection sort algorithm // Uses exchange and findIndexOfMin // Sorts the data in array items (items[0] // through items[n-1]). // Pre: items is defined and n <= declared size // of actual argument array. // Post: The values in items[0] through items // [n-1] are in increasing order.

48 ArrayOperations.cpp void selSort(int items[], int n) { // Local data... int minSub; for (int i = 0; i < n-1; i++) { // Find index of smallest element in // unsorted section of items. minSub = findIndexOfMin(items, i, n-1);

49 ArrayOperations.cpp // Exchange items at position minSub and i exchange(items[minSub], items[i]); }

Analyzing Algorithms Big O Notation t How to compare efficiency of various algorithms t A mathematical measuring stick to do quantitative analysis on algorithms t Typically sorting and searching t Based on looping constructs and placed into categories based on their efficiency t Most algorithms have BigO published

51 Analyzing Algorithms Big O Notation t Run time efficiency is in direct proportion to the number of elementary machine operations –Compares –Exchanges

52 Analyzing Algorithms Big O Notation t Two independent loops –Sum of the loops is efficiency –n/2 + n^2 is Big O(N^2) Example: for (k=1; k<=n/2; ++k) { } for (j=1; j<=n*n; ++j) { }

53 Analyzing Algorithms Big O Notation t Two nested loops –Product of the loops is efficiency –n/2 * n^2 = n^3/2 is Big O(N^3) Example: for (k=1; k<=n/2; ++k) { for (j=1; j<=n*n; ++j) { }

The Struct Data Type t struct used to store related data items t Individual components of the struct are called its members t Each member can contain different types of data t Employee example

55 Struct Employee // Definition of struct employee struct employee { string id; string name; char gender; int numDepend; money rate; money totWages; };

56 Accessing Members of a struct t Members are accessed using the member access operator, a period t For struct variable s and member variable m to access m you would use the following: –cout << s.m << endl; t Can use all C++ operators and operations on structs

57 Accessing Members of a struct organist.id = 1234; organist.name = “Noel Goddard”; organist.gender = ‘F’; organist.numDepend = 0; organist.rate = 6.00; organist.totWages += organist.rate * 40.0;

Structs as Operands and Arguments t How to do arithmetic and other operations using structs t Process entire struct using programmer defined functions t Often better to pass an entire structure rather than individual elements t struct copies organist = janitor;

59 Passing struct as an Argument t Grading program example t Keep track of students grades t Prior to our learning structs we needed to store each item into a single variable t Group all related student items together t Pass struct by const reference if you do not want changes made

60 ExamStat.h // FILE: ExamStat.h struct examStats { string stuName; int scores[3]; float average; char grade; };

61 PrintStats.cpp // File: printStats.cpp // Prints the exam statistics // Pre: The members of the struct variable // stuExams are assigned values. // Post: Each member of stuExams is displayed. void printStats(examStats stuExams) { cout << "Exam scores for " << stuExams.stuName << ": "

62 PrintStats.cpp cout << stuExams.scores[0] << ' ' << stuExams.scores[1]<< ' ' << stuExams.scores[2] << endl; cout << "Average score: " << stuExams.average << endl; cout << "Letter grade : " << stuExams.grade << endl; }

63 ReadEmp.cpp // File: ReadEmp.cpp // Reads one employee record into oneemployee #include // Pre: None // Post: Data are read into struct oneEmployee void readEmployee(employee& oneEmployee) { cout << "Enter a name terminated with the symbol # : ";

64 ReadEmp.cpp getline(cin, oneEmployee.name, '#'); cout << "Enter an id number: "; cin >> oneEmployee.id; cout << "Enter gender (F or M): "; cin >> oneEmployee.gender; cout << "Enter number of dependents: "; cin >> oneEmployee.numDepend; cout << "Enter hourly rate: "; cin >> oneEmployee.rate; }

Common Programming Errors t Watch non int subscripts (ASCII value) t Enumerated types can be used t Out of range errors –C++ no range error checking t Lack of subscript to gain access t Subscript reference to non-array variable t Type mixing when using with functions t Initialization of arrays

66 Common Programming Errors t No prefix to reference a struct member t Incorrect prefix reference to a struct member t Missing ; following definition of struct t Initialization of struct members