lecture 21: arrays. 2 lecture contents: t declaring and referencing arrays t array subscripts t...

91
Lecture 21: Arrays

Upload: scot-greer

Post on 19-Jan-2018

224 views

Category:

Documents


0 download

DESCRIPTION

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)

TRANSCRIPT

Page 1: Lecture 21: Arrays. 2 Lecture Contents: t Declaring and referencing arrays t Array subscripts t Using…

Lecture 21:Arrays

Page 2: Lecture 21: Arrays. 2 Lecture Contents: t Declaring and referencing arrays t Array subscripts t Using…

2

Lecture Contents:

Declaring and referencing arrays Array subscripts Using for/while loops for sequential access Demo programs Exercises

Page 3: Lecture 21: Arrays. 2 Lecture Contents: t Declaring and referencing arrays t Array subscripts t Using…

3

Basic description

Data structure: composite of related data items stored in memory under the same name.

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)

Page 4: Lecture 21: Arrays. 2 Lecture Contents: t Declaring and referencing arrays t Array subscripts t Using…

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.

Page 5: Lecture 21: Arrays. 2 Lecture Contents: t Declaring and referencing arrays t Array subscripts t Using…

5

Array: a collection of data items of the same type

How to define (declare) an array:

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

Page 6: Lecture 21: Arrays. 2 Lecture Contents: t Declaring and referencing arrays t Array subscripts t Using…

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

Page 7: Lecture 21: Arrays. 2 Lecture Contents: t Declaring and referencing arrays t Array subscripts t Using…

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

Page 8: Lecture 21: Arrays. 2 Lecture Contents: t Declaring and referencing arrays t Array subscripts t Using…

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

Page 9: Lecture 21: Arrays. 2 Lecture Contents: t Declaring and referencing arrays t Array subscripts t Using…

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 initializersint prime1[10]={2,3,5,7,11,13,17,19,23,29}; 

Page 10: Lecture 21: Arrays. 2 Lecture Contents: t Declaring and referencing arrays t Array subscripts t Using…

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 initializersint prime1[10] = { 2, 3, 5, 7, 11, 13, 17, 19, 23, 29 }; 

// size omittedint prime2[ ] = { 2, 3, 5, 7, 11, 13 }; 

Page 11: Lecture 21: Arrays. 2 Lecture Contents: t Declaring and referencing arrays t Array subscripts t Using…

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 initializersint prime1[10] = { 2, 3, 5, 7, 11, 13, 17, 19, 23, 29 }; 

// size omittedint prime2[ ] = { 2, 3, 5, 7, 11, 13 }; 

// size is greater than the list of initializersint prime3[20] = { 2, 3, 5, 7 };

Page 12: Lecture 21: Arrays. 2 Lecture Contents: t Declaring and referencing arrays t Array subscripts t Using…

12

Referencing array elements

The access to an array element:

Using subscript, also named index– Always integer valued

In What context:– assignment statements, – Input/Output (cin, cout) statements– arguments in function calling statement

Page 13: Lecture 21: Arrays. 2 Lecture Contents: t Declaring and referencing arrays t Array subscripts t Using…

13

Referencing array elements

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

Page 14: Lecture 21: Arrays. 2 Lecture Contents: t Declaring and referencing arrays t Array subscripts t Using…

14

Referencing array elementsArray 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

Page 15: Lecture 21: Arrays. 2 Lecture Contents: t Declaring and referencing arrays t Array subscripts t Using…

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

Page 16: Lecture 21: Arrays. 2 Lecture Contents: t Declaring and referencing arrays t Array subscripts t Using…

16

Referencing array elementsArray 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

Page 17: Lecture 21: Arrays. 2 Lecture Contents: t Declaring and referencing arrays t Array subscripts t Using…

17

Array size & Array indexes

Array size of 10 Valid index values are 0, 1, 2, … , 9 Attention: Highest value is 9, but

not 10

int x[10];

x[0], x[1], … , x[9]

Page 18: Lecture 21: Arrays. 2 Lecture Contents: t Declaring and referencing arrays t Array subscripts t Using…

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.

Page 19: Lecture 21: Arrays. 2 Lecture Contents: t Declaring and referencing arrays t Array subscripts t Using…

19

Sequential access to array

Using while loops for sequential accessGiven: 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.

Page 20: Lecture 21: Arrays. 2 Lecture Contents: t Declaring and referencing arrays t Array subscripts t Using…

20

More on arrays

Extract from Friedman/Koffman, chapter 9

Page 21: Lecture 21: Arrays. 2 Lecture Contents: t Declaring and referencing arrays t Array subscripts t Using…

Data Structures Arrays and Structs

Chapter 9

Page 22: Lecture 21: Arrays. 2 Lecture Contents: t Declaring and referencing arrays t Array subscripts t Using…

222

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

Page 23: Lecture 21: Arrays. 2 Lecture Contents: t Declaring and referencing arrays t Array subscripts t Using…

233

Arrays Analogies

– Egg carton– Apartments– Cassette carrier

More terminology– Ability to refer to a particular element

• Indexing or sub_scripting– Ability to look inside an element

• Accessing value

Page 24: Lecture 21: Arrays. 2 Lecture Contents: t Declaring and referencing arrays t Array subscripts t Using…

244

Arrays Language restrictions

– Subscripts are denoted as expressions within brackets: [ ]

– Base type can be • any fundamental type, or• library-defined type, or• programmer-defined type

Page 25: Lecture 21: Arrays. 2 Lecture Contents: t Declaring and referencing arrays t Array subscripts t Using…

255

Arrays– The index type is always integer and the

index range must be0 ... n-1• where n is a programmer-defined constant

expression.– Parameter passing style

• Always call by reference (no indication necessary)

Page 26: Lecture 21: Arrays. 2 Lecture Contents: t Declaring and referencing arrays t Array subscripts t Using…

266

Array Declaration

Type ofvalues in

list

BaseType Id [ SizeExp ] ;

Nameof list

Bracketedconstant

expressionindicatingnumber of

elements inlist

Page 27: Lecture 21: Arrays. 2 Lecture Contents: t Declaring and referencing arrays t Array subscripts t Using…

277

Sample Declarations Suppose

const int N = 20;const int M = 40;const int MaxStringSize = 80;const int MaxListSize = 1000;

Page 28: Lecture 21: Arrays. 2 Lecture Contents: t Declaring and referencing arrays t Array subscripts t Using…

288

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

Page 29: Lecture 21: Arrays. 2 Lecture Contents: t Declaring and referencing arrays t Array subscripts t Using…

299

Subscripting 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 0A[0]

Page 30: Lecture 21: Arrays. 2 Lecture Contents: t Declaring and referencing arrays t Array subscripts t Using…

3010

Subscripting– Second element of A has index 1, and so onA[1]

– Last element has an index one less than the size of the arrayA[9]

Incorrect indexing is a common error

Page 31: Lecture 21: Arrays. 2 Lecture Contents: t Declaring and referencing arrays t Array subscripts t Using…

3111

Array Elements Suppose

int A[10]; // array of 10 uninitialized ints

To access an individual element we must apply a subscript to array name A

-- -- ----AA[4] A[5] A[6]A[3]A[0] A[2] A[8] A[9]A[7]A[1]

-- -- ---- -- --

Page 32: Lecture 21: Arrays. 2 Lecture Contents: t Declaring and referencing arrays t Array subscripts t Using…

3212

Array Element Manipulation 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;

Page 33: Lecture 21: Arrays. 2 Lecture Contents: t Declaring and referencing arrays t Array subscripts t Using…

3313

Array Element Manipulation

cin >> A[k]; // where the next input value is 3

-- 8 61AA[4] A[5] A[6]A[3]A[0] A[2] A[8] A[9]A[7]A[1]

-- -- 53 --12

Page 34: Lecture 21: Arrays. 2 Lecture Contents: t Declaring and referencing arrays t Array subscripts t Using…

3414

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

}

Page 35: Lecture 21: Arrays. 2 Lecture Contents: t Declaring and referencing arrays t Array subscripts t Using…

3515

Displaying An Array// List A of n elements has// already been setfor (int i = 0; i < n; ++i) {

cout << A[i] << " ";}cout << endl;

Page 36: Lecture 21: Arrays. 2 Lecture Contents: t Declaring and referencing arrays t Array subscripts t Using…

3616

Remember Arrays are always passed by reference

– Artifact of C Can use const if array elements are not to be

modified You do not need to include the array size within

the brackets when defining an array parameter Initialize array with 0 or some other known value

Page 37: Lecture 21: Arrays. 2 Lecture Contents: t Declaring and referencing arrays t Array subscripts t Using…

3717

9.2 Sequential Access to Array Elements

Random Access– Access elements in random order

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

Page 38: Lecture 21: Arrays. 2 Lecture Contents: t Declaring and referencing arrays t Array subscripts t Using…

3818

ShowDiff.cpp#include <iostream>#include <iomanip>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 < 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; cout << "The average value is " << average << endl;

Page 39: Lecture 21: Arrays. 2 Lecture Contents: t Declaring and referencing arrays t Array subscripts t Using…

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

Page 40: Lecture 21: Arrays. 2 Lecture Contents: t Declaring and referencing arrays t Array subscripts t Using…

4022

ShowDiff.cpp

Program OutputEnter 8 numbers: 16 12 6 8 2.5 12 14 -54.5The average value is 2.0Table of differences between x[i] and the averageI x[I] difference0 16.0 14.01 12.0 10.02 6.0 4.03 8.0 6.0etc etc

Page 41: Lecture 21: Arrays. 2 Lecture Contents: t Declaring and referencing arrays t Array subscripts t Using…

41

9.3 Array Arguments

Use <, ==, >, +, - to test and modify array elements

At times it might benefit you to pass an entire array to a function

Can pass array elements to functions– actual function callexchange (s[3], s[5]);

Examples follow

Page 42: Lecture 21: Arrays. 2 Lecture Contents: t Declaring and referencing arrays t Array subscripts t Using…

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

Page 43: Lecture 21: Arrays. 2 Lecture Contents: t Declaring and referencing arrays t Array subscripts t Using…

43

Arrays as Function Arguments Remember arrays are pass by reference

– Passing the array address 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

Page 44: Lecture 21: Arrays. 2 Lecture Contents: t Declaring and referencing arrays t Array subscripts t Using…

44

Arrays as Function Arguments 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

SameArray.cpp example

Page 45: Lecture 21: Arrays. 2 Lecture Contents: t Declaring and referencing arrays t Array subscripts t Using…

45

Problem

To check two arrays for identity

Page 46: Lecture 21: Arrays. 2 Lecture Contents: t Declaring and referencing arrays t Array subscripts t Using…

4627

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 ar2bool flag; flag = sameArray(ar1, ar2, 20);if (flag) cout << “Two identical arrays”;else cout << “Two non identical arrays”;

}

Page 47: Lecture 21: Arrays. 2 Lecture Contents: t Declaring and referencing arrays t Array subscripts t Using…

4727

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.

Page 48: Lecture 21: Arrays. 2 Lecture Contents: t Declaring and referencing arrays t Array subscripts t Using…

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

Page 49: Lecture 21: Arrays. 2 Lecture Contents: t Declaring and referencing arrays t Array subscripts t Using…

49

Problem

To add two arrays (to add their corresponding elements)

Result saved to third array, same size

Page 50: Lecture 21: Arrays. 2 Lecture Contents: t Declaring and referencing arrays t Array subscripts t Using…

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}

Page 51: Lecture 21: Arrays. 2 Lecture Contents: t Declaring and referencing arrays t Array subscripts t Using…

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

Page 52: Lecture 21: Arrays. 2 Lecture Contents: t Declaring and referencing arrays t Array subscripts t Using…

52

9.4 Reading Part of an Array

Sometimes it is difficult to know how many elements will be in an array

Scores example– 150 students– 200 students

Always allocate enough space at compile time

Remember to start with index [0]

Page 53: Lecture 21: Arrays. 2 Lecture Contents: t Declaring and referencing arrays t Array subscripts t Using…

53

ReadScoresFile.cpp

POSTPONE TO LECTURE ON FILESSkip 6 coming slides

// File: ReadScoresFile.cpp// Reads an array of exam scores for a lecture// section of up to max_size students.

#include <iostream>#include <fstream>using namespace std;

#define inFile "Scores.txt"

Page 54: Lecture 21: Arrays. 2 Lecture Contents: t Declaring and referencing arrays t Array subscripts t Using…

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

Page 55: Lecture 21: Arrays. 2 Lecture Contents: t Declaring and referencing arrays t Array subscripts t Using…

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

Page 56: Lecture 21: Arrays. 2 Lecture Contents: t Declaring and referencing arrays t Array subscripts t Using…

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

Page 57: Lecture 21: Arrays. 2 Lecture Contents: t Declaring and referencing arrays t Array subscripts t Using…

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;

Page 58: Lecture 21: Arrays. 2 Lecture Contents: t Declaring and referencing arrays t Array subscripts t Using…

5836

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

Page 59: Lecture 21: Arrays. 2 Lecture Contents: t Declaring and referencing arrays t Array subscripts t Using…

59

Strings and Arrays of Characters

String object uses an array whose elements are type char

First position of a string object is 0– example string find function ret of position 0

Can use the find function to locate or search an array

We will study some various search functions

Page 60: Lecture 21: Arrays. 2 Lecture Contents: t Declaring and referencing arrays t Array subscripts t Using…

60

12.4 Recursive Functions with Array Arguments

// File: findSumTest.cpp// Program and recursive function to sum an// array's elements

#include <iostream>using namespace std;

// Function prototype int findSum(int[], int);int binSearch(int[], int, int, int);

Page 61: Lecture 21: Arrays. 2 Lecture Contents: t Declaring and referencing arrays t Array subscripts t Using…

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;

Page 62: Lecture 21: Arrays. 2 Lecture Contents: t Declaring and referencing arrays t Array subscripts t Using…

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

Page 63: Lecture 21: Arrays. 2 Lecture Contents: t Declaring and referencing arrays t Array subscripts t Using…

63

FindSumTest.cpp

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

Page 64: Lecture 21: Arrays. 2 Lecture Contents: t Declaring and referencing arrays t Array subscripts t Using…

6465

9.9 Common Programming Errors

Watch non int subscripts (ASCII value) Enumerated types can be used Out of range errors

– C++ no range error checking Lack of subscript to gain access Subscript reference to non-array variable Type mixing when using with functions Initialization of arrays

Page 65: Lecture 21: Arrays. 2 Lecture Contents: t Declaring and referencing arrays t Array subscripts t Using…

65

Exercise 21.1-21.5

Build programs using arraysArrays as actual arguments and formal parameters: function to add two same size arrays (values associated

to all array elements); function to evaluate the first 20 elements of Fibonacci

series; sum (product) of the elements of an initialized array; average value of the sum of array elements entered as

input values; count the number of digit characters in the input stream.

Page 66: Lecture 21: Arrays. 2 Lecture Contents: t Declaring and referencing arrays t Array subscripts t Using…

66

Before lecture end

Lecture:Arrays

More to read:Friedman/Koffman, Chapter 09

Page 67: Lecture 21: Arrays. 2 Lecture Contents: t Declaring and referencing arrays t Array subscripts t Using…

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

Page 68: Lecture 21: Arrays. 2 Lecture Contents: t Declaring and referencing arrays t Array subscripts t Using…

Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley 68

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

Page 69: Lecture 21: Arrays. 2 Lecture Contents: t Declaring and referencing arrays t Array subscripts t Using…

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

Page 70: Lecture 21: Arrays. 2 Lecture Contents: t Declaring and referencing arrays t Array subscripts t Using…

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

Page 71: Lecture 21: Arrays. 2 Lecture Contents: t Declaring and referencing arrays t Array subscripts t Using…

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

16.0 12.0 6.0 8.0 2.5 12.0 14.0 -54.5

Page 72: Lecture 21: Arrays. 2 Lecture Contents: t Declaring and referencing arrays t Array subscripts t Using…

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

Page 73: Lecture 21: Arrays. 2 Lecture Contents: t Declaring and referencing arrays t Array subscripts t Using…

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

Page 74: Lecture 21: Arrays. 2 Lecture Contents: t Declaring and referencing arrays t Array subscripts t Using…

Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley 74

Figure 9.3 Arrays onVacation, vacationDays, and dayOff

Page 75: Lecture 21: Arrays. 2 Lecture Contents: t Declaring and referencing arrays t Array subscripts t Using…

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

Page 76: Lecture 21: Arrays. 2 Lecture Contents: t Declaring and referencing arrays t Array subscripts t Using…

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

Page 77: Lecture 21: Arrays. 2 Lecture Contents: t Declaring and referencing arrays t Array subscripts t Using…

Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley 77

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

Page 78: Lecture 21: Arrays. 2 Lecture Contents: t Declaring and referencing arrays t Array subscripts t Using…

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;

Page 79: Lecture 21: Arrays. 2 Lecture Contents: t Declaring and referencing arrays t Array subscripts t Using…

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 )

Page 80: Lecture 21: Arrays. 2 Lecture Contents: t Declaring and referencing arrays t Array subscripts t Using…

Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley 80

9.3 Array Arguments

• Use <, ==, >, +, -, etc. to test and modify array elements individually

• Can pass array elements to functionsexchange (s[3], s[5]);

Page 81: Lecture 21: Arrays. 2 Lecture Contents: t Declaring and referencing arrays t Array subscripts t Using…

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

Page 82: Lecture 21: Arrays. 2 Lecture Contents: t Declaring and referencing arrays t Array subscripts t Using…

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

Page 83: Lecture 21: Arrays. 2 Lecture Contents: t Declaring and referencing arrays t Array subscripts t Using…

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;

Page 84: Lecture 21: Arrays. 2 Lecture Contents: t Declaring and referencing arrays t Array subscripts t Using…

Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley 84

Listing 9.4 Function sameArray

Page 85: Lecture 21: Arrays. 2 Lecture Contents: t Declaring and referencing arrays t Array subscripts t Using…

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

Page 86: Lecture 21: Arrays. 2 Lecture Contents: t Declaring and referencing arrays t Array subscripts t Using…

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

Page 87: Lecture 21: Arrays. 2 Lecture Contents: t Declaring and referencing arrays t Array subscripts t Using…

Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley 87

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

Page 88: Lecture 21: Arrays. 2 Lecture Contents: t Declaring and referencing arrays t Array subscripts t Using…

Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley 88

Listing 9.7 Function readScoresFile

Page 89: Lecture 21: Arrays. 2 Lecture Contents: t Declaring and referencing arrays t Array subscripts t Using…

Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley 89

Listing 9.7 Function readScoresFile (continued)

Page 90: Lecture 21: Arrays. 2 Lecture Contents: t Declaring and referencing arrays t Array subscripts t Using…

Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley 90

9.10 Common Programming Errors• Arrays

– Out-of-range subscript references– Unsubscripted array references– Subscripted references to nonarray variables– Mixing types in passing arrays to functions

Page 91: Lecture 21: Arrays. 2 Lecture Contents: t Declaring and referencing arrays t Array subscripts t Using…

91

Thank You For

Your Attention!