You are on page 1of 49

Programming Logic and Design Sixth Edition

Chapter 6 Arrays

Objectives
In this chapter, you will learn about: Arrays and how they occupy computer memory Manipulating 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 Using a for loop to process arrays
2

Programming Logic & Design, Sixth Edition

Understanding Arrays and How They Occupy Computer Memory


Array
Conceptually a collection of variables in computer memory
the term element is used instead of variable all elements share the same name each element has a different subscript each element has the same data type

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.
Programming Logic & Design, Sixth Edition 3

How Arrays Occupy Computer Memory


Each element has the:
same name
same data type

Array elements are contiguous in 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
Programming Logic & Design, Sixth Edition 4

How Arrays Occupy Computer Memory (continued)

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

Programming Logic & Design, Sixth Edition

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

Arrays in Java are objects!


Programming Logic & Design, Sixth Edition

int someVals[ ] = new int[3];


6

Using Arrays
Given the declaration: num someVals[3]

valid references are:


invalid references:

someVals[0], someVals[1], someVals[2]


someVals[-1], someVals[3]

would usually generate an error message such as: Java: ArrayIndexOutOfBoundsException

Subscript represents the distance from first element


this is the notion of an offset

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 an expression of the same type can be used.

Programming Logic & Design, Sixth Edition

Manipulating an Array to Replace Nested Decisions


Example: Human Resources Department Dependents report
List employees who have claimed zero through five dependents ( 0 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
Programming Logic & Design, Sixth Edition 8

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.

Figure 6-3

Flowchart and pseudocode of decision-making process using a series of decisions 9

Programming Logic & Design, Sixth Edition

Manipulating 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 single array: num count[6]
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]

Programming Logic & Design, Sixth Edition

10

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.

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.

Figure 6-4 Flowchart and pseudocode of decision-making


Programming Logic & Design, Sixth Edition 11

Still not there yet

Can you see the pattern developing? Replace the integer literal subscript with the variable dep

Figure 6-5

Flowchart and pseudocode of decision-making process


12

Programming Logic & Design, Sixth Edition

Manipulating an Array to Replace Nested Decisions (continued)

Aha!

One statement!

This statement in Java would probably be written as: count[dep]++; or ++count[dep];

Both statements add 1 to (increment) count[dep]

Figure 6-6

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

Programming Logic & Design, Sixth Edition

Named constant

Figure 6-7

Flowchart and pseudocode for Dependents Report program


14

Programming Logic & Design, Sixth Edition

Manipulating an Array to Replace Nested Decisions (continued)


Notice the module names:
getReady() countDependents() finishUp()

Sentinel-controlled loop.

Counter-controlled loop.
Should have used a for loop.

Figure 6-7 Flowchart and pseudocode for Dependents


Programming Logic & Design, Sixth Edition 15

Using Constants with Arrays


Remember, constants are
named constants [ final variables in Java ] literals

Use the constants in several ways


array size

array value
array subscript
Programming Logic & Design, Sixth Edition 16

Using a Constant as the Size of an Array


Avoid magic numbers (unnamed constants)
magic numbers are literals

Declare a named numeric 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

Programming Logic & Design, Sixth Edition

17

Using Constants as Array Element Values


Sometimes the values stored in arrays should be constants
num ARRAY_SIZE = 12 string MONTH[ARRAY_SIZE] = "January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"

Valid subscripts are 0 - 11


Programming Logic & Design, Sixth Edition 18

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", "April", "July", "October", };

"February", "May", "August", "November",

"March", "June", "September", "December"

Valid subscripts are 0 12. Subscripts actually used are 1 12


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

Programming Logic & Design, Sixth Edition

Using a Constant as an Array Subscript


Use a numeric constant as a subscript to an array
Example
Declare a named constant as
num INDIANA = 5

Display value with: output salesArray[INDIANA]

Programming Logic & Design, Sixth Edition

20

Searching an Array
Sometimes you must search through an array to find a value or determine if the values 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
Programming Logic & Design, Sixth Edition 21

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).
"Constant Array" Most languages won't let you create a constant array. Declaration for array VALID_ITEM in Java would look more like this:

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

Figure 6-8

Flowchart and pseudocode for program that verifies item availability


22

Programming Logic & Design, Sixth Edition

String foundIt is being used as a flag. It would normally be declared as a boolean variable in Java like this:

boolean foundIt = false;

Figure 6-8 Flowchart and pseudocode for program that verifies item availability
Programming Logic & Design, Sixth Edition 23

for sub = 0 to SIZE-1 if item = VALID_ITEM[sub] then foundIt = "Y" endif endfor
Sample Java code: boolean foundIt = false; for ( sub = 0; sub < SIZE; sub++ ) if ( item == validItem[sub] ) foundIt = true;

Figure 6-8 Flowchart and pseudocode for program that verifies item availability
Programming Logic & Design, Sixth Edition 24

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 foundIt = 0; //0 for false, 1 for true
//best choice for Java

boolean foundIt = false;

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 array

Programming Logic & Design, Sixth Edition

25

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 element in same relative position in other array

Look through valid item array for customer item


When match is found, get price from item price array

Programming Logic & Design, Sixth Edition

26

Figure 6-9

Parallel arrays in memory

Programming Logic & Design, Sixth Edition

27

Using Parallel Arrays


Use 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 )


Programming Logic & Design, Sixth Edition 28

Figure 6-10

Flowchart and pseudocode for a program that finds an items price using parallel arrays 29

Programming Logic & Design, Sixth Edition

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.

Figure 6-10 Flowchart and pseudocode of program that finds an items price using parallel arrays (continued)
Programming Logic & Design, Sixth Edition 30

Figure 6-10

Flowchart and pseudocode of program that finds an items price using parallel arrays 31

Programming Logic & Design, Sixth Edition

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 exit
Programming Logic & Design, Sixth Edition 32

Java sample code to search an array for a value boolean foundIt = false; int sub = 0; // item and price are defined elsewhere while ( foundIt == false && sub < valid_item.length ) { if ( valid_item[sub] == item ) { foundIt = true; price = valid_price[sub]; } } if ( foundIt == true ) System.out.printf( "The price of the item is %,7.2f%n", price ); else { System.out.println( "Item was not found in the array valid_item."); badItemCount++; //defined elsewhere }

Figure 6-11

Flowchart and pseudocode of the module that finds item price, exiting the loop as soon as it is found
33

Programming Logic & Design, Sixth Edition

Improving Search Efficiency (continued)

Figure 6-11 Flowchart and pseudocode of the module that finds item price, exiting the loop as soon as it is found (continued)
Programming Logic & Design, Sixth Edition 34

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
Programming Logic & Design, Sixth Edition 35

Searching an Array for a Range Match (continued)

Figure 6-13

Usablebut inefficientdiscount array

Programming Logic & Design, Sixth Edition

36

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 comparisons


Programming Logic & Design, Sixth Edition 37

Searching an Array for a Range Match (continued)


quantity -------0 - 8 9 - 12 13 - 25 26 discount rate ------------no discount 10% 15% 20% subscript --------0 1 2 3

Figure 6-14 Parallel arrays to use for determining discount

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 loop: while quantity < minimum_size_for_range 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.

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

This example is checking the low end of each range.

Programming Logic & Design, Sixth Edition

38

range check

Figure 6-15

Program that determines discount rate


39

Programming Logic & Design, Sixth Edition

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

Programming Logic & Design, Sixth Edition

40

Figure 6-16

Determining the month string from the users numeric entry


41

Programming Logic & Design, Sixth Edition

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

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.

Programming Logic & Design, Sixth Edition

42

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 expression
Programming Logic & Design, Sixth Edition 43

Using a for Loop to Process Arrays (continued)

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( depts[dep] );

Programming Logic & Design, Sixth Edition

44

Using a for Loop to Process Arrays (continued)

Figure 6-26 Pseudocode that uses a more efficient for loop to output month names -- Ha! Nothing more efficient about this approach

Programming Logic & Design, Sixth Edition

45

Summary
Array
series or list of variables in memory Same name and type Different subscript

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)
Programming Logic & Design, Sixth Edition 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 highend value of each range
Programming Logic & Design, Sixth Edition 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
Programming Logic & Design, Sixth Edition 48

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

2
evenNumbers
length = 5

10

Object of type int[ ]

Programming Logic & Design, Sixth Edition

49

You might also like