Chapter 9: Data Structures: Arrays

Slides:



Advertisements
Similar presentations
One Dimensional Arrays
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 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.
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.
Engineering Problem Solving With C++ An Object Based Approach Chapter 6 One-Dimensional Arrays.
Arrays Hanly - Chapter 7 Friedman-Koffman - Chapter 9.
 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.
C++ for Engineers and Scientists Third Edition
Chapter 8 Arrays and Strings
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 © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Chapter 12: Recursion Problem Solving, Abstraction, and Design using C++
Chapter 8 Arrays and Strings
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++ for Engineers and Scientists Second Edition Chapter 11 Arrays.
Week # 2: Arrays.  Data structure  A particular way of storing and organising data in a computer so that it can be used efficiently  Types of data.
Section 5 - Arrays. Problem solving often requires information be viewed as a “list” List may be one-dimensional or multidimensional List is implemented.
12/15/2015Engineering Problem Solving with C++, Second Edition, J. Ingber 1 Engineering Problem Solving with C++, Etter Chapter 6 One-Dimensional Arrays.
Copyright © 2012 Pearson Addison-Wesley. All rights reserved. Chapter 7 Arrays.
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.
JAVA: An Introduction to Problem Solving & Programming, 5 th Ed. By Walter Savitch and Frank Carrano. ISBN © 2008 Pearson Education, Inc., Upper.
Arrays Chapter 7. MIS Object Oriented Systems Arrays UTD, SOM 2 Objectives Nature and purpose of an array Using arrays in Java programs Methods.
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.
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.
C LANGUAGE UNIT 3. UNIT 3 Arrays Arrays – The concept of array – Defining arrays – Initializing arrays.
Arrays Chapter 7.
Chapter 6 Arrays in C++ 2nd Semester King Saud University
An Introduction to Programming with C++ Sixth Edition
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.
Computer Programming BCT 1113
Chapter 7 Part 1 Edited by JJ Shepherd
Chapter 7 Arrays Copyright © 2008 Pearson Addison-Wesley. All rights reserved. 1.
Arrays Part-1 Armen Keshishian.
Arrays and Records.
Chapter 9: Data Structures: Arrays and Structs
CS 1430: Programming in C++.
Arrays … The Sequel Applications and Extensions
7 Arrays.
Arrays Kingdom of Saudi Arabia
Chapter 8 Arrays Objectives
CS-161 Computer Programming Lecture 14: Arrays I
Object Oriented Programming in java
Data Structures (CS212D) Week # 2: Arrays.
Review of Everything Arrays
Arrays Week 2.
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.
Engineering Problem Solving with C++, Etter
CIS16 Application Development and Programming using Visual Basic.net
7 Arrays.
CS150 Introduction to Computer Science 1
Chapter 8 Arrays Objectives
CS150 Introduction to Computer Science 1
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.
Arrays.
Lecture 2 Arrays & Pointers September 7, 2004
COMS 261 Computer Science I
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.
Chapter 7 Arrays. Chapter 7 Arrays Overview 7.1 Introduction to Arrays 7.2 Arrays in Functions 7.3 Programming with Arrays 7.4 Multidimensional.
4.1 Introduction Arrays A few types Structures of related data items
Presentation transcript:

Chapter 9: Data Structures: Arrays Problem Solving, Abstraction, and Design using C++ 6e by Frank L. Friedman and Elliot B. Koffman

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

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

element-type array-name [array-size]; 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

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.0 12.0 6.0 8.0 2.5 14.0 -54.5

Example 1 (con’t) cout << x[0]; x[3] = 25.0; sum = x[0] + x[1]; x[2] = x[0] + x[1];

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];

Figure 9.3 Arrays onVacation, vacationDays, and dayOff

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 ([ ])

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

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

Example of Sequential Access int cube[10]; for (int i = 0; i < 10; i++) cube[i] = i * i * i;

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 )

9.3 Array Arguments Use <, ==, >, +, -, etc. to test and modify array elements individually Can pass array elements to functions exchange (s[3], s[5]);

Listing 9.3 Function to exchange the contents of two floating-point memory locations

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

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;

Listing 9.4 Function sameArray

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);

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]; }

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

Listing 9.7 Function readScoresFile

Listing 9.7 Function readScoresFile (continued)

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

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

Listing 9.8 Function findIndexOfMin

Listing 9.8 Function findIndexOfMin (continued)

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

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.

Listing 9.9 The function linSearch

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

Selection Sort Input arguments Output arguments Local variables 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

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

Listing 9.10 Function selSort

9.13 Common Programming Errors Arrays Out-of-range subscript references Unsubscripted array references Subscripted references to nonarray variables Mixing types in passing arrays to functions