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.

Slides:



Advertisements
Similar presentations
1 Arrays Chapter 9. 2 Outline  The array structure (Section 9.1)  Array declaration  Array initialization  Array subscripts  Sequential access to.
Advertisements

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.
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.
Chapter 10.
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)
© Copyright 1992–2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved. 1 Chapter 6 - Arrays Outline 6.1Introduction 6.2Arrays.
Introduction to Computers and Programming Lecture 15: Arrays Professor: Evan Korth New York University.
Arrays Hanly - Chapter 7 Friedman-Koffman - Chapter 9.
1 Lecture 20:Arrays and Strings Introduction to Computer Science Spring 2006.
1 CS 201 Passing Function as Parameter & Array Debzani Deb.
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.
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 9: Arrays and Strings
Chapter 9: Arrays and Strings
C++ for Engineers and Scientists Third Edition
Chapter 8 Arrays and Strings
Arrays. Objectives Learn about arrays Explore how to declare and manipulate data into arrays Learn about “array index out of bounds” Become familiar with.
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.
 2007 Pearson Education, Inc. All rights reserved C Arrays.
Basic Elements of C++ Chapter 2.
Lecture 9m: Top-Down Design with Functions COS120 Software Development Using C++ AUBG, COS dept.
Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Chapter 12: Recursion Problem Solving, Abstraction, and Design using C++
© 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 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
JAVA: An Introduction to Problem Solving & Programming, 5 th Ed. By Walter Savitch and Frank Carrano. ISBN © 2009 Pearson Education, Inc., Upper.
C++ Programming: From Problem Analysis to Program Design, Fifth Edition Arrays.
Copyright 2003 Scott/Jones Publishing Standard Version of Starting Out with C++, 4th Edition Chapter 11 Structured Data.
Value and Reference Parameters. CSCE 1062 Outline  Summary of value parameters  Summary of reference parameters  Argument/Parameter list correspondence.
Copyright © 2009 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Chapter 11: Structured Data.
 2003 Prentice Hall, Inc. All rights reserved. 1 Arrays Outline Introduction Arrays Declaring Arrays Examples Using Arrays.
1 Chapter 2 C++ Syntax and Semantics, and the Program Development Process.
COS120 Software Development Using C++ AUBG Fall semester 2010 Ref book: Problem Solving, Abstraction and Design Using C++ Authors: Frank Friedman, Elliot.
Copyright © 2012 Pearson Education, Inc. Chapter 11: Structured Data.
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.
Chapter 5 Arrays. Copyright © 2006 Pearson Addison-Wesley. All rights reserved. 5-2 Learning Objectives  Introduction to Arrays  Declaring and referencing.
1 One Dimensional Arrays Chapter 11 2 "All students to receive arrays!" reports Dr. Austin. Declaring arrays scores :
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.
Liang, Introduction to C++ Programming, (c) 2007 Pearson Education, Inc. All rights reserved X 1 Chapter Array Basics.
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.
COMPUTER PROGRAMMING. Array C++ provides a data structure, the array, which stores a fixed-size sequential collection of elements of the same type. An.
JAVA: An Introduction to Problem Solving & Programming, 5 th Ed. By Walter Savitch and Frank Carrano. ISBN © 2008 Pearson Education, Inc., Upper.
Module 1: Array ITEI222 - Advance Programming Language.
Copyright © 2015, 2012, 2009 Pearson Education, Inc., Publishing as Addison-Wesley All rights reserved. Chapter 11: Structured Data.
Copyright © 2015, 2012, 2009 Pearson Education, Inc., Publishing as Addison-Wesley All rights reserved. Chapter 11: Structured Data.
C++ Programming Lecture 14 Arrays – Part I The Hashemite University Computer Engineering Department (Adapted from the textbook slides)
SEQUENTIAL AND OBJECT ORIENTED PROGRAMMING Arrays.
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.
Chapter 5 Arrays Copyright © 2016 Pearson, Inc. All rights reserved.
Copyright © 2013 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Starting Out with Programming Logic & Design Third Edition by Tony Gaddis.
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.
1 C++ Data Types structured array struct union class address pointer reference simple integral enum char short int long bool floating float double long.
Bill Tucker Austin Community College COSC 1315
Arrays Kingdom of Saudi Arabia
Chapter 9: Data Structures: Arrays
Arrays Arrays A few types Structures of related data items
COMS 261 Computer Science I
4.1 Introduction Arrays A few types Structures of related data items
Presentation transcript:

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 t Exercises

3 Basic description t Data structure: composite of related data items stored in memory under the same name. t Typical data structures available in most PL: – Array: to be discussed today – Structure: (struct in C like PLs) – Class: structure with methods (OOP) – File (I/O processing aside keyboard and screen)

4 Basic description Array: a collection of data items of the same type. Reminder: Simple data type: Data type used to store a single value. scalar variable stores a single value. Therefore array may store many data items (scalar values) of the same type.

5 Array: a collection of data items of the same type How to define (declare) an array: t Using a definition statement to specify: – data type for all array elements – name of the array, i.e. identifier – size of the array, number of array elements See next three slides

6 Array: a collection of data items of the same type How to define (declare) an array: int a[6]; // array named a with size of 6 // a names a collection of 6 integer data items // where 6 integer values may store

7 Array: a collection of data items of the same type How to define (declare) an array: float b[10]; // array named b with size of 10 // b names a collection of 10 real data items // where 10 real (float) values may store

8 Array: a collection of data items of the same type How to define (declare) an array: char c[20]; // array named c with size of 20 // c names a collection of 20 char data items // where 20 symbols (char values) may store

9 Array initialization: to set value at time of definition Reminder: scalar variable initialization int pom = 56;double quantity = 77.8; // size matches the list of initializers int prime1[10]={2,3,5,7,11,13,17,19,23,29};

10 Array initialization: to set value at time of definition Reminder: scalar variable initialization int pom = 56;double quantity = 77.8; // size matches the list of initializers int prime1[10] = { 2, 3, 5, 7, 11, 13, 17, 19, 23, 29 }; // size omitted int prime2[ ] = { 2, 3, 5, 7, 11, 13 };

11 Array initialization: to set value at time of definition Reminder: scalar variable initialization int pom = 56;double quantity = 77.8; // size matches the list of initializers int prime1[10] = { 2, 3, 5, 7, 11, 13, 17, 19, 23, 29 }; // size omitted int prime2[ ] = { 2, 3, 5, 7, 11, 13 }; // size is greater than the list of initializers int prime3[20] = { 2, 3, 5, 7 };

12 Referencing array elements The access to an array element: t Using subscript, also named index –Always integer valued t In What context: –assignment statements, –Input/Output ( cin, cout ) statements –arguments in function calling statement

13 Referencing array elements Subscripted /indexed/ variable: a variable followed by a subscript in brackets, designating an array element.

14 Referencing array elements Array subscript: integer literal or integer variable or integer valued expression enclosed in brackets after array name, specifying which element to access. Examples on Array subscripts: Given: int x[10], I=5; x[4] integer literal

15 Referencing array elements Array subscript: an integer literal, integer variable or integer valued expression enclosed in brackets after array name, specifying which element to access. Examples on Array subscripts: Given: int x[10], I=5; x[I] integer variable

16 Referencing array elements Array subscript: an integer literal, integer variable or integer valued expression enclosed in brackets after array name, specifying which element to access. Examples on Array subscripts: Given: int x[10], I=5; x[I+1] x[2*I-3]x[I++] integer expression – 3 examples

17 Array size & Array indexes t Array size of 10 t Valid index values are 0, 1, 2, …, 9 t Attention: Highest value is 9, but not 10 int x[10]; x[0],x[1], …, x[9]

18 Sequential access to array Using for loops for sequential access Given: int x[10], i; for(i=0; i<=9; i++)x[i] = i * 10; for(i=9; i>=0; i--) cout << ‘\n’ << x[i] ; Statistical computation using arrays: computing mean and standard deviations.

19 Sequential access to array Using while loops for sequential access Given: int x[10], i; i=0; while (i<=9){ x[i] = i*20; i++; } i=9; while (i>=0) { cout << ‘\n’ << x[i]; i--; } Statistical computation using arrays: computing mean and standard deviations.

20 More on arrays Extract from Friedman/Koffman, chapter 9

Data Structures Arrays and Structs Chapter 9

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

23 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

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

25 5 Arrays –The index type is always 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)

26 6 Array Declaration

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

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

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

30 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

31 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

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

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

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

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

36 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 in 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

38 18 ShowDiff.cpp #include using namespace std; int main() { const int MAX_ITEMS = 8; float x[MAX_ITEMS], average, sum; // Enter the data. cout << "Enter " << MAX_ITEMS << " numbers: "; for (int i = 0; i > x[i]; // Compute the average value. sum = 0.0; for (int i = 0; i < MAX_ITEMS; i++) sum += x[i]; average = sum / MAX_ITEMS; cout << "The average value is " << average << endl;

39 ShowDiff.cpp // 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; for (int i = 0; i < MAX_ITEMS; i++) cout << setw (4) << i << setw (8) << x[i] << setw (14) << (x[i] - average) << endl; return 0; }

40 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

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

43 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

44 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

45 Problem t To check two arrays for identity

46 27 SameArray.cpp // FILE: SameArray.cpp // COMPARES TWO FLOAT ARRAYS FOR EQUALITY BY // COMPARING CORRESPONDING ELEMENTS bool sameArray (float a[], float b[], const int size); void main() { float ar1[20], float ar2[20]; // assgn values to ar1 and ar2 bool flag; flag = sameArray(ar1, ar2, 20); if (flag) cout << “Two identical arrays”; else cout << “Two non identical arrays”; }

47 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.

48 SameArray.cpp bool sameArray (float a[], float b[], const int size) { int i; i = 0; while ((i < size-1) && (a[i] == b[i])) i++; return (a[i] == b[i]); }

49 Problem t To add two arrays (to add their corresponding elements) t Result saved to third array, same size

50 AddArray.cpp // to add two arrays // Post: c[i] = a[i] + b[i] (0 <= i <= size-1) void addArray (int size, const float a[], const float b[], float c[]); void main() { float x[40], y[40], z[40]; // assgn values to arrays x, y addArray( 40, x, y, z); // display array z }

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

53 ReadScoresFile.cpp POSTPONE TO LECTURE ON FILES Skip 6 coming slides // 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"

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

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

57 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).

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

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

59 Strings and Arrays of Characters  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

Recursive Functions with Array Arguments // File: findSumTest.cpp // Program and recursive function to sum an // array's elements #include using namespace std; // Function prototype int findSum(int[], int); int binSearch(int[], int, int, int);

61 FindSumTest.cpp int main() { const int SIZE = 10; int x[SIZE]; int sum1; int sum2; // Fill array x for (int i = 0; i < SIZE; i++) x[i] = i + 1;

62 FindSumTest.cpp // Calulate sum two ways sum1 = findSum(x, SIZE); sum2 = (SIZE * (SIZE + 1)) / 2; cout << "Recursive sum is " << sum1 << endl; cout << "Calculated sum is " << sum2 << endl; cout << binSearch(x, 10, 10, SIZE-1) << endl; return 0; }

63 FindSumTest.cpp // Finds the sum of integers in an n-element // array int findSum(int x[], int n) { if (n == 1) return x[0]; else return x[n-1] + findSum(x, n-1); }

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

65 Exercise Build programs using arrays Arrays as actual arguments and formal parameters: t function to add two same size arrays (values associated to all array elements); t function to evaluate the first 20 elements of Fibonacci series; t sum (product) of the elements of an initialized array; t average value of the sum of array elements entered as input values; t count the number of digit characters in the input stream.

66 Before lecture end Lecture: Arrays More to read: Friedman/Koffman, Chapter 09

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

Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley 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 69 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 70 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 71 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};

Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley 72 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 73 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 74 Figure 9.3 Arrays onVacation, vacationDays, and dayOff

Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley 75 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 76 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 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 78 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 79 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 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 81 Listing 9.3 Function to exchange the contents of two floating-point memory locations

Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley 82 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 83 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 84 Listing 9.4 Function sameArray

Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley 85 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 86 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 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 88 Listing 9.7 Function readScoresFile

Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley 89 Listing 9.7 Function readScoresFile (continued)

Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Common Programming Errors Arrays –Out-of-range subscript references –Unsubscripted array references –Subscripted references to nonarray variables –Mixing types in passing arrays to functions

91 Thank You For Your Attention!