Although the value of a variable may change during execution of a program, in all our programs so far, a single value has been associated with each variable name at any given time. In this chapter, we will discuss the concept of an array—a collection of variables of the same type and referenced by the same name. We will discuss one-dimensional arrays (lists) at length and focus briefly on twodimensional arrays (tables). You will learn how to set up and use arrays to accomplish various tasks.
After reading this chapter, you will be able to do the following: Declare and use one-dimensional arrays [Section 6.1] Manipulate parallel arrays [Section 6.1] Use the serial search technique to search an array for a specified element [Section 6.2] Use the bubble sort technique to sort an array into a specified order [Section 6.2] Use the binary search procedure for locating an item in an array [Section 6.3] Use the selection sort procedure for sorting an array [Section 6.3] Represent character strings as arrays [Section 6.4] Declare and use two-dimensional arrays [Section 6.5]
6
ISBN 1-256-14455-X
285
Prelude to Programming: Concepts and Design, Fifth Edition, by Stewart Venit and Elizabeth Drake. Published by Addison-Wesley. Copyright © 2011 by Pearson Education, Inc.
286
Chapter 6
Arrays: Lists and Tables
In the Everyday World
Arrays
Chances are that you frequently use lists in your daily life. The following is a common example:
Shopping List
1. 2. 3. 4.
Milk Bread Eggs Butter
Or if you’ve ever done a home improvement project, you might have developed a list such as the following:
Tools Required List
1. Hammer 2. Saw 3. Screwdriver
If you write individual items on separate random pieces of paper, you might get them confused, and end up going to the grocery store for a saw. By presenting a convenient method of organizing and separating your data, a list prevents this from happening. Sometimes a single list