Presentation on theme: "Chapter 6: Arrays: Lists and Tables"— Presentation transcript:
1 Chapter 6: Arrays: Lists and Tables Prelude to Programming Concepts & DesignFourth EditionbyStewart Venit and Elizabeth Drake
2 6.1 One-Dimensional Arrays A one-dimensional array is a list of related data of the same data type, referenced by the same name.Declaring one dimentional ArraysDeclare ArrayName[number-of-elements] as data typeExample:Declare ShoppingItems as String
3 Declaring ArraysWhen an array is declared, the computer sets aside memory to store the values of the elements of the array.Declaring an array means telling the computer what is the data type of the array and how many elements will be stored in it.Pseudocode to declare arrays:Declare items Of Stringdeclares an array with 5 elements, all of which are stringsNote: the first element of an array has subscript 0Address:ItemsItemsitemsitemsitemsContent:“Milk”“Bread”“Eggs”“Butter”“Apples”
4 Accessing individual elements of an Array Each element in the array is referenced by the array name and the element’s position in the array.e.g., itemsThe position of an element in an array is called a subscript or an index.Array indexes start from 0. That is the first element of an array is referred to with index 0.items returns the 4th element of an array.
5 Entering Elements in an Array If we wanted to input the final exam scores of a class of 25 students using an array named Scores which has 25 elements, we could use a loop as follows:Declare scores as floatFor (K = 0; K < 25; K++)Write “Enter score: “Input Scores[K]End ForNote that, since the count (K) begins at 0, the test condition goes up to 24 (the loop ends when K = 25) to enter 25 elements.
6 Here is how to load an array with 52 values Here is how to load an array with 52 values. The values represent a salesperson’s sales for each week of the year.Declare WeeklySales As FloatDeclare K As IntegerFor (K = 0; K <= 51; K++)Write “Enter sales for week #” + (K + 1)Input WeeklySales[K]End ForNote that the sales for Week 1 correspond to the element WeeklySales and the sales for Week 52 correspond to the element WeeklySales.
7 Parallel ArraysParallel arrays are arrays of the same size in which elements of the same subscript are related.It is necessary that the data in each array be loaded in the correct order.If we have arrays salesPerson and sales (as below), each element of salesPerson is related to an element in sales by the position in the array.salePerson: “Joey” “Ellie” “Sarah” “Kim”Sales: $ $ $ $
8 Parallel Arrays Example This program segment inputs the names of salespersons and their total sales for the month into two parallel arrays (Names and sales) and dtermines which sales person has the max sales Declare Names As String Declare Sales As float Declare max,k, index As Integer Set max=0 Set k=0 Write “Enter a salesperson’s name and monthly sale” Write “enter *,0 when done” Input names[k], sales[k] While (name[k] != “*”) if sales[k] > max set max= sales[k] set index=k end if Set k=k+1 Write “Enter name and sales (enter *,0 when done)” End while Write “The salesperson: “ + name[index]+ “got the max sales: “ + max
9 QuestionIn the last example why the names and sales arrays have been declared to have 100 elements?In some programming languages you may have to specify the size of the array even if you do not know the exact number of its elements. In this case, it is better to declare an array for a larger number of elements than you plan to use.
10 Why Use Arrays?Arrays reduce the number of variable names in the program.Sales[K] versus Sales1, Sales2, SalesN, ….Arrays increase the flexibility of the program.Arrays reduce the number of If-Then statements needed in selection processing.If Sales[K] Thenrather thanIf Sales1 Then …If Sales2 Then …If Sales3 Then …Arrays improve efficiency by allowing data to be read into the program once but processed as many times as necessary
11 Practice questions from textbook (Self check problems for section 6.1) What does the following program do?Declare letter As CharacterDeclare j As Integerfor (j=0; j<=4; j++)input letter[j]end forfor (j=0; j<=4; j+2)write letter[j]Write a program segment that inputs 10 characters and displays them in a reverse order?
12 6.2 Searching and Sorting Arrays we often need to search an array for an itemwe often need to sort an arraythere are many algorithms for searching and sortingserial search and bubble sort are presented first
13 The Serial Search Steps: Load, or populate, the arrays. Search the array that contains the key to find a match.Display the key and corresponding values in the non-key arrays with the same subscript as the one with the key value, if a match is found.Display an ‘unsuccessful search’ message if no matches are found.
14 The Serial Search (continued) Use a flag, or switch, to decide which message to print.A flag is a variable that is set to zero or one, depending on the results of an operation.The value of the flag can be checked later in the program with an If statement to determine which action to take.
15 The Serial Search (continued) Pseudocode for the serial search of an array named KeyData containing N elements:Set Index = 0//Set a flag (Found) equal to 0Set Found = 0While (Found == 0) AND (Index < N)If KeyData[Index] == Key ThenSet Found = 1End IfSet Index = Index + 1End WhileIf Found == 1 Then//Display the array element with subscript of Index–1Write KeyData[Index-1]ElseWrite “The item you are searching for was not found.”
16 A serial search Example This program segment displays the test score of a particular student when the student’s id is input by the user.“Enter the id of the student whose score you want to find”Input IDKeySet Index = 0Set Found = 0While (Found == 0) AND (Index < N)If DINumbers[index] == IDKey ThenSet Found = 1End IfSet Index = Index + 1End WhileIf Found == 0 ThenWrite “student ID not found”ElseWrite “id number: ” + IDKeyWrite “student name: ” + names[index -1]write “test score: “ + scores[index -1]
17 Binary SearchThe binary search method is a good way to search a large amount of data for a particular item, which is called the search keymore efficient than the serial search techniquerequires that the table keys, the array of data to be searched, is in numerical or alphabetical order
18 Binary Search(continued) First compare the search key (the target) to the table key midway through the given array.Because the array data is ordered, it is possible to see in which half of the array the search key lies.Then compare the search key to the table key in the middle of this halfcan determine in which quarter of the array the search key is located.Then look at the middle entry in this quarterAnd so forth, continuing this process until search key is found
19 Binary Search ExampleSuppose we are looking for “cat” in the following array:Check outYoutube example
20 The Bubble Sort Technique To sort data means to arrange it in a particular numerical or alphabetical order, ascending or descending.To sort small amounts of data, use the bubble sort technique.Make several passes through the data.Compare adjacent pairs of data.If the pairs are not in order, swap them.Continue until all data is processed.
21 Bubble Sort ExampleLet us take the array of numbers " ", and sort the array from lowest number to greatest number using bubble sort algorithm. In each step, elements written in bold are being compared.First Pass: ( ) ( ), Here, algorithm compares the first two elements, and swaps them. ( ) ( ), Swap since 5 > 4 ( ) ( ), Swap since 5 > 2 ( ) ( ), Now, since these elements are already in order (8 > 5), algorithm does not swap them.Second Pass: ( ) ( ) ( ) ( ), Swap since 4 > 2 ( ) ( ) ( ) ( )Now, the array is already sorted.Also check out Youtube Example
22 Bubble Sort General Algorithm While the Array A is not sorted For (k=0; k<N; k++) if (A[k] > A[k+1]) interchange A[k] and A[k+1] End if End for End While
24 6.3 More About Searching and Sorting The selection sort procedure is a more efficient way to sort data stored in an array than the bubble sort technique
25 Selection SortOn 1st pass, locate the smallest array element and swap it with the first array elementOn 2nd pass, locate the second smallest element and swap it with the second element of the arrayOn the 3rd pass, locate the next smallest element and swap it with the third element of the array and so forth....If the array contains N elements, it will be completely sorted after at most N–1 passes.
26 Selection Sort Example first passsecond passthird passfourth passAlso check out Youtube Example
27 Selection Sort General Algorithm For (k=0; k<N; k++) set index = The index of the smallest element of the array if (A[index] != A[k]) interchange A[k] and A[index] End if End for
28 6.4 Strings as Arrays of Characters Some programming languages do not contain a string data type.Strings are implemented as arrays whose elements are characters.In programming languages that contain this data type, strings can be formed as arrays of characters.To define a string as an array of characters, indicate the data type in the Declare statement.The following statement:Declare FirstName, LastName As Characterdefines the variables FirstName and LastName to be strings of at most, 15 and 20 characters, respectively.
29 String Length and the Length Function The length of a string is the number of characters it contains.The Length function returns the number of characters in a given string.For example:Declare Str As CharacterSet Str = “Hello!”Write Length(Str)The output will be 6 because the string “Hello!” is made up of 6 characters.
30 PracticeWrite a program that inputs user’name and displays its first and the last character. Write a program that inputs a string from the user and reverse it.
31 6.5 Two-Dimensional Arrays In a two-dimensional array, the value of an element depends on two factors instead of just one.Sometimes it’s convenient to use arrays whose elements are determined by two factors.Example: the records of the monthly sales for salespeople for a year.Each salesperson has 12 numbers (one for each month’s sales) associated with him or herthe value we look for would depend on which salesperson and which month is of interestIn these cases, we use two-dimensional arrays.Here is how to declare a two-dimensional array:Declare Profit[12, 24] As Integer
32 A Two-Dimensional Array Example A two-dimensional array is like a matrix or an electronic preadsheetDeclaring a two dimensional array:Declare studentGrades[30,5] Of IntegerAccessing the elements of a two dimensional arraystudentGrades[0,3] is the grade of the first student in the 4th test
33 Nested Loops Help Load Arrays To input data into a two-dimensional array, use a nested loop.