520 likes | 666 Vues
Programming Logic and Design Seventh Edition. Chapter 6 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
E N D
Programming Logic and DesignSeventh Edition Chapter 6 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
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 indexandoffset) • 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.
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)
How Arrays Occupy Computer Memory (continued) Figure 6-1 Appearance of a three-element array in computer memory
Declaring Arrays • Array Declaration • <data_type> <array_name> [ <number_of_elements> ] • numsomeVals[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];
Arrays in RAPTOR Arrays_in_RAPTOR Programming Logic and Design, Seventh Edition
Using Arrays • Given the declaration: numsomeVals[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 • 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 a variable of the same type can be used.
Using an Array to Replace Nested 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
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
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: num 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]
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'sare 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 Version 2
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 Version 3
Using an Array to Replace Nested Decisions (continued) Aha! One statement! Figure 6-6 Flowchart and pseudocode of efficient decision-making process using an array
Named constant What would this loop look like in RAPTOR? Figure 6-7 Flowchart and pseudocode for Dependents Report program Final Version
Using an Array to Replace Nested Decisions (continued) Figure 6-7 Flowchart and pseudocode for Dependents Final Version Sentinel-controlled loop. • “mainline” logic • main() Notice the module names: main() getReady() countDependents() finishUp() Counter-controlled loop. Should have used a for loop.
Using Constants with Arrays • Remember, constants are • named constants • literals • Use the constants in several ways • array size • array value • array subscript
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
Using Constants as Array Element Values • Sometimes the values stored in arrays should be constants • num 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
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
Using a Constant as an Array Subscript • Use a named constant as a subscript in an array • Example • Declare a named constant as • num INDIANA = 5 • Display value with: output salesArray[INDIANA]
Searchingan 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
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 Rest of program is on the next page
String foundIt is being used as a flagbetter choice is to use a boolean variable bool foundIt = false; foundIt = true; //bool var Figure 6-8 Flowchart and pseudocode for program that verifies item availability
foundIt ="N" forsub = 0 to SIZE-1 if item = VALID_ITEM[sub] then foundIt = "Y" endif endfor Using a boolean variable foundIt 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
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 • IntfoundIt = 0; //0 for false, 1 for true • bool foundIT = false; //C and C++ • 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
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 • Look through valid item array for customer item • When match is found, get price from item price array
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 )
Figure 6-10 Flowchart and pseudocode for a program that finds an item’s price using parallel arrays Program continues on next slide
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 item’s price using parallel arrays (continued)
Figure 6-10 Flowchart and pseudocode of program that finds an item’s price using parallel arrays 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
Java sample code to search an array for a value boolean foundIt = false num sub = 0 // item and price are defined elsewhere while foundIt = false && sub < SIZE if valid_item[sub] = item foundIt = true price = valid_price[sub] endif Endwhile if foundIt = true print "The price of the item is “ + price else print "Item was not found in the array valid_item." badItemCount+= 1 //defined elsewhere } Figure 6-11 Flowchart and pseudocode of the module that finds item price, exiting the loop as soon as it is found
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)
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
Searching an Array for a Range Match (continued) Max 76 items Quantity Rate 0 – 8 0% 9 – 12 10% 13 – 25 15% >= 26 20% Figure 6-13Usable—but inefficient—discount array
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
Searching an Array for a Range Match (continued) quantity discount rate subscript -------- ------------- --------- 0 - 8 no discount 0 9 - 12 10% 1 13 - 25 15% 2 26 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 = 4 loop: 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. 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.
range check Checking from higher to lower rates Figure 6-15 Program that determines discount rate
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
Remaining within Array Bounds Figure 6-16 Determining the month string from the user’s numeric entry
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.
Using a forLoop to Process Arrays • forloop • 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
Using a forLoop 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( 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)
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
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
Java Arrays int evenNumbers[] = { 2, 4, 6, 8, 10 }; length = 5 evenNumbers Object of type int[ ]