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 Data Structures base type Arrays and Structs Individual elements of the array are referenced by sub_scripting the group name Chapter 9
2
Arrays Arrays
Analogies Language restrictions – Egg carton – Subscripts are denoted as expressions – Apartments within brackets: [ ] – Cassette carrier – Base type can be any fundamental, More terminology library-defined, or programmer -defined – Ability to refer to a particular element type • Indexing or sub_scripting – Ability to look inside an element • Accessing value 3 4
Arrays Array Declaration – The index type is integer and the index range must be BaseTypeId [ SizeExp] ; 0 ... n-1 Type of Bracketed • where n is a programmer-defined constant values in constant list Name expression expression. of list indicating – Parameter passing style number of elements in • Always call by reference (no indication list necessary)
5 6
1 Sample Declarations Sample Declarations
Suppose Then the following are all correct array const int N = 20; declarations. const int M = 40; int A[10]; const int MaxStringSize = 80; char B[MaxStringSize]; const int MaxListSize = 1000; float C[M*N]; int Values[MaxListSize]; Rational D[N-15];
7 8
Subscripting Subscripting
Suppose – Second element of A has index 1, and so on int A[10]; // array of 10 ints A[1] To access an individual element we must – Last element has an index one less than the size apply a subscript to array name A of the array A[9] – A subscript is a bracketed expression • The expression in the brackets is known as the index Incorrect indexing is a common error – First element of A has index 0 A[0]
9 10
Array Elements Array Element Manipulation
Suppose Given the following: int A[10]; // array of 10 uninitialized ints int i = 7, j = 2, k = 4; To access an individual element we must A[0] = 1; apply a subscript to array name A A[i] = 5; A[j] = A[i] + 3; A ------A[j+1] = A[i] + A[0]; A[0]A[1] A[2]A[3]A[4]A[5]A[6]A[7] A[8]A[9] A[A[j]] = 12;
11 12
2 Array Element Manipulation Inputting Into An Array
int A[MaxListSize]; int n = 0; int CurrentInput; A 1 -- 8 6 3 -- -- 5 12 -- A[0]A[1] A[2]A[3]A[4]A[5]A[6]A[7] A[8]A[9] while((n < MaxListSize) && (cin >> CurrentInput)) cin >> A[k]; // where the next input value is 3 { A[n] = CurrentInput; ++n; }
13 14
Displaying An Array Remember
// List A of n elements has Arrays are always passed by reference // already been set – Artifact of C for (int i = 0; i < n; ++i) Can use const if array elements are not to be { modified cout << A[i] << " "; You do not need to include the array size } within the brackets when defining an array parameter cout << endl; Initialize array with 0 or some other known
15 value 16
9.2 Sequential Access to ShowDiff.cpp Array Elements
Random Access #include
– Process elements in sequential order starting int main() with the first { – ShowDiff.cpp a program that looks at values const int MAX_ITEMS = 8; float x[MAX_ITEMS]; and calculates a difference between the element float average; and the average float sum;
17 18
3 ShowDiff.cpp ShowDiff.cpp
// Enter the data. cout << "The average value is " << cout << "Enter " << MAX_ITEMS << " numbers: "; average << endl << endl; for (int i = 0; i < MAX_ITEMS; i++) cin >> x[i]; // Display the difference between each item // and the average. // Compute the average value. cout << "Table of differences between x[i] sum = 0.0; and the average." << endl; for (int i = 0; i < MAX_ITEMS; i++) cout << setw (4) << "i" << setw (8) << "x[i]" sum += x[i]; << setw (14) << "difference" << endl; average = sum / MAX_ITEMS;
19 20
ShowDiff.cpp ShowDiff.cpp
for (int i = 0; i < MAX_ITEMS; i++) Program Output cout << setw (4) << i << setw (8) << x[i] << setw (14) << (x[i] - average) << Enter 8 numbers: 16 12 6 8 2.5 12 14 -54.5 endl; The average value is 2.0 Table of differences between x[i] and the average I x[I] difference return 0; 0 16.0 14.0 } 1 12.0 10.0 2 6.0 4.0 3 8.0 6.0 etc etc 21 22
9.3 Array Arguments Exchange.cpp
Use <, ==, >, +, - to test and modify array // FILE: Exchange.cpp // Exchanges two type float values elements At times it might benefit you to pass an void exchange (float& a1, float& a2) { entire array to a function float temp; Can pass array elements to functions temp = a1; – actual function call a1 = a2; exchange (s[3], s[5]); a2 = temp; } Examples follow
23 24
4 Arrays as Function Arguments Arrays as Function Arguments
Remember arrays are pass by reference Remember these points when passing arrays – Passing the array address to functions Remember these points when passing arrays – Formal array arguments that are not to be to functions altered by a function should be specified using the reserved word const . When this – The formal array argument in a function is not specification is used, any attempt to alter the itself an array but rather is a name that contents will cause the compiler generate an represents an actual array argument. Therefore error message in the function definition, you need only inform the compiler with [] that the actual argument SameArray.cpp example
will be an array 25 26
SameArray.cpp SameArray.cpp
// FILE: SameArray.cpp { // COMPARES TWO FLOAT ARRAYS FOR EQUALITY BY // Local data ... // COMPARING CORRESPONDING ELEMENTS int i; i = 0; // Pre: a[i] and b[i] (0 <= i <= size-1) are // assigned values. while ((i < size-1) && (a[i] == b[i])) // Post: Returns true if a[i] == b[i] for all I i++; // in range 0 through size - 1; otherwise, return (a[i] == b[i]); // returns false. } bool sameArray (float a[], float b[], const int size) 27 28
AddArray.cpp 9.4 Reading Part of an Array
// Array elements with subscripts ranging from Sometimes it is difficult to know how many // 0 to size-1 are summed element by element. // Pre: a[i] and b[i] are defined elements will be in an array // (0 <= i <= size-1 Scores example // Post: c[i] = a[i] + b[i] (0 <= i <= size-1) void addArray (int size, const float a[], – 150 students const float b[], float c[]) – 200 students { // Add corresponding elements of a and b and Always allocate enough space at compile store in c. time for (int i = 0; i < size; i++) c[i] = a[i] + b[i]; Remember to start with index [0]
} // end addArray 29 30
5 ReadScoresFile.cpp ReadScoresFile.cpp
// File: ReadScoresFile.cpp void readScoresFile (ifstream& ins,int scores[], // Reads an array of exam scores for a lecture const int MAX_SIZE, int& sectionSize); // section of up to max_size students. int main() #include
#define inFile "Scores.txt" ins.open(inFile);
31 32
ReadScoresFile.cpp ReadScoresFile.cpp
if (ins.fail()) // File: ReadScoresFile.cpp { // Reads an array of exam scores for a lecture cout << "Error" << endl; // section of up to MAX_SIZE students from a return 1; // file. } readScoresFile(ins, scores, 5, size); // Pre: None for (int i = 0; i < size; i++) // Post: The data values are read from a file cout << scores[i] << " " ; // and stored in array scores. cout << endl; // The number of values read is stored in // sectionSize.(0 <= sectionSize < MAX_SIZE).
return 0; } 33 34
ReadScoresFile.cpp ReadScoresFile.cpp void readScoresFile (ifstream& ins, int scores[], sectionSize++; const int MAX_SIZE, int& sectionSize) ins >> tempScore; { } // end while // Local data ... int tempScore; // End of file reached or array is filled. if (!ins.eof()) // Read each array element until done. { sectionSize = 0; cout << "Array is filled!" << endl; ins >> tempScore; cout << tempScore << " not stored" << endl; while (!ins.eof() && (sectionSize < MAX_SIZE)) } { } scores[sectionSize] = tempScore; 35 36
6 9.5 Searching and Sorting ArrayOperations.cpp Arrays
Look at 2 common array problems // File: arrayOperations.cpp // Finds the subscript of the smallest value in a – Searching // subarray. – Sorting // Returns the subscript of the smallest value How do we go about finding the smallest // in the subarray consisting of elements number in an array? // x[startindex] through x[endindex] – Assume 1st is smallest and save its position // Returns -1 if the subarray bounds are invalid. // Pre: The subarray is defined and 0 <= – Look for one smaller // startIndex <= endIndex. – If you locate one smaller save its position // Post: x[minIndex] is the smallest value in // the array. 37 38
ArrayOperations.cpp ArrayOperations.cpp
int findIndexOfMin(const float x[], cerr << "Error in subarray bounds" << endl; int startIndex, int endIndex) return -1; { } // Local data ... int minIndex; // Assume the first element of subarray is int i; // smallest and check the rest. // minIndex will contain subscript of smallest // Validate subarray bounds // examined so far. if ((startIndex < 0) || (startIndex > minIndex = startIndex; endIndex)) for (i = startIndex + 1; i <= endIndex; i++) { if (x[i] < x[minIndex]) minIndex = i; 39 40
Strings and Arrays of ArrayOperations.cpp Characters
String object uses an array whose elements // All elements are examined and minIndex is are type char // the index of the smallest element. return minIndex; First position of a string object is 0 } // end findIndexOfMin – 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
41 42
7 Linear Search ArrayOperations.cpp
The idea of a linear search is to walk // Searches an integer array for a given element through the entire until a target value is // (the target) // Array elements ranging from 0 to size - 1 are located // searched for an element equal to target. If the target is not located some type of // Pre: The target and array are defined. // Post: Returns the subscript of target if indicator needs to be returned // found; otherwise, returns -1.
int linSearch (const int items[], int target, int size) { for (int i = 0, i < size, i++) 43 44
Sorting in Ascending Order ArrayOperations.cpp Selection Sort
Idea of the selection sort is to locate the if (items[next] == target) smallest value in the array return next; Then switch positions of this value and that // All elements were tested without success. in position [0] return -1; } // end linSearch We then increment the index and look again for the next smallest value and swap Continue until sorted
45 46
ArrayOperations.cpp ArrayOperations.cpp
// Sorts an array (ascending order) using void selSort(int items[], int n) // selection sort algorithm { // Uses exchange and findIndexOfMin // Local data ... // Sorts the data in array items (items[0] int minSub; // through items[n-1]). // Pre: items is defined and n <= declared size for (int i = 0; i < n-1; i++) // of actual argument array. { // Post: The values in items[0] through items // Find index of smallest element in // [n-1] are in increasing order. // unsorted section of items. minSub = findIndexOfMin(items, i, n-1);
47 48
8 9.7 Analyzing Algorithms ArrayOperations.cpp Big O Notation
How to compare efficiency of various algorithms // Exchange items at position minSub and i exchange(items[minSub], items[i]); A mathematical measuring stick to do } quantitative analysis on algorithms } Typically sorting and searching Based on looping constructs and placed into categories based on their efficiency Most algorithms have BigO published
49 50
Analyzing Algorithms Analyzing Algorithms Big O Notation Big O Notation
Run time efficiency is in direct proportion Two independent loops to the number of elementary machine – Sum of the loops is efficiency operations – n/2 + n^2 is Big O(N^2) – Compares Example: – Exchanges for (k=1; k<=n/2; ++k) { } for (j=1; j<=n*n; ++j) { 51 } 52
Analyzing Algorithms 9.7 The Struct Data Type Big O Notation
Two nested loops struct used to store related data items – Product of the loops is efficiency Individual components of the struct are – n/2 * n^2 = n^3/2 is Big O(N^3) called its members Example: Each member can contain different types of for (k=1; k<=n/2; ++k) data { Employee example for (j=1; j<=n*n; ++j) { } } 53 54
9 Accessing Members of a Struct Employee struct
// Definition of struct employee Members are accessed using the member struct employee access operator , a period { For struct variable s and member variable m string id; string name; to access m you would use the following: char gender; – cout << s.m << endl; int numDepend; money rate; Can use all C++ operators and operations on money totWages; structs };
55 56
Accessing Members of a 9.8 Structs as Operands and struct Arguments organist.id = 1234; How to do arithmetic and other operations organist.name = “Noel Goddard”; using structs organist.gender = ‘F’; Process entire struct using programmer organist.numDepend = 0; defined functions organist.rate = 6.00; Often better to pass an entire structure organist.totWages += organist.rate * 40.0; rather than individual elements struct copies organist = janitor;
57 58
Passing struct as an Argument ExamStat.h
Grading program example // FILE: ExamStat.h
Keep track of students grades struct examStats { Prior to our learning structs we needed to string stuName; store each item into a single variable int scores[3]; Group all related student items together float average; char grade; Pass struct by const reference if you do not }; want changes made
59 60
10 PrintStats.cpp PrintStats.cpp
// File: printStats.cpp // Prints the exam statistics cout << stuExams.scores[0] << ' ' << stuExams.scores[1]<< ' ' << // Pre: The members of the struct variable stuExams.scores[2] << endl; // stuExams are assigned values. cout << "Average score: " << // Post: Each member of stuExams is displayed. stuExams.average << endl; cout << "Letter grade : " << void printStats(examStats stuExams ) stuExams.grade << endl; { } cout << "Exam scores for " << stuExams.stuName << ": "
61 62
ReadEmp.cpp ReadEmp.cpp
// File: ReadEmp.cpp // Reads one employee record into oneemployee getline(cin, oneEmployee.name, '#'); cout << "Enter an id number: "; #include
9.9 Common Programming Common Programming Errors Errors
Watch non int subscripts (ASCII value) No prefix to reference a struct member Enumerated types can be used Incorrect prefix reference to a struct Out of range errors member – C++ no range error checking Missing ; following definition of struct Lack of subscript to gain access Initialization of struct members Subscript reference to non-array variable Type mixing when using with functions Initialization of arrays 65 66
11