Data Structures Arrays and Structs 9.1 the Array Data Type Arrays Arrays

Data Structures Arrays and Structs 9.1 the Array Data Type Arrays Arrays

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 <iostream> #include <iomanip> – Access elements is random order Sequential Access using namespace std; – 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 <iostream> { int scores[100]; #include <fstream> int size; using namespace std; ifstream ins; #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.

View Full Text

Details

  • File Type
    pdf
  • Upload Time
    -
  • Content Languages
    English
  • Upload User
    Anonymous/Not logged-in
  • File Pages
    11 Page
  • File Size
    -

Download

Channel Download Status
Express Download Enable

Copyright

We respect the copyrights and intellectual property rights of all users. All uploaded documents are either original works of the uploader or authorized works of the rightful owners.

  • Not to be reproduced or distributed without explicit permission.
  • Not used for commercial purposes outside of approved use cases.
  • Not used to infringe on the rights of the original creators.
  • If you believe any content infringes your copyright, please contact us immediately.

Support

For help with questions, suggestions, or problems, please contact us