Arrays Chapter 8 Spring 2017, CSUS Array Basics Chapter 8.1 1
Array Basics Normally, variables only have one piece of data associated with them An array allows you to store a group of items of the same data type together in memory 1/21/2017 Sacramento State - CSc 10A 3 Array Basics Why? Instead of creating multiple similar variables such as employee1, employee2, employee3 and so on It s more efficient to create just one variable with a shared, but multiple values 1/21/2017 Sacramento State - CSc 10A 4 2
Metaphor for Arrays Think of an array as a set of mailboxes Each mailbox belongs to the same variable Each mailbox has a unique number 1/21/2017 Sacramento State - CSc 10A 5 Metaphor for Arrays... or think of arrays as a group of boxes Each box belongs to the same variable Each box has a unique number 1/21/2017 Sacramento State - CSc 10A 6 3
Array Terminology Each value located in an array is called an element Each can be accessed using an unique number called an index (also called a subscript) 1/21/2017 Sacramento State - CSc 10A 7 What Value Do We Start With? So, what are the valid values for the index? Most languages use 0-indexing other languages use 1-indexing the success of C set the standard nowadays, most major languages use 0-indexing (e.g. Visual Basic) 1/21/2017 Sacramento State - CSc 10A 8 4
Zero Indexing This means the first element in any array has the index 0 So, even though this will be odd and strange, it is something you must learn to live with 1/21/2017 Sacramento State - CSc 10A 9 Creating Arrays Chapter 8.1 5
Creating Arrays Arrays are created pretty much the same as any other variable However, since the array can contain multiple values, you must specify its size 1/21/2017 Sacramento State - CSc 10A 11 Book Pseudocode: Array Declare total number of elements Declare type name [ size ] Real, Integer, or String 1/21/2017 Sacramento State - CSc 10A 12 6
Examples Declare String employees[50] Declare Real salesamounts[7] 1/21/2017 Sacramento State - CSc 10A 13 Accessing Elements 1/21/2017 Sacramento State - CSc 10A 14 7
Array Declarations age Declare Real age[3] 0 1 2 1/21/2017 Sacramento State - CSc 10A 15 Accessing Each Cell After an array is created you can read/write any element You can also access the entire array using the variable name 1/21/2017 Sacramento State - CSc 10A 16 8
Accessing Each Cell The notation is incredibly simple Simply follow the array name by square brackets and the index of the element you want 1/21/2017 Sacramento State - CSc 10A 17 How You Access an Element Variable Name name [index] 0, 1, 2, 1/21/2017 Sacramento State - CSc 10A 18 9
Example Variables sacstate totalcost Normal variables test[4] name[2] Array elements 1/21/2017 Sacramento State - CSc 10A 19 Array Elements 1/21/2017 Sacramento State - CSc 10A 8-20 10
Array Example What Happens? Declare Integer test[2] Set test[0] = 1947 Set test[1] = 42 Display test[0] Display test[1] 1/21/2017 Sacramento State - CSc 10A 21 Array Example What Happens? Declare Integer test[2] test Set test[0] = 1947 Set test[1] = 42 0 1 1/21/2017 Sacramento State - CSc 10A 22 11
Array Example What Happens? Declare Integer test[2] Set test[0] = 1947 Set test[1] = 42 0 1 test 1947 1/21/2017 Sacramento State - CSc 10A 23 Array Example What Happens? Declare Integer test[2] Set test[0] = 1947 Set test[1] = 42 0 1 test 1947 42 1/21/2017 Sacramento State - CSc 10A 24 12
Array Example Declare Integer test[2] Set test[0] = 1947 Set test[1] = 42 Display test[0] Display test[1] 1/21/2017 Sacramento State - CSc 10A 25 Array Example Output 1947 42 1/21/2017 Sacramento State - CSc 10A 26 13
Array Initialization Just like regular variables, arrays can be initialized to 0 or specific values Not all languages support this however, the big ones such as C#, Java, and Visual Basic do even though the notation varies a bit 1/21/2017 Sacramento State - CSc 10A 8-27 Example Declare String days[7] = "Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday" 1/21/2017 Sacramento State - CSc 10A 28 14
Bounds Checking Sometimes the program will use an invalid index Naturally, this is attempting to access data that does not exist Array bounds checking prevents the use of an invalid subscript 1/21/2017 Sacramento State - CSc 10A 8-29 Example Declare String days[7] days[7] = "Saturday" Invalid because there is no 7 index 1/21/2017 Sacramento State - CSc 10A 30 15
Bounds Checking A common error is running a loop one time more than is necessary, exceeding the bound of the array This is an off-by-one error and is happens quite often (especially so because we use 0-indexing) 1/21/2017 Sacramento State - CSc 10A 8-31 Loops and Arrays Chapter 8.1 16
For Loops and Arrays For Loops are extremely well suited for iterating through all the values of an array In fact, one of the reasons For Loops exists is to interact with arrays 1/21/2017 Sacramento State - CSc 10A 33 Loops and Arrays Using For Loops, it is easy to access all the elements of an array linearly The loop variable is used as the index in the array 1/21/2017 Sacramento State - CSc 10A 34 17
Declare String name[4] Declare Integer n name[0] = "Tappa Kegga Bru" name[1] = "Cuppa Kappa Chino" name[2] = "Hu Delta Phart" name[3] = "Eta Lotta Pi" For n = 0 TO 3 Display name[n] End For 1/21/2017 Sacramento State - CSc 10A 35 Greek Example Output Tappa Kegga Bru Cuppa Kappa Chino Hu Delta Phart Eta Lotta Pi 1/21/2017 Sacramento State - CSc 10A 36 18
Loop Example Declare Integer n Declare String days[7] = "Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday" For n = 0 to 6 Display days[n] End For 1/21/2017 Sacramento State - CSc 10A 37 Loop Example Output Sunday Monday Tuesday Wednesday Thursday Friday Saturday 1/21/2017 Sacramento State - CSc 10A 38 19
Loop Example 2 Declare Integer n Declare String days[7] = "Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday" For n = 0 to 6 Display n, days[n] End For 1/21/2017 Sacramento State - CSc 10A 39 Loop Example 2 Output 0 Sunday 1 Monday 2 Tuesday 3 Wednesday 4 Thursday 5 Friday 6 Saturday 1/21/2017 Sacramento State - CSc 10A 40 20
Declare Real score[3] Set score[0] = 85 Set score[1] = 98 Set score[2] = 61 For n = 0 to 2 If score[n] >= 70 Then Display score[n], " passes" Else Display score[n], " fails" End If End For 1/21/2017 Sacramento State - CSc 10A 41 Array Example 2 Output 85 passes 98 passes 61 fails 1/21/2017 Sacramento State - CSc 10A 42 21
The For Each Loop Some languages provide a For Each loop It works with an array, iterating once for each array element During each iteration, the loop copies an element's value to a variable. 1/21/2017 Sacramento State - CSc 10A 8-43 For Each Example Constant Integer SIZE = 4 Declare Integer numbers[size] = 5, 10, 15, 20 Declare Integer num For Each num In numbers Display num End For 1/21/2017 Sacramento State - CSc 10A 44 22
Partially Filled Array Chapter 8.1 Partially Filled Array Sometimes an array is only partially filled To avoid processing the unfilled elements, you must use an integer variable that holds the number of items stored in the array 1/21/2017 Sacramento State - CSc 10A 46 23
Partially Filled Array When the array is empty, 0 is stored in this variable The variable is incremented each time an item is added to the array The variable's value is used as the array's size when stepping through the array. 1/21/2017 Sacramento State - CSc 10A 8-47 Declare Real score[100] Declare Integer Count 100 Capacity Display "How many tests?" Input Count Not using all of it For n = 0 to Count - 1 End For Input score[n] 1/21/2017 Sacramento State - CSc 10A 48 24
Array Example 2 Output How many tests? 3 65 89 77 1/21/2017 Sacramento State - CSc 10A 49 Sequentially Searching an Array Chapter 8.2 25
Sequentially Searching an Array A sequential search algorithm is a simple technique for finding an item in a string or numeric array One of the most common and ways of locating data 1/21/2017 Sacramento State - CSc 10A 8-51 How it Works Uses a loop to sequentially step through an array Compares each element with the value being searched for Stops when the value is found or the end of the array is hit 1/21/2017 Sacramento State - CSc 10A 52 26
Example Set found = False Set index = 0 While not found AND index <= SIZE - 1 If array[index] == searchvalue Then Set found = True Else End if found Set index = index + 1 End If End While If not, look at next item (next index) 1/21/2017 Sacramento State - CSc 10A 53 Processing the Contents of an Array Chapter 8.3 27
Processing the Contents of an Array It is common to use an array to store multiple values to be analyzed The information is first stored, and then analyzed later by a different loop 1/21/2017 Sacramento State - CSc 10A 8-55 Calculating the Average Loops are used to accumulate the values create a total Then, the total is simply divided by the size 1/21/2017 Sacramento State - CSc 10A 8-56 28
Calculate the Average Set total = 0 For n = 0 to SIZE 1 total = total + score[n] End For Set average = total / SIZE 1/21/2017 Sacramento State - CSc 10A 57 Highest and Lowest Value Finding the highest & lowest values in an array is common It basically works by scanning the array and setting a high (or low value) based on the current value 1/21/2017 Sacramento State - CSc 10A 8-58 29
Steps Involved Highest Value Create a variable to hold the highest value Assign the value at element 0 to the highest Use a loop to step through the rest of the elements Each iteration, a comparison is made to the highest variable If the element is greater than the highest value, that value is then the assigned to the highest variable 1/21/2017 Sacramento State - CSc 10A 8-59 Highest Value Set highest = scores[0] For n = 1 to count 1 If score[n] > highest Set highest = score[n] End if End For 1/21/2017 Sacramento State - CSc 10A 60 30
Lowest Value Set lowest = scores[0] For n = 1 to count 1 if score[n] < lowest Set lowest = score[n] end if End For 1/21/2017 Sacramento State - CSc 10A 61 Example 2 The following is a full program that uses many of the techniques we covered arrays counter for partially filled arrays sentinel loops and more So, if you understand this program, then you understand the material 1/21/2017 Sacramento State - CSc 10A 62 31
Constant Integer SIZE = 100 Declare Integer values[size] Declare Integer count = 0 Declare Integer number Declare Integer Index Display "Enter a number, or -1 to quit." Input number While (number!= -1 AND count < SIZE) Set values[count] = number Set count = count + 1 Display "Enter a number, or -1 to quit." Input number End While Display "Here are the values you entered:" For index = 0 To count - 1 Display values[index] End For 1/21/2017 Sacramento State - CSc 10A 8-63 Parallel Arrays Chapter 8.4 32
Parallel Arrays Often more than one piece of information needs to be saved for the same "object" One common approach is to use multiple arrays one for each type of data 1/21/2017 Sacramento State - CSc 10A 65 Parallel Arrays These are called parallel arrays They are separate arrays but we used the same index for each By using the same index, we can establish a relationship between them 1/21/2017 Sacramento State - CSc 10A 66 33
Parallel Arrays 1/21/2017 Sacramento State - CSc 10A 8-67 Example: Part 1 Input Constant SIZE = 10 Declare String name[size] Declare Real cash[size] For n = 0 to SIZE 1 Input name[n] Input cash[n] End For 1/21/2017 Sacramento State - CSc 10A 68 34
Example: Part 2 Search Set best = 0 For n = 1 to SIZE 1 If cash[n] > cash[best] Set best = n End If End For 1/21/2017 Sacramento State - CSc 10A 69 Example: Part 3 Results Display name[highest], Display "got the most donations of $", cash[best] 1/21/2017 Sacramento State - CSc 10A 70 35
Example Output Tappa Kegga Bru 32.23 Lambda Lambda Lambda 432.11 Eta Lotta Pi 54.25 Lambda Lambda Lambda got the most donations of $432.11 1/21/2017 Sacramento State - CSc 10A 71 Two Dimension Arrays Chapter 8.5 36
Two Dimension Arrays A two-dimensional array is like several identical arrays put together Suppose a teacher has six students who take five tests 1/21/2017 Sacramento State - CSc 10A 73 Two-Dimensional Arrays 1/21/2017 Sacramento State - CSc 10A 8-74 37
Multiple Sizes Needed Two size variables are required when declaring two dimensional arrays Accessing is done with two loops, and both indexes 1/21/2017 Sacramento State - CSc 10A 75 Declaring Arrays Constant Integer ROWS = 3 Constant Integer COLS = 4 Declare Integer values[rows][cols] 1/21/2017 Sacramento State - CSc 10A 76 38
Using Loops For row = 0 To ROWS -1 For col = 0 To COLS 1 Display "Enter a number." Input values[row][col] End For End For 1/21/2017 Sacramento State - CSc 10A 77 Arrays of Three or More Dimensions Chapter 8.6 39
Arrays of Three or More Dimensions Arrays can also be three or more dimensions In fact, there are no limitations once the number of dimensions 1/21/2017 Sacramento State - CSc 10A 79 Arrays of Three or More Dimensions Declare Real seats[3][5][8] 1/21/2017 Sacramento State - CSc 10A 8-80 40
Arrays of Three or More Dimensions 1/21/2017 Sacramento State - CSc 10A 81 41