1 / 53

Chapter 08

Chapter 08. Arrays. Understanding Arrays. Array – a series or list of variables in computer memory, all of which have the same name but are differentiated with special numbers called Subscripts . If You . . .

shel
Download Presentation

Chapter 08

An Image/Link below is provided (as is) to download presentation Download Policy: Content on the Website is provided to you AS IS for your information and personal use and may not be sold / licensed / shared on other websites without getting consent from its author. Content is provided to you AS IS for your information and personal use only. Download presentation by click this link. While downloading, if for some reason you are not able to download a presentation, the publisher may have deleted the file from their server. During download, if you can't get a presentation, the file might be deleted by the publisher.

E N D

Presentation Transcript


  1. Chapter 08 Arrays

  2. Understanding Arrays Array – a series or list of variables in computer memory, all of which have the same name but are differentiated with special numbers called Subscripts. If You . . . • store important papers in a series of file folders and label each folder with a consecutive letter of the alphabet • store mementos in a series of stacked shoeboxes, each labeled with a year • sort mail into slots, each labeled with a name • look down the left side of a tax table to find your income level before looking to the right to find your income obligation • look down the left side of a train schedule to find your station before looking to the right to find your train’s arrival time

  3. Using an organized storage and display system makes your life easier in each case – using a programming array will accomplish the same results for your data. Some programmers refer to an array as a Table or a Matrix

  4. How Arrays Occupy Computer Memory Characteristics of An Array • A programming structure that contains Multiple variables • Each Variable within an array has the Same Name • Each Variable within an array as the Same Data Type • Each separate Variable is called an Element of the array

  5. Array Elements are Contiguous, next to each other in memory • The Size of the Array, how many elements it will hold, is indicated at array declaration • Each array Element has the Same Group Name • Each array Element has a unique Subscript, which indicates how far away the individual element is from the first Element. • The Subscripts are always a sequence of Integers • Some languages use Parentheses, others use Brackets following the Group Name to indicates the Subscript

  6. Figure 8-1, page 286 someVals[1] someVals[2] someVals[3] aNumber

  7. Variations Among Programming Languages In languages like Java, C#, and C++, the subscript of the first array element is 0 In languages like Visual Basic and COBOL, the subscript of the first array element is 1 You are never required to use arrays within your programs, but learning to use arrays correctly can make many programming tasks far more efficient and professional.

  8. Manipulating an Array to Replace Using Nested Decisions Consider a program that keeps statistics for a recycling drive competition at a high school. The school is holding a competition between freshman, sophomore, junior and senior classes to see which class can collect the greatest number of aluminum cans. Each time a student brings in some cans, a clerk adds a record to a file. At the end of the recycling competition after all records have been collected, the file might contain hundreds of records, each holding a one-digit number representing a class and up to a three-digit number representing cans. You want to write a program that summarizes the total of the cans brought in by each class.

  9. File name: STURECORD FIELD DESCRIPTION POSITIONS DATA TYPE DECIMALS Student class 1 Numeric 0 Cans collected 2-4 Numeric 0 Declare and Initialize Counters: num count1 = 0 num count2 = 0 num count3 = 0 num count4 = 0 See Figure 8-4, page 289 through Figure 8-7, page 291

  10. What if the recycling drive is held at an elementary school with eight classes, in a school district with 12 grade levels, or in a company with 30 departments? • Addition of Many Accumulator Variables • Addition of Many Decisions within mainLoop( ) • Addition of Many Print Statements within finish( ) Using an Array provides an alternative approach to this programming problem, which greatly reduces the number of statements you need.

  11. Modified mainLoop( ) using count Array When you declare an array, you provide a group name for a number of associated variables in memory. Declare and Initialize count Array Elements: num count[1] = 0 num count[2] = 0 num count[3] = 0 num count[4] = 0 See Figure 8-8, page 292 through Figure 8-9, page 293

  12. Is this an improvement over the original? The true benefit of using an array lies in your ability to use a variable as a subscript to the array rather than using a constant such as 1 or 4 Modified mainLoop( ) using variable stuClass as Subscript See Figure 8-10, page 294

  13. Is this logic any more efficient? • Do you see any differences?

  14. Modified mainLoop( ) eliminating decisions See Figure 8-11, page 295 See Figure 8-12, page 296

  15. Is this logic any more efficient? • Would the mainLoop( ) remain the same logic structure regardless of the number of classes whether there are 4 or 40? • If so, what is one thing that must be taken into consideration? • How Can the finish( ) module be Improved?

  16. The stuClass variable is handy to use as a subscript, but any variable could have been used as long as it was: • Numeric with no decimal places • Initialized to 1 • Incremented by 1 each time the logic passes through the loop

  17. Array Declaration and Initialization 1. In the previous example, the array elements of count were Declared and initialized individually: num count[1] = 0 num count[2] = 0 num count[3] = 0 num count[4] = 0 This is only acceptable only if there are a small number of elements.

  18. 2. The different languages declare arrays in various ways • DIM COUNT(30) BASIC, Visual Basic • int count[30]; C#, C++ • int count = new int[30] Java • COUNT OCCURS 30 TIMES PIC 9999 COBOL See Figure 8-13, page 297 3. Declaring a numeric array does not necessarily set its individual elements to zero. 4. Initialization Loop – a loop structure that provides initial values for every element in any array. See Figure 8-14, page 298

  19. Run-Time and Compile-Time Arrays Run-Time Array or Execution-Time Array – the values that you want to use are created during an actual run, or execution, of the program – the value is accumulated during the execution of the program and is not known until the end. Compile-Time Array – one whose final desired values are fixed at the beginning of the program.

  20. Let’s say you own an apartment building with five floors and have records for all your tenants. The combination of each tenant’s floor number and apartment letter provides you with a specific apartment. Every month you print a rent bill for each tenant. Your rent charges are based on the floor of the building. You want to create a program that prints each tenant’s name and rent due. File Name: TENANTS FIELD DESCRIPTION POSITIONS DATA TYPE DECIMALS Tenant name 1-40 Character Floor number 41 Numeric 0 Apartment number 42 Character Options: (1) Utilize five decisions concerning the floor number (2) Utilize a Compile-Time Array to hold the five rent figures

  21. Option 2: 1. The rent amounts are hard-coded into the array; that is, they are explicitly assigned to the array elements. Floor Rent in $ Initialization of rent array 1 350 num rent[1] = 350 2 400 num rent[2] = 400 3 475 num rent[3] = 475 4 600 num rent[4] = 500 5 1000 num rent[5] = 1000 2. When deciding what variable to use as a subscript with an array, ask yourself: Of all the values available in the array, what does the correct selection depend on?”

  22. 3. Without a rent array, the figureRent( ) module would have to contain four decisions and five different resulting actions. 4. With the rent array there are no decisions. See Figure 8-17, page 300 through Figure 8-20, page 302

  23. Loading an Array From a File Consider writing the rent program for a skyscraper with 100 floors. Why would the use of a Compile-Time Array Not be the most efficient logic to store the rent amount for each floor? Advantages of Reading from a File: 1. The file can be updated as frequently as needed 2. Assures that each rent is always accurate and up-to-date 3. Very tedious to have to change the hard-coded rent amount for 100 floors See Figure 8-21, page 303

  24. Searching For an Exact Match in an Array Sometimes you do not have a variable that conveniently holds an array position; sometimes you have to search through an array to find a value you need. Consider a mail-order business in which orders come in with a customer name, address, item number ordered, and quantity ordered. The item numbers are three-digit numbers, but perhaps are not consecutive 001 through 999. This is due to the fact that over the years items have been deleted and new items have been added. When a customer orders an item you want to determine whether the customer has ordered a valid item number. If an item is not found, the program should display “No such item”.

  25. File name: CUSTREC FIELD DESCRIPTION POSITIONS DATA TYPE DECIMALS Customer name 1-20 Character Address 21-40 Character Item Number 41-43 Numeric 0 Quantity 44-45 Numeric 0 Item Number (Sample Data) 106 108 307 405 457 688

  26. Options: (1) Use a series of six decisions to determine whether the ordered item is valid (2) Create an array that holds the list of valid item numbers Declare and Initialize validItem Array (Figure 8-24, pg 305) num validItem[1] = 106 num validItem[2] = 108 num validItem[3] = 307 num validItem[4] = 405 num validItem[5] = 457 num validItem[6] = 688

  27. Using a Flag 1. The technique for verifying that an item number exists involves setting a subscript to 1 and setting a Flag variable to indicate that you have not yet determined whether the customer’s order is valid. 2. A Flag is a variable that you set to indicate a true or false state. 3. Typically, a variable is called a Flag when its only purpose is to tell you whether some event has occurred.

  28. Using Parallel Arrays Consider modifying the mail-order company program so that it does more than simply verify that the item exists. You also want to determine the price of the ordered item, multiply that price by quantity ordered, and print a bill.

  29. Parallel Array – each element in one array is associated with the element in the same relative position in the other array; the same Subscript can be used for each individual array. Declare and Initialize validItem Array (Figure 8-28, pg 308) num validItem[1] = 106 num validItem[2] = 108 num validItem[3] = 307 num validItem[4] = 405 num validItem[5] = 457 num validItem[6] = 688 Declare and Initialize validItemPrice Array (Figure 8-28, pg 308) num validItemPrice[1] = 0.59 num validItemPrice[2] = 0.99 num validItemPrice[3] = 4.50 num validItemPrice[4] = 15.99 num validItemPrice[4] = 17.50 num validItemPrice[6] = 39.00

  30. Remaining Within Array Bounds The getPrice( ) module in Figure 8-29 is not perfect. Why? The logic makes one dangerous assumption; that every customer will order a valid item number. Out of Bounds – when you use a subscript that is not within the range of acceptable subscripts.

  31. How Do Programming Languages Handle Out of Bounds? 1. Some programming languages will stop execution of the program and issue an error message. 2. Other programming languages will not issue an error message but will continue to search through computer memory beyond the end of the array. See Figure 8-30, page 311 A good program should be able to handle the mistake and not allow the subscript to go out of bounds.

  32. Improving Search Efficiency Usingan Early Exit The mail-order program is still a little inefficient in that if customers order item 006 and 008 on a regular basis, their price is found on the first or second pass through the loop. Early Exit – leaving a loop as soon as a match is found. See Figure 8-31, page 313

  33. Searching an Array for a Range Match Suppose the mail-order company decides to offer quantity discounts based on the number of items ordered as indicated in the table below:

  34. Range of Values – any set of contiguous values, for example 1-5. Options: (1) Set up an array with as many elements as any customer might ever order and store the appropriate discount for each possible number (See Figure 8-34) This Approach has Three Drawbacks: • it requires a very large array that uses a lot of memory • you must store the same value repeatedly • where do you stop adding array elements?

  35. (2) Create four discount array elements, one for each of the possible discount rates (See Figure 8-35) num discount[1] = 0 num discount[2] = .10 num discount[3] = .15 num discount[4] = .25

  36. Create a parallel array discountRange to search through the appropriate level for the discount. Incorrect Initialization of discountRange array num discountRange[1] = 1 through 9 num discountRange[2] = 10 through 24 num discountRange[3] = 25 through 48 num discountRange[4] = 49 and higher An array element can hold 1 or 9 but it cannot hold every value 1 through 9.

More Related