C - Program - 2e - Chapter06.pdf
(
1009 KB
)
Pobierz
6
Arrays
CHAPTER OBJECTIVES
Introduce the concept of an array—which is a list of variables
with the same name and requires an index value.
KEY TERMS AND CONCEPTS
array
array dimension
array index
array pointers
arrays and functions
atoi,atof
functions
character string
C-string
element
filling arrays from data files
ifstream
multidimensional array
null character
null-terminated string
ofstream
out of bounds array
single-dimensional array
zero-indexed
Demonstrate how the C++ language automatically creates a
pointer to any array that is declared.
Present single (one-dimensional) and multiply dimensioned
(two-dimensional, three-dimensional, etc.) array concepts.
Illustrate how arrays are passed and used in functions.
Explore the problems of an array that is out of bounds in a C++
program.
Explain how to read data from a data file, a particularly useful
tool when working with arrays.
Present example programs that read data from a file into an
array and then pass the array to functions.
KEYWORDS AND OPERATORS
array index [ ]
Run Faster! Jump Higher!
O
ne part of writing software is designing the data variables to represent
accurately the situation the program models. The software may be a
computer game, an accounting program, an engineering data analysis
package or drivers for a hardware device. Whatever the application, it is impor-
tant to spend time during the program design phase thinking about what vari-
ables and their data types are needed.
In the previous chapters, we declared variables so that each one provided
a location for storing one value. We had variables such as age, name, sum, and
count. We asked the user his name and age, calculated PI and weekly pay val-
ues. In each case, we had one variable for each data value. Your work built up
your confidence using different variable types. Now we raise the bar and say,
“Run faster! Jump higher!”
In this chapter, we expand our C++ knowledge and learn how to declare
a single variable that contains a list of data values of the same type. These
new data types should be grouped logically i.e., they should relate naturally to
each other. For example, you may declare a single variable that is actually a
list of phone bills for one year. It’s time to run faster, jump higher, and expand
your C++ skills.
6.1
Using Single Data Variables
Let’s start with a programming problem that shows how the ability to create a
single variable containing a list of values can simplify life. Assume that you need
to write a program that totals and averages the phone bills for a year, starting in
January and ending with December. You need twelve variables—one for each
month in the year—and you need to ask the user to enter these twelve values.
Your program calculates and reports the average value. (Eventually it will be
nice to have the program read the numbers from a data file instead of entering
the data by hand. We will learn how to read data files later in this chapter.)
First, we must name our twelve variables. How about using abbreviations for
the months as variable names to keep track of the twelve months? Then we ask for
the numbers and calculate the average cost.
293
294
❚
Chapter 6
Arrays
//Program 6-Incomplete program for finding the yearly total and
//average monthly phone bill.
#include <iostream>
using namespace std;
int main()
{
// Declare 12 individual variables
float jan, feb, mar, apr, may, jun;
float jul, aug, sept, oct, nov, dec;
float ave, yearSum;
// Obtain monthly billing information
cout << "\n Please enter your bill for January:";
cin >> jan;
cout << "\n Please enter your bill for February:";
cin >> feb;
cout << "\n Please enter your bill for March:";
cin >> mar;
// Program needs to ask for values for Apr to Dec here
// This is left as an exercise for the reader. ;-)
// Now average
sum = jan + feb + mar + apr + may + jun + jul
+ aug + sept + oct + nov + dec;
ave = sum/12.0;
cout << "\n Total yearly phone cost is $" << sum
<< "\n Average monthly phone bill is $"
<< ave << endl;
return 0;
}
array
list of variables of the
same data type ref-
erenced with a single
name
Writing a program in this manner is enough to drive anyone crazy. We will need
twelve input statements. Then the average calculation takes three lines. Can you
imagine what a hassle it would be to write out the twelve individual bills? There
must be a better way to do this. Yes, there is. We will use an
array
.
6.2
Array Fundamentals
C++ allows the programmer to declare an
array variable
that groups together
variables of the same data type, and references to this group of values can be made
with a single name. Each array member or
element
is accessed via the array name
and the
array index
. An array index is an integer value. The general format for an
array declaration is:
dataType arrayName[ size ];
where
dataType
is
float
,
int
,
double
, etc., the
arrayName
is the variable name for
the array, and
size
is an integer that represents how many variables are in this array.
For the phone bills program, we declare an array of twelve floating point values:
float phone_bills[12];
array variable
a variable in C++
that contains a num-
ber of elements of
the same type, refer-
enced with same
name
element
member of an array
array index
the integer value
that references a
specific element or
member of an array
295
❚
Section 6.2
Array Fundamentals
The size is often referred to as the array dimension. When a programmer
creates a list using one dimension (one size) value, as we did with
phone_bills
,
it is referred to as a
single-dimensional array
and can be thought of as a single
list or as a row of values. These values are stored contiguously in memory.
Figure 6-1 illustrates the
phone_bills
array. It is useful to visualize an array
as a group of boxes. Each box represents a separate variable and each box has its
own name. The array index is used to access the individual elements in the array.
For example, when we assign the values into each element, we must use the array
name and an integer index. This combination of array name plus index is how we
refer to that specific variable location in memory.
It is possible to make arrays in C++ of any data type or class. For example,
here are four more array declaration statements:
single-dimensional
array
an array that repre-
sents a single list or
column of values
int numbers[1000];
// array of 1000 integers, named numbers
double rays[200];
// array of 200 double variables, named rays
string students[25];
// array of 25 strings, named students
char name[25];
// array of 25 characters
The last declaration (
char name[25];
) is an array of characters known as a
null-terminated character string
.This name array is designed to hold up to 24 in-
dividual letters/characters with the 25
th
character being a null (a null is ASCII
zero). These character strings or character arrays are also referred to as
C-strings
,
and were used in the C language to handle textual data in programs before the
C++ string class was invented. (Remember that the C language was in use by the
late 1970s and C++ didn’t come into existence until the late 1990s.) The C-string
was widely used, and is commonly found in C and C++ code today. We’ll cover it
later in detail in this chapter.
null-terminated
character string or
C-string
a character array
(C-string) that has a
null character (zero)
at the end of the
pertinent data
int main()
{
phone_bills[0]
float phone_bills[12];
phone_bills[1]
phone_bills[2]
:
Each box represents one element
of the array.
.
.
.
:
:
phone_bills[11]
Array
name
Index
Figure 6-1
A single-dimensional
array.
Think of a one-dimensional array as a column of boxes — each
box is referred to with name
integer index.
296
❚
Chapter 6
Arrays
Arrays in C++ are Zero Indexed
C++ arrays are referred to as
zero indexed
, which means that the array elements
(boxes in Figure 6-1) are numbered starting with zero,
not
one! The name of the
first element of any array has zero as the first index, and the last element’s name
is the size index value. In the phone bill array, the first element (box) is
phone_bills[0]
and the last element is
phone_bills[11]
. Recall that a C++
string object’s first character and a C++ vector’s first element is indexed at 0, too.
Some programming languages, such as FORTRAN, allow the programmer to
specify the starting array index. C++ does not allow this choice. Some beginning C++
programmers want to add an additional array element to the declaration and then
ignore the first (index of zero) array element to make coding “easier.” This technique
is not recommended. All arrays in C++ have the first index value of zero, and the last
element is one less than the size. Do not create your own indexing scheme!
zero-indexed:
when the first ele-
ment of an array is
referenced using a
zero
[0]
-1
for
Loops and Arrays and the Phone Bills Program
When writing software with arrays, the
for
loop is the programmer’s best friend.
The
for
loop provides an efficient method for going through (traversing) an array.
The index of the loop is used not only as a counter for the loop, it can also be used
as the index value for the array. If you are not comfortable writing
for
loops, go
back to Chapter 3, reread the
for
loop section, and look at the practice sample
programs.
The Phone Bills program can be written with a
for
loop that makes coding
much easier. The loop index is used to access each element of our phone bill array.
Program 6-1 asks the user to enter the bill amounts for months 1 to 12. Figure 6-2 illus-
trates how the
for
loop index variable is used to access the array elements. Figure 6-3
// Obtain monthly billing information
for(i = 0; i < 12; ++i)
{
cout << "\n Enter bill for month # " << i + 1<< "$";
cin >> phone_bills[i];
}
45.14
phone_bills[0]
45.14
phone_bills[1]
47.72
phone_bills[2]
The first time this loop runs, i = 0.
It asks the user for month number 1 (i + 1 = 0 + 1 = 1).
The user's value (i.e., 45.14) is placed in phone_bills[0].
:
.
.
.
:
The second time this loop runs, i = 1.
It asks the user for month number 2.
The value the user enters (i.e., 45.14) is placed in phone_bills[1].
:
The last time this loop runs, i = 11.
It asks the user for month number 12.
The value the user enters (i.e., 48.99) is placed in phone_bills[11].
48.99
phone_bills[11]
Figure 6-2
The
for
loop is a convenient tool for accessing array elements.
Plik z chomika:
Januszek66
Inne pliki z tego folderu:
Back Seat_ A Mumbai Tale - Aditya Kripalani.mobi
(755 KB)
Brief Wondrous Life of Oscar Wao, The - Junot Diaz.opf
(3 KB)
Don't Make Me Think, Revisited_ - Steve Krug.mobi
(9256 KB)
M. T. Anderson - Norumbegan 03 - The Empire of Gut and Bone # (v5.0).epub
(2209 KB)
M. T. Anderson - Norumbegan 02 - The Suburb Beyond the Stars # (v5.0).epub
(2105 KB)
Inne foldery tego chomika:
Dokumenty
Galeria
LUDLUM ROBERT
Midi - Kar
Mszał Rzymski PL
Zgłoś jeśli
naruszono regulamin