Download presentation
Presentation is loading. Please wait.
Published byRegina Waters Modified over 9 years ago
1
11/26/2015 CSI 201 -- Chapter 10, Part I 1 Introducing Arrays… An array is a collection of sequentially indexed elements, each element having the same type. Examples: A list of names A list of temperatures Each element of the array has a unique index number identifying that element. Why do we need arrays? Imagine keeping track of 5 test scores, or 100, or 1000 in memory How would you name all the variables? How would you process each of the variables?
2
11/26/2015 CSI 201 -- Chapter 10, Part I 2 Declaring Arrays Syntax: Type_name Array_Name [ Declared_Size ]; Type_name is the type of each element in the array. (Called the base type of the array.) Array_Name is an identifier that names the array. Declared_Size is an constant integer expression that specifies the number of elements in the array. (Called the size of the array.) Example: To declare an array of five integers, named score, the declaration looks like: int score[ 5 ]; Name of the array is score. Base type is int. Size is 5. The result – 5 distinct integer variables are set up in memory. You may also use a const int variable to declare an array: const int MAX_SIZE = 20; int score[MAX_SIZE];
3
11/26/2015 CSI 201 -- Chapter 10, Part I 3 Array Elements Each variable in the array is referred to as an element of the array. To access an element of the array, we need the index number of the element. Every element has a unique index number. The index range is 0 to size – 1. Use [] with the index of the variable you want to access in between the brackets. Example: int score[3]; // Declare the array score[0] = 10; // Set the first indexed variable to 10 score[1] = 20; // Set the second indexed variable to 20 score[2] = 30; // Set the third indexed variable to 30 Terminology: Indexed variable – refers to an element of the array through use of [ ] Also known as: Array location "sub" – e.g. score[2] will often be referred to as "score sub 2" The value in brackets is called the index or a subscript Array index values always begin at index number 0. This is important to remember.
4
11/26/2015 CSI 201 -- Chapter 10, Part I 4 Types of indexed variables Indexed variables form expressions Each indexed variable has a type – the base type of the array. Any type can be used as a base type of an array: int score[5]; double temperature[20]; Student st[15]; Therefore, an indexed array variable can be used anywhere an ordinary variable of the base type is used: int x; cin >> x; Extracts an integer from the keyboard to store in variable x int score[5]; cin >> score[0]; Extracts an integer from the keyboard to store in the first indexed variable in array score.
5
11/26/2015 CSI 201 -- Chapter 10, Part I 5 Assigning values to indexed variables The index can be any expression that evaluates to an integer. Example: In this example, the last indexed variable of the array is assigned a value of 99: int score[5]; int n = 2; score[n+2] = 99; It is legal to use a variable as an index into an array. Can you use a variable as the size in an array declaration? How does this different than the restrictions of an index?
6
11/26/2015 CSI 201 -- Chapter 10, Part I 6 Loops and Arrays – ex1.cpp for loops are commonly used to iterate through an array. See ex1.cpp for(int i = 0; i < MAX_SCORES; i++) { fin >> score[i]; // If we have an end-of-file condition, then // terminate the loop early if (fin.eof()) break; // If we made it here, we read in a valid score, so // increment count. count++; } It is common to declare arrays using a const int variable to specify the size Why? Because you often need to go back and change an array size. Thus, you only need to change the value of one variable in your code.
7
11/26/2015 CSI 201 -- Chapter 10, Part I 7 Variables and declarations Do not use a non-const variable to declare an array. Example: cout > number; int score[number]; Why is this illegal? Because the size of an array must be known at compile time. A const int variable does NOT change at run-time, which is why using a const variable is legal. Later in the course, we will see how to use dynamic memory to allocate memory at run-time.
8
11/26/2015 CSI 201 -- Chapter 10, Part I 8 Arrays in Memory Recall memory and variables from the beginning of the course… Computer memory consists of individual cells that store bytes. Each byte has a unique address that indicates its location in memory. Every variable is stored in memory, and thus has a unique address indicating it's location. The number of bytes set aside for the variable depends on the type of the variable. int uses 4 bytes char uses 1 byte double uses 8 bytes A variable's address is the address of the first byte of the variable. The address of an array is the address of the first indexed variable in the array. This is referred to as the base address of the array.
9
11/26/2015 CSI 201 -- Chapter 10, Part I 9 Arrays in Memory Declaring the array: int a[6]; The base type is int. Therefore, memory is reserved for six variables of type int. The variables are allocated contiguously. The address of the first indexed variable, a[0], is the base address of the entire array a. With the base address, you can find the address of any indexed variable by: address = base_address + (index * size_of_base_type) See next slide…
10
11/26/2015 CSI 201 -- Chapter 10, Part I 10 An Array in Memory Some compilers use 4 bytes for an int, some use two. In this diagram, we use two bytes to represent an int variable.
11
11/26/2015 CSI 201 -- Chapter 10, Part I 11 Array Index Out of Range When an index expression evaluates to some value other than those allowed by the array declaration, the index is said to be out of range Unfortunately, the compiler has no way of checking for an out of range index, therefore you will NOT see an error message when you compile! Accessing your array with an out of range index value will usually crash your program with a run time error called a memory access violation. Sometimes, your program won't crash at run-time… it'll just write over other variables, often having disastrous effects! BE CAREFUL when indexing an array! Run ex2.cpp and watch and see what happens…
12
11/26/2015 CSI 201 -- Chapter 10, Part I 12 Initializing Arrays at Declaration Like most variables we've seen, arrays are initialized with garbage values. However, like most variables, C++ provides a mechanism to initialize an array as part of the variable declaration. Example: int children[3] = { 2, 12, 1 }; This is equivalent to: int children[3]; children[0] = 2; children[1] = 12; children[2] = 1; If you list fewer values than there are indexed variables, the remaining indexed variables will be initialized to zero: int children[5] = { 2, 12, 1 }; What are the values in this array? You can omit the size of an array, ONLY IF you use an initialization list as part of the declaration: int children[] = { 2, 12, 1 }; The array children is automatically declared to be of size 3.
13
11/26/2015 CSI 201 -- Chapter 10, Part I 13 Examples What is the output of the following code? int x[5] = { 2, 3, 1, 4, 5 }; for (int index = 0; index <5; index++) cout << x[index] << " "; What is the output of the following code? int x[5] = { 2, 3, 1 }; for (int index = 0; index <5; index++) cout << x[index] << " "; What is the output of the following code? int x[5] = { 2, 3, 1 }; for (int index = 0; index <5; index++) { if (index + 1 < 5) x[index] = x[index+1]; cout << x[index] << " "; }
14
11/26/2015 CSI 201 -- Chapter 10, Part I 14 Indexed variables as function arguments Suppose you have the following declarations: int x[10]; void output_func(int a); Then, this is legal: output_func(x[1]); This would call the function output_func passing the second variable in array x. See ex3.cpp
15
11/26/2015 CSI 201 -- Chapter 10, Part I 15 Entire Arrays as Function Arguments You can pass an entire array to a function. To do so, declare your formal parameter for your function to take an array type. An array parameter is indicated by using empty brackets in the parameter list: output_scores(ostream &out, int score[], int size); No size is specified between the brackets A parameter of this type is simply called an array parameter It is not a call-by-value parameter It is not a call-by-reference parameter However, array parameters behave much like call-by- reference parameters. Why? Because they both pass the address of the variable to the function. Arrays pass the base address to the function. See ex4.cpp
16
11/26/2015 CSI 201 -- Chapter 10, Part I 16 Arrays as Function arguments When we see an array declaration, we know the following attributes of the array: The base type The base address (which is the address of the first indexed variable.) The number of indexed variables When passing an array as an parameter into a function, the function only knows: The base type The base address The size of the array is NOT passed as part of the array Therefore, you must make a provision to pass the size of the array into the function. output_scores(ostream &out, int score[], int size); It is worth mentioning that there is no means in C++ of returning an array from a function. We will explore this again when we talk about pointers.
17
11/26/2015 CSI 201 -- Chapter 10, Part I 17 const modifier with array parameters Your function may change the value of the indexed variables in the array. If this is undesired, you may use the const modifier with an array parameter to prevent this from happening. The compiler does extra checking to ensure that no line of code in your function changes any element of the array. Example: void output_scores(ostream &out, const int scoreList[], int count); The const modifier must be used in both the function declaration and the function definition.
18
11/26/2015 CSI 201 -- Chapter 10, Part I 18 Programming with Arrays Two common routines are used throughout programming with arrays Searching arrays Sequential search (works with any array) Binary search (requires array to be sorted) Sorting array values Selection sort Insertion sort Bubble sort When considering searching and sorting, one must consider a special key value to search for or sort on. For each of these algorithms, consider a file cabinet of student records for example purposes. (The file cabinet is analogous to an array.) Let the student id be our key value. We will then be performing one of two tasks: searching for a particular student id arranging (or sorting) the folders in order of increasing student id's.
19
11/26/2015 CSI 201 -- Chapter 10, Part I 19 Sequential Search This is analogous to opening the file cabinet drawer, where the folders are in no particular order. You search each folder one by one, starting with the first folder, until you find the id you are looking for.
20
11/26/2015 CSI 201 -- Chapter 10, Part I 20 ex5.cpp – sequential search int search(const int id[], int size, int target_id) { int index = 0; bool bFound = false; while (!bFound && index < size) { if (id[index] == target_id) bFound = true; else index++; } if (bFound) return index; else return -1; }
21
11/26/2015 CSI 201 -- Chapter 10, Part I 21 Questions An iteration of a search algorithm is considered to be one pass through the search criterion of the algorithm. We typically ask, "How many iterations does the loop execute until the target is found?" Given an array of 10 integers with the following values: 10, 3, 5, 8, 20, 21, 1, 7, 4, 11 Using sequential search, how many iterations does it take to find the number 4? How about 10?
22
11/26/2015 CSI 201 -- Chapter 10, Part I 22 Selection sort We will arrange the order of the records in the drawer by order of increasing student id number. Algorithm: You know the smallest id belongs in the first position. So, open the drawer, and look throughout the entire drawer for the smallest id number. When you find it, swap that record with the record that is currently in the first position (assuming that it isn't already in that position.) You now know that the first position in the drawer is correctly sorted. Repeat this procedure for the second position in the drawer and so on until all records have been iterated through.
23
11/26/2015 CSI 201 -- Chapter 10, Part I 23 ex6 – selection sort void sort(int id[], int size) { int next_smallest; for(int i = 0; i < size; i++) { // Find the index of the smallest id between // index values i and size. next_smallest = index_of_smallest(id,i,size); // Swap this value with correct location this // value belongs in swap(id[i], id[next_smallest]); }
24
11/26/2015 CSI 201 -- Chapter 10, Part I 24 ex6.cpp continued… int index_of_smallest(const int id[], int start_index, int size) { // We'll start by assuming that the first position has the smallest int minimum_id = id[start_index], index_of_min = start_index; // Now start comparing each position up to the last position in the array. for(int i = start_index + 1; i < size; i++) { // Did we find a new minimum? Then remember it! if (id[i] < minimum_id) { minimum_id = id[i]; index_of_min = i; } // Return the index of the smallest id return index_of_min; } void swap(int &a, int &b) { int temp; temp = a; a = b; b = temp; return; }
25
11/26/2015 CSI 201 -- Chapter 10, Part I 25 Questions Given an array of 7 integers with the following values: 10, 3, 8, 21, 5, 11, 1 Using selection sort, show the state of the array after all 7 iterations of the outer loop of the algorithm:
26
11/26/2015 CSI 201 -- Chapter 10, Part I 26 Bubble sort This algorithm iterates through the list, and compares adjacent elements as it iterates through. If they are out of order, the items are swapped. During each outer iteration of the loop, the smallest value is "bubbled-up" to the index position of the outer loop. Algorithm: Start at the end of the drawer. Look at the last two records in the drawer. If they are out of order, then swap them. Now, do the same thing with the previous two records, and continue repeating this process until you work your way all the way to the first position. You now know that the first position in the drawer is correctly sorted. Repeat this procedure until all records are sorted.
27
11/26/2015 CSI 201 -- Chapter 10, Part I 27 ex7.cpp – Bubble sort /////////////////////////////////////////////////////////////// // void sort // // Perform a bubble sort on the array of ids to sort them in // order of increasing id. // void sort(int id[], int size) { // i represents the "bubble" position for(int i = 0; i < size - 1; i++) { for(int j = size - 1; j > i; j--) { // If the j-th value is less than the one behind it, swap if (id[j] < id[j-1]) swap(id[j],id[j-1]); }
28
11/26/2015 CSI 201 -- Chapter 10, Part I 28 Questions Given an array of 7 integers with the following values: 10, 3, 8, 21, 5, 11, 1 Using bubble sort, show the state of the array after all 7 iterations of the outer loop of the algorithm:
29
11/26/2015 CSI 201 -- Chapter 10, Part I 29 Binary search Binary search is a much more efficient search algorithm than sequential search. It requires that the array of elements be sorted in order to work properly. We keep "halving" our list until we find the element we are looking for. Algorithm: Starting with a sorted drawer, we look at the middle record in the drawer. If we found a match, we're done! Otherwise, if this record is less than our target id we are looking for, then the target must be in the upper half of our range. Otherwise, if it's greater, then the target is in the lower half. Keep halving the range of records until we run out of records to search for, or we found the target.
30
11/26/2015 CSI 201 -- Chapter 10, Part I 30 ex8 – binary search int search(const int id[], int size, int target_id) { // Initialze our range to seach to contain the entire array int first = 0, last = size-1, index; bool bFound = false; while (!bFound && first <= last) { // Look in the middle index = (last+first)/2; if (id[index] == target_id) bFound = true; else { if (id[index] < target_id) first = index + 1; else last = index - 1; } if (bFound) return index; else return -1; }
31
11/26/2015 CSI 201 -- Chapter 10, Part I 31 Questions Given a sorted array of 10 integers with the following values: 1, 2, 4, 5, 7, 8, 10, 11, 20, 21 Using binary search, how many iterations does it take to find the number 4? How about 20?
32
11/26/2015 CSI 201 -- Chapter 10, Part I 32 Analyzing running times In computer science, we are often interested in analyzing running times to give us a means of determining if one algorithm will perform better than another. The most common terminology you will see in future courses of CSI is the "big-Oh" notation, often denoted, O(g(n)). g(n) is some function of n, where n is the size of the input to the algorithm. It allows us to place an asymptotic upper bound on the running time of an algorithm with an input size of n. It gives us a way of placing an upper bound on the number of iterations of a particular searching or sorting algorithm will execute to completion.
33
11/26/2015 CSI 201 -- Chapter 10, Part I 33 Running times of searching Sequential search has a running time of O(n). Why? It's a straight brute-force linear search. On an input of an array with n elements to search through, it could take a maximum of n iterations of sequential search to find our target element. Thus, we say that sequential search has a running time of O(n). Binary search has a running time of O(log 2 n) We continually reduce the total possible number of iterations in half after each completed iteration! Much more efficient than sequential search, but at a cost of requiring the array to be sorted first. The cost of sorting is worth it if searching is going to be repeatedly performed.
34
11/26/2015 CSI 201 -- Chapter 10, Part I 34 Running times of sorting Both algorithms have a running time of O(n 2 ). There is an outer loop that runs in O(n), however, that outer loop runs an inner loop that also runs in O(n) time. Therefore, the total running time of these sorting algorithms are O(n 2 ).
35
11/26/2015 CSI 201 -- Chapter 06 35 Structures A structure (or struct ) is a simplified class, and makes a good introduction to exploring classes. Structs allow us to define new data types that are am amalgam of other data types. A good analogy of a struct is a record of a database. A student record may include fields such as: Name Student ID GPA Status (1=freshman, …, 4 = senior, 5 graduate) Structs are sometimes referred to as records in some texts.
36
11/26/2015 CSI 201 -- Chapter 06 36 Struct definition syntax struct Identifier { variable_declaration_1; variable_declaration_2; … variable_declaration_n; }; Identifier names the structure type. We call this the structure tag. It is an industry standard to have the first letter of a class or struct name be a CAPITAL letter (This is not a C++ syntax requirement.) Each one of the variable declarations between the braces are referred to as the members of the struct, also called member names or member fields. The structure definition ends with a semi-colon. The structure tag becomes a new data type for your program.
37
11/26/2015 CSI 201 -- Chapter 06 37 The student record as a struct struct Student { char name[30]; int id; double GPA; int status; }; Student is the structure tag above, and therefore names a new type available in our program. Student has 4 members. They are name, id, GPA and status.
38
11/26/2015 CSI 201 -- Chapter 06 38 Declaring a struct variable #include using namespace std; struct Student { char name[30]; // Student name int id; // Student id double GPA; // Current GPA (0.0 - 4.0) int status; // Current status }; int main() { Student st; return 0; } Our struct definition goes outside of any function, in the global declaration space. The struct definition defines a new type called Student. The main program has a variable declaration of type Student called st. The variable declaration for st allocates within it memory to store each of the members of st.
39
11/26/2015 CSI 201 -- Chapter 06 39 Accessing members – the "dot" operator The dot operator is used to access members of a struct variable. cout << "Enter the student id: "; cin >> st.id; cout << "Enter the student's GPA: "; cin >> st.GPA; cout << "Enter current standing (1 = freshman... 5 = graduate): "; cin >> st.status; To the left of the dot operator is a struct variable. To the right of the dot operator is a member name. Struct members are treated just like any other variables, as long as they are accessed through the dot operator. Think about the type of the expressions in bold above. What type are they? Why wouldn't the following work? (Ask yourself, does an istream object know how to extract a variable of type Student ?) cin >> st;
40
11/26/2015 CSI 201 -- Chapter 06 40 Ex1.cpp #include using namespace std; struct Student { int id; // Student id double GPA; // Current GPA (0.0 - 4.0) int status; // Current status (1 = freshman.. 4 = senior, 5 = graduate) }; int main() { Student st; cout << "Enter the student id: "; cin >> st.id; cout << "Enter the student's GPA: "; cin >> st.GPA; cout << "Enter their current standing (1 = freshman... 4 = senior, 5 = graduate): "; cin >> st.status; cout.setf(ios::right); cout << setw(15) << "Student id: " << setw(10) << st.id << endl; cout << setw(15) << "GPA: " << setw(10) << st.GPA << endl; cout << setw(15) << "Status: " << setw(10) << st.status << endl; return 0; }
41
11/26/2015 CSI 201 -- Chapter 06 41 More on structs… Multiple struct definitions can have the same member names: struct Employee { int id; int years; }; struct Student { int id; double GPA; int status; }; Both structs have members called id. This is legal because variable declarations inside of different struct definitions are independent of each other. They are tied to the struct in which they are defined.
42
11/26/2015 CSI 201 -- Chapter 06 42 Struct assignments You can assign one struct variable to another struct variable, as long as both variables are of the same type: Student s1, s2; s1.id = 8675309; s1.GPA = 3.98; s2 = s1; // This is legal! It's illegal to assign struct variables of different types: Student st; Employee emp; st.id = 1234567; emp = st; // This is illegal!
43
11/26/2015 CSI 201 -- Chapter 06 43 Structures as function arguments You can pass structures as parameters into functions the same way you pass simple types as parameters. Example: bool isHonorStudent(Student& s); It is not necessary for a struct parameter to be a call-by-reference parameter. Do what makes sense for your program.
44
11/26/2015 CSI 201 -- Chapter 06 44 ex2.cpp – Structures within structures struct Date { int month; int day; int year; }; struct Student { int id; // Student id Date bday; // Student birthday double GPA; // Current GPA (0.0 - 4.0) int status; // Current status }; You can also define a hierarchy of structures.
45
11/26/2015 CSI 201 -- Chapter 06 45 ex2.cpp continued… void print_student(Student &s, ostream &out); int main() { Student st; cout << "Enter the student id: "; cin >> st.id; cout << "Enter student's birthday as month day year: "; cin >> st.bday.month >> st.bday.day >> st.bday.year; cout << "Enter the student's GPA: "; cin >> st.GPA; cout << "Enter their current standing (1 = freshman... 4 = senior, 5 = grad uate): "; cin >> st.status; print_student(st,cout); return 0; } What type is st ? What type is st.bday ? What type is st.bday.month ?
46
11/26/2015 CSI 201 -- Chapter 06 46 ex2.cpp continued… void print_student(Student &s, ostream &out) { out.setf(ios::right); out << setw(15) << "Student id: " << setw(10) << s.id << endl; out << setw(15) << "Birthday: " << setw(2) << s.bday.month << "/" << setw(2) << s.bday.day << "/" << setw(4) << s.bday.year << endl; out << setw(15) << "GPA: " << setw(10) << s.GPA << endl; out << setw(15) << "Status: " << setw(10); if (s.status == 1) out << "Freshman"; else if (s.status == 2) out << "Sophomore"; else if (s.status == 3) out << "Junior"; else if (s.status == 4) out << "Senior"; else if (s.status == 5) out << "Graduate"; else out << "UNKNOWN"; out << endl; }
47
11/26/2015 CSI 201 -- Chapter 06 47 Initializing structures You can initialize structures at the time they are declared. Simple structures: struct Date { int month; int day; int year; }; Date d = { 12, 25, 2004 }; Hierarchical structures: struct Student { char name[30];// Student name int id; // Student id Date bday; // Student birthday double GPA; // Current GPA (0.0 - 4.0) int status; // Current status }; Student s = { "Fred Jones", 123043243, { 12, 25, 2004 }, 3.23, 3 };
Similar presentations
© 2025 SlidePlayer.com. Inc.
All rights reserved.