49
Arrays

Arrays. Objectives In this chapter, you will learn about: Arrays and how they occupy computer memory Using an array to replace nested decisions Using

Embed Size (px)

Citation preview

Arrays

Objectives

In this chapter, you will learn about:

• Arrays and how they occupy computer memory• Using an array to replace nested decisions• Using constants with arrays• Searching an array• Using parallel arrays• Searching an array for a range match• Remaining within array bounds (bounds checking)• Using a for loop to process arrays

2

Understanding Arrays and How They Occupy Computer Memory

• Array– Conceptually – a collection of variables in computer memory

• an array is an aggregate data type

• the term element is used instead of variable

• all elements share the same name (the array name)

• You access an element in the array using a subscript

• each element has the same data type

num weeklyTotals[6] valid subscripts for weekly Totals is 0 .. 5

• Subscript (aka index and offset)– Position number of an item in an array

– May be a named constant, literal, variable, or in general, an expression that evaluates to an integer.

3

How Arrays Occupy Computer Memory

• Array elements are stored in contiguous memory

• The size of an array is the number of elements it will hold

• For most languages: – the value of the smallest subscript is 0

– the value of the largest subscript is array size – 1(0 based indexing)

4

How Arrays Occupy Computer Memory (continued)

5

Figure 6-1 Appearance of a three-element array in computer memory

Declaring Arrays• Array Declaration

– <data_type> <array_name> [ <number_of_elements> ]

– num someVals[3] //pseudocode

• data type is num

• name is someVals

• size of the array is 3 elements

• valid subscripts are: 0, 1, 2

• Languages have differences in syntax for arrays

– some languages use ( ) instead of [ ]

– style of declaration can be quite different

• Java array declaration: int someVals[] = new int[3];6

Arrays in RAPTOR

7Programming Logic and Design, Seventh Edition

The index in a RAPTOR array starts at 1!

Arrays in RAPTOR are easily expanded

SET counter[5] TO 0 indices are: 1, 2, 3, 4, 5

SET counter[7] TO 0 indices are: 1, 2, 3, 4, 5, 6, 7

SET counter[100] TO 0 indices are: 1, 2, 3, … , 100

Using Arrays

• Given this pseudocode declaration: int someVals[3]

– valid references are: someVals[0], someVals[1], someVals[2]

– invalid references: someVals[-1], someVals[3]

• would usually generate an error message such as:

– Java: ArrayIndexOutOfBoundsException

– A subscript used in an array reference can be any integer expression

• variable, literal, named constant, calculation

An array element can be used in any statement in which a variable of the same type can be used.

8

Using an Array to Replace Nested If Decisions

• Example: Human Resources - Department Dependents report

– Count employees who have claimed zero through five dependents ( 0 – 5 ) to get count for each: count[0] .. count[5]

• Assume no employee has more than five dependents

• Application produces counts for dependent categories by using a series of decisions.

• Application does not scale easily to a different range of dependents

9

10

Figure 6-3 Flowchart and pseudocode of decision-making process using a series of decisions

Variable dep may have the values 0 – 5.

Test dep to determine which counter to increment.

6 variables had to be declared to implement this solution.

Using an Array to Replace Nested Decisions (continued)

• Replacing the nested-if logic with array logic reduces the number of statements needed

• Six dependent count accumulators can be redefined as a single array: int count[6] //valid subscripts are 0 - 5

• The array elements should be initialized to zero since they will be used as counters.

• Use the variable dep as a subscript for the array: count[dep]

11

12

Figure 6-4 Flowchart and pseudocode of decision-making Version 2

This approach has not simplified the logic because nested-if's are still being used.

All of this nested-if logic can be replaced by a single assignment statement.

The comma separated list of values here is called an "initializer list".

This declaration could be written in Java as:

int count[] = new int[6];

All of the elements in the array would automatically be initialized to zero in Java.

13

Figure 6-5 Flowchart and pseudocode of decision-making process Version 3

Still not there yet…

Can you see the pattern developing?

Replace the integer literal subscript with the variable dep

Using an Array to Replace Nested Decisions (continued)

14

Figure 6-6 Flowchart and pseudocode of efficient decision-making process using an array

Aha!

One statement!

15

Figure 6-7 Flowchart and pseudocode for Dependents Report program Final Version

Named constant

What would this loop look like in RAPTOR?

Using an Array to Replace Nested Decisions (continued)

Figure 6-7 Flowchart and pseudocode for Dependents Final Version

16

Notice the module names:

main()getReady()countDependents()finishUp()

Sentinel-controlled loop.

Counter-controlled loop.

Should have used a for loop.

“mainline” logicmain()

Using Constants with Arrays

• Remember, constants are – named constants

– literals

• Use the constants in several ways– array size

– array value

– array subscript

17

Using a Constant as the Size of an Array

• Avoid “magic numbers” (unnamed constants)– magic numbers are literals…

• Declare a numeric named constant to be used:– in the declaration of the array

– to determine array size in other parts of your code

• Make sure any subscript remains less than the constant value

• Many languages provide a mechanism for determining the size of an array without needing to refer to a named constant.

– Java has a public field called length

– The expression myArray.length would return the number of elements in the array myArray

– RAPTOR provides the Length_of procedure Length_of(counters)

18

Using Constants as Array Element Values

• Sometimes the values stored in arrays should be constants

• int ARRAY_SIZE = 12

string MONTH[ARRAY_SIZE] = //initializer list "January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"

• Valid subscripts are 0 – 11 [ RAPTOR 1 – 12 ]19

Using Constants as Array Element Values

• Here is a modified version of the previous example which makes it possible for use to use the array more naturally.

• num ARRAY_SIZE = 13 //this allows us to ignore element 0 //instead of 0 – 11, now we can use 1 – 12

string MONTH[ARRAY_SIZE] = "",

"January", "February", "March",

"April", "May", "June",

"July", "August", "September",

"October", "November", "December"

• Valid subscripts are 0 – 12. Subscripts actually used are 1 – 12. Ignore element 0

• Element 0 is unused, however, note that we still need to give it a value!– Small price to pay for the simplified functionality

20

Using a Constant as an Array Subscript

• Use a named constant as a subscript in an array

• Example

– Declare a named constant as • int INDIANA = 5

– Display value with:output salesArray[INDIANA]

21

Searching an Array• Sometimes you must search through an array to find a value or

determine if the value is even in the array

• Example: mail-order business

– Item numbers are three-digit, non-consecutive numbers

– Customer orders an item

– Program needs to check if item number is valid

• Solution:– Create an array that holds valid item numbers

– Search array for exact match

22

23

Figure 6-8 Flowchart and pseudocode for program that verifies item availability

Rest of program is on the next page

The list of values to be assigned to the array elements is called an initializer list.

String foundIt is being used as a flag (boolean variable).

Declaration for array VALID_ITEM in Java would look more like this:

int validItem[ ] = { 106, 108, 307, 405, 457, 688 };

"Constant Array"

Most languages won't let you create a constant array.

24

Figure 6-8 Flowchart and pseudocode for program that verifies item availability

String foundIt is being used as a flag

better choice is to use a boolean variable

boolean foundIt = false;

foundIt = true;

Programming Logic & Design, Sixth Edition 25

Figure 6-8 Flowchart and pseudocode for program that verifies item availability

foundIt = "N"

for sub = 0 to SIZE-1 if item = VALID_ITEM[sub] then foundIt = "Y" endifendfor

Using boolean variable foundIt in Java

foundIt = false;

for ( sub = 0; sub < SIZE; sub++ ) if ( item == validItem[sub] ) foundIt = true;

Searching an Array (continued)• Flag

– variable that indicates whether an event occurred

– declared as a string in the book: String foundIt = "N";

– usually declared as a boolean or integer variable in most languages

• int found_it = 0; //0 for false, 1 for true

• boolean found_it = false; //Java

• string found_it = “Y” //PLD textbook

• SET found_it TO True //RAPTOR

• Technique for searching an array– Set a subscript variable to 0 to start at the first element

– Initialize a flag variable to false to indicate the desired value has not been found

– Examine each element in the array

– If the value matches, set the flag to true

– If the value does not match, increment the subscript and examine the next array element

An example is given later for searching an array26

Using Parallel Arrays• Example: mail-order business

– Two arrays, each with the same number of elements

• Valid item numbers

• Valid item prices

– Each price in valid item price array in same position as corresponding item in valid item number array

• Parallel arrays

– Each element in one array associated with an element in the same relative position in other array

– Do a search on one array and find an associated value in another array

– all arrays should be the same size!

• Look through valid item array for customer item

– When match is found, get price from item price array27

28

Figure 6-9 Parallel arrays in memory

Using Parallel Arrays

• Parallel arrays

– Two or more arrays contain related data

– A subscript relates the arrays• Elements at the same position in each array are logically related

– A similar approach is to have an array of structures or objects ( advanced topic )

29

30

Figure 6-10 Flowchart and pseudocode for a program that finds an item’s price using parallel arrays

Program continues on next slide

31

Figure 6-10 Flowchart and pseudocode of program that finds an item’s price using parallel arrays (continued)

This search logic works correctly but is inefficient because it doesn't stop searching if a match is found.

A more efficient approach is shown later.

Programming Logic & Design, Sixth Edition 32

Figure 6-10 Flowchart and pseudocode of program that finds an item’s price using parallel arrays

Improving Search Efficiency

• Program should stop searching the array when a match is found

• Use a flag (boolean variable) as a second condition for the search criteria ( AND logic )

• Improves efficiency• The larger the array, the better the improvement by

doing an early exit33

34

Figure 6-11 Flowchart and pseudocode of the module that finds item price, exiting the loop as soon as it is found

Pseudocode to search an array for a value

boolean foundIt = falseint sub = 0 // item and price are defined elsewhere

while foundIt = false and sub < SIZE if valid_item[sub] = item then foundIt = true price = valid_price[sub] endifendwhile

if foundIt = true print "The price of the item is “ + priceelse print "Item was not found in the array valid_item." badItemCount += 1 //defined elsewhereendif

Improving Search Efficiency (continued)

35

Figure 6-11 Flowchart and pseudocode of the module that finds item price, exiting the loop as soon as it is found (continued)

Searching an Array for a Range Match

• Sometimes programmers want to work with ranges of values in arrays

• Example: mail-order business– Read customer order data– determine discount based on quantity ordered

• First approach– Array with as many elements as each possible order quantity– Store appropriate discount for each possible order quantity

36

Searching an Array for a Range Match (continued)

37

Figure 6-13 Usable—but inefficient—discount array

Quantity Rate

0 – 8 0%

9 – 12 10%

13 – 25 15%

>= 26 20%

Max 76 items

Searching an Array for a Range Match (continued)

• Drawbacks of first approach– Requires very large array; uses a lot of memory

– Stores same value repeatedly

– How do you know you have enough elements?• Customer can always order more

• Better approach– Create four discount array elements for each discount rate

– Parallel array with discount range

• Use loop to make comparisons38

Searching an Array for a Range Match (continued)

39

Figure 6-14

Parallel arrays to use for determining discount

For range comparisons, store either the low- or high-end value of each range.

This example is checking the low end of each range.

quantity discount rate subscript-------- ------------- --------- 0 - 8 no discount 09 - 12 10% 113 - 25 15% 226 or more 20% 3

Set value of subscript initially to array size – 1 ( 3 )

Use a loop to determine what subscript to use to access the discount rate in the discount array.

This logic is more challenging than the if-then-else or switch logic but is very flexible

subscript = 3loop: while quantity < quan_limit[subscript] //26, 13, 9, 0 subtract 1 from the subscript end while When you exit the loop, use the value of the subscript to access the discount rate from the discount array.

40

Figure 6-15 Program that determines discount rate

range check

Checking from higher to lower rates

Array Size in Memory• Every array has a finite size

– There are a specific number of elements in the array

– Each element uses some number of bytes (1,2,4,8,etc)

• The number of bytes in an array is always a multiple of number of array elements

41

42Figure 6-16 Determining the month string from the user’s numeric entry

Remaining within Array Bounds

Remaining within Array Bounds

• Program logic assumes every number entered by the user is valid

• If an invalid subscript is used:

– Some languages stop execution and issue an error

– Other languages access a memory location outside of the array

– Java generates an exception ArrayIndexOutOfBoundsException

• Attempting to use an invalid array subscript is a logic error

• Out of bounds

– using a subscript that is not within the acceptable range for the array

• The Program should prevent bounds errors from occuring.

43

Using a for Loop to Process Arrays

• for loop– single statement

– Initializes loop control variable

– Compares it to a limit

– Alters it

• A for loop is especially convenient when working with arrays– To process every element

• Must stay within array bounds

• Highest usable subscript is one less than array size.

• Java gives us a field we can use in an expression44

Using a for Loop to Process Arrays (continued)

45

Figure 6-17 Pseudocode that uses a for loop to display an array of department names

Java for loops to process array elements: Standard for loop: for ( int dep = 0; dep < depts.length; dep++ )

System.out.println( depts[dep] );

Enhanced for loop: for ( int dep : depts ) System.out.println( dep );

Summary

• Array – series or list of variables in memory– common name – common type– different subscripts

• Use a variable as a subscript to the array to replace multiple nested decisions

• Some array values determined during program execution– Other arrays have hard-coded values (constant array)

46

Summary (continued)

• Search an array– Initialize the subscript– Test each array element value in a loop– Set a flag when a match is found

• Parallel arrays– each element in one array is associated with the element in

second array– Elements have same relative position

• For range comparisons, store either the low- or high-end value of each range

47

Summary (continued)

• Access data in an array– Use subscript containing a value that accesses memory

occupied by the array

• Subscript is out of bounds if not within defined range of acceptable subscripts

• for loop is a convenient tool for working with arrays– Process each element of an array from beginning to end

48

Java Arrays

int evenNumbers[] = { 2, 4, 6, 8, 10 };

49

2 4 6 8 10

evenNumbers

Object of type int[ ]

length = 5