Professional Documents
Culture Documents
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
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
Declaring Arrays
Array Declaration
<data_type> <array_name> [ <number_of_elements> ] num someVals[3] //pseudocode
Using Arrays
Given the declaration: num someVals[3]
An array element can be used in any statement in which an expression of the same type can be used.
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
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.
10
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.
Can you see the pattern developing? Replace the integer literal subscript with the variable dep
Figure 6-5
Aha!
One statement!
Figure 6-6
Named constant
Figure 6-7
Sentinel-controlled loop.
Counter-controlled loop.
Should have used a for loop.
array value
array subscript
Programming Logic & Design, Sixth Edition 16
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
17
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
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:
Figure 6-8
String foundIt is being used as a flag. It would normally be declared as a boolean variable in Java like this:
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
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
25
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
26
Figure 6-9
27
Figure 6-10
Flowchart and pseudocode for a program that finds an items price using parallel arrays 29
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
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
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
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
Figure 6-13
36
Better approach
Create four discount array elements for each discount rate
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.
38
range check
Figure 6-15
40
Figure 6-16
42
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
Figure 6-17
Java for loops to process array elements: Standard for loop: for ( int dep = 0; dep < depts.length; dep++ ) System.out.println( depts[dep] );
44
Figure 6-26 Pseudocode that uses a more efficient for loop to output month names -- Ha! Nothing more efficient about this approach
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
49