Presentation is loading. Please wait.

Presentation is loading. Please wait.

An Object-Oriented Approach to Programming Logic and Design Fourth Edition Chapter 5 Arrays.

Similar presentations


Presentation on theme: "An Object-Oriented Approach to Programming Logic and Design Fourth Edition Chapter 5 Arrays."— Presentation transcript:

1 An Object-Oriented Approach to Programming Logic and Design Fourth Edition
Chapter 5 Arrays

2 Objectives In this chapter, you will learn about:
Storing data in arrays How an array can replace nested decisions Using constants with arrays Searching an array for an exact match Using parallel arrays Searching an array for a range match Remaining within array bounds Using a for loop to process arrays An Object-Oriented Approach to Programming Logic and Design

3 Storing Data in Arrays Need for handling large amounts of data
Using individual variables becomes unwieldy Data structure Collection of data items that are organized for efficient use An array is a type of data structure Array Consists of a series or list of values All values have the same name and data type Differentiated with subscripts Sometimes referred to as a table or matrix An Object-Oriented Approach to Programming Logic and Design

4 How Arrays Occupy Computer Memory
Array Element Each item in an array is known as an element of the array Occupies an area in memory next to the other elements Same group name but unique subscript Subscript A nonnegative integer that indicates the position of an item within an array Also called an index Must be sequential integers Usually starts at zero An Object-Oriented Approach to Programming Logic and Design

5 How Arrays Occupy Computer Memory (cont’d)
Size of the array Indicates number of array elements Determined when array is declared Array declaration Declared structure containing multiple values Variables have the same name and data type Populating the Array Assigning values to the array elements Array Syntax Square brackets usually hold array element subscripts An Object-Oriented Approach to Programming Logic and Design

6 How Arrays Occupy Computer Memory (cont’d)
Assigning array values Or assign values to elements individually Can be done when array is declared Figure 5-1 shows a 3-element array in computer memory // Assigns values individually num someVals[3] someVals[0] = 25 someVals[1] = 36 someVals[2] = 47 // Assigns values when array is declared num someVals[3] = 25, 36, 47 Figure 5-1 An Object-Oriented Approach to Programming Logic and Design

7 How Arrays Occupy Computer Memory (cont’d)
After array declared and values assigned Data items can be used in the same way as other items of the same data type Can be input or output Numeric items can have arithmetic operations performed on them answer = someVals[0] + someVals[2] An Object-Oriented Approach to Programming Logic and Design

8 How an Array Can Replace Nested Decisions
Human resources application example Produce statistics on employees’ claimed dependents Report lists number of employees who have claimed zero, one, two, three, four, or five dependents Assume no employees have more than five dependents Figure 5-2 represents typical report output See Figure 5-3 on the next slide for decision-making pseudocode and flowchart Figure 5-2 An Object-Oriented Approach to Programming Logic and Design

9 Figure 5-3: Approach uses individual variables
Decision-making process uses a series of decisions An Object-Oriented Approach to Programming Logic and Design

10 How an Array Can Replace Nested Decisions (cont’d)
Alternative to example approach: use an array Greatly reduces number of statements needed Replace dependent count accumulators with single array named count See Figure 5-4 on the next slide An Object-Oriented Approach to Programming Logic and Design

11 Figure 5-4: Approach uses an array
Decision-making process still uses a series of decisions An Object-Oriented Approach to Programming Logic and Design

12 How an Array Can Replace Nested Decisions (cont’d)
Main benefit of using array Ability to use a variable as a subscript to the array Allows loop to cycle through all elements in array Same action taken for each array element Shortens code Implement using variable for subscript See Figure 5-5 on next slide An Object-Oriented Approach to Programming Logic and Design

13 Figure 5-5: Approach uses an array with variable subscript
Decision-making process still uses a series of decisions Flaw: If always taking same action no matter what answer is, why ask question? An Object-Oriented Approach to Programming Logic and Design

14 How an Array Can Replace Nested Decisions (cont’d)
Rewrite decision-making process because action taken is the same for each array element Continue using variable for subscript Replace need for decision structures Figure 5-6 shows efficient decision-making process Figure 5-6 An Object-Oriented Approach to Programming Logic and Design

15 How an Array Can Replace Nested Decisions (cont’d)
Figure 5-6 uses single statement Eliminates entire decision-making process in Figure 5-5 Substantial improvement to original process Process logic adjusts easily to new conditions No logic changes if there are 20, 30, or any other number of possible categories See Figure 5-7 on next slide Entire application takes advantage of array Produces a report showing dependent category counts An Object-Oriented Approach to Programming Logic and Design

16 Final version of Dependents Report program
Final analysis of program changes: Series of decisions worked, but inefficiently Using an array resulted in more efficient code Figure 5-7 An Object-Oriented Approach to Programming Logic and Design

17 Using Constants with Arrays
Ways to use constants To hold the size of the array As the array values As a subscript Minor flaw in Figure 5-7 program report-printing part Array subscript compares to constant “6” To improve, use a named constant instead Declare named numeric constant: ARRAY_SIZE = 6 Use named constant when accessing array Ensure subscript remains less than constant value An Object-Oriented Approach to Programming Logic and Design

18 Using Constants with Arrays (cont’d)
Some programming languages automatically create constant Provided at array declaration time Represents array size Java example Array named count declared Size stored in field named count.length C# and Visual Basic example Array size is count.Length An Object-Oriented Approach to Programming Logic and Design

19 Using Constants as Array Element Values
Constants can be used to populate array values Example: array that holds months of the year string MONTH[12] = “January”, “February”, “March”, “April”, “May”, “June”, “July”, “August”, “September”, “October”, “November”, “December” An Object-Oriented Approach to Programming Logic and Design

20 Using a Constant as an Array Subscript
Constants can be used as a subscript to an array Example: output salesArray[0] If array holds sales values for each state, and Indiana is state 5 output salesArray[5] or num INDIANA = 5 output salesArray[INDIANA] Using a named constant is self-documenting in this case An Object-Oriented Approach to Programming Logic and Design

21 Searching an Array for an Exact Match
Linear search Search through a list from one end to another Mail-order business example Want to test ID number of ordered item to see if it is valid See Figure 5-8 on next slide for program that verifies that the item number is valid An Object-Oriented Approach to Programming Logic and Design

22 Figure 5-8 Program searches an array that stores the valid item numbers to find a match to the ordered item Figure 5-8 An Object-Oriented Approach to Programming Logic and Design

23 Searching an Array for an Exact Match (cont’d)
If no match is found, options are Display error message (as in Figure 5-8) Re-prompt for item number Set a default number Set a flag Flag Variable set to indicate some event has occurred An Object-Oriented Approach to Programming Logic and Design

24 Using Parallel Arrays Parallel arrays
Two arrays in which each element in one array is associated with the element in the same relative position of the other array Figure 5-9 An Object-Oriented Approach to Programming Logic and Design

25 Using Parallel Arrays (cont’d)
When using parallel arrays Two or more arrays contain related data A subscript relates the arrays Figure 5-10 shows a program that declares and uses parallel arrays An Object-Oriented Approach to Programming Logic and Design

26 Figure 5-10 Flowchart and pseudocode of a program that finds an item price using parallel arrays Figure 5-10 An Object-Oriented Approach to Programming Logic and Design

27 Using Parallel Arrays (cont’d)
Previous example searches through VALID_ITEM array for item number and then pulls corresponding price out of VALID_PRICE Indirect relationship Relationship between item number and its price Don’t access price directly by knowing the item number, but by item number’s position in the VALID_ITEM array If VALID_ITEM[sub] contains the correct item, VALID_PRICE[sub] contains the correct price for the item [sub] links the parallel arrays An Object-Oriented Approach to Programming Logic and Design

28 Improving Search Efficiency
Previous example is inefficient Search continues until sub reaches the value SIZE To improve efficiency Exit loop once value has been found and number of comparisons does not exceed SIZE The larger the array, the greater the efficiency improvement achieved by leaving the search loop early Figure 5-11 shows improved version of price-finding example An Object-Oriented Approach to Programming Logic and Design

29 Improved version of price-finding example
Figure 5-11 Improved version of price-finding example Program exits loop once value has been found and number of comparisons does not exceed SIZE An Object-Oriented Approach to Programming Logic and Design

30 Searching an Array for a Range Match
Range of values Any series of contiguous values between specified limits Figure 5-12 provides a chart that applies a discount on orders by quantity Figure 5-12 An Object-Oriented Approach to Programming Logic and Design

31 Searching an Array for a Range Match (cont’d)
One approach to discount example Create a large array with all possible order quantities Drawbacks of such an approach Requires a large array using a lot of memory Must store same value repeatedly How many array elements is enough? A customer could always order more An Object-Oriented Approach to Programming Logic and Design

32 Searching an Array for a Range Match (cont’d)
One approach to discount example Create a large array with all possible order quantities Figure 5-13 shows a usable, but inefficient, discount array Drawbacks Requires a large array using a lot of memory Must store same value repeatedly How many array elements is enough? A customer could always order more Figure 5-13 An Object-Oriented Approach to Programming Logic and Design

33 Searching an Array for a Range Match (cont’d)
Better approach Two parallel arrays Figure 5-14 creates parallel arrays to use for determining discount Figure 5-15 on the next slide shows the use of the arrays Figure 5-14 An Object-Oriented Approach to Programming Logic and Design

34 Flowchart and pseudocode for program that determines discount rate
Figure 5-15 Flowchart and pseudocode for program that determines discount rate Program uses parallel arrays named DISCOUNT and QUAN_LIMIT to store a given discount for a quantity range An Object-Oriented Approach to Programming Logic and Design

35 Remaining within Array Bounds
Array size is finite When accessing array Ensure subscript accesses location within the array If subscript is negative or larger than array size Some programming languages end program and issue error message Other languages access an area in memory outside of the array (likely contains garbage or incorrect data) Out of bounds Subscript is not within range of acceptable subscripts An Object-Oriented Approach to Programming Logic and Design

36 Remaining within Array Bounds (cont’d)
Figure 5-16 Program accepts numeric value for month and displays month name Program makes assumption that every user input is valid To improve program test if subscript is within bounds An Object-Oriented Approach to Programming Logic and Design

37 Using a for Loop to Process Arrays
Uses single statement Initializes loop control variable, compare to limit, alter it Convenient tool for working with arrays Figure 5-17 on the next slide Uses a for loop to display an array of department names Figure 5-18 Provides a better solution An Object-Oriented Approach to Programming Logic and Design

38 Using a for Loop to Process Arrays (cont’d)
Pseudocode that uses a for loop to display an array of department names Subtracts 1 from SIZE for each loop iteration Figure 5-17 An Object-Oriented Approach to Programming Logic and Design

39 Using a for Loop to Process Arrays (cont’d)
Pseudocode that uses a more efficient for loop to output department names The constant LIMIT is calculated once, then used in loop test. Figure 5-18 An Object-Oriented Approach to Programming Logic and Design

40 Summary Array: named series of values in memory Array elements
All have same data type; different subscripts Array elements have a unique subscript Are contiguous Using variable as an array subscript can eliminate nested decisions Same code operates on each array element Constants can be used to hold array values, size, or subscript An Object-Oriented Approach to Programming Logic and Design

41 Summary (cont’d) Searching an array involves: Parallel arrays
Initializing a subscript Using a loop to test each element Setting a flag when a match is found Parallel arrays Two arrays: each element in one array is related to element in same subscript position in other array Arrays can be used to search for a range match Remaining within array bounds is critical A for loop can be used to process arrays An Object-Oriented Approach to Programming Logic and Design


Download ppt "An Object-Oriented Approach to Programming Logic and Design Fourth Edition Chapter 5 Arrays."

Similar presentations


Ads by Google