Presentation is loading. Please wait.

Presentation is loading. Please wait.

Lecture 7 1 Dimension Arrays Richard Gesick.

Similar presentations


Presentation on theme: "Lecture 7 1 Dimension Arrays Richard Gesick."— Presentation transcript:

1 Lecture 7 1 Dimension Arrays Richard Gesick

2 Topics Declaring and Using a One-Dimensional Array
Passing an Array as a Function Argument Using const in Function Prototypes Using an Array of struct or class Objects Using an enum Index Type for an Array

3 C++ Data Types simple structured address integral enum floating
float double long double array struct union class char short int long bool address pointer reference

4 Structured Data Type A structured data type is a type that
Stores a collection of individual components with one variable name And allows individual components to be stored and retrieved by their position within the collection

5 Declare variables to store and total 3 blood pressures
int bp1, bp2, bp3; int total; 4000 4002 4004 bp1 bp2 bp3 cin >> bp1 >> bp2 >> bp3; total = bp1 + bp2 + bp3;

6 What if you wanted to store and total 1000 blood pressures?
int bp[1000]; // Declares an array of 1000 int values bp[0] bp[1] bp[2] bp[999]

7 One-Dimensional Array Definition
An array is a structured collection of components (called array elements): Arrays are all of the same data type, given a single name, and stored in adjacent memory locations

8 One Dimensional Array Definiton,
The individual components are accessed by using the array name together with an integral valued index in square brackets The index indicates the position of the component within the collection

9 Functions and Arrays An array identifier, without subscripts, references the starting address(first element) of the array. In C++, arrays are passed by reference (i.e. the starting address is passed, no size information) Arrays in C++ do not know their size. Generally we specify an additional parameter representing the number of elements in the array.

10 Another Example Declare an array called temps which will hold up to 5 individual float values float temps[5]; // Declaration allocates memory number of elements in the array Base Address temps[0] temps[1] temps[2] temps[3] temps[4] indexes or subscripts

11 Declaration of an Array
The index is also called the subscript In C++, the first array element always has subscript 0, the second array element has subscript 1, etc. The base address of an array is its beginning address in memory SYNTAX DataType ArrayName[ConstIntExpression];

12 Yet Another Example Declare an array called name which will hold up to 10 individual char values char name[10]; // Declaration allocates memory number of elements in the array Base Address name[0] name[1] name[2] name[3] name[4] name[9]

13 Assigning Values to Individual Array Elements
float temps[5]; int m = 4; // Allocates memory temps[2] = 98.6; temps[3] = 101.2; temps[0] = 99.4; temps[m] = temps[3] / 2.0; temps[1] = temps[3] - 1.2; // What value is assigned? ? temps[0] temps[1] temps[2] temps[3] temps[4]

14 What values are assigned?
float temps[5]; // Allocates memory int m; for (m = 0; m < 5; m++) { temps[m] = m * 0.2 ; } ? ? ? ? ? temps[0] temps[1] temps[2] temps[3] temps[4]

15 Now what values are printed?
float temps[5]; // Allocates memory Int m; for (m = 4; m >= 0; m--) { cout << temps[m] << endl; } temps[0] temps[1] temps[2] temps[3] temps[4]

16 Variable Subscripts float temps[5]; // Allocates memory int m = 3; What is temps[m + 1] ? What is temps[m] + 1 ? temps[0] temps[1] temps[2] temps[3] temps[4]

17 A Closer Look at the Compiler
float temps[5]; // Allocates memory To the compiler, the value of the identifier temps is the base address of the array We say temps is a pointer (because its value is an address); it “points” to a memory location temps[0] temps[1] temps[2] temps[3] temps[4]

18 Initializing in a Declaration
int ages[5] ={ 40, 13, 20, 19, 36 }; for (int m = 0; m < 5; m++) { cout << ages[m]; } ages[0] ages[1] ages[2] ages[3] ages[4]

19 Passing Arrays as Arguments
In C++, arrays are always passed by reference Whenever an array is passed as an argument, its base address is sent to the called function

20 In C++, No Aggregate Array Operations
The only thing you can do with an entire array as a whole (aggregate) is to pass it as an argument to a function Exception: aggregate I/O is permitted for C strings (special kinds of char arrays)

21 Using Arrays as Arguments to Functions
Generally, functions that work with arrays require two items of information: The beginning memory address of the array (base address) and The number of elements to process in the array

22 Example with Array Parameters
#include <iomanip> #include <iostream> void Obtain (int[], int); // Prototypes here void FindWarmest (const int[], int , int&); void FindAverage (const int[], int , int&); void Print (const int[], int); using namespace std;

23 Example continued... int main ( ) { // Array to hold up to 31 temperatures int temp[31]; int numDays; int average; int hottest; int m;

24 Example continued cout << “How many daily temperatures? ”; cin >> numDays; Obtain(temp, numDays); // Call passes value of numDays // and address temp cout << numDays << “ temperatures“ << endl; Print (temp, numDays);

25 Example continued... FindAverage (temp, numDays, average);
FindWarmest (temp, numDays, hottest); cout << endl << “Average was: “ << average << endl; cout << “Highest was: “ << hottest << endl; return 0; }

26 Memory Allocated for Array
// Array to hold up to 31 temperatures int temp[31]; temp[0] temp[1] temp[2] temp[3] temp[4] temp[30] 6000 Base Address

27 void Obtain ( /* out */ int temp[] ,
/* in */ int number ) // User enters number temperatures at keyboard // Precondition: // number is assigned && number > 0 // Postcondition: // temp[0 . . number -1] are assigned

28 { int m; for (m = 0; m < number; m++) cout << “Enter a temperature : “; cin >> temp[m]; }

29 void Print ( /* in */ const int temp[],
/* in */ int number ) // Prints number temperature values to screen // Precondition: // number is assigned && number > 0 // temp[0 . . number -1] are assigned // Postcondition: // temp[0 . . number -1] printed 5 per line

30 { int m; cout << “You entered: “; for (m = 0; m < number; m++) if (m % 5 == 0) cout << endl; cout << setw(7) << temp[m]; }

31 Use of const Because the identifier of an array holds the base address of the array, & is never needed for an array in the parameter list : Arrays are always passed by reference To prevent elements of an array used as an argument from being unintentionally changed by the function: You place const in the function prototype and heading

32 Use of const in prototypes
void Obtain (int[], int); void FindWarmest (const int[], int , int &); void FindAverage (const int[], int , int &); void Print (const int[], int); Do not use const with outgoing array because function is supposed to change array values use const with incoming array values to prevent unintentional changes by function

33 void FindAverage( /* in */ const int temp[],
/* in */ int number, /* out */ int & avg) // Determines average of temp[0 . . number-1] // Precondition: // number is assigned && number > 0 // temp[0 . . number -1] are assigned // Postcondition: // avg == average of temp[0 . . number-1] { int m; int total = 0; for (m = 0; m < number; m++) total = total + temp[m]; } avg = int (float(total) / float(number) + .5); Example, cont... void FindAverage( /* in */ const int temp[], /* in */ int number, /* out */ int & avg) // Determines average of temp[0 . . number-1] // Precondition: // number is assigned && number > 0 // temp[0 . . number -1] are assigned // Postcondition: // avg == average of temp[0 . . number-1]

34 Example, cont... { int m; int total = 0; for (m = 0; m < number; m++) total = total + temp[m]; } avg = int (float(total) / float(number) + .5);

35 Another Example void FindWarmest ( /* in */ const int temp[], /* in */ int number, /* out */ int& largest) // Determines largest of temp[0 . . number-1] // Precondition: // number is assigned && number > 0 // temp[0 . . number -1] are assigned // Postcondition: // largest== largest value in // temp[0 . . number-1]

36 Another Example, cont... { int m; // Initialize to first element largest = temp[0]; for (m = 0; m < number; m++) if (temp[m] > largest) largest = temp[m]; }

37 Using Arrays for Counters
Write a program to count the number of each alphabetic letter in a text file letter ASCII ‘A’ 65 ‘B’ 66 ‘C’ 67 ‘D’ 68 ‘Z’ 90 A:\my.dat This is my text file. It contains many things! 5 + 8 is not 14. Is it?

38 const int SIZE 91; int freqCount[SIZE];
freqCount[65] freqCount[66] freqCount[89] freqCount[90] unused counts ‘A’ and ‘a’ counts ‘B’ and ‘b’ . counts ‘ Y’ and ‘y’ counts ‘Z’ and ‘z’

39 Main Module Pseudocode
Level 0 Open dataFile (and verify success) Zero out freqCount Read ch from dataFile WHILE NOT EOF on dataFile If ch is alphabetic character If ch is lowercase alphabetic Change ch to uppercase Increment freqCount[ch] by 1 Print characters and frequencies

40 Counting Frequency of Alphabetic Characters
// Program counts frequency of each alphabetic // character in text file. #include < fstream > #include < iostream > #include < cctype > const int SIZE=91; void PrintOccurrences(const int[]); // Prototype

41 Counting Frequency of Alphabetic Characters
int main () { ifstream dataFile; int freqCount[SIZE]; char ch; char index;

42 Counting Frequency of Alphabetic Characters
dataFile.open (“my.dat”); // Open if (! dataFile) // Verify success { cout << “ CAN’T OPEN INPUT FILE ! “ << endl; return 1; } for ( int m = 0; m < SIZE; m++) // Zero array freqCount[m] = 0;

43 Counting Frequency of Alphabetic Characters
// Read file one character at a time dataFile.get (ch); // Priming read while (dataFile) // While read successful { if (isalpha (ch)) if (islower (ch)) ch = toupper (ch); freqCount[ch] = freqCount[ch] + 1;

44 Counting Frequency of Alphabetic Characters
} dataFile. get (ch); // Get next character PrintOccurrences (freqCount); return 0;

45 Counting Frequency of Alphabetic Characters
void PrintOccurrences ( /* in */ const int freqCount []) // Prints each alphabet character and its frequency // Precondition: // freqCount[‘A’ . . ‘Z’] are assigned // Postcondition: // freqCount[‘A’ . . ‘Z’] have been printed

46 Counting Frequency of Alphabetic Characters
{ char index; cout << “File contained “ << endl; cout << “LETTER OCCURRENCES” << endl; for ( index = ‘A’ ; index < = ‘Z’; index ++) cout << setw(4) << index << setw(10) << freqCount[index] << endl; }

47 More about Array Indexes
Array indexes can be any integral type including char and enum types The index must be within the range 0 through the declared array size minus one It is the programmer’s responsibility to make sure that an array index does not go out of bounds

48 More About Array Indexes
The index value determines which memory location is accessed Using an index value outside this range causes the program to access memory locations outside the array

49 Array with enum Index Type
DECLARATION enum Department { WOMENS, MENS, CHILDRENS, LINENS, HOUSEWARES, ELECTRONICS }; float salesAmt[6]; Department which; USE for (which = WOMENS; which <= ELECTRONICS; which = Department(which + 1)) cout << salesAmt[which] << endl;

50 float salesAmt[6]; salesAmt[WOMENS] (i. e. salesAmt[0])
salesAmt[MENS] (i. e. salesAmt[1]) salesAmt[CHILDRENS] (i. e. salesAmt[2]) salesAmt[LINENS] (i. e. salesAmt[3]) salesAmt[HOUSEWARES] (i. e. salesAmt[4]) salesAmt[ELECTRONICS] (i. e. salesAmt[5])

51 Parallel Arrays Parallel arrays are two or more arrays that have the same index range and whose elements contain related information, possibly of different data types EXAMPLE const int SIZE 50; int idNumber[SIZE]; float hourlyWage[SIZE]; parallel arrays

52 const int SIZE 50; int idNumber[SIZE]; // Parallel arrays hold float hourlyWage[SIZE]; // Related information idNumber[0] hourlyWage[0] idNumber[1] hourlyWage[1] 6278 idNumber[2] hourlyWage[2] idNumber[48] hourlyWage[48] idNumber[49] hourlyWage[49]

53 Array of Structures const int MAX_SIZE = 500; enum HealthType { POOR, FAIR, GOOD, EXCELLENT }; struct AnimalType // Declares struct type { long id; string name; string genus; string species; string country; int age; float weight; HealthType health; }; // Declares array AnimalType bronxZoo[MAX_SIZE];

54 AnimalType bronxZoo[MAX_SIZE];
[0] [1] . . [498] [499] bronxZoo[0].id bronxZoo[0].name “camel” bronxZoo[0].genus “Camelus” bronxZoo[0].species “dromedarius” bronxZoo[0].country “India” bronxZoo[0].age bronxZoo[0].weight bronxZoo[0].health Fair

55 AnimalType bronxZoo[MAX_SIZE];
.id name .genus species country .age .weight .health bronxZoo[0] “camel” “Camelus” “dromedarius” “India” Fair bronxZoo[1] bronxZoo[2] bronxZoo[3] bronxZoo[498] bronxZoo[499]

56 Add 1 year to the age member of each element of the bronxZoo array
for (j = 0; j < MAX_SIZE; j++) bronxZoo[j].age = bronxZoo[j].age + 1; OR, bronxZoo[j].age++;

57 Find total weight of all elements of the bronxZoo array
float total = 0.0; for (j = 0; j < MAX_SIZE; j++) total += bronxZoo[j].weight;

58 The focus Searching - examining the contents of the array to see if an element exists within the array Sorting - rearranging the elements of the array to be in a particular order

59 Sorting There are many ways to order elements within a collection.  There is typically a trade-off between complexity of the algorithm and the performance of the algorithm. a simple approach to sorting realize that it is slower than other methods that are more complex to code yet more efficient.

60 Bubble Sort Repeatedly pair-wise examine elements and swap them if needed; this is called a "Bubble sort" since elements "bubble" to their correct positions. 

61 Bubble Sort Algorithm //numEl is size of the array
for (int i = 0; i < numEl - 1; i++) for (int j = i; j < numEl; j++) { if (A[j] < A[i]) int temp = A[j]; A[j] = A[i]; A[i] = temp; }

62 Selection Sort The selection sort algorithm repeatedly finds the smallest element in the unsorted tail region of the array and moves it to the front

63 Sorting an Array of Integers
Array in original order Find the smallest and swap it with the first element Find the next smallest. It is already in the correct place

64 Sorting an Array of Integers (2)
Find the next smallest and swap it with the first element of unsorted portion Repeat When the unsorted portion is of length 1, we are done This algorithm is slow when run on large data sets

65 Time Taken By Selection Sort on Various Size Arrays

66 Selection Sort Algorithm
int i = 0; int j = 0; for (i = 0; i numEl- 1; i++) { int minPos = i; for (j = i + 1; j < numEl; j++) if (B[j] < B[minPos]) minPos = j; } if (i != minPos && minPos < numEl) int temp = B[minPos]; B[minPos] = B[i]; B[i] = temp;

67 Insertion Sort Consider what you would do to sort a set of cards.  This approach is an insertion sort - taking a new item and place it correctly relative to the other items in the "finished" portion.  You continually maintain two sets - unexamined, unsorted cards and a set of examined/sorted cards.  For each card in the unexamined set, take it out of that set and place it correctly relative to the examined set.

68 Insertion Sort The yellow cards are sorted and the white cards are not. To insert the 4, we compare it to the 9. 4 is smaller, so we shift 9 to the right. We compare the 4 to the 5. 4 is smaller, so we shift 5 to the right. We compare the 4 to the 3. 4 is larger, so we insert 4 into the correct slot.

69 Insertion Sort Algorithm
Insertion Sort uses a double loop. Outer Loop : executes n - 1 times and iterates through the array elements from indexes 1 through n - 1. If the variable i represents the counter of the outer loop, the array can be thought of as made of three parts: a sorted subarray (although they may not be in their final position yet) from index 0 to i - 1, the array element (at index i ) that we are currently inserting, a subarray (from index i + 1 to n - 1) of elements that have not yet been inserted. At each iteration of the outer loop, we insert the current array element at its proper place within the sorted subarray.

70 Insertion Sort Algorithm
The inner loop compares the current array element to the elements of the sorted array from right to left and shifts these elements to the right until it finds the proper insert location. After all elements have been inserted, the array is sorted.

71 Insertion Sort Pseudocode
for i = 1 to last array index by 1 j = i temp = element at index i while ( j != 0 and value of current element is less than value of element at index j - 1 ) shift element at index j - 1 to the right decrement j by 1 assign current element value (stored in temp) to element at index j

72 Insertion Sort Example
At the beginning, the array is: The first element of the array, 17, is automatically in the correct position when we consider the subarray as consisting of that element only. The value of the outer loop counter (i) is 1, and we will now insert the second array element, 26, into the left subarray. First, we save the value of the element to be inserted by storing it in temp.

73 Insertion Sort Example (con’t)
We compare elements 26 and 17. Since 26 is larger than 17, we exit the inner loop. We then assign the value of the current element, 26, stored in temp, to the element at index j = 1; in this case, there is no change to the array. The value 26 has been inserted.

74 Insertion Sort Example (con’t)
The outer loop counter (i) is incremented, and its value is 2. We will now insert the third array element, 5, into the left subarray (at this point comprised of the two inserted elements, 17 and 26).

75 Insertion Sort Example (con’t)
The value of the inner loop counter ( j ) is set to the value of the outer loop counter (i ), i.e. 2. We compare the current element, 5, stored in temp, and 26 (index j - 1 = 1). Since 5 is smaller than 26, we shift 26 to the right and decrement j by 1; j now has the value 1.

76 Insertion Sort Example (con’t)
We then compare the current element, 5, stored in temp, and 17 (index j - 1 = 0). Since 5 is smaller than 17, we shift 17 to the right and decrement j by 1; j now has the value 0.

77 Insertion Sort Example (con’t)
Since j is 0, we exit the inner loop and assign the value of the current element, 5, stored in temp, to the array element at index j = 0. The value 5 has now been inserted.

78 Insertion Sort Example (con’t)
The outer loop counter (i) is incremented, and its value is 3. We will now insert the fourth array element, 2, into the left subarray (at this point comprised of the three inserted elements: 5, 17, and 26).

79 Insertion Sort Example (con’t)
The value of the inner loop counter ( j ) is set to the value of the outer loop counter (i ), i.e. 3. We compare the current element, 2, stored in temp, and 26 (index j - 1 = 2). Since 2 is smaller than 26, we shift 26 to the right and decrement j by 1; j now has the value 2.

80 Insertion Sort Example (con’t)
We then compare the current element, 2, stored in temp, and 17 (index j - 1 = 1). Since 2 is smaller than 17, we shift 17 to the right and decrement j by 1; j now has the value 1.

81 Insertion Sort Example (con’t)
We then compare the current element, 2, stored in temp, and 5 (index j - 1 = 0). Since 2 is smaller than 5, we shift 5 to the right and decrement j by 1; j now has the value 0.

82 Insertion Sort Example (con’t)
Since j is 0, we exit the inner loop and assign the value of the current element, 2, stored in temp, to the array element at index j. The value 2 has now been inserted. And the entire array is sorted.

83 Insertion Sort Code int j, temp; for ( int i = 1; i < numEl; i++ ) { j = i; temp = array[i]; while ( j != 0 && array[j - 1] > temp ) array[j] = array[j - 1]; j--; } array[j] = temp;

84 Linear Search Also called sequential search
Examines all values in an array until it finds a match or reaches the end Number of visits for a linear search of an array of n elements - The average search visits n/2 elements - The maximum visits is n A linear search is an O(n) algorithm

85 Searching Algorithms Search algorithms are grouped according to those that required an ordered dataset and those that do not (i.e. unordered datasets). Unordered datasets searched sequentially. Ordered datasets may be searched sequentially, however binary searches are more efficient.

86 Searching Unordered Datasets
Simple Sequential Search Examine each element starting with the first one until: a match is found. end of the list is reached. Sequential search can be implemented as: a function which returns true if item in the list, false if item is not in the list. a function which returns the location of the item if found, or –1 if not found.

87 Searching Ordered Datasets
Modified Sequential Search: examine every element in the list until: item is found. list element is larger/smaller than the item you are searching for (search fails). Binary Search Examine middle element: if element equals item, item found, return location. if element is larger than item ignore bottom of list. if element is smaller than item ignore top of list. Repeat until: top and bottom cross over (search failed).

88 Binary Search Locates a value in a sorted array by determining whether the value occurs in the first or second half, then repeating the search in one of the halves Number of visits to search an sorted array of size n We visit one element (the middle element) then search either the left or right subarray Binary search is a O( log(n) ) algorithm

89 Example of Binary Search for 48
5 11 14 22 28 37 43 56 59 70 arr[top] arr[mid] arr[bot] 37 43 56 59 70 mid is 7 arr[top] arr[mid] arr[bot] mid is 5 43 37 arr[top] arr[bot] mid is 6 43 arr[6] 43 arr[bot] arr[top]

90 Binary Search Algorithm
int low=0; int high= numEl; int mid = 0; while (!found) { steps++; mid = (low + high) / 2; if (find == G[mid]) return true; else if (find < G[mid]) high = mid; else low = mid; if (low > high-1 || high < low +1) return false; }

91 The vector Class Predefined type included in the Standard Template Library Provides a generic implementation of the array concept. Numerous operators and methods are defined on vectors.

92 The vector class The vector class implements or defines an array, and vector doesn't have to be fixed in size As a result, subarray processing becomes unnecessary as does the need to decide how big to make the array when one declares it Vector must be instantiated with a constructor at run time Thus, one cannot declare a vector using an initialization list as one can do with an array

93 vector Examples vector<char> v1; //Define vector of type char, capacity 0. vector<int> v2(10); //Define v2 with capacity for 10 integers. vector<string> v3(n); //Define v3 with capacity for n strings. vector<double> v4(n,1.0); //Define v4 with capacity for n doubles. //Initialize each element to 1.0.

94 Simple Calls to Vector Constructors
Examples: vector<int> intVec(20); // A vector holding 20 integers // all initialized to 0, vector<string> noSizeVec; // A vector holding 0 strings The first statement makes sense–similar to writing this code: int intVec[20] But why declare a vector with no space in it, as in the second statement?

95 vector Constructors The reason is that a vector automatically expands to hold as much data as one puts into it In the second statement , the programmer did not know how many strings he or she would put into noSizeVec Consequently, the programmer declares the vector with no elements and lets the structure grow as one inserts value

96 vector Constructors When one knows a maximum size in advance, one should indicate that value in the constructor commonly used with vector These operators include: at, back, begin, capacity, clear, empty, end, erase, front, insert, push_back, rbegin, rend, reserve, and size

97 A vector <char> for which 10 Spaces Reserved and 6 Elements Inserted

98 Initializing a vector from an Array of Values
While unable to use an initializer list with a vector; however, one can initialize it from an array of values int occData[] = {3,4,0,3,4,1,1,2,3,2,1,4,2,3,0,5,2,3}; vector<int> occupants(occData, occData+sizeof(occData)/sizeof(int));

99 Initializing a vector from an Array of Values,
First argument, occData, is the base address of the already initialized array Second argument, occData+sizeof(occData)/sizeof(int), is the address that is one greater than the location of the last element of the array C++ automatically casts these addresses into iterators of the appropriate type as they are passed to the constructor Constructor designed so that the address just beyond the array doesn't copy that location into the vector

100 Common Methods of the vector Class
back() begin() capacity() empty( ) end() erase() insert() pop_back() pop_front() resize( ) size( )

101 Passing string and vector Instances to Functions
Unlike arrays, objects of vector and string types are passed by value to functions. Thus a copy is made of the arguments to the function call, and changes made to the formal parameter will NOT affect the argument value. Pass string and vector objects by reference to allow the function to alter the argument. Pass string and vector objects by const reference to avoid copying potentially large datasets.


Download ppt "Lecture 7 1 Dimension Arrays Richard Gesick."

Similar presentations


Ads by Google