# Chapter 6: Arrays: Lists and Tables

## Presentation on theme: "Chapter 6: Arrays: Lists and Tables"— Presentation transcript:

Chapter 6: Arrays: Lists and Tables
Prelude to Programming Concepts & Design Fourth Edition by Stewart Venit and Elizabeth Drake

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 Arrays Declare ArrayName[number-of-elements] as data type Example: Declare ShoppingItems[4] as String

Declaring Arrays When 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[5] Of String declares an array with 5 elements, all of which are strings Note: the first element of an array has subscript 0 Address: Items[0] Items[1] items[2] items[3] items[4] Content: “Milk” “Bread” “Eggs” “Butter” “Apples”

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., items[3] The 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[3] returns the 4th element of an array.

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[25] as float For (K = 0; K < 25; K++) Write “Enter score: “ Input Scores[K] End For Note 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.

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[52] As Float Declare K As Integer For (K = 0; K <= 51; K++) Write “Enter sales for week #” + (K + 1) Input WeeklySales[K] End For Note that the sales for Week 1 correspond to the element WeeklySales[0] and the sales for Week 52 correspond to the element WeeklySales[51].

Parallel Arrays Parallel 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: \$ \$ \$ \$

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[100] As String Declare Sales[100] 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

Question In 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.

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] Then rather than If 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

Practice questions from textbook (Self check problems for section 6.1)
What does the following program do? Declare letter[5] As Character Declare j As Integer for (j=0; j<=4; j++) input letter[j] end for for (j=0; j<=4; j+2) write letter[j] Write a program segment that inputs 10 characters and displays them in a reverse order?

6.2 Searching and Sorting Arrays
we often need to search an array for an item we often need to sort an array there are many algorithms for searching and sorting serial search and bubble sort are presented first

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.

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.

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 0 Set Found = 0 While (Found == 0) AND (Index < N) If KeyData[Index] == Key Then Set Found = 1 End If Set Index = Index + 1 End While If Found == 1 Then //Display the array element with subscript of Index–1 Write KeyData[Index-1] Else Write “The item you are searching for was not found.”

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 IDKey Set Index = 0 Set Found = 0 While (Found == 0) AND (Index < N) If DINumbers[index] == IDKey Then Set Found = 1 End If Set Index = Index + 1 End While If Found == 0 Then Write “student ID not found” Else Write “id number: ” + IDKey Write “student name: ” + names[index -1] write “test score: “ + scores[index -1]

Binary Search The binary search method is a good way to search a large amount of data for a particular item, which is called the search key more efficient than the serial search technique requires that the table keys, the array of data to be searched, is in numerical or alphabetical order

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 half can determine in which quarter of the array the search key is located. Then look at the middle entry in this quarter And so forth, continuing this process until search key is found

Binary Search Example Suppose we are looking for “cat” in the following array: Check outYoutube example

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.

Bubble Sort Example Let 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

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

Figure 6.5 Flowchart for the bubble sort

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

Selection Sort On 1st pass, locate the smallest array element and swap it with the first array element On 2nd pass, locate the second smallest element and swap it with the second element of the array On 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.

Selection Sort Example
first pass second pass third pass fourth pass Also check out Youtube Example

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

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[15], LastName[20] As Character defines the variables FirstName and LastName to be strings of at most, 15 and 20 characters, respectively.

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[10] As Character Set Str = “Hello!” Write Length(Str) The output will be 6 because the string “Hello!” is made up of 6 characters.

Practice Write 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.

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 her the value we look for would depend on which salesperson and which month is of interest In these cases, we use two-dimensional arrays. Here is how to declare a two-dimensional array: Declare Profit[12, 24] As Integer

A Two-Dimensional Array Example
A two-dimensional array is like a matrix or an electronic preadsheet Declaring a two dimensional array: Declare studentGrades[30,5] Of Integer Accessing the elements of a two dimensional array studentGrades[0,3] is the grade of the first student in the 4th test