Download presentation
Presentation is loading. Please wait.
Published byScot Greer Modified over 8 years ago
1
Lecture 21: Arrays
2
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
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
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
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
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
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
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
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
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
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
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
13 Referencing array elements Subscripted /indexed/ variable: a variable followed by a subscript in brackets, designating an array element.
14
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
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
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
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
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
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
20 More on arrays Extract from Friedman/Koffman, chapter 9
21
Data Structures Arrays and Structs Chapter 9
22
22 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
23
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
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
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
26 6 Array Declaration
27
27 7 Sample Declarations Suppose const int N = 20; const int M = 40; const int MaxStringSize = 80; const int MaxListSize = 1000;
28
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
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
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
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
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
33 13 Array Element Manipulation cin >> A[k]; // where the next input value is 3
34
34 14 Inputting Into An Array int A[MaxListSize]; int n = 0; int CurrentInput; while (n < MaxListSize) { cin >> CurrentInput; A[n] = CurrentInput; ++n; }
35
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
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
37
37 17 9.2 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
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
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
40 22 ShowDiff.cpp Program Output Enter 8 numbers: 16 12 6 8 2.5 12 14 -54.5 The average value is 2.0 Table of differences between x[i] and the average Ix[I]difference 016.014.0 112.010.0 2 6.0 4.0 3 8.0 6.0 etc
41
41 9.3 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
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
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
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
45 Problem t To check two arrays for identity
46
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
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
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
49 Problem t To add two arrays (to add their corresponding elements) t Result saved to third array, same size
50
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
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
52
52 9.4 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
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
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
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; }
56
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
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
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
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
60
60 12.4 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
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
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
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); }
64
64 65 9.9 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
65 Exercise 21.1-21.5 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
66 Before lecture end Lecture: Arrays More to read: Friedman/Koffman, Chapter 09
67
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
68
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
69
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
70
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
71
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.012.06.08.02.512.014.0-54.5
72
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];
73
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];
74
Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley 74 Figure 9.3 Arrays onVacation, vacationDays, and dayOff
75
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 ([ ])
76
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
77
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
78
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;
79
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 )
80
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 functions exchange (s[3], s[5]);
81
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
82
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
83
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;
84
Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley 84 Listing 9.4 Function sameArray
85
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);
86
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]; }
87
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
88
Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley 88 Listing 9.7 Function readScoresFile
89
Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley 89 Listing 9.7 Function readScoresFile (continued)
90
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
91
91 Thank You For Your Attention!
Similar presentations
© 2024 SlidePlayer.com. Inc.
All rights reserved.