© 2009 pearson addison-wesley. all rights reserved. addison wesley is an imprint of prelude to...

34
© 2009 Pearson Addison-Wesley. All rights reserved. Addison Wesley is an imprint of Prelude to Programming Concepts & Design Fourth Edition by Stewart Venit and Elizabeth Drake Chapter 6: Arrays: Lists and Tables

Upload: russell-james

Post on 03-Jan-2016

220 views

Category:

Documents


0 download

TRANSCRIPT

Page 1: © 2009 Pearson Addison-Wesley. All rights reserved. Addison Wesley is an imprint of Prelude to Programming Concepts & Design Fourth Edition by Stewart

© 2009 Pearson Addison-Wesley. All rights reserved.

Addison Wesley is an imprint of

Prelude to Programming Concepts & Design

Fourth Edition

by

Stewart Venit and

Elizabeth Drake

Chapter 6:Arrays: Lists and Tables

Page 2: © 2009 Pearson Addison-Wesley. All rights reserved. Addison Wesley is an imprint of Prelude to Programming Concepts & Design Fourth Edition by Stewart

1-2

© 2009 Pearson Addison-Wesley. All rights reserved. 6-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 type

Example:

Declare ShoppingItems[4] as String

Page 3: © 2009 Pearson Addison-Wesley. All rights reserved. Addison Wesley is an imprint of Prelude to Programming Concepts & Design Fourth Edition by Stewart

1-3

© 2009 Pearson Addison-Wesley. All rights reserved. 6-3

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”

Page 4: © 2009 Pearson Addison-Wesley. All rights reserved. Addison Wesley is an imprint of Prelude to Programming Concepts & Design Fourth Edition by Stewart

1-4

© 2009 Pearson Addison-Wesley. All rights reserved.

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.

6-4

Page 5: © 2009 Pearson Addison-Wesley. All rights reserved. Addison Wesley is an imprint of Prelude to Programming Concepts & Design Fourth Edition by Stewart

1-5

© 2009 Pearson Addison-Wesley. All rights reserved. 6-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[25] 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.

Page 6: © 2009 Pearson Addison-Wesley. All rights reserved. Addison Wesley is an imprint of Prelude to Programming Concepts & Design Fourth Edition by Stewart

1-6

© 2009 Pearson Addison-Wesley. All rights reserved. 6-6

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 FloatDeclare K As IntegerFor (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].

Page 7: © 2009 Pearson Addison-Wesley. All rights reserved. Addison Wesley is an imprint of Prelude to Programming Concepts & Design Fourth Edition by Stewart

1-7

© 2009 Pearson Addison-Wesley. All rights reserved. 6-7

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: 5000$ 3000$ 7000$ 2000$

Page 8: © 2009 Pearson Addison-Wesley. All rights reserved. Addison Wesley is an imprint of Prelude to Programming Concepts & Design Fourth Edition by Stewart

1-8

© 2009 Pearson Addison-Wesley. All rights reserved.

Parallel Arrays ExampleThis 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 StringDeclare Sales[100] As floatDeclare max,k, index As IntegerSet max=0Set k=0Write “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 ifSet k=k+1Write “Enter name and sales (enter *,0 when done)”Input names[k], sales[k]

End whileWrite “The salesperson: “ + name[index]+ “got the max sales: “ + max

6-8

Page 9: © 2009 Pearson Addison-Wesley. All rights reserved. Addison Wesley is an imprint of Prelude to Programming Concepts & Design Fourth Edition by Stewart

1-9

© 2009 Pearson Addison-Wesley. All rights reserved.

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.

6-9

Page 10: © 2009 Pearson Addison-Wesley. All rights reserved. Addison Wesley is an imprint of Prelude to Programming Concepts & Design Fourth Edition by Stewart

1-10

© 2009 Pearson Addison-Wesley. All rights reserved. 6-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] 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

Page 11: © 2009 Pearson Addison-Wesley. All rights reserved. Addison Wesley is an imprint of Prelude to Programming Concepts & Design Fourth Edition by Stewart

1-11

© 2009 Pearson Addison-Wesley. All rights reserved.

Practice questions from textbook (Self check problems for section 6.1)

What does the following program do?Declare letter[5] As CharacterDeclare j As Integer

for (j=0; j<=4; j++)input letter[j]

end for for (j=0; j<=4; j+2)

write letter[j] end for

Write a program segment that inputs 10 characters and displays them in a reverse order?

6-11

Page 12: © 2009 Pearson Addison-Wesley. All rights reserved. Addison Wesley is an imprint of Prelude to Programming Concepts & Design Fourth Edition by Stewart

1-12

© 2009 Pearson Addison-Wesley. All rights reserved. 6-12

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

Page 13: © 2009 Pearson Addison-Wesley. All rights reserved. Addison Wesley is an imprint of Prelude to Programming Concepts & Design Fourth Edition by Stewart

1-13

© 2009 Pearson Addison-Wesley. All rights reserved. 6-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.

Page 14: © 2009 Pearson Addison-Wesley. All rights reserved. Addison Wesley is an imprint of Prelude to Programming Concepts & Design Fourth Edition by Stewart

1-14

© 2009 Pearson Addison-Wesley. All rights reserved. 6-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.

Page 15: © 2009 Pearson Addison-Wesley. All rights reserved. Addison Wesley is an imprint of Prelude to Programming Concepts & Design Fourth Edition by Stewart

1-15

© 2009 Pearson Addison-Wesley. All rights reserved. 6-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 = 1

End IfSet Index = Index + 1

End WhileIf 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.”End If

Page 16: © 2009 Pearson Addison-Wesley. All rights reserved. Addison Wesley is an imprint of Prelude to Programming Concepts & Design Fourth Edition by Stewart

1-16

© 2009 Pearson Addison-Wesley. All rights reserved.

A serial search ExampleThis 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 = 1

End IfSet Index = Index + 1

End WhileIf Found == 0 Then

Write “student ID not found”Else

Write “id number: ” + IDKeyWrite “student name: ” + names[index -1]write “test score: “ + scores[index -1]

6-16

Page 17: © 2009 Pearson Addison-Wesley. All rights reserved. Addison Wesley is an imprint of Prelude to Programming Concepts & Design Fourth Edition by Stewart

1-17

© 2009 Pearson Addison-Wesley. All rights reserved.

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

6-17

Page 18: © 2009 Pearson Addison-Wesley. All rights reserved. Addison Wesley is an imprint of Prelude to Programming Concepts & Design Fourth Edition by Stewart

1-18

© 2009 Pearson Addison-Wesley. All rights reserved. 6-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 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

Page 19: © 2009 Pearson Addison-Wesley. All rights reserved. Addison Wesley is an imprint of Prelude to Programming Concepts & Design Fourth Edition by Stewart

1-19

© 2009 Pearson Addison-Wesley. All rights reserved.

Binary Search Example

6-19

Suppose we are looking for “cat” in the following array:

Check outYoutube example

Page 20: © 2009 Pearson Addison-Wesley. All rights reserved. Addison Wesley is an imprint of Prelude to Programming Concepts & Design Fourth Edition by Stewart

1-20

© 2009 Pearson Addison-Wesley. All rights reserved. 6-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.

Page 21: © 2009 Pearson Addison-Wesley. All rights reserved. Addison Wesley is an imprint of Prelude to Programming Concepts & Design Fourth Edition by Stewart

1-21

© 2009 Pearson Addison-Wesley. All rights reserved.

Bubble Sort Example

6-21

Let us take the array of numbers "5 1 4 2 8", 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:

( 5 1 4 2 8 ) ( 1 5 4 2 8 ), Here, algorithm compares the first two elements, and swaps them.

( 1 5 4 2 8 ) ( 1 4 5 2 8 ), Swap since 5 > 4

( 1 4 5 2 8 ) ( 1 4 2 5 8 ), Swap since 5 > 2

( 1 4 2 5 8 ) ( 1 4 2 5 8 ), Now, since these elements are already in order (8 > 5), algorithm does not swap

them.

Second Pass:

( 1 4 2 5 8 ) ( 1 4 2 5 8 )

( 1 4 2 5 8 ) ( 1 2 4 5 8 ), Swap since 4 > 2

( 1 2 4 5 8 ) ( 1 2 4 5 8 )

( 1 2 4 5 8 ) ( 1 2 4 5 8 )

Now, the array is already sorted.

Also check out Youtube Example

Page 22: © 2009 Pearson Addison-Wesley. All rights reserved. Addison Wesley is an imprint of Prelude to Programming Concepts & Design Fourth Edition by Stewart

1-22

© 2009 Pearson Addison-Wesley. All rights reserved.

Bubble Sort General Algorithm

While the Array A is not sortedFor (k=0; k<N; k++) if (A[k] > A[k+1])

interchange A[k] and A[k+1]

End if

End forEnd While

6-22

Page 23: © 2009 Pearson Addison-Wesley. All rights reserved. Addison Wesley is an imprint of Prelude to Programming Concepts & Design Fourth Edition by Stewart

1-23

© 2009 Pearson Addison-Wesley. All rights reserved. 6-23

Figure 6.5 Flowchart for the bubble sort

Page 24: © 2009 Pearson Addison-Wesley. All rights reserved. Addison Wesley is an imprint of Prelude to Programming Concepts & Design Fourth Edition by Stewart

1-24

© 2009 Pearson Addison-Wesley. All rights reserved. 6-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

Page 25: © 2009 Pearson Addison-Wesley. All rights reserved. Addison Wesley is an imprint of Prelude to Programming Concepts & Design Fourth Edition by Stewart

1-25

© 2009 Pearson Addison-Wesley. All rights reserved. 6-25

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.

Page 26: © 2009 Pearson Addison-Wesley. All rights reserved. Addison Wesley is an imprint of Prelude to Programming Concepts & Design Fourth Edition by Stewart

1-26

© 2009 Pearson Addison-Wesley. All rights reserved.

Selection Sort Example

6-26

first pass

second pass

third pass

fourth pass

Also check out Youtube Example

Page 27: © 2009 Pearson Addison-Wesley. All rights reserved. Addison Wesley is an imprint of Prelude to Programming Concepts & Design Fourth Edition by Stewart

1-27

© 2009 Pearson Addison-Wesley. All rights reserved.

Selection Sort General Algorithm

6-27

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

Page 28: © 2009 Pearson Addison-Wesley. All rights reserved. Addison Wesley is an imprint of Prelude to Programming Concepts & Design Fourth Edition by Stewart

1-28

© 2009 Pearson Addison-Wesley. All rights reserved. 6-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[15], LastName[20] As Character

defines the variables FirstName and LastName to be strings of at most, 15 and 20 characters, respectively.

Page 29: © 2009 Pearson Addison-Wesley. All rights reserved. Addison Wesley is an imprint of Prelude to Programming Concepts & Design Fourth Edition by Stewart

1-29

© 2009 Pearson Addison-Wesley. All rights reserved. 6-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[10] As CharacterSet Str = “Hello!”

Write Length(Str)

• The output will be 6 because the string “Hello!” is made up of 6 characters.

Page 30: © 2009 Pearson Addison-Wesley. All rights reserved. Addison Wesley is an imprint of Prelude to Programming Concepts & Design Fourth Edition by Stewart

1-30

© 2009 Pearson Addison-Wesley. All rights reserved.

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-30

Page 31: © 2009 Pearson Addison-Wesley. All rights reserved. Addison Wesley is an imprint of Prelude to Programming Concepts & Design Fourth Edition by Stewart

1-31

© 2009 Pearson Addison-Wesley. All rights reserved. 6-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 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

Page 32: © 2009 Pearson Addison-Wesley. All rights reserved. Addison Wesley is an imprint of Prelude to Programming Concepts & Design Fourth Edition by Stewart

1-32

© 2009 Pearson Addison-Wesley. All rights reserved. 6-32

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

Page 33: © 2009 Pearson Addison-Wesley. All rights reserved. Addison Wesley is an imprint of Prelude to Programming Concepts & Design Fourth Edition by Stewart

1-33

© 2009 Pearson Addison-Wesley. All rights reserved. 6-33

Nested Loops Help Load Arrays

To input data into a two-dimensional array, use a nested loop.

Page 34: © 2009 Pearson Addison-Wesley. All rights reserved. Addison Wesley is an imprint of Prelude to Programming Concepts & Design Fourth Edition by Stewart

1-34

© 2009 Pearson Addison-Wesley. All rights reserved. 6-34

Nested Loops Help Load Arrays (continued)

Declare studentGrades[30, 5]

For (SIndex = 0; SIndex <30; SIndex++)

Write “for student # “ + (SIndex + 1)

For (tIndex = 0; tIndex < 15; tIndex++)

write “enter grade of test #” + (tIndex+1)

Input [SIndex, tIndex]

End For(Week)

End For(Student)