Programming Abstractions in C++
Programming Abstractions in C++
Abstractions in C++
Eric S. Roberts and Julie Zelenski
This course reader has had an interesting evolutionary history that in some ways mirrors
the genesis of the C++ language itself. Just as Bjarne Stroustup’s first version of C++
was implemented on top of a C language base, this reader began its life as Eric Roberts’s
textbook Programming Abstractions in C (Addison-Wesley, 1998). In 2002-03, Julie
Zelenski updated it for use with the C++ programming language, which we began using
in CS106B and CS106X during that year.
Although the revised text worked fairly well at the outset, CS106B and CS106X have
evolved in recent years so that their structure no longer tracks the organization of the
book. This year, we’re engaged in the process of rewriting the book so that students in
these courses can use it as both a tutorial and a reference. As always, that process takes a
considerable amount to time, and there are likely to be some problems as we update the
reader. At the same time, we’re convinced that the material in CS106B and CS106X is
tremendously exciting and will be able to carry us through a quarter or two of instability,
and we will end up with an even better course in the future.
We want to thank our colleagues at Stanford, several generations of section leaders (with
special thanks to Dan Bentley and Keith Schwarz), and so many students over the
years—all of whom have helped make it so exciting to teach this wonderful material.
Programming Abstractions in C++
Chapter 1. An Overview of C++ 1
1.1 What is C++? 2
The object-oriented paradigm; The compilation process
1.2 The structure of a C++ program 5
Comments; Library inclusions; Program-level definitions; Function prototypes;
The main program; Function definitions
1.3 Variables, values, and types 9
Naming conventions; Local and global variables; The concept of a data type;
Integer types; Floating-point types; Text types; Boolean type; Simple input and
output
1.4 Expressions 16
Precedence and associativity; Mixing types in an expression; Integer division and
the remainder operator; Type casts; The assignment operator; Increment and
decrement operators; Boolean operators
1.5 Statements 24
Simple statements; Blocks; The if statement; The switch statement; The while
statement; The for statement
1.6 Functions 32
Returning results from functions; Function definitions and prototypes; The
mechanics of the function-calling process; Passing parameters by reference
Summary 38
Review questions 39
Programming exercises 41
ii
Summary 74
Review questions 74
Programming exercises 77
iii
Summary 163
Review questions 164
Programming exercises 165
iv
Chapter 8. Algorithmic analysis 277
8.1 The sorting problem 278
The selection sort algorithm; Empirical measurements of performance; Analyzing
the performance of selection sort
8.2 Computational complexity and big-O notation 282
Big-O notation; Standard simplifications of big-O; Predicting computational
complexity from code structure; Worst-case versus average-case complexity; A
formal definition of big-O
8.3 Recursion to the rescue 288
The power of divide-and-conquer strategies; Merging two vectors; The merge sort
algorithm; The computational complexity of merge sort; Comparing N 2 and N log
N performance
8.4 Standard complexity classes 294
8.5 The Quicksort algorithm 296
Partitioning the vector; Analyzing the performance of Quicksort
8.6 Mathematical induction 301
Summary 304
Review questions 305
Programming exercises 307
v
10.5 Implementing the editor using linked lists 357
The concept of a linked list; Designing a linked-list data structure; Using a linked
list to represent the buffer; Insertion into a linked-list buffer; Deletion in a linked-
list buffer; Cursor motion in the linked-list representation; Linked-list idioms;
Completing the buffer implementation; Computational complexity of the linked-
list buffer; Doubly linked lists; Time-space tradeoffs
Summary 371
Review questions 372
Programming exercises 373
vi
13.2 Binary search trees 459
The underlying motivation for using binary search trees; Finding nodes in a
binary search tree; Inserting new nodes in a binary search tree; Tree traversals
13.3 Balanced trees 466
Tree-balancing strategies; Illustrating the AVL idea; Single rotations; Double
rotations; Implementing the AVL algorithm
13.4 Defining a general interface for binary search trees 477
Allowing the client to define the node data; Generalizing the types used for keys;
Removing nodes; Implementing the binary search tree package; Implementing the
map.h interface using binary trees; Using the static keyword
Summary 488
Review questions 489
Programming exercises 492
vii
Chapter 16. Graphs 563
16.1 The structure of a graph 564
Directed and undirected graphs; Paths and cycles; Connectivity
16.2 Implementation strategies for graphs 568
Representing connections using an adjacency list; Representing connections using
an adjacency matrix; Representing connections using a set of arcs
16.3 Designing a low-level graph abstraction 571
Using the low-level graph.h interface
16.4 Graph traversals 575
Depth-first search; Breadth-first search
16.5 Defining a Graph class 580
Using classes for graphs, nodes, and arcs; Adopting an intermediate strategy
16.6 Finding minimum paths 589
16.7 An efficient implementation of priority queues 593
Summary 596
Review questions 597
Programming exercises 599
Index 657
viii
Chapter 1
An Overview of C++
In Lewis Carroll’s Alice’s Adventures in Wonderland, the King asks the White Rabbit to
“begin at the beginning and go on till you come to the end: then stop.” Good advice, but
only if you’re starting from the beginning. This book is designed for a second course in
computer science and therefore assumes that you have already begun your study of
programming. At the same time, because first courses vary considerably in what they
cover, it is difficult to rely on any specific material. Some of you, for example, will
already have experience programming in C or C++. Many of you, however, are coming
from a first course taught in some other language.
Because of this wide disparity in background, the best approach is to adopt the King’s
advice and begin at the beginning. The first three chapters in this text therefore move
quickly through the material I consider to be essential background for the later chapters.
Chapters 1 and 2 discuss C++ in general and may be skimmed if you’ve had experience
with C++. Chapter 3 discusses standard interfaces and some interfaces particular to this
text. By the end of these three chapters, you will be up to speed on the fundamentals of
C++ programming.
As Figure 1-1 illustrates, C++ represents the coming together of two branches in the
evolution of programming languages. One of its ancestors is a language called C, which
was designed at Bell Laboratories by Dennis Ritchie in 1972 and then later revised and
standardized by the American National Standards Institute (ANSI) in 1989. But C++ also
descends from another line of languages that have dramatically changed the nature of
modern programming.
Unfortunately, the specific details of the compilation process vary considerably from
one machine to another. There is no way that a general textbook like this can tell you
exactly what commands you should use to run a program on your system. Because those
commands are different for each system, you need to consult the documentation that
comes with the compiler you are using on that machine. The good news, however, is that
the C++ programs themselves will look the same. One of the principal advantages of
programming in a higher-level language like C++ is that doing so often allows you to
ignore the particular characteristics of the hardware and create programs that will run on
many different machines.
#define N 10
main() compiler
{
int i;
executable file
for (i=1; i<=N; i++) { 0100100101011001000
printf("%d\n", i); 1000010100011101011
} 0110100111010101100
} 1001011010110001011
0100100101001011011
0101101011010100101
linker
other object
files/libraries
1001011010110001011
0100100101001011011
0101101011010100101
An Overview of C++ –5–
PowerTable
| 2 | N
N | N | 2
----+-----+------
0 | 0 | 1
1 | 1 | 2
2 | 4 | 4
3 | 9 | 8
4 | 16 | 16
5 | 25 | 32
6 | 36 | 64
7 | 49 | 128
8 | 64 | 256
9 | 81 | 512
10 | 100 | 1024
11 | 121 | 2048
12 | 144 | 4096
As the annotations in Figure 1-3 indicate, the powertab.cpp program is divided into
several components, which are discussed in the next few sections.
Comments
Much of the text in Figure 1-3 consists of English-language comments. A comment is
text that is ignored by the compiler but which nonetheless conveys information to other
programmers. A comment consists of text enclosed between the markers /* and */ and
may continue over several lines. Alternatively, a single-line comment is begun by the
marker // and continues until the end of the line. The powertab.cpp program includes a
comment at the beginning that describes the operation of the program as a whole, one
before the definition of the RaiseIntToPower function that describes what it does, and a
couple of one-line comments that act very much like section headings in English text.
Library inclusions
The lines beginning with #include such as
#include "genlib.h"
#include <iostream>
#include <iomanip>
indicate that the compiler should read in definitions from a header file. The inclusion of
a header file indicates that the program uses facilities from a library, which is a
collection of prewritten tools that perform a set of useful operations. The different
punctuation in these #include lines reflects the fact that the libraries come from different
sources. The angle brackets are used to specify a system library, such as the standard
input/output stream library (iostream) or the stream manipuator library (iomanip) that is
supplied along with C++. The quotation marks are used for private libraries, including
the general library (genlib), which was designed for use with the programs in this text.
Every program in this book will include at least this library most will require other
libraries as well and must contain an #include line for each one.
An Overview of C++ –6–
/*
* File: powertab.cpp
* ------------------ program
* This program generates a table comparing values comment
* of the functions n^2 and 2^n.
*/
/*
* Constants section
* ---------
comment
* LOWER_LIMIT -- Starting value for the table
* UPPER_LIMIT -- Final value for the table
*/
constant
const int LOWER_LIMIT = 0;
const int UPPER_LIMIT = 12; definitions
int main() {
cout << " | 2 | N" << endl;
cout << " N | N | 2" << endl;
cout << "----+-----+------" << endl; main
for (int n = LOWER_LIMIT; n <= UPPER_LIMIT; n++) {
program
cout << setw(3) << n << " |" ;
cout << setw(4) << RaiseIntToPower(n, 2) << " |" ;
cout << setw(5) << RaiseIntToPower(2, n) << endl;
}
return 0;
}
/*
* Function: RaiseIntToPower
* Usage: p = RaiseIntToPower(n, k); function
* --------------------------------- comment
* This function returns n to the kth power.
*/
Program-level definitions
After the #include lines for the libraries, many programs define constants that apply to
the program as a whole. In the powertab.cpp program, the following lines
const int LOWER_LIMIT = 0;
const int UPPER_LIMIT = 12;
which defines the constant name to be of type type and initialized to value. A constant must
be initialized when it is defined and once initialized, it cannot be assigned a new value or
changed in any way. Attempting to do so will result in a compiler error. After a named
constant is defined, it is available to be used anywhere in the rest of the program. For
example, after encountering the line
const double PI = 3.14159265;
any subsequent use of the name PI refers to the constant value 3.14159265.
Giving symbolic names to constants has several important advantages in terms of
programming style. First, the descriptive names give readers of the program a better
sense of what the constant value means. Second, centralizing such definitions at the top
of the file makes it easier to change the value associated with a name. For example, all
you need to do to change the limits used for the table in the powertab.cpp program is
change the values of the constants. And lastly, a const declaration protects from the
value from any unintended modification.
In addition to constants, programs often define new data types in this section of the
source file, as you will see in Chapter 2.
Function prototypes
Computation in a C++ program is carried out in the context of functions. A function is a
unit of code that (1) performs a specific operation and (2) is identified by name. The
powertab.cpp program contains two functions—main and RaiseIntToPower—which
are described in more detail in the next two sections. The line
You must provide the declaration or definition of each function before making any
calls to that function. C++ requires this in order for the compiler to check whether calls to
functions are compatible with the corresponding prototypes and can therefore aid you in
the process of finding errors in your code.
An Overview of C++ –8–
The first three statements of the main function in the powertab.cpp program are
sending information to the cout stream to display output on the screen. A few useful
notes about streams are included in the section on “Simple input and output” later in this
chapter and more features are explored in detail in Chapter 3. At this point, you need to
have an informal sense of how to display output to understand any programming example
that communicates results to the user. In its simplest form, you use the insertion operator
<< to put information into the output stream cout . If you insert a string enclosed in
double quotes, it will display that string on the console. You must indicate explicitly that
you want to move on to the next line by inserting the stream manipulator endl. Thus,
the first three lines in main display the header for the table.
The rest of the function main consists of the following code, which is responsible for
displaying the table itself:
for (int n = LOWER_LIMIT; n <= UPPER_LIMIT; n++) {
cout << setw(3) << n << " |" ;
cout << setw(4) << RaiseIntToPower(n, 2) << " |" ;
cout << setw(5) << RaiseIntToPower(2, n) << endl;
}
This code is an example a for loop, which is used to specify repetition. In this case, the
for statement indicates that the body of the loop should be repeated for each of the
values of n from LOWER_LIMIT to UPPER_LIMIT. A section on the detailed structure of
the for loop appears later in the chapter, but the example shown here represents a
common idiomatic pattern that you can use to count between any specified limits.
The body of the loop illustrates an important new feature: the ability to include values
as part of the output display. Rather than just displaying fixed strings, we can display
numeric values and computed results. We can also use stream manipulators to format the
output. Let’s examine the first statement in the body of the loop:
cout << setw(3) << n << " |" ;
This line will display the current value of the variable n followed by a string
containing a space and a vertical bar. The setw(3) that is inserted into the stream just
before n indicates that the stream should format the next value in a field that is three
characters wide. Similarly, the next statement prints the formatted result taken from the
expression RaiseIntToPower(n, 2) . Obtaining the value of the expression requires
making a call on the RaiseIntToPower function, which is discussed in the following
section. The value that RaiseIntToPower returns is displayed as part of the output. So
is the result of the call to RaiseIntToPower(2, n), which supplies the value for the third
column in the table.
The last statement in main is
return 0;
which indicates that the function result is 0. The return value from the main function is
used to communicate the success or failure of the entire program. By convention, a result
of 0 indicates success.
An Overview of C++ –9–
Function definitions
Because large programs are difficult to understand in their entirety, most programs are
broken down into several smaller functions, each of which is easier to understand. In the
powertab.cpp program, the function RaiseIntToPower is responsible for raising an
integer to a power—an operation that is not built into C++ and must therefore be defined
explicitly.
The first line of RaiseIntToPower is the variable declaration
int result;
which introduces a new variable named result capable of holding values of type int,
the standard type used to represent integers. The syntax of variable declarations is
discussed in more detail in the section on “Variables, values, and types” later in this
chapter. For now, all you need to know is that this declaration creates space for an
integer variable that you can then use in the body of the function.
The next line in the body of RaiseIntToPower is
result = 1;
This statement is a simple example of an assignment statement, which sets the variable
on the left of the equal sign to the value of the expression on the right. In this case, the
statement sets the variable result to the constant 1. The next statement in the function is
a for loop that executes its body k times. The repeated code consists of the line
result *= n;
which is a C++ shorthand for the English sentence “Multiply result by n.” Because the
function initializes the value of result to 1 and then multiplies result by n a total of k
times, the variable result ends up with the value nk.
The last statement in RaiseIntToPower is
return result;
which indicates that the function should return result as the value of the function.
where type indicates the data type and namelist is a list of variable names separated by
commas. For example, the function RaiseIntToPower in the powertab.cpp program
contains the line
int result;
is a shorthand for the following code, in which the declaration and assignment are
separate:
int result;
result = 0;
Naming conventions
The names used for variables, functions, types, constants, and so forth are collectively
known as identifiers. In C++, the rules for identifier formation are
1. The name must start with a letter or the underscore character (_).
2. All other characters in the name must be letters, digits, or the underscore. No spaces
or other special characters are permitted in names.
3. The name must not be one of the reserved keywords listed in Table 1-1
Uppercase and lowercase letters appearing in an identifier are considered to be different.
Thus, the name ABC is not the same as the name abc. Identifiers can be of any length, but
C++ compilers are not required to consider any more than the first 31 characters in
determining whether two names are identical. Implementations may impose additional
restrictions on identifiers that are shared between modules.
You can improve your programming style by adopting conventions for identifiers that
help readers identify their function. In this text, names of variables and data types begin
An Overview of C++ – 11 –
with a lowercase letter, such as n1, total, or string. By contrast, function names, such
as RaiseIntToPower, usually begin with an uppercase letter. Moreover, whenever a
name consists of several English words run together, the first letter in each word after the
first is capitalized to make the name easier to read. By tradition, constant names, such as
LOWER_LIMIT are written entirely in uppercase, with underscores between the words.
Integer types
Although the concept of an integer seems like a simple one, C++ actually includes several
different data types for representing integer values. In most cases, all you need to know
is the type int, which corresponds to the standard representation of an integer on the
computer system you are using. In certain cases, however, you need to be more careful.
Like all data, values of type int are stored internally in storage units that have a limited
capacity. Those values therefore have a maximum size, which limits the range of
integers you can use. To get around this problem, C++ defines three integer types—
short, int, and long—distinguished from each other by the size of their domains.
Unfortunately, the language definition for C++ does not specify an exact range for
these three types. As a result, the range for the different integer types depends on the
machine and the compiler you’re using. On many personal computers, the maximum
value of type int is 32,767, which is rather small by computational standards. If you
wanted, for example, to perform a calculation involving the number of seconds in a year,
you could not use type int on those machines, because that value (31,536,000) is
considerably larger than the largest available value of type int. The only properties you
can rely on are the following:
• The internal size of an integer cannot decrease as you move from short to int to
long. A compiler designer for C++ could, for example, decide to make short and int
the same size but could not make int smaller than short.
• The maximum value of type int must be at least 32,767 (215–1).
• The maximum value of type long must be at least 2,147,483,647 (231–1).
The designers of C++ could have chosen to define the allowable range of type int
more precisely. For example, they could have declared—as the designers of Java did—
that the maximum value of type int would be 231–1 on every machine. Had they done
so, it would be easier to move a program from one system to another and have it behave
in the same way. The ability to move a program between different machines is called
portability, which is an important consideration in the design of a programming
language.
In C++, each of the integer types int , long , and short may be preceded by the
keyword unsigned . Adding u n s i g n e d creates a new data type in which only
nonnegative values are allowed. Because unsigned variables do not need to represent
negative values, declaring a variable to be one of the unsigned types allows it to hold
twice as many positive values. For example, if the maximum value of type int is 32,767,
the maximum value of type unsigned int will be 65,535. C++ allows the type unsigned
int to be abbreviated to unsigned , and most programmers who use this type tend to
follow this practice. Sometimes variables intended to store sizes are declared as
unsigned, because a size will always be nonnegative.
An integer constant is ordinarily written as a string of digits representing a number in
base 10. If the number begins with the digit 0, however, the compiler interprets the value
as an octal (base 8) integer. Thus, the constant 040 is taken to be in octal and represents
the decimal number 32. If you prefix a numeric constant with the characters 0x, the
compiler interprets that number as hexadecimal (base 16). Thus, the constant 0xFF is
equivalent to the decimal constant 255. You can explicitly indicate that an integer
constant is of type long by adding the letter L at the end of the digit string. Thus, the
constant 0L is equal to 0, but the value is explicitly of type long. Similarly, if you use the
letter U as a suffix, the constant is taken to be unsigned.
An Overview of C++ – 13 –
Floating-point types
Numbers that include a decimal fraction are called floating-point numbers, which are
used to approximate real numbers in mathematics. As with integers, C++ defines three
different floating-point types: float, double, and long double. Although ANSI C++
does not specify the exact representation of these types, the way to think about the
difference is that types that appear later in the list allow numbers to be represented with
greater precision but require more memory space. Unless you are doing exacting
scientific calculation, the differences between these types will not matter a great deal. In
keeping with a common convention among C++ programmers, this text uses the type
double as its standard floating-point type.
Floating-point constants in C++ are written with a decimal point. Thus, if 2.0 appears
in a program, the number is represented internally as a floating-point value if the
programmer had written 2, this value would be an integer. Floating-point values can also
be written in a special programmer’s style of scientific notation, in which the value is
represented as a floating-point number multiplied by a integral power of 10. To write a
number using this style, you write a floating-point number in standard notation, followed
immediately by the letter E and an integer exponent, optionally preceded by a + or - sign.
For example, the speed of light in meters per second can be written in C++ as
2.9979E+8
Text types
In the early days, computers were designed to work only with numeric data and were
sometimes called number crunchers as a result. Modern computers, however, work less
with numeric data than they do with text data, that is, any information composed of
individual characters that appear on the keyboard and the screen. The ability of modern
computers to process text data has led to the development of word processing systems,
on-line reference libraries, electronic mail, and a wide variety of other useful
applications.
The most primitive elements of text data are individual characters, which are
represented in C++ using the predefined data type char. The domain of type char is the
set of symbols that can be displayed on the screen or typed on the keyboard: the letters,
digits, punctuation marks, spacebar, Return key, and so forth. Internally, these values are
represented inside the computer by assigning each character a numeric code. In most
implementations of C++, the coding system used to represent characters is called ASCII,
which stands for the American Standard Code for Information Interchange. The numeric
values of the characters in the ASCII set are shown in Table 1-2.
Although it is important to know that characters are represented internally using a
numeric code, it is not generally useful to know what numeric value corresponds to a
particular character. When you type the letter A, the hardware logic built into the
keyboard automatically translates that character into the ASCII code 65, which is then
sent to the computer. Similarly, when the computer sends the ASCII code 65 to the
screen, the letter A appears.
You can write a character constant in C++ by enclosing the character in single quotes.
Thus, the constant 'A' represents the internal code of the uppercase letter A. In addition
to the standard characters, C++ allows you to write special characters in a two-character
form beginning with a backward slash (\). These two-character combinations are called
An Overview of C++ – 14 –
escape sequences and you can see several listed in the first few rows of Table 1-2. A
few of the more commonly used escape sequences are '\n' the newline character,'\t'
the tab character, and '\\' the backslash character.
Characters are most useful when they are collected together into sequential units. In
programming, a sequence of characters is called a string. Strings make it possible to
display informational messages on the screen. You have already seen strings in the
sample program powertab.cpp. It is important, however, to recognize that strings are
data and that they can be manipulated and stored in much the same way that numbers can.
The standard C++ library defines a string type and operations that manipulate strings.
The details of type string are not important at this point strings are considered in more
detail in Chapter 3. In this chapter, strings are treated as atomic values and used
exclusively to specify text that is displayed directly on the display screen.
You write string constants in C++ by enclosing the characters contained within the
string in double quotes. C++ supports the same escape sequences for strings as for
characters. If two or more string constants appear consecutively in a program, the
compiler concatenates them together. The most important implication of this rule is that
you can break a long string over several lines so that it doesn’t end up running past the
right margin of your program.
Boolean type
In the programs you write, it is often necessary to test a particular condition that affects
the subsequent behavior of your code. Typically, that condition is specified using an
expression whose value is either true or false. This data type—for which the only legal
values are true and false—is called Boolean data, after the mathematician George Boole,
who developed an algebraic approach for working with such values.
In C++, the Boolean type is called bool and its domain consists of the values true and
false. You can declare variables of type bool and manipulate them in the same way as
other data objects.
An Overview of C++ – 15 –
#include "simpio.h"
The simpio library defines the functions GetInteger , GetLong , GetReal , and
GetLine, which wait for the user to enter a line at the keyboard and then return a value of
type int, long, double, and string, respectively. To let the user know what value is
expected, it is conventional to display a message to the user, which is called a prompt,
before calling the input function. Thus, if you need to request a value from the user for
the integer variable n, you would typically use a pair of statements like this:
cout << "Enter an integer: ";
n = GetInteger();
Output operations in this book use the insertion operator <<. The operand on the left of
the operator is a stream, such as the standard output stream cout. The operand on the
right is the data that you wish to insert into the stream. Several insertions to the same
stream can be chained together as shown here:
cout << "The result is " << val << endl;
Stream manipulators can be used to control the formatting of the output. A manipulator
is inserted into the stream ahead of the value it affects. The manipulator does not print
anything to the stream, but changes the state of the stream such that subsequent insertions
will use the requested formatting. A few of the more common stream manipulators are
shown in Table 1-3. To use these manipulators, you must include the <iomanip>
interface file in the library-inclusion section of your program.
As an example of the use of the simple I/O facilities, the following main program reads
in three floating-point values and displays their average:
int main() {
cout << "This program averages three numbers." << endl;
cout << "1st number: ";
double n1 = GetReal();
cout << "2nd number: ";
double n2 = GetReal();
cout << "3rd number: ";
double n3 = GetReal();
double average = (n1 + n2 + n3) / 3;
cout << "The average is " << average << endl;
return 0;
}
An Overview of C++ – 16 –
1.4 Expressions
Whenever you want a program to perform calculations, you need to write an expression
that specifies the necessary operations in a form similar to that used for expressions in
mathematics. For example, suppose that you wanted to solve the quadratic equation
ax2 + bx + c = 0
As you know from high-school mathematics, this equation has two solutions given by the
formula
–b ± √ b2 – 4ac
x = 2a
The first solution is obtained by using + in place of the ± symbol the second is obtained
by using – instead. In C++, you could compute the first of these solutions by writing the
following expression:
(-b + sqrt(b * b - 4 * a * c)) / (2 * a)
operand, the one that appears higher in the precedence table is applied first. Thus, in the
expression
(-b + sqrt(b * b - 4 * a * c)) / (2 * a)
Without the parentheses, the division operator would be performed first because / and *
have the same precedence and associate to the left.
automatically converts the operands to a common type by determining which of the two
operand types appears closest to the top in Table 1-5. The result of applying the
operation is always that of the arguments after any conversions are applied. This
convention ensures that the result of the computation is as precise as possible.
As an example, suppose that n is declared as an int, and x is declared as a double.
The expression
n + 1
is evaluated using integer arithmetic and produces a result of type int. The expression
x + 1
however, is evaluated by converting the integer 1 to the floating-point value 1.0 and
adding the results together using double-precision floating-point arithmetic, which results
in a value of type double.
Integer division and the remainder operator
The fact that applying an operator to two integer operands generates an integer result
leads to an interesting situation with respect to the division operator. If you write an
expression like
9 / 4
C++’s rules specify that the result of this operation must be an integer, because both
operands are of type int . When C++ evaluates this expression, it divides 9 by 4 and
discards any remainder. Thus, the value of this expression in C++ is 2, not 2.25.
If you want to compute the mathematically correct result of 9 divided by 4, at least one
of the operands must be a floating-point number. For example, the three expressions
9.0 / 4
9 / 4.0
9.0 / 4.0
each produce the floating-point value 2.25. The decimal fraction is thrown away only if
both operands are of type int. The operation of discarding a decimal fraction is called
truncation.
There is an additional arithmetic operator that computes a remainder, which is
indicated in C++ by the percent sign (%). The % operator returns the remainder when the
first operand is divided by the second, and requires that both operands be of one of the
is 1, since 4 goes into 9 twice, with 1 left over. The following are some other examples
of the % operator:
0 % 4 = 0 19 % 4 = 3
1 % 4 = 1 20 % 4 = 0
4 % 4 = 0 2001 % 4 = 1
Type casts
In C++, you can specify explicit conversion by using what is called a type cast, a unary
operator that consists of the desired type followed by the value you wish to convert in
parentheses. For example, if num and den were declared as integers, you could compute
the floating-point quotient by writing
quotient = double(num) / den;
The first step in evaluating the expression is to convert num to a double, after which the
division is performed using floating-point arithmetic as described in the section on
“Mixing types in an expression” earlier in this chapter.
As long as the conversion moves upward in the hierarchy shown in Table 1-5, the
conversion causes no loss of information. If, however, you convert a value of a more
precise type to a less precise one, some information may be lost. For example, if you use
a type cast to convert a value of type double to type int, any decimal fraction is simply
dropped. Thus, the value of the expression
int(1.9999)
is the integer 1.
the effect is that the value 1 is assigned to the variable result. In most cases, assignment
expressions of this sort appear in the context of simple statements, which are formed by
adding a semicolon after the expression, as in the line
result = 1;
that appears in the powertab.cpp program. Such statements are often called assignment
statements, although they in fact have no special status in the language definition.
The assignment operator converts the type of the value on the right-hand side so that it
matches the declared type of the variable. Thus, if the variable total is declared to be of
type double, and you write the assignment statement
total = 0;
the integer 0 is converted into a double as part of making the assignment. If n is declared
to be of type int, the assignment
n = 3.14159265;
has the effect of setting n to 3, because the value is truncated to fit in the integer variable.
Even though assignment operators usually occur in the context of simple statements,
they can also be incorporated into larger expressions, in which case the result of applying
the assignment operator is simply the value assigned. For example, the expression
z = (x = 6) + (y = 7)
has the effect of setting x to 6, y to 7, and z to 13. The parentheses are required in this
example because the = operator has a lower precedence than +. Assignments that are
written as part of larger expressions are called embedded assignments.
Although there are contexts in which embedded assignments are extremely convenient,
they often make programs more difficult to read because the assignment is easily
overlooked in the middle of a complex expression. For this reason, this text limits the use
of embedded assignments to a few special circumstances in which they seem to make the
most sense. Of these, the most important is when you want to set several variables to the
same value. C++’s definition of assignment as an operator makes it possible, instead of
writing separate assignment statements, to write a single statement like
n1 = n2 = n3 = 0;
which has the effect of setting all three variables to 0. This statement works because C++
evaluates assignment operators from right to left. The entire statement is therefore
equivalent to
n1 = (n2 = (n3 = 0));
The expression n3 = 0 is evaluated, which sets n3 to 0 and then passes 0 along as the
value of the assignment expression. That value is assigned to n2, and the result is then
assigned to n1. Statements of this sort are called multiple assignments.
As a programming convenience, C++ allows you to combine assignment with a binary
operator to produce a form called a shorthand assignment. For any binary operator op,
the statement
variable op= expression;
An Overview of C++ – 21 –
is equivalent to
variable = variable op (expression);
where the parentheses are required only if the expression contains an operator whose
precedence is lower than that of op. Thus, the statement
balance += deposit;
is a shorthand for
balance = balance + deposit;
As it happens, these operators are more intricate than the previous examples would
suggest. To begin with, each of these operators can be written in two ways. The operator
An Overview of C++ – 22 –
The first form, in which the operator follows the operand, is called the postfix form, the
second, the prefix form.
If all you do is execute the ++ operator in isolation—as you do in the context of a
separate statement or a typical for loop like those in the powertab.cpp example—the
prefix and postfix operators have precisely the same effect. You notice the difference
only if you use these operators as part of a larger expression. Then, like all operators, the
++ operator returns a value, but the value depends on where the operator is written
relative to the operand. The two cases are as follows:
x++ Calculates the value of x first, and then increments it. The value
returned to the surrounding expression is the original value before
the increment operation is performed.
++x Increments the value of x first, and then uses the new value as the
value of the ++ operation as a whole.
The -- operator behaves similarly, except that the value is decremented rather than
incremented.
You may wonder why would anyone use such an arcane feature. The ++ and - -
operators are certainly not essential. Moreover, there are not many circumstances in
which programs that embed these operators in larger expressions are demonstrably better
than those that use a simpler approach. On the other hand, ++ and -- are firmly
entrenched in the historical tradition shared by C++ programmers. They are idioms, and
programmers use them frequently. Because these operators are so common, you need to
understand them so that you can make sense of existing code.
Boolean operators
C++ defines three classes of operators that manipulate Boolean data: the relational
operators, the logical operators, and the ?: operator. The ;relational operators are used
to compare two values. C++ defines six relational operators, as follows:
== Equal
!= Not equal
> Greater than COMMON PITFALLS
< Less than When writing programs that
>= Greater than or equal to test for equality, be sure to
<= Less than or equal to use the == operator and
not the single = operator,
When you write programs that test for equality, be careful to use the which signifies assignment.
== operator, which is composed of two equal signs. A single equal This error is extremely
sign is the assignment operator. Since the double equal sign violates common and can lead to
bugs that are very difficult
conventional mathematical usage, replacing it with a single equal sign to find, because the
is a particularly common mistake. This mistake can also be very compiler cannot detect the
difficult to track down because the C++ compiler does not usually error.
catch it as an error. A single equal sign usually turns the expression
An Overview of C++ – 23 –
into an embedded assignment, which is perfectly legal in C++; it just isn’t at all what you
want.
The relational operators can be used to compare atomic data values like integers,
floating-point numbers, Boolean values, and characters. Some of the types supplied in
the libraries, such as string, also can be compared using the relational operators.
In addition to the relational operators, C++ defines three logical operators that take
Boolean operands and combine them to form other Boolean values:
! Logical not (true if the following operand is false)
&& Logical and (true if both operands are true)
|| Logical or (true if either or both operands are true)
p q p && q p || q !p
false false false false true
false true false true true
true false false true false
true true true true false
C++ interprets the && and || operators in a way that differs from the interpretation
used in many other programming languages such as Pascal. Whenever a C++ program
evaluates an expression of the form
exp1 && exp2
or
exp1 || exp2
the individual subexpressions are always evaluated from left to right, and evaluation ends
as soon as the answer can be determined. For example, if exp1 is false in the expression
involving && , there is no need to evaluate exp2 since the final answer will always be
false . Similarly, in the example using || , there is no need to evaluate the second
operand if the first operand is true. This style of evaluation, which stops as soon as the
answer is known, is called short-circuit evaluation.
The C++ programming language provides another Boolean operator that can be
extremely useful in certain situations: the ?: operator. (This operator is referred to as
question-mark colon, even though the two characters do not appear adjacent to one
another in the code.) Unlike any other operator in C++, ?: is written in two parts and
requires three operands. The general form of the operation is
(condition) ? exp1 : exp2
An Overview of C++ – 24 –
The parentheses around the condition are not technically required, but C++ programmers
often include them to emphasize the boundaries of the conditional test.
When a C++ program encounters the ?: operator, it first evaluates the condition. If the
condition turns out to be true , exp1 is evaluated and used as the value of the entire
expression if the condition is false , the value is the result of evaluating exp2 . For
example, you can use the ?: operator to assign to max either the value of x or the value of
y, whichever is greater, as follows:
max = (x > y) ? x : y;
1.5 Statements
Programs in C++ are composed of functions, which are made up in turn of statements.
As in most languages, statements in C++ fall into one of two principal classifications:
simple statements, which perform some action, and control statements, which affect
the way in which other statements are executed. The sections that follow review the
principal statement forms available in C++ and give you the fundamental tools you need
to write your own programs.
Simple statements
The most common statement in C++ is the simple statement, which consists of an
expression followed by a semicolon:
expression;
Blocks
As C++ is defined, control statements typically apply to a single statement. When you
are writing a program, you often want the effect of a particular control statement to apply
to a whole group of statements. To indicate that a sequence of statements is part of a
coherent unit, you can assemble those statements into a block, which is a collection of
statements enclosed in curly braces, as follows:
{
statement1
statement2
. . .
statementn
}
When the C++ compiler encounters a block, it treats the entire block as a single
statement. Thus, whenever the notation statement appears in a pattern for one of the
control forms, you can substitute for it either a single statement or a block. To emphasize
that they are statements as far as the compiler is concerned, blocks are sometimes referred
to as compound statements. In C++, the statements in any block may be preceded by
declarations of variables. In this text, variable declarations are introduced only in the
block that defines the body of a function.
The statements in the interior of a block are usually indented relative to the enclosing
context. The compiler ignores the indentation, but the visual effect is extremely helpful
to the human reader, because it makes the structure of the program jump out at you from
An Overview of C++ – 25 –
the format of the page. Empirical research has shown that indenting three or four spaces
at each new level makes the program structure easiest to see; the programs in this text use
four spaces for each new level. Indentation is critical to good programming, so you
should strive to develop a consistent indentation style in your programs.
The only aspect of blocks that tends to cause any confusion for new students is the role
of the semicolon. In C++, the semicolon is part of the syntax of a simple statement; it
acts as a statement terminator rather than as a statement separator. While this rule is
perfectly consistent, it can cause trouble for people who have previously been exposed to
the language Pascal, which uses a different rule. In practical terms, the differences are:
1. In C++, there is always a semicolon at the end of the last simple statement in a block.
In Pascal, the semicolon is usually not present although most compilers allow it as an
option.
2. In C++, there is never a semicolon after the closing brace of a statement block. In
Pascal, a semicolon may or may not follow the END keyword, depending on context.
The convention for using semicolons in C++ has advantages for program maintenance
and should not cause any problem once you are used to it.
The if statement
In writing a program, you will often want to check whether some condition applies and
use the result of that check to control the subsequent execution of the program. This type
of program control is called conditional execution. The easiest way to express
conditional execution in C++ is by using the if statement, which comes in two forms:
if (condition) statement
You use the first form of the if statement when your solution strategy calls for a set of
statements to be executed only if a particular Boolean condition is true. If the condition
is false, the statements that form the body of the if statement are simply skipped. You
use the second form of the if statement for situations in which the program must choose
between two independent sets of actions based on the result of a test. This statement
form is illustrated by the following program, which reads in a number and classifies it as
either even or odd.
int main() {
int n;
cout << "This program classifies a num even or odd." << endl;
cout << "Enter a number: ";
n = GetInteger();
if (n % 2 == 0) {
cout << "That number is even." << endl;
} else {
cout << "That number is odd." << endl;
}
return 0;
}
As with any control statement, the statements controlled by the if statement can be
either a single statement or a block. Even if the body of a control form is a single
An Overview of C++ – 26 –
statement, you are free to enclose it in a block if you decide that doing so improves the
readability of your code. The programs in this book enclose the body of every control
statement in a block unless the entire statement—both the control form and its body—is
so short that it fits on a single line.
The expression e is called the control expression. When the program executes a
switch statement, it evaluates the control expression and compares it against the values
c1, c 2 , and so forth,
each of which must be a constant. If one of the constants matches the
value of the control expression, the statements in the associated case clause are executed.
When the program reaches the break statement at the end of the clause, the operations
specified by that clause are complete, and the program continues with the statement that
follows the entire switch statement.
The default clause is used to specify what action occurs if none of the constants
match the value of the control expression. The default clause, however, is optional. If
none of the cases match and there is no default clause, the program simply continues on
with the next statement after the switch statement without taking any action at all. To
avoid the possibility that the program might ignore an unexpected case, it is good
programming practice to include a default clause in every switch statement unless you
are certain you have enumerated all the possibilities, even if the default clause is simply
default:
Error("Unexpected case value");
The Error function is part of the genlib library and provides a uniform way of
responding to errors. This function takes one string parameter, the error message. The
Error function does not return; after the error message is displayed, the program
terminates.
The code pattern I’ve used to illustrate the syntax of the switch statement deliberately
suggests that break statements are required at the end of each clause. In fact, C++ is
defined so that if the break statement is missing, the program starts executing statements
An Overview of C++ – 27 –
from the next clause after it finishes the selected one. While this design can be useful in
some cases, it causes many more problems than it solves. To reinforce the importance of
remembering to exit at the end of each case clause, the programs in this text always
include a break or return statement in each such clause.
The one exception to this rule is that multiple case lines specifying COMMON PITFALLS
different constants can appear together, one after another, before the
same statement group. For example, a switch statement might It is good programming
practice to include a break
include the following code: statement at the end of
every case clause within a
case 1:
switch statement. Doing
case 2:
so will help you avoid
statements
programming errors that
break;
can be extremely difficult to
which indicates that the specified statements should be executed if the find. It is also good
practice to include a
select expression is either 1 or 2. The C++ compiler treats this
default clause unless
construction as two case clauses, the first of which is empty. Because you are sure you have
the empty clause contains no break statement, a program that selects covered all the cases.
the first path simply continues on with the second clause. From a
conceptual point of view, however, you are better off if you think of
this construction as a single case clause representing two possibilities.
The operation of the switch statement is illustrated by the following function, which
computes the number of days for a given month and year:
int MonthDays(int month, int year) {
switch (month) {
case September:
case April:
case June:
case November:
return 30;
case February:
return (IsLeapYear(year)) ? 29 : 28;
default:
return 31;
}
}
The code assumes that there is a function IsLeapYear(year) which tests whether year
is a leap year and that the names of the months have been defined using constants, as
follows:
const int JANUARY = 1;
const int FEBRUARY = 2;
const int MARCH = 3;
const int APRIL = 4;
const int MAY = 5;
const int JUNE = 6;
const int JULY = 7;
const int AUGUST = 8;
const int SEPTEMBER = 9;
const int OCTOBER = 10;
const int NOVEMBER = 11;
const int DECEMBER = 12;
An Overview of C++ – 28 –
The constants in a switch statement must be of integer type or a type that behaves like
an integer. (The actual restriction is that the type must be a scalar type, which is defined
in Chapter 2.) In particular, characters are often used as case constants, as illustrated by
the following function, which tests to see if its argument is a vowel:
bool IsVowel(char ch) {
switch (ch) {
case 'A': case 'E': case 'I': case 'O': case 'U':
case 'a': case 'e': case 'i': case 'o': case 'u':
return true;
default:
return false;
}
}
1. Read in a value.
2. If the value is equal to the sentinel, exit from the loop.
3. Perform whatever processing is required for that value.
Unfortunately, there is no test you can perform at the beginning of the loop to determine
whether the loop is finished. The termination condition for the loop is reached when the
input value is equal to the sentinel; in order to check this condition, the program must
first read in some value. If the program has not yet read in a value, the termination
condition doesn’t make sense. Before the program can make any meaningful test, it must
have executed the part of the loop that reads in the input value. When a loop contains
some operations that must be performed before testing for completion, you have a
situation that programmers call the loop-and-a-half problem.
One way to solve the loop-and-a-half problem in C++ is to use the break statement,
which, in addition to its use in the switch statement, has the effect of immediately
terminating the innermost enclosing loop. By using break, it is possible to code the loop
structure for the sentinel problem in a form that follows the natural structure of the
problem:
while (true) {
Prompt user and read in a value.
if (value == sentinel) break;
Process the data value.
}
line itself seems to introduce an infinite loop because the value of the constant true can
never become false. The only way this program can exit from the loop is by executing
the break statement inside it. The loop-and-a-half strategy is illustrated by the
addlist.cpp program in Figure 1-4, which computes the sum of a list of integers
terminated by the sentinel value 0.
An Overview of C++ – 30 –
/*
* File: addlist.cpp
* -----------------
* This program adds a list of numbers. The end of the
* input is indicated by entering a sentinel value, which
* is defined by setting the value of the constant SENTINEL.
*/
#include <iostream>
#include "genlib.h"
#include "simpio.h"
/*
* Constant: SENTINEL
* ------------------
* This constant defines the value used to terminate the input
* list and should therefore not be a value one would want to
* include as a data value. The value 0 therefore makes sense
* for a program that adds a series of numbers because the
* user can simply skip any 0 values in the input.
*/
const int SENTINEL = 0;
/* Main program */
int main() {
cout << "This program adds a list of numbers." << endl;
cout << "Use " << SENTINEL << " to signal the end." << endl;
int total = 0;
while (true) {
cout << " ? ";
int value = GetInteger();
if (value == SENTINEL) break;
total += value;
}
cout << "The total is " << total << endl;
return 0;
}
There are other strategies for solving the loop-and-a-half problem that involve copying
part of the code outside the loop. However, empirical studies have demonstrated that
students are more likely to write correct programs if they use a break statement to exit
from the middle of the loop than if they are forced to use some other strategy. This
evidence and my own experience have convinced me that using the break statement
inside a while loop is the best solution to the loop-and-a-half problem.
The operation of the for loop is determined by the three italicized expressions on the
for control line: init, test, and step. The init expression indicates how the for loop should
be initialized and usually declares and initializes the index variable. For example, if you
write
for (int i = 0; . . .
the loop will begin by setting the index variable i to 0. If the loop begins
for (int i = -7; . . .
begins with i equal to 0 and continues as long as i is less than n , which turns out to
represent a total of n cycles, with i taking on the values 0, 1, 2, and so forth, up to the
final value n–1. The loop
for (int i = 1; i <= n; i++)
begins with i equal to 1 and continues as long as i is less than or equal to n. This loop
also runs for n cycles, with i taking on the values 1, 2, and so forth, up to n.
The step expression indicates how the value of the index variable changes from cycle to
cycle. The most common form of step specification is to increment the index variable
using the ++ operator, but this is not the only possibility. For example, one can count
backward by using the -- operator, or count by twos by using += 2 instead of ++.
As an illustration of counting in the reverse direction, the program
int main() {
for (int t = 10; t >= 0; t--) {
cout << t << endl;
}
cout << "Liftoff!" << endl;
return 0;
}
1 The C++ standard states that the scope of an index variable declared in the initialization expression of a
for loop extends to the end of the loop body and no further. Some C++ compilers, such as Visual C++ 6.0,
mistakenly extend the scope to the end of the block enclosing the entire loop.
An Overview of C++ – 32 –
Countdown
10
9
8
7
6
5
4
3
2
1
0
Liftoff!
The expressions init, test, and s t e p in a for statement are each optional, but the
semicolons must appear. If init is missing, no initialization is performed. If test is
missing, it is assumed to be true . If step is missing, no action occurs between loop
cycles.
1.6 Functions
A function consists of a set of statements that have been collected together and given a
name. The act of using the name to invoke the associated statements is known as calling
that function. To indicate a function call in C++, you write the name of the function,
followed by a list of expressions enclosed in parentheses. These expressions, called
arguments, allow the calling program to pass information to the function. For example,
in the p o w e r t a b . c p p program at the beginning of this chapter, the function
RaiseIntToPower took two integer arguments, n and k, which are the values it needs to
know in order to compute nk. If a function requires no information from its caller, it need
not have any arguments, but an empty set of parentheses must appear in the function call.
Once called, the function takes the data supplied as arguments, does its work, and then
returns to the program step from which the call was made. Remembering what the
calling program was doing and being able to get back precisely to that point is one of the
defining characteristics of the function-calling mechanism. The operation of going back
to the calling program is called returning from the function.
return result;
the value of the local variable result is passed back to the main program as the value of
the function. This operation is called returning a value.
Functions can return values of any type. The following function, for example, returns
a value of type bool, which can then be used in conditional expressions:
bool IsLeapYear(int year) {
return ((year % 4 == 0) && (year % 100 != 0))
|| (year % 400 == 0);
}
An Overview of C++ – 33 –
Functions that return Boolean results play an important role in programming and are
called predicate functions.
Functions, however, do not need to return a value at all. A function that does not
return a value and is instead executed for its effect is called a procedure. Procedures are
indicated in the definition of a function by using the reserved word void as the result
type.
The return statement in C++ has two forms. For procedures, you write the statement
as
return;
For functions that return a value, the return keyword is followed by an expression, as
follows:
return expression;
Executing either form of the return statement causes the current function to return
immediately to its caller, passing back the value of the expression, if any, to its caller as
the value of the function.
In this example, result-type is the type of value returned by the function, name is the
function name, and parameter-list is a list of declarations separated by commas, giving the
type and name of each parameter to the function. Parameters are placeholders for the
arguments supplied in the function call and act like local variables except for the fact that
they are given initial values by the calling program. If a function takes no parameters, the
entire parameter list in the function header line is empty. The body of the function is a
block and typically contains declarations for the local variables required by the function.
Before you use a function in a C++ program, you declare it by specifying its prototype.
A prototype has exactly the same form as a function definition, except that the entire
body is replaced by a semicolon. The names of the parameter variables are optional in a
prototype, but supplying them usually helps the reader.
1. The calling program computes values for each argument. Because the arguments are
expressions, this computation can involve operators and other functions, all of which
are evaluated before execution of the new function actually begins.
2. The system creates new space for all the local variables required by the new function,
including the parameter variables. These variables are usually allocated together in a
block, which is called a stack frame.
3. The value of each argument is copied into the corresponding parameter variable. If
there is more than one argument, the arguments are copied into the parameters in
An Overview of C++ – 34 –
order; the first argument is copied into the first parameter, and so forth. If necessary,
type conversions are performed between the argument values and the parameter
variables, as in an assignment statement. For example, if you pass a value of type int
to a function that expects a parameter of type double, the integer is converted into the
equivalent floating-point value before it is copied into the parameter variable.
4. The statements in the function body are executed until a return statement is
encountered or there are no more statements to execute.
5. The value of the return expression, if any, is evaluated and returned as the value of
the function. If the value being returned does not precisely match the result type
declared for the function, a type conversion is performed. Thus, if a return
statement specifies a floating-point value in a function defined to return an int, the
result is truncated to an integer.
6. The stack frame created for this function call is discarded. In the process, all local
variables disappear.
7. The calling program continues, with the returned value substituted in place of the call.
inside the function sets the local copy to 0 but leaves x unchanged in the calling program.
To address this problem, you can change the parameter to a reference parameter by
adding an ampersand to the parameter declaration in the function header. Now the
parameter value will not be copied, instead a reference is made to the original variable.
Changes to the parameter are reflected in the original variable. The new coding is
void SetToZero(int & var) {
var = 0;
}
To use this function, the caller must pass an assignable integer variable. To set x to 0,
for example, you would need to make the following call:
SetToZero(x);
The use of reference parameters makes it possible for functions to change values in the
frame of their caller. This mechanism is referred to as call by reference.
In C++, one of the common uses of call by reference occurs when a function needs to
return more than one value to the calling program. A single result can easily be returned
as the value of the function itself. If you need to return more than one result from a
function, the return value is no longer appropriate. The standard approach to solving the
problem is to turn that function into a procedure and pass values back and forth through
the argument list.
As an example, suppose that you wanted to write a program to solve the quadratic
equation
ax2 + bx + c = 0
but that—because of your desire to practice good programming style—you were
committed to dividing the work of the program into three phases as represented by the
boxes in the following flowchart:
Input phase:
Accept values of
the coefficients
from the user.
Computation phase:
Solve the quadratic
equation for those
coefficients.
Output phase:
Display the roots
of the equation
on the screen.
Decomposing this problem into separate functions that are responsible for each of these
phases is somewhat tricky because several values must be passed from each phase to the
next. Because there are three coefficients, you would like the input phase to return three
values. Similarly, the computation phase must return two values, because a quadratic
equation has two solutions.
Figure 1-5 shows how call by reference makes it possible to decompose the quadratic
equation problem in this way. At each level, parameters that act as input to each function
are passed in the conventional way; parameters that represent output from the function
are passed by reference.
Stepwise refinement
Procedures and functions enable you to divide a large programming problem into smaller
pieces that are individually easy to understand. The process of dividing a problem into
manageable pieces, called decomposition, is a fundamental programming strategy.
Finding the right decomposition, however, turns out to be a difficult task that requires
considerable practice. If you choose the individual pieces well, each one will have
An Overview of C++ – 36 –
/*
* File: quadeq.cpp
* ----------------
* This program finds roots of the quadratic equation
*
* 2
* a x + b x + c = 0
*
* If a is 0 or if the equation has no real roots, the
* program exits with an error.
*/
#include <iostream>
#include <cmath>
#include "genlib.h"
#include "simpio.h"
/* Main program */
int main() {
double a, b, c, r1, r2;
GetCoefficients(a, b, c);
SolveQuadratic(a, b, c, r1, r2);
DisplayRoots(r1, r2);
return 0;
}
/*
* Function: GetCoefficients
* Usage: GetCoefficients(a, b, c);
* --------------------------------
* This function is responsible for reading in the coefficients
* of a quadratic equation. The values of the coefficients are
* passed back to the main program in the variables a, b, and c,
* which are reference parameters.
*/
void GetCoefficients(double & a, double & b, double & c) {
cout << "Enter coefficients for the quadratic equation:" << endl;
cout << "a: ";
a = GetReal();
cout << "b: ";
b = GetReal();
cout << "c: ";
c = GetReal();
}
An Overview of C++ – 37 –
/*
* Function: SolveQuadratic
* Usage: SolveQuadratic(a, b, c, x1, x2);
* ---------------------------------------
* This function solves a quadratic equation. The coefficients
* are supplied as the arguments a, b, and c, and the roots are
* returned in x1 and x2, which are reference parameters.
*/
/*
* Function: DisplayRoots
* Usage: DisplayRoots(x1, x2);
* ----------------------------
* This function displays the values x1 and x2, which are
* the roots of a quadratic equation.
*/
conceptual integrity as a unit and make the program as a whole much simpler to
understand. But if you choose unwisely, the decomposition can get in your way. There
are no hard-and-fast rules for selecting a particular decomposition; you will learn how to
apply this process through experience.
When you are faced with the task of writing a program, the best strategy is usually to
start with the main program. At this level, you think about the problem as a whole and
then try to identify the major pieces of the entire task. Once you figure out what the big
pieces of the program are, you can define them as independent functions. Since some of
these functions may themselves be complicated, it is often appropriate to decompose
them into still smaller ones. You can continue this process until every piece of the
problem is simple enough to be solved on its own. This process is called top-down
design, or stepwise refinement.
Summary
This chapter is itself a summary, which makes it hard to condense it to a few central
points. Its purpose was to introduce you to the C++ programming language and give you
a crash course in how to write simple programs in that language. This chapter
concentrated on the low-level structure of the language, proceeding in turn through the
An Overview of C++ – 38 –
topics of expressions, statements, and functions. The facilities that C++ offers for
defining new data structures are detailed in Chapter 2.
Important points in this chapter include:
• In the 25 years of its existence, the C++ programming language has become one of the
most widely used languages in the world.
• A typical C++ program consists of comments, library inclusions, program-level
definitions, function prototypes, a function named main that is called when the
program is started, and a set of auxiliary function definitions that work together with
the main program to accomplish the required task.
• Variables in a C++ program must be declared before they are used. Most variables in
C++ are local variables, which are declared within a function and can only be used
inside the body of that function.
• A data type is defined by a domain of values and a set of operations. C++ includes
several predefined types that allow programs to store data of several different types,
such as integers, floating-point numbers, Booleans, and characters. In addition to these
built-in types, the standard library defines the type string, which is treated in this
book as if it were an integral part of the language.
• The easiest way to read input data from the user is to call functions in the simplified
I/O library (simpio ), which defines such functions as GetInteger, GetReal, and
GetLine. To display output on the computer screen, the usual approach is to insert the
values into the standard cout stream using the insertion operator <<.
• Expressions in C++ are written in a form similar to that in most programming
languages, with individual terms connected by operators. A complete list of the
operators available in C++ appears in Table 1-4, which also indicates the relative
precedence of each operator.
• Statements in C++ fall into two classes: simple statements and control statements. A
simple statement consists of an expression—typically an assignment or a function
call—followed by a semicolon. The control statements described in this chapter are
the i f , switch , while , and for statements. The first two are used to express
conditional execution, while the last two are used to specify repetition.
• C++ programs are typically subdivided into several functions. Each function consists
of a sequence of statements that can be invoked by writing the name of the function,
followed by a list of arguments enclosed in parentheses. These arguments are copied
into the corresponding parameter variables inside the function. The function can
return a result to the caller by using the return statement and can share values using
reference parameters.
Review questions
1. What is the difference between a source file and an object file?
2. What characters are used to mark comments in a C++ program?
3. In an #include line, the name of the library header file can be enclosed in either
angle brackets of double quotation marks. What is the difference between the two
forms of punctuation?
4. How would you define a constant called CENTIMETERS_PER_INCH with the value
2.54?
An Overview of C++ – 39 –
5. What is the name of the function that must be defined in every C++ program?
6. What is the purpose of inserting endl into the output stream cout?
7. What four properties are established when you declare a variable?
8. Indicate which of the following are legal variable names in C++:
a. x g. total output
b. formula1 h. aReasonablyLongVariableName
c. average_rainfall i. 12MonthTotal
d. %correct j. marginal-cost
e. short k. b4hand
f. tiny l. _stk_depth
9. What are the two attributes that define a data type?
10. What is the difference between the types short, int, and long?
11. What does ASCII stand for?
12. List all possible values of type bool.
13. What statements would you include in a program to read a value from the user and
store it in the variable x, which is declared as a double?
14. Suppose that a function contains the following declarations:
int i;
double d;
char c;
string s;
Write a statement that displays the values of each of these variables on the screen.
15. Indicate the values and types of the following expressions:
a. 2 + 3 d. 3 * 6.0
b. 19 / 5 e. 19 % 5
c. 19.0 / 5 f. 2 % 7
16. What is the difference between the unary minus and the binary subtraction operator?
17. What does the term truncation mean?
18. Calculate the result of each of the following expressions:
a. 6 + 5 / 4 - 3
b. 2 + 2 * (2 * 2 - 2) % 2 / 2
c. 10 + 9 * ((8 + 7) % 6) + 5 * 4 % 3 * 2 + 1
d. 1 + 2 + (3 + 4) * ((5 * 6 % 7 * 8) - 9) - 10
19. How do you specify a shorthand assignment operation?
20. What is the difference between the expressions ++x and x++?
21. What does the term short-circuit evaluation mean?
An Overview of C++ – 40 –
22. Write out the general syntactic form for each of the following control statements: if,
switch, while, for.
Programming exercises
1. Write a program that reads in a temperature in degrees Celsius and displays the
corresponding temperature in degrees Fahrenheit. The conversion formula is
9
F = 5 C + 32
6. Using the DigitSum function from the section entitled “The while statement” as a
model, write a program that reads in an integer and then displays the number that has
the same digits in the reverse order, as illustrated by this sample run:
ReverseInteger
This program reverses the digits in an integer.
Enter a positive integer: 123456789
The reversed integer is 987654321
To make sure your program can handle integers as large as the one shown in the
example, use the type long instead of int in your program.
7. Greek mathematicians took a special interest in numbers that are equal to the sum of
their proper divisors (a proper divisor of N is any divisor less than N itself). They
called such numbers perfect numbers. For example, 6 is a perfect number because
it is the sum of 1, 2, and 3, which are the integers less than 6 that divide evenly into
6. Similarly, 28 is a perfect number because it is the sum of 1, 2, 4, 7, and 14.
Write a predicate function IsPerfect that takes an integer n and returns true if n
is perfect, and false otherwise. Test your implementation by writing a main
program that uses the IsPerfect function to check for perfect numbers in the range
1 to 9999 by testing each number in turn. When a perfect number is found, your
program should display it on the screen. The first two lines of output should be 6
and 28. Your program should find two other perfect numbers in the range as well.
8. Every positive integer greater than 1 can be expressed as a product of prime
numbers. This factorization is unique and is called the prime factorization. For
example, the number 60 can be decomposed into the factors 2 x 2 x 3 x 5, each of
which is prime. Note that the same prime can appear more than once in the
factorization.
Write a program to display the prime factorization of a number n, as illustrated by
the following sample run:
Factor
Enter number to be factored: 60
2 * 2 * 3 * 5
10. The German mathematician Leibniz (1646–1716) discovered the rather remarkable
fact that the mathematical constant π can be computed using the following
mathematical relationship:
π
– 1 + 1 – 1 + 1 – 1 + . . .
4 ≅ 1 3 5 7 9 11
The formula to the right of the equal sign represents an infinite series; each fraction
represents a term in that series. If you start with 1, subtract one-third, add one-fifth,
and so on, for each of the odd integers, you get a number that gets closer and closer
to the value of π/4 as you go along.
Write a program that calculates an approximation of π consisting of the first
10,000 terms in Leibniz’s series.
11. You can also approximate π by approximating the area bounded by a circular arc.
Consider the following quarter circle:
which has a radius r equal to two inches. From the formula for the area of a circle,
you can easily determine that the area of the quarter circle should be π square inches.
You can also approximate the area computationally by adding up the areas of a series
of rectangles, where each rectangle has a fixed width and the height is chosen so that
the circle passes through the midpoint of the top of the rectangle. For example, if
you divide the area into 10 rectangles from left to right, you get the following
diagram:
The sum of the areas of the rectangles approximates the area of the quarter circle.
The more rectangles there are, the closer the approximation.
For each rectangle, the width w is a constant derived by dividing the radius by the
number of rectangles. The height h, on the other hand, varies depending on the
position of the rectangle. If the midpoint of the rectangle in the horizontal direction
is given by x, the height of the rectangle can be computed using the distance formula
An Overview of C++ – 43 –
h = r 2 – x2
√
The area of each rectangle is then simply h x w.
Write a program to compute the area of the quarter circle by dividing it into 100
rectangles.
12. When you write a check, the dollar amount appears twice: once as a number and once
as English text. For example, if you write a check for $1729, you need to translate
that number to the English text “one thousand seven hundred twenty-nine.” Your task
in this problem is to write a program that reads in integers from the user and writes
out the equivalent value in figures on the next line, stopping when the user enters any
negative number. For example, the following is a sample run of this program:
NumberToText
Enter numbers in figures; use a negative value to stop.
Number: 0
zero
Number: 1
one
Number: 11
eleven
Number: 256
two hundred fifty-six
Number: 1729
one thousand seven hundred twenty-nine
Number: 2001
two thousand one
Number: 12345
twelve thousand three hundred forty-five
Number: 13000
thirteen thousand
Number: -1
The key idea in this exercise is decomposition. The problem is not nearly as hard as
it looks if you break it down into separate procedures that accomplish parts of the
task. Many of these procedures will have a form that looks something like this:
void PrintOneDigit(int d) {
switch (d) {
case 0: cout << "zero"; break;
case 1: cout << "one"; break;
case 2: cout << "two"; break;
case 3: cout << "three"; break;
case 4: cout << "four"; break;
case 5: cout << "five"; break;
case 6: cout << "six"; break;
case 7: cout << "seven"; break;
case 8: cout << "eight"; break;
case 9: cout << "nine"; break;
default: Error("Illegal call to PrintOneDigit");
}
}
In writing your program, you should keep the following points in mind:
• You don’t need to perform any string manipulation. All you have to do is display
the value on the screen, which means that inserting to cout is all you need.
An Overview of C++ – 44 –
• Your program need work only with values up to 999,999, although it should give
the user some kind of error message if a number is outside of its range.
• It is perfectly acceptable for all the letters in the output to be lowercase. The
problem is much harder if you try to capitalize the first word.
• You should remain on the lookout for functions that you can reuse. For example,
printing the number of thousands is pretty much the same as printing out the last
three digits, and you should be able to use the same procedure more than once.
• Several special cases arise in this problem. For example, the number 11 must be
treated differently than 21 or 31, because eleven doesn’t fit the pattern established
by twenty-one and thirty-one.
Chapter 2
Data Types in C++
Chapter 1 of this text is a capsule summary of the features of C++ necessary to code the
algorithmic structure of a program. The algorithmic structure, however, represents only
part of the story. It is equally important to consider the structure of the data.
Like control statements and function calls—each of which can be nested hierarchically
to represent increasingly complex algorithmic structures—data types in a language also
form a hierarchy. The base of the hierarchy is composed of the atomic types that were
introduced in Chapter 1, coupled with a new class of atomic types called enumeration
types that are introduced in the following section. Starting from this base, you can extend
the hierarchy using the following mechanisms for creating new types from existing ones:
• Pointers. A pointer is simply the internal machine address of a value inside the
computer’s memory. C++ allows you to work directly with pointers as data and makes
them part of the type hierarchy, which means that you can define new types whose
domains consist of pointers to values of some existing type.
• Arrays. An array is an ordered collection of data values, each of which has the same
type.
• Records. A record is a collection of data values that represents some logically
coherent whole. The individual components are identified by name rather than by
order and may be of different types.
Each of these types is described in detail in a separate section later in this chapter. For
now, the main point is that you can combine these mechanisms to generate new types at
whatever level of complexity the program requires. You can, for example, create new
types that are pointers to records containing arrays or any other nested structure you
choose. The hierarchy of types in a program defines its data structure.
where element-list is a list of identifiers, which are called enumeration constants, and
name is the name of the new type. For example, the following enumeration type defines
the four principal compass directions:
Similarly, the following definition introduces the type colorT, which consists of the six
primary and secondary colors available on a standard color monitor:
Data Types in C++ – 47 –
enum colorT {
Red, Green, Blue, Yellow, Cyan, Magenta
};
Once you have defined an enumeration type, you can declare variables of that type just
as you do with any of the built-in types. For example, the declaration
directionT dir;
declares the variable dir to be of type directionT, which means that it can take on any
of the values North, East, South, or West.
enum coinT {
Penny = 1,
Nickel = 5,
Dime = 10,
Quarter = 25,
HalfDollar = 50
};
each of the enumeration constants Penny, Nickel, Dime, Quarter, and HalfDollar is
represented internally as its corresponding monetary value. If the value of any
enumeration constant is not specified, the compiler simply adds one to the value of the
previous constant. Thus, in the definition,
enum monthT {
January = 1, February, March, April, May, June,
July, August, September, October, November, December
};
Inside the machine, the two strategies produce the same result: every element of the
enumeration type is represented by an integer code. From the programmer’s point of
view, however, defining separate enumeration types has these advantages:
• The programmer does not need to specify the internal codes explicitly.
• The fact that there is a separate type name often makes the program easier to read
because declarations can use a meaningful type name instead of the general-purpose
designation int.
• A C++ compiler does some rudimentary checking for enumeration types. For example,
an integer value cannot be assigned to an enum variable without a typecast, which
helps to draw attention to possible mistakes such as assigning a value out of range for
the enumeration.
• On many systems, programs that use enumeration types are easier to debug because
the compiler makes the names of the enumeration constants available to the debugger.
Thus, if you ask it about a value of type monthT, a well-designed debugger would be
able to display the value January instead of the integer constant 1.
Scalar types
In C++, enumeration types, characters, and the various representations of integers form a
more general type class called scalar types. When a value of a scalar type is used in a
C++ expression, the compiler automatically converts it to the integer used to represent
that value. The effect of this rule is that the operations you can perform on values of any
scalar type are the same as those for integers.
As an example, suppose that you want to write a function RightFrom(dir) that takes
a directionT and returns the direction you would be facing if you turned 90 degrees
from that starting position. Thus, RightFrom(North) should return East. Because the
directions appear in order as you move right around the compass points, turning right
corresponds arithmetically to adding one to the underlying value, except for
RightFrom(West), which has to generate 0 instead of 4 as the underlying value. As is
often the case with enumerated types that represent a value which is logically cyclical,
you can use the % operator to write a one-line implementation of RightFrom, as follows:
C++ allows implicit conversion from enumeration type to integer, since every
enumeration value has a corresponding integer representation. However, there is no
implicit conversion in the other direction because most integer values do not have a
representation in a particular enumeration. In the above example, the enumeration type is
automatically converted to an integer when used in an arithmetic expression. Once you
have computed the resulting integer value, you must use an explicit typecast to return that
value as a directionT.
You can substitute scalar types in any context in which an integer might appear. For
example, a variable of an enumeration type can be used as the control expression in a
switch statement, so that you can define a function DirectionName(dir), which returns
the name of a direction as a string, like this:
Data Types in C++ – 49 –
You can also use scalar types as index variables in for loops. For example, you can
cycle through each of the four directions using the following loop control line:
Memory addresses
Within the memory system, every byte is identified by a numeric address. Typically, the
first byte in the computer is numbered 0, the second is numbered 1, and so on, up to the
number of bytes in the machine. For example, if your computer has four megabytes of
memory (which actually means 4 x 220 or 4,194,304 bytes), the addresses of the memory
cells would look like this:
Data Types in C++ – 50 –
1000
1001
1002
1003
4194301
4194302
4194303
Each byte of memory is large enough to hold one character. For example, if you were
to declare the character variable ch, the compiler would reserve one byte of storage for
that variable as part of the current function frame. Suppose that this byte happened to be
at address 1000. If the program then executed the statement
ch = 'A';
the internal representation of the character 'A' would be stored in location 1000. Since
the ASCII code for 'A' is 65, the resulting memory configuration would look like this:
1000 65 ch
1001
1002
1003
1004
1005
1006
1007
In most programming applications, you will have no way of predicting the actual
address at which a particular variable is stored. In the preceding diagram, the variable ch
is assigned to address 1000, but this choice is entirely arbitrary. Whenever your program
makes a function call, the variables within the function are assigned to memory locations,
but you have no way of predicting the addresses of those variables in advance. Even so,
you may find it useful to draw pictures of memory and label the individual locations with
addresses beginning at a particular starting point. These addresses—even though you
choose them yourself—can help you to visualize what is happening inside the memory of
the computer as your program runs.
Values that are larger than a single character are stored in consecutive bytes of
memory. For example, if an integer takes up four bytes on your computer, that integer
Data Types in C++ – 51 –
requires four consecutive bytes of memory and might therefore be stored in the shaded
area in the following diagram:
1000
1001
1002
1003
1004
1005
1006
1007
Data values requiring multiple bytes are identified by the address of the first byte, so the
integer represented by the shaded area is the word stored at address 1000.
When you write a C++ program, you can determine how much memory will be
assigned to a particular variable by using the sizeof operator. The sizeof operator
takes a single operand, which must be a type name enclosed in parentheses or an
expression. If the operand is a type, the sizeof operator returns the number of bytes
required to store a value of that type; if the operand is an expression, sizeof returns the
number of bytes required to store the value of that expression. For example, the
expression
sizeof(int)
returns the number of bytes required to store a value of type int. The expression
sizeof x
2.3 Pointers
One of the principles behind the design of C++ was that programmers should have as
much access as possible to the facilities provided by the hardware itself. For this reason,
C++ makes the fact that memory locations have addresses visible to the programmer. A
data item whose value is an address in memory is called a pointer. In many high-level
programming languages, pointers are used sparingly because those languages provide
other mechanisms that eliminate much of the need for pointers; the Java programming
language, for example, hides pointers from the programmer altogether. In C++, pointers
are pervasive, and it is impossible to understand C++ programs without knowing how
pointers work.
In C++, pointers serve several purposes, of which the following are the most
important:
• Pointers allow you to refer to a large data structure in a compact way. Data structures
in a program can become arbitrarily large. No matter how large they grow, however,
the data structures still reside somewhere in the computer’s memory and therefore
have an address. Pointers allow you to use the address as a shorthand for the complete
Data Types in C++ – 52 –
value. Because a memory address typically fits in four bytes of memory, this strategy
offers considerable space savings when the data structures themselves are large.
• Pointers make it possible to reserve new memory during program execution. Up to
now, the only memory you could use in your programs was the memory assigned to
variables that you have declared explicitly. In many applications, it is convenient to
acquire new memory as the program runs and to refer to that memory using pointers.
This strategy is discussed in the section on “Dynamic allocation” later in this chapter.
• Pointers can be used to record relationships among data items. In advanced
programming applications, pointers are used extensively to model connections
between individual data values. For example, programmers often indicate that one
data item follows another in a conceptual sequence by including a pointer to the
second item in the internal representation of the first.
x = 1.0;
Many values in C++, however, are not lvalues. For example, constants are not lvalues
because a constant cannot be changed. Similarly, although the result of an arithmetic
expression is a value, it is not an lvalue, because you cannot assign a value to the result of
an arithmetic expression.
The following properties apply to lvalues in C++:
int *p;
declares the variable p to be of the conceptual type pointer-to-int. Similarly, the line
char *cptr;
declares the variable cptr to be of type pointer-to- char. These two types—pointer-to-
int and pointer-to-char—are distinct in C++, even though each of them is represented
internally as an address. To use the value at that address, the compiler needs to know
how to interpret it and therefore requires that its type be specified explicitly. The type of
the value to which a pointer points is called the base type of that pointer. Thus, the type
pointer-to-int has int as its base type.
Data Types in C++ – 53 –
It is important to note that the asterisk used to indicate that a variable is a pointer
belongs syntactically with the variable name and not with the base type. If you use the
same declaration to declare two pointers of the same type, you need to mark each of the
variables with an asterisk, as in
The declaration
& Address-of
* Value-pointed-to
The & operator takes an lvalue as its operand and returns the memory address in which
that lvalue is stored. The * operator takes a value of any pointer type and returns the
lvalue to which it points. This operation is called dereferencing the pointer. The *
operation produces an lvalue, which means that you can assign a value to a dereferenced
pointer.
The easiest way to illustrate these operators is by example. Consider the declarations
int x, y;
int *p1, *p2;
These declarations allocate memory for four words, two of type int and two of type
pointer-to- int . For concreteness, let’s suppose that these values are stored in the
machine addresses indicated by the following diagram:
1000
x
1004
y
1008
p1
1012
p2
You can assign values to x and y using assignment statements, just as you always have.
For example, executing the assignment statements
x = –42;
y = 163;
1000
-42 x
1004
163 y
1008
p1
1012
p2
To initialize the pointer variables p1 and p2, you need to assign values that represent
the addresses of some integer objects. In C++, the operator that produces addresses is the
& operator, which you can use to assign the addresses of x and y to p 1 and p 2 ,
respectively:
p1 = &x;
p2 = &y;
1000
-42 x
1004
163 y
1008
1000 p1
1012
1004 p2
The arrows in the diagram are used to emphasize the fact that the values of the variables
p1 and p2 point to the cells indicated by the heads of the arrows. Drawing arrows makes
it much easier to understand how pointers work, but it is important to remember that
pointers are simply numeric addresses and that there are no arrows inside the machine.
To move from a pointer to the value it points to, you use the * operator. For example,
the expression
*p1
indicates the value in the memory location to which p1 points. Moreover, since p1 is
declared as a pointer to an integer, the compiler knows that the expression *p1 must refer
to an integer. Thus, given the configuration of memory illustrated in the diagram, *p1
turns out to be another name for the variable x.
Like the simple variable name x, the expression *p1 is an lvalue, and you can assign
new values to it. Executing the assignment statement
*p1 = 17;
changes the value in the variable x because that is where p1 points. After you make this
assignment, the memory configuration is
Data Types in C++ – 55 –
1000
17 x
1004
163 y
1008
1000 p1
1012
1004 p2
You can see that the value of p1 itself is unaffected by this assignment. It continues to
hold the value 1000 and therefore still points to the variable x.
It is also possible to assign new values to the pointer variables themselves. For
instance, the statement
p1 = p2;
instructs the computer to take the value contained in the variable p2 and copy it into the
variable p1. The value contained in p2 is the pointer value 1004. If you copy this value
into p1, both p1 and p2 point to the variable y, as the following diagram shows:
1000
17 x
1004
163 y
1008
1004 p1
1012
1004 p2
In terms of the operations that occur inside the machine, copying a pointer is exactly the
same as copying an integer. The value of the pointer is simply copied unchanged to the
destination. From a conceptual perspective, the diagram shows that the effect of copying
a pointer is to replace the destination pointer with a new arrow that points to the same
location as the old one. Thus, the effect of the assignment
p1 = p2;
is to change the arrow leading from p1 so that it points to the same memory address as
the arrow originating at p2.
It is important to be able to distinguish the assignment of a pointer from that of a value.
Pointer assignment, such as
p1 = p2;
makes p1 and p2 point to the same location. Value assignment, which is represented by
the statement
*p1 = *p2;
copies the value from the memory location addressed by p2 into the location addressed
by p1.
Data Types in C++ – 56 –
2.4 Arrays
An array is a collection of individual data values with two distinguishing characteristics:
1. An array is ordered. You must be able to count off the individual components of an
array in order: here is the first, here is the second, and so on.
2. An array is homogeneous. Every value stored in an array must be of the same type.
Thus, you can define an array of integers or an array of floating-point numbers but
not an array in which the two types are mixed.
From an intuitive point of view, it is best to think of an array as a sequence of boxes, one
box for each data value in the array. Each of the values in an array is called an element.
For example, the following diagram represents an array with five elements:
• The element type, which is the type of value that can be stored in the elements of the
array
• The array size, which is the number of elements the array contains
Whenever you create a new array in your program, you must specify both the element
type and the array size.
Array declaration
Like any other variable in C++, an array must be declared before it is used. The general
form for an array declaration is
type name[size];
1 The constant NULL is defined in the <cstddef> header file. You may also just use the constant zero.
Data Types in C++ – 57 –
where type is the type of each element in the array, name is the name of the array variable,
and size is a constant indicating the number of elements allocated to the array. For
example, the declaration
int intArray[10];
declares an array named intArray with 10 elements, each of which is of type int. In
most cases, however, you should specify the size as a symbolic constant rather than an
explicit integer so that the array size is easier to change. Thus, a more conventional
declaration would look like this:
int intArray[N_ELEMENTS];
You can represent this declaration pictorially by drawing a row of ten boxes and giving
the entire collection the name intArray:
intArray
0 1 2 3 4 5 6 7 8 9
Each element in the array is identified by a numeric value called its index. In C++, the
index numbers for an array always begin with 0 and run up to the array size minus one.
Thus, in an array with 10 elements, the index numbers are 0, 1, 2, 3, 4, 5, 6, 7, 8, and 9, as
the preceding diagram shows.
As is the case with any variable, you use the name of an array to indicate to other
readers of the program what sort of value is being stored. For example, suppose that you
wanted to define an array that was capable of holding the scores for a sporting event, such
as gymnastics or figure skating, in which scores are assigned by a panel of judges. Each
judge rates the performance on a scale from 0 to 10, with 10 being the highest score.
Because a score may include a decimal fraction, as in 9.9, each element of the array must
be of some floating-point type, such as double. Thus the declaration
double scores[N_JUDGES];
declares an array named scores with five elements, as shown in the following diagram:
scores
0 1 2 3 4
Array selection
To refer to a specific element within an array, you specify both the array name and the
index corresponding to the position of that element within the array. The process of
identifying a particular element within an array is called selection, and is indicated in
C++ by writing the name of the array and following it with the index written in square
brackets. The result is a selection expression, which has the following form:
Data Types in C++ – 58 –
array[index]
Within a program, a selection expression acts just like a simple variable. You can use
it in an expression, and, in particular, you can assign a value to it. Thus, if the first judge
(judge #0, since C++ counts array elements beginning at zero) awarded the contestant a
score of 9.2, you could store that score in the array by writing the assignment statement
scores[0] = 9.2;
scores
9.2
0 1 2 3 4
You could then go ahead and assign scores for each of the other four judges using, for
example, the statements
scores[1] = 9.9;
scores[2] = 9.7;
scores[3] = 9.0;
scores[4] = 9.5;
scores
9.2 9.9 9.7 9.0 9.5
0 1 2 3 4
In working with arrays, it is essential to understand the distinction between the index
of an array element and the value of that element. For instance, the first box in the array
has index 0, and its value is 9.2. It is also important to remember that you can change the
values in an array but never the index numbers.
The real power of array selection comes from the fact that the index value need not be
constant, but can be any expression that evaluates to an integer or any other scalar type.
In many cases, the selection expression is the index variable of a for loop, which makes
it easy to perform an operation on each element of the array in turn. For example, you
can set each element in the scores array to 0.0 with the following statement:
where n is a variable whose value changes in response to the needs of the application.
C++ requires that arrays be declared with a constant size.
The usual strategy for solving this problem is to declare an array that is larger than you
need and use only part of it. Thus, instead of declaring the array based on the actual
number of elements—which you often do not know in advance—you define a constant
indicating the maximum number of elements and use that constant in the declaration of
the array. On any given use of the program, the actual number of elements is always less
than or equal to this bound. When you use this strategy, you need to maintain a separate
integer variable that keeps track of the number of values that are actually in use. The size
of the array specified in the declaration is called the allocated size; the number of
elements actively in use is called the effective size.
As an example, suppose that you wanted to change the declaration of the array scores
introduced in the preceding section so that the program would work with any reasonable
number of judges. Since you can’t imagine that the number of judges at a sports event
would ever be larger than 100, you might declare the array like this:
const int MAX_JUDGES = 100;
int scores[MAX_JUDGES];
To keep track of the effective size, you would need to declare an additional variable, as
follows:
int nJudges;
When a function takes an array argument, the value of that argument is not copied in
the way that simple variables are. Instead, the function always gets a pointer to the array,
which means that the storage used for the parameter array is shared with that of the actual
argument. Changing the value of an element of the parameter array therefore changes the
value of the corresponding element in the argument array.
Data Types in C++ – 60 –
Initialization of arrays
Array variables can be given initial values at the time they are declared. In this case, the
equal sign specifying the initial value is followed by a list of initializers enclosed in curly
braces. For example, the declaration
int digits[10] = { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 };
declares an array called digits in which each of the 10 elements is initialized to its own
index number. When initializers are provided for an array, it is legal to omit the array
size from the declaration. Thus, you could also write the declaration of digits like this:
int digits[] = { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 };
When the compiler encounters a declaration of this form, it counts the number of
initializers and reserves exactly that many elements for the array.
In the digits example, there is little advantage in leaving out the array bound. You
know that there are 10 digits and that new digits are not going to be added to this list. For
arrays whose initial values may need to change over the life cycle of the program, having
the compiler compute the array size from the initializers is useful for program
maintenance because it frees the programmer from having to maintain the element count
as the program evolves.
For example, imagine you’re writing a program that requires an array containing the
names of all U.S. cities with populations of over 1,000,000. Taking data from the 1990
census, you could declare and initialize bigCities as a global array using the following
declaration:
string bigCities[] = {
"New York",
"Los Angeles",
"Chicago",
"Houston",
"Philadelphia",
"San Diego",
"Detroit",
"Dallas",
};
When the figures are in from the 2000 census, it is likely that Phoenix and San Antonio
will have joined this list. If they have, you can then simply add their names to the
initializer list. The compiler will expand the array size to accommodate the new values.
Note that a comma follows the last initializer for the bigCities array. This comma is
optional, but it is good programming practice to include it. Doing so allows you to add
new cities without having to change the existing entries in the initializer list.
If you write a program that uses the bigCities array, you will probably need to know
how many cities the list contains. The compiler has this number because it counted the
Data Types in C++ – 61 –
/*
* File: gymjudge.cpp
* ------------------
* This program averages a set of gymnastic scores.
*/
#include <iostream>
#include "genlib.h"
#include "simpio.h"
/* Constants */
/* Main program */
int main() {
double scores[MAX_JUDGES];
cout << "Enter number of judges: ";
int nJudges = GetInteger();
if (nJudges > MAX_JUDGES) Error("Too many judges");
ReadAllScores(scores, nJudges);
cout << "The average score is " << Mean(scores, nJudges) << endl;
return 0;
}
/*
* Function: ReadAllScores
* Usage: ReadAllScores(scores, nJudges);
* --------------------------------------
* This function reads in scores for each of the judges. The
* array scores must be declared by the caller and must have
* an allocated size that is at least as large as nJudges.
* Because people tend to count starting at 1 rather than 0,
* this program adds 1 to the argument to GetScore, which means
* that the values the user sees will range from 1 to n instead
* of between 0 and n-1.
*/
/*
* Function: GetScore
* Usage: score = GetScore(judge);
* -------------------------------
* This function reads in the score for the specified judge.
* The implementation makes sure that the score is in the
* legal range before returning.
*/
/*
* Function: Mean
* Usage: mean = Mean(array, n);
* -----------------------------
* This function returns the statistical mean (average) of a
* distribution stored in array, which has effective size n.
*/
initializers. The question is how to make that information available to the program. In
C++, there is a standard idiom for determining the number of elements in an array whose
size is established by static initialization. Given any array a, the number of elements in a
can be computed using the expression
sizeof a / sizeof a[0]
Described in English, this expression takes the size of the entire array and divides it by
the size of the initial element in the array. Because all elements of an array are the same
size, the result is the number of elements in the array, regardless of the element type.
Thus you could initialize a variable nBigCities to hold the number of cities in the
bigCities array by writing
Multidimensional arrays
In C++, the elements of an array can be of any type. In particular, the elements of an
array can themselves be arrays. Arrays of arrays are called multidimensional arrays.
The most common form is the two-dimensional array, which is most often used to
represent data in which the individual entries form a rectangular structure marked off into
Data Types in C++ – 63 –
rows and columns. This type of two-dimensional structure is called a matrix. Arrays of
three or more dimensions are also legal in C++ but occur much less frequently.
double mat[3][3];
Conceptually, the storage for mat forms a two-dimensional structure in which the
individual elements are laid out like this:
Internally, C++ represents the variable mat as an array of three elements, each of
which is an array of three floating-point values. The memory allocated to mat consists of
nine cells arranged in the following form:
mat[0][0]
mat[0] mat[0][1]
mat[0][2]
mat[1][0]
mat[1] mat[1][1]
mat[1][2]
mat[2][0]
mat[2] mat[2][1]
mat[2][2]
In the two-dimensional diagram, the first index is assumed to indicate the row number.
This choice, however, is arbitrary because the two-dimensional geometry of the matrix is
entirely conceptual; in memory, these values form a one-dimensional list. If you want the
first index to indicate the column and the second to indicate the row, you do not need to
change the declaration, only the way in which you select the elements. In terms of the
internal arrangement, however, it is always true that the first index value varies least
rapidly. Thus all the elements of mat[0] appear in memory before any elements of
mat[1].
You can also use initializers with multidimensional arrays. To emphasize the overall
structure, the values used to initialize each internal array are usually enclosed in an
additional set of curly braces. For example, the declaration
double identityMatrix[3][3] = {
{ 1.0, 0.0, 0.0 },
{ 0.0, 1.0, 0.0 },
{ 0.0, 0.0, 1.0 }
};
This particular matrix comes up frequently in mathematical applications and is called the
identity matrix.
As in the case of parameters, the declaration of a statically initialized multidimensional
array must specify all index bounds except possibly the first, which can be determined by
counting the initializers. As was true with parameters, however, it is usually best to
specify all the index bounds explicitly when you declare a multidimensional array.
which reserves enough space for three values of type double. Assuming that a double is
eight bytes long, the memory diagram for the array would look like this:
1000
list[0]
1008
list[1]
1016
list[2]
Data Types in C++ – 65 –
Because each of the elements in the array is an lvalue, it has an address that can be
derived using the & operator. For example, the expression
&list[1]
has the pointer value 1008 because the element list[1] is stored at that address.
Moreover, the index value need not be constant. The selection expression
list[i]
Because the address of the ith element in list depends on the value of the variable i,
the C++ compiler cannot compute this address when compiling the program. To
determine the address, the compiler generates instructions that take the base address of
the array and then add the value of i multiplied by the size of each array element in bytes.
Thus, the numeric calculation necessary to find the address of list[i] is given by the
formula
1000 + i x 8
If i is 2, for example, the result of the address calculation is 1016, which matches the
address shown in the diagram for list[2] . Because the process of calculating the
address of an array element is entirely automatic, you don’t have to worry about the
details when writing your programs.
allocates space for an array of five integers, which is assigned storage somewhere inside
the computer’s memory, as illustrated in the following diagram:
2000
intList[0]
2004
intList[1]
2008
intList[2]
2012
intList[3]
2016
intList[4]
Data Types in C++ – 66 –
The name intList represents an array but can also be used directly as a pointer value.
When it is used as a pointer, intList is defined to be the address of the initial element in
the array. For any array arr, the following identity always holds in C++:
arr is defined to be identical to &arr[0]
Given any array name, you can assign its address directly to any pointer variable.
The most common example of this equivalence occurs when an array is passed from
one function to another. For example, suppose that you make the function call
sum = SumIntegerArray(intList, 5);
The SumIntegerArray function would work exactly the same way if the prototype had
been written as
int SumIntegerArray(int *array, int n)
In this case, the first argument is declared as a pointer, but the effect is the same as in the
preceding implementation, which declared this parameter as an array. The address of the
first element in intList is copied into the formal parameter array and manipulated
using pointer arithmetic. Inside the machine, the declarations are equivalent and the same
operations can be applied in either case.
As a general rule, you should declare parameters in the way that reflects their use. If
you intend to use a parameter as an array and select elements from it, you should declare
that parameter as an array. If you intend to use the parameter as a pointer and dereference
it, you should declare it as a pointer.
The crucial difference between arrays and pointers in C++ comes into play when
variables are originally declared, not when those values are passed as parameters. The
fundamental distinction between the declaration
int array[5];
is one of memory allocation. The first declaration reserves five consecutive words of
memory capable of holding the array elements. The second declaration reserves only a
single word, which is large enough to hold a machine address. The implication of this
difference is extremely important to you as a programmer. If you declare an array, you
have storage to work with; if you declare a pointer variable, that variable is not associated
with any storage until you initialize it.
Data Types in C++ – 67 –
Given your current level of understanding, the only way to use a pointer as an array is
to initialize the pointer by assigning the base address of the array to the pointer variable.
If, after making the preceding declarations, you were to write
p = array;
the pointer variable p would then point to the same address used for array, and you could
use the two names interchangeably.
The technique of setting a pointer to the address of an existing array is rather limited.
After all, if you already have an array name, you might as well use it. Assigning that
name to a pointer does not really do you any good. The real advantage of using a pointer
as an array comes from the fact that you can initialize that pointer to new memory that
has not previously been allocated, which allows you to create new arrays as the program
runs. This important programming technique is described in the section on “Dynamic
allocation” later in this chapter.
2.6 Records
To understand the idea of a record, imagine for a moment that you are in charge of the
payroll system for a small company. You need to keep track of various pieces of
information about each employee. For example, in order to print a paycheck, you need to
know the employee’s name, job title, Social Security number, salary, withholding status,
and perhaps some additional data as well. These pieces of information, taken together,
form the employee’s data record.
What do employee records look like? It is often easiest to think of records as entries in
a table. For example, consider the case of the small firm of Scrooge and Marley,
portrayed in Charles Dickens’s A Christmas Carol, as it might appear in this day of
Social Security numbers and withholding allowances. The employee roster contains two
records, which might have the following values:
Name Job title Soc. Sec. # Salary # With.
Ebenezer Scrooge Partner 271-82-8183 250.00 1
Bob Cratchit Clerk 314-15-9265 15.00 7
Each record is broken up into individual components that provide a specific piece of
information about the employee. Each of these components is usually called a field,
although the term member is also used, particularly in the context of C++ programming.
For example, given an employee record, you can talk about the name field or the salary
field. Each of the fields is associated with a type, which may be different for different
fields. The name and title field are strings, the salary field might well be represented as a
floating-point number, and the number of withholding exemptions is presumably an
integer. The Social Security number could be represented as either an integer or a string;
because Social Security numbers are too big to fit within the limits imposed on integers
by many systems, they are represented here as strings.
Even though a record is made up of individual fields, it must have meaning as a
coherent whole. In the example of the employee roster, the fields in the first line of the
table represent a logically consistent set of data referring to Ebenezer Scrooge; those in
the second line refer to Bob Cratchit. The conceptual integrity of each record suggests
that the data for that employee should be collected into a compound data structure.
Moreover, since the individual fields making up that structure are of different types,
arrays are not suited to the task. In cases such as this, you need to define the set of data
for each employee as a record.
Data Types in C++ – 68 –
1. Define a new structure type. Before you declare any variables, you must first define a
new structure type. The type definition specifies what fields make up the record,
what the names of those fields are, and what type of information each field contains.
This structure type defines a model for all objects that have the new type but does not
by itself reserve any storage.
2. Declare variables of the new type. Once you have defined the new type, you can then
declare variables of that type so that you can store actual data values.
The general form for defining a new structure type looks like this:
struct name {
field-declarations
};
where field-declarations are standard variable declarations used to define the fields of the
structure and name indicates the name of the newly defined type. For example, the
following code defines a new structure type called employeeRecordT to represent
employee records:
struct employeeRecordT {
string name;
string title;
string ssnum;
double salary;
int withholding;
};
This definition provides a template for all objects that have the new type
employeeRecordT . Each such object will have five fields, starting with a name field,
which is a string, and continuing through a withholding field, which is an int.
employeeRecordT empRec;
If you want to illustrate this variable using a box diagram, you can choose to represent
it in either of two ways. If you take a very general view of the situation—which
corresponds conceptually to looking at the diagram from a considerable distance—what
you see is just a box named empRec:
empRec
If, on the other hand, you step close enough to see the details, you discover that the box
labeled empRec is composed internally of five individual boxes:
Data Types in C++ – 69 –
empRec
name title
Record selection
Once you have declared the variable empRec by writing
employeeRecordT empRec;
you can refer to the record as a whole simply by using its name. To refer to a specific
field within a record, you write the name of the complete record, followed by a period,
followed by the name of the field. Thus, to refer to the job title of the employee stored in
empRec, you need to write
empRec.title
When used in this context, the period is invariably called a dot, so that you would read
this expression aloud as “empRec dot title.” Selecting a field using the dot operator is
called record selection.
Initializing records
As with any other type of variable, you can initialize the contents of a record variable by
assigning values to its components. The dot operator returns an lvalue, which means that
you can assign values to a record selection expression. For example, if you were to
execute the statements
you would create the employee record for Ebenezer Scrooge used in the earlier examples.
You can also initialize its contents at the time the record is declared, using much the
same syntax as you use to initialize the elements of an array. Initializers for a record are
specified in the order in which they appear in the structure definition. Thus, you could
declare and initialize a record named manager that contains the data for Mr. Scrooge, as
follows:
employeeRecordT manager = {
"Ebenezer Scrooge", "Partner", "271-82-8183", 250.00, 1
};
Pointers to records
Although small records are sometimes used directly in C++, variables that hold structured
data in C++ are often declared to be pointers to records rather than the records
Data Types in C++ – 70 –
themselves. A pointer to a record is usually smaller and more easily manipulated than the
record itself.
Suppose, for example, that you want to declare a variable that points to employee
records. The syntax for such a declaration is the same as that for any other pointer. The
line
employeeRecordT *empPtr;
is still around, which means that you can make empPtr point to the empRec record by
writing
empPtr = &empRec;
empPtr empRec
name title
Starting from empPtr , how can you refer to an individual field in the underlying
record? In seeking an answer to this question, it is easy to be misled by your intuition. It
is not appropriate to write, for example,
Contrary to what you might have expected, this statement does not select the salary
component of the object to which empPtr points, because the precedence of the operators
in the expression does not support that interpretation. The selection operator takes
precedence over dereferencing, so the expression has the meaningless interpretation
*(empPtr.salary)
The latter form has the desired effect but is much too cumbersome for everyday use.
Pointers to structures are used all the time. Forcing programmers to include parentheses
in every selection would make records much less convenient. For this reason, C++
defines the operator ->, which combines the operations of dereference and selection into
a single operator. Thus, the conventional way to refer to the salary in the record to which
empPtr points is to write
empPtr->salary
The call to new operator will return the address of a storage location in the heap that has
been set aside to hold an integer.
The new operator can also be used to allocate variables of compound type. To allocate an
employee record in the heap, you could use the call:
The new[] operator is a variant that is used to allocate an array in the heap. Within the
square brackets, you specify the number of array elements, as shown in these examples:
The address returned by new[] is the base address of a contiguous piece of memory large
enough for the entire array. You can index into dynamic array using ordinary subscript
notation just as you would for a static array.
Data Types in C++ – 72 –
One way to help ensure that you don’t run out of memory is to free any storage you
have allocated when you are finished using it. C++ supplies the operator delete, which
takes a pointer previously allocated by new and returns the memory associated with that
pointer to the heap. If, for example, you determine that you are completely finished using
the storage allocated for ptr, you can free that storage for later reuse by calling
delete ptr;
The delete[] operator is used to free storage that was allocated using the new[]
operator. You do not indicate the number of elements in the square brackets when using
delete[].
Knowing when to free a piece of memory is not always an easy task, particularly as
programs become large. If several parts of a program share some data structure that has
been allocated in the heap, it may not be possible for any single part to recognize that the
memory can be freed. Given the size of memories today, however, you can often allocate
whatever memory you need without ever bothering to free it again. The problem of
limited memory typically becomes critical only when you design an application that
needs to run for a long period of time, such as the operating system on which all the other
facilities of the system depend. In these applications, it is important to free memory
when you no longer need it.
Some languages, including Java, support a system for dynamic allocation that actively
goes through memory to see what parts of it are in use, freeing any storage that is no
longer needed. This strategy is called garbage collection. Garbage-collecting allocators
exist for C++, and it is likely that their use will increase in coming years, particularly as
people become more familiar with their advantages. If it does, the policy of ignoring
deallocation will become reasonable even in long-running applications because you can
rely on the garbage collector to perform the deallocation operations automatically.
For the most part, this text assumes that your applications fall into the class of
problems for which allocating memory whenever you need it is a workable strategy. This
assumption will simplify your life considerably and make it easier for you to concentrate
on algorithmic details.
Dynamic arrays
From a conceptual perspective, an assignment of the form
cp = new char[10];
cp
The variable cp points to a set of 10 consecutive bytes that have been allocated in the
heap. Because pointers and arrays are freely interchangeable in C++, the variable now
acts exactly as if it had been declared as an array of 10 characters.
Arrays that you allocate on the heap and reference using a pointer variable are called
dynamic arrays and play a significant role in modern programming. The principal
differences between declared arrays and dynamic arrays are that
• The memory associated with a declared array is allocated automatically as part of the
declaration process. When the frame for the function declaring the array is created, all
the elements of that array are allocated as part of the frame. In the case of a dynamic
array, the actual memory is not allocated until you invoke the new[] operator.
• The size of a declared array must be a constant in the program. In contrast, because its
memory comes from the heap, a dynamic array can be of any size. Moreover, you can
adjust the size of a dynamic array according to the amount of data. If you know you
need an array with precisely N elements, you can reserve just the right amount of
storage.
You can allocate a dynamic array using the new[] operator. For example, if you
wanted to initialize the variable darray to a dynamic array of n values of type double,
you would declare darray using the line
double *darray;
Dynamic records
Dynamic memory allocation is just as useful for records as it is for arrays. If you declare
a pointer to a record, you can allocate memory to store the actual data in the record by
calling new. For example, if the type employeeRecordT is defined as
struct employeeRecordT {
string name;
string title;
string ssnum;
double salary;
int withholding;
};
you can assign space for a newly allocated record to the variable empPtr as follows:
employeeRecordT *empPtr;
empPtr = new employeeRecordT;
empPtr->name = "Eric S. Roberts";
Data Types in C++ – 74 –
Summary
In this chapter, you have learned how to use the data structure definition capabilities of
C++ to create new data types. The data structures presented in this chapter—pointers,
arrays, and records—form the foundation for abstract data types, which are presented in
later in this text. The principal advantage of these structures is that you can use them to
represent data in a way that reflects the real-world structure of an application. Moreover,
by combining pointers, arrays, and records in the right way, you can create hierarchical
structures that allow you to manage data complexity in much the same way that
decomposing a large program into separate functions allows you to manage algorithmic
complexity.
Important points in this chapter include:
• C++ allows you to define new atomic types by listing the elements that comprise the
domain of the type. Such types are called enumeration types and are part of a more
general class called scalar types that also includes characters and integers.
• Data values inside a computer are represented as collections of bits that are organized
into larger structures called bytes and words. Every byte in memory is associated with
a numeric address that can be used to refer to the data contained at that location.
• Addresses of data in memory are themselves data values and can be manipulated as
such by a program. A data value that is the address of some other piece of data is
called a pointer. Pointer variables are declared in C++ by writing an asterisk in front
of the variable name in its declaration line.
• The fundamental operations on pointers are & and *, which indicate the address of a
stored value and the value stored at a particular address, respectively.
• There is a special pointer value called NULL, which is used to indicate that a pointer
does not refer to anything.
• An array is an ordered, homogeneous collection of data values composed of elements
indicated by an index number. In C++, index numbers in an array always begin with
0. Arrays are declared by specifying a constant size in square brackets after the name
of the array. The size specified in the declaration is called the allocated size of the
array and is typically larger than the effective size, which is the number of elements
actually in use.
• When an array is passed as a parameter, the elements of the array are not copied.
Instead, the function is given the address of the actual array. As a result, if a function
changes the values of any elements of an array passed as a parameter, those changes
will be visible to the caller, which is working with the same array.
• A record is a heterogeneous collection of data values that forms a logically consistent
unit.
• The storage for arrays and records can be allocated dynamically from a pool of unused
memory called the heap. The standard operators new and new[] are used to allocate
records and dynamic arrays, respectively.
Review questions
1. Define each of the following terms: pointer, array, record.
2. What type definition would you use to define a new enumeration type polygonT
consisting of the following elements: Triangle , Square , Pentagon , Hexagon,
Octagon? How would you change the definition so that internal representation for
each constant name corresponded to the number of sides for that polygon?
Data Types in C++ – 75 –
3. What three advantages are cited in the text for defining a new enumeration type as
opposed to defining named constants to achieve an equivalent effect?
4. True or false: In C++, you may apply any operation defined on integers to values of
any scalar type.
5. At first glance, the following function looks very much like RightFrom, which is
defined in the section on “Scalar types”:
The RightFrom implementation works fine, but this one has a small bug. Identify
the problem, and then rewrite the function so that it correctly calculates the compass
direction that is 90 degrees to the left of dir.
8. True or false: In C++, a value of type int always requires four bytes of memory.
9. True or false: In C++, a value of type char always requires one byte of memory.
10. What is the purpose of the sizeof operator? How do you use it?
11. What reasons for using pointers are cited in this chapter?
13. What are the types of the variables introduced by the following declaration:
int * p1, p2;
14. What declaration would you use to declare a variable named pFlag as a pointer to a
Boolean value?
15. What are the two fundamental pointer operations? Which one corresponds to the
term dereferencing?
16. Explain the difference between pointer assignment and value assignment.
17. Draw diagrams showing the contents of memory after each line of the following
code:
v1 = 10; v2 = 25; p1 = &v1; p2 = &v2;
*p1 += *p2;
p2 = p1;
*p2 = *p1 + *p2;
21. Write the variable declaration and for loop necessary to create and initialize the
following integer array:
squares
0 1 4 9 16 25 36 49 64 81 100
0 1 2 3 4 5 6 7 8 9 10
22. What is the difference between allocated size and effective size?
23. Assuming that the base address for rectangular is 1000 and that values of type int
require four bytes of memory, draw a diagram that shows the address of each
element in the array declared as follows:
int rectangular[2][3];
24. Write a variable declaration that you could use to record the state of a chessboard,
which consists of an 8 x 8 array of squares, each of which may contain any one of the
following symbols:
K white king k black king
Q white queen q black queen
R white rook r black rook
B white bishop b black bishop
N white knight n black knight
P white pawn p black pawn
– empty square
Explain how you could initialize this array so that it holds the standard starting
position for a chess game:
r n b q k b n r
p p p p p p p p
- - - - - - - -
- - - - - - - -
- - - - - - - -
- - - - - - - -
P P P P P P P P
R N B Q K B N R
Data Types in C++ – 77 –
int intArray[10];
and that j is an integer variable, describe the steps the computer would take to
determine the value of the following expression:
&intArray[j + 3];
arr
and
&arr[0]
are equivalent.
27. Assume that variables of type double take up eight bytes on the computer system
you are using. If the base address of the array doubleArray is 1000, what is the
address value of doubleArray + 5?
int array[5];
and
int *p;
30. If the variable p is declared as a pointer to a record that contains a field called cost,
what is wrong with the expression
*p.cost
as a means of following the pointer from p to its value and then selecting the cost
field? What expression would you write in C++ to accomplish this dereference-and-
select operation?
32. Describe the effect of the following operators: new and delete.
Programming exercises
1. Define an enumeration type weekdayT whose elements are the days of the week.
Write functions NextDay and PreviousDay that take a value of type weekdayT and
return the day of the week that comes after or before the specified day, respectively.
Data Types in C++ – 78 –
Also write a function IncrementDay(startDay, delta) that returns the day of the
week that comes delta days after startDay. Thus, IncrementDay(Thursday, 4)
should return Monday. Your implementation of IncrementDay should work if the
value of delta is negative, in which case it should proceed backward in time.
2. Write a program that computes the surface area and volume of a cylinder, given the
height (h) and radius of the base (r) as shown in the following diagram:
A = 2π hr
V = π h r2
In this exercise, design your main program so that it consists of three function
calls: one to read the input data, one to compute the results, and one to display the
answers. When appropriate, use call by reference to communicate data between the
functions and the main program.
3. Because individual judges may have some bias, it is common practice to throw out
the highest and lowest score before computing the average. Modify the
gymjudge.cpp program from Figure 2-1 to discard the highest and lowest scores
before computing the average score.
4. Write a predicate function IsSorted(array, n) that takes an integer array and its
effective size as parameters and returns true if the array is sorted in nondecreasing
order.
5. In the third century B.C., the Greek astronomer Eratosthenes developed an algorithm
for finding all the prime numbers up to some upper limit N. To apply the algorithm,
you start by writing down a list of the integers between 2 and N. For example, if N
were 20, you would begin by writing down the following list:
2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20
Next you circle the first number in the list, indicating that you have found a prime.
You then go through the rest of the list and cross off every multiple of the value you
have just circled, since none of those multiples can be prime. Thus, after executing
the first step of the algorithm, you will have circled the number 2 and crossed off
every multiple of two, as follows:
2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20
From this point, you simply repeat the process by circling the first number in the
list that is neither crossed off nor circled, and then crossing off its multiples. In this
Data Types in C++ – 79 –
example, you would circle 3 as a prime and cross off all multiples of 3 in the rest of
the list, which would result in the following state:
2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20
Eventually, every number in the list will either be circled or crossed out, as shown in
this diagram:
2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20
The circled numbers are the primes; the crossed-out numbers are composites. This
algorithm for generating a list of primes is called the sieve of Eratosthenes.
Write a program that uses the sieve of Eratosthenes to generate a list of the primes
between 2 and 1000.
6. A histogram is a graphical way of displaying data by dividing the data into separate
ranges and then indicating how many data values fall into each range. For example,
given the set of exam scores
100, 95, 47, 88, 86, 92, 75, 89, 81, 70, 55, 80
a traditional histogram would have the following form:
*
*
*
* * *
* * * * * *
0–9 10–19 20–29 30–39 40–49 50–59 60–69 70–79 80–89 90–99 100
The asterisks in the histogram indicate one score in the 40s, one score in the 50s, five
scores in the 80s, and so forth.
When you generate histograms using a computer, however, it is usually much
easier to display them sideways on the page, as in this sample run:
HistogramSideways
0:
10:
20:
30:
40: *
50: *
60:
70: **
80: *****
90: **
100: *
Write a program that reads in an array of integers and then displays a histogram of
those numbers, divided into the ranges 0–9, 10–19, 20–29, and so forth, up to the
range containing only the value 100. Your program should generate output that
looks as much like the sample run as possible.
Data Types in C++ – 80 –
7. Rewrite the histogram program from the preceding exercise so that it displays the
histogram in a more traditional vertical orientation, like this:
Histogram
*
*
*
* * *
* * * * * *
0 10 20 30 40 50 60 70 80 90 100
nScores
13
scores
65 0 95 0 0 79 82 0 84 94 86 90 0
0 1 2 3 4 5 6 7 8 9 10 11 12
should remove the 0 scores, compressing the array into the following configuration:
nScores
8
scores
65 95 79 82 84 94 86 90
0 1 2 3 4 5 6 7 8 9 10 11 12
The dark squares in the bottom three rows are occupied by red checkers; the dark
squares in the top three rows contain black checkers. The two center rows are
unoccupied.
If you want to store the state of a checkerboard in a computer program, you need a
two-dimensional array indexed by rows and columns. The elements of the array
could be of various different types, but a reasonable approach is to use characters.
For example, you could use the letter r to represent a red checker and the letter b to
represent a black checker. Empty squares could be represented as spaces or hyphens
depending on whether the color of the square was light or dark.
Implement a function InitCheckerboard that initializes a checkerboard array so
that it corresponds to the starting position of a checkers game. Implement a second
function DisplayCheckerboard that displays the current state of a checkerboard on
the screen, as follows:
Checkerboard.sp
b b b b
b b b b
b b b b
- - - -
- - - -
r r r r
r r r r
r r r r
10. Design a function prototype that would allow a single function to find and return
simultaneously both the lowest and highest values in an array of type double.
Implement and test your function as shown in the following sample run:
FindRange
Enter the elements of the array, one per line.
Use -1 to signal the end of the list.
? 67
? 78
? 75
? 70
? 71
? 80
? 69
? 86
? 65
? 54
? 76
? 78
? 70
? 68
? 77
? -1
The range of values is 54-86
int *ip;
Data Types in C++ – 82 –
the statement
ip = IndexArray(10);
ip
0 1 2 3 4 5 6 7 8 9
12. Design a new type called payrollT that is capable of holding the data for a list of
employees, each of which is represented using the employeeT type introduced in the
section on “Dynamic records” at the end of the chapter. The type payrollT should
be a pointer type whose underlying value is a record containing the number of
employees and a dynamic array of the actual employeeT values, as illustrated by the
following data diagram:
Partner Clerk
271-82-8183 314-15-9265
250.00 15.00
1 7
After writing the types that define this data structure, write a function GetPayroll
that reads in a list of employees, as shown in the following sample run:
GetPayroll
How many employees: 2
Employee #1:
Name: Ebenezer Scrooge
Title: Partner
SSNum: 271-82-8183
Salary: 250.00
Withholding exemptions: 1
Employee #2:
Name: Bob Cratchit
Title: Clerk
SSNum: 314-15-9265
Salary: 15.00
Withholding exemptions: 7
Data Types in C++ – 83 –
After the input values have been entered, the GetPayroll function should return a
value of type payrollT that matches the structure shown in the diagram.
13. Write a program that generates the weekly payroll for a company whose employment
records are stored using the type payrollT, as defined in the preceding exercise.
Each employee is paid the salary given in the employee record, after deducting taxes.
Your program should compute taxes as follows:
• Deduct $1 from the salary for each withholding exemption. This figure is the
adjusted income. (If the result of the calculation is less than 0, use 0 as the
adjusted income.)
• Multiply the adjusted income by the tax rate, which you should assume is a flat
25 percent.
For example, Bob Cratchit has a weekly income of $15. Because he has seven
dependents, his adjusted income is $15 – (7 x $1), or $8. Twenty-five percent of $8
is $2, so Mr. Cratchit’s net pay is $15 – $2, or $13.
The payroll listing should consist of a series of lines, one per employee, each of
which contains the employee’s name, gross pay, tax, and net pay. The output should
be formatted in columns, as shown in the following sample run:
PrintPayroll
Name Gross Tax Net
----------------------------------------------
Ebenezer Scrooge 250.00 - 62.25 = 187.75
Bob Cratchit 15.00 - 2.00 = 13.00
14. Suppose that you have been assigned the task of computerizing the card catalog
system for a library. As a first step, your supervisor has asked you to develop a
prototype capable of storing the following information for each of 1000 books:
• The title
• A list of up to five authors
• The Library of Congress catalog number
• A list of up to five subject headings
• The publisher
• The year of publication
• Whether the book is circulating or noncirculating
Design the data structures that would be necessary to keep all the information
required for this prototype library database. Given your definition, it should be
possible to write the declaration
libraryT libdata;
and have the variable libdata contain all the information you would need to keep
track of up to 1000 books. Remember that the actual number of books will usually
be less than this upper bound.
Data Types in C++ – 84 –
that returns a dynamically allocated array of integers read in from the user. The
sentinel argument indicates the value used to signal the end of the input. The
second argument is an integer reference parameter, which is used to return the
effective size of the array. Note that it is impossible to know in advance how many
values the user will enter. As a result, the implementation must allocate new array
space as needed.
Chapter 3
Libraries and Interfaces
client implementation
interface
By mediating the communication between the two sides, an interface reduces the
conceptual complexity of the programming process by ensuring that details that lie on
one side of the interface boundary do not escape to complicate the code on the other side.
The code for each of your functions goes in the mylib.cpp implementation file. The
mylib.h interface contains only the function prototypes, which contain the information
the compiler needs to interpret any calls to those functions. Putting the prototypes in the
interface makes them available to clients and is called exporting those functions.
Although function prototypes are the most common component of an interface,
interfaces can export other definitions as well. In particular, interfaces often export data
types and constants. A single definition exported by an interface is called an interface
entry.
Once you have written the interface and implementation for a library, you—or some
other programmer with whom you are collaborating—can then write separate source files
that act as clients of the mylib.h interface. The relationship between the files
representing the client, interface, and implementation is illustrated in the following
diagram:
client.cpp mylib.h mylib.cpp
The distinction between the abstract concept of an interface and the header file that
represents it may at first seem subtle. In many ways, the distinction is the same as that
between an algorithm and a program that implements it. The algorithm is an abstract
strategy; the program is the concrete realization of that algorithm. Similarly, in C++,
header files provide a concrete realization of an interface.
implement those abstractions and make them real, in the sense that they can then be used
by programmers.
• Unified. A single interface should define a consistent abstraction with a clear unifying
theme. If a function does not fit within that theme, it should be defined in a separate
interface.
• Simple. To the extent that the underlying implementation is itself complex, the
interface must hide as much of that complexity from the client as possible.
• Sufficient. When clients use an abstraction, the interface must provide sufficient
functionality to meet their needs. If some critical operation is missing from an
interface, clients may decide to abandon it and develop their own, more powerful
abstraction. As important as simplicity is, the designer must avoid simplifying an
interface to the point that it becomes useless.
• General. A well-designed interface should be flexible enough to meet the needs of
many different clients. An interface that performs a narrowly defined set of operations
for one client is not as useful as one that can be used in many different situations.
• Stable. The functions defined in an interface should continue to have precisely the
same structure and effect, even if their underlying implementation changes. Making
changes in the behavior of an interface forces clients to change their programs, which
compromises the value of the interface.
Some interface changes, however, are more drastic than others. For example, adding
an entirely new function to an interface is usually a relatively straightforward process,
since no clients already depend on that function. Changing an interface in a way that
requires no changes to existing programs is called extending the interface. If you find
that you need to make evolutionary changes over the lifetime of an interface, it is usually
best to make those changes by extension.
#ifndef _random_h
#define _random_h
#endif
These three lines are often referred to as interface boilerplate. When you design your
own interfaces, you should be sure to include similar boilerplate lines, substituting the
name of your own interface for the name random in this example.
The purpose of the interface boilerplate is to prevent the compiler from reading the
same interface many times during a single compilation. The line
#ifndef _random_h
causes the compiler to skip any text up to the #endif line if the symbol _random_h has
been previously defined. When the compiler reads this interface for the first time,
_random_h is undefined, which means that the compiler goes ahead and reads the
contents of the file. The compiler immediately thereafter encounters the definition
#define _random_h
Libraries and Interfaces – 90 –
/*
* File: random.h
* --------------
* This interface provides several functions for generating
* pseudorandom numbers.
*/
#ifndef _random_h
#define _random_h
/*
* Function: RandomInteger
* Usage: n = RandomInteger(low, high);
* ------------------------------------
* This function returns a random integer in the range low to high,
* inclusive.
*/
/*
* Function: RandomReal
* Usage: d = RandomReal(low, high);
* ---------------------------------
* This function returns a random real number in the half-open
* interval [low .. high), meaning that the result is always
* greater than or equal to low but strictly less than high.
*/
/*
* Function: RandomChance
* Usage: if (RandomChance(p)) . . .
* ---------------------------------
* The RandomChance function returns true with the probability
* indicated by p, which should be a floating-point number between
* 0 (meaning never) and 1 (meaning always). For example, calling
* RandomChance(.30) returns true 30 percent of the time.
*/
/*
* Function: Randomize
* Usage: Randomize();
* -------------------
* This function initializes the random-number generator so that
* its results are unpredictable. If this function is not called,
* the other functions will return the same values on each run.
*/
void Randomize();
#endif
Libraries and Interfaces – 91 –
which defines the symbol _random_h. If the compiler reads the random.h interface a
second time, the symbol _random_h has already been defined, which means that the
compiler ignores the entire contents of the file on the second pass.
The remainder of the interface consists of function prototypes and their associated
comments. The first prototype is for the function RandomInteger(low, high), which
returns a randomly chosen integer in the range between low and high, inclusive. For
example, calling RandomInteger(1, 6) would return 1, 2, 3, 4, 5, or 6 and could be used
to simulate rolling a die. Similarly, calling RandomInteger(0, 36) returns an integer
between 0 and 36 and could be used to model a European roulette wheel, which is
marked with those 37 numbers.
The function RandomReal(low, high) is conceptually similar to RandomInteger and
returns a floating-point value r subject to the condition that low _ r < high. For example,
calling RandomReal(0, 1) returns a random number that can be as small as 0 but is
always strictly less than 1. In mathematics, a range of real numbers that can be equal to
one endpoint but not the other is called a half-open interval. On a number line, a half-
open interval is marked using an open circle to show that the endpoint is excluded, like
this:
0 1
In text, the standard convention is to use square brackets to indicate closed ends of
intervals and parentheses to indicate open ones, so that the notation [0, 1) indicates the
half-open interval corresponding to this diagram.
The function RandomChance(p) is used to simulate random events that occur with
some fixed probability. To be consistent with the conventions of statistics, a probability
is represented as a number between 0 and 1, where 0 means that the event never occurs
and 1 means that it always does. The RandomChance function returns a Boolean value
that is true with probability p, so that RandomChance(0.75) returns true 75 percent of
the time. You can use RandomChance to simulate flipping a coin, as illustrated by the
following function, which returns either "heads" or "tails":
string FlipCoin() {
if (RandomChance(0.50)) {
return "heads";
} else {
return "tails";
}
}
The last function in the random.h interface requires a little more explanation. Because
computers are deterministic machines, random numbers are usually computed by going
through a deterministic calculation that nonetheless appears random to the user. Random
numbers computed in this way are called pseudorandom numbers. If you take no
special action, the computer always applies the same process to generate its sequence of
random numbers, which means that the results will be the same every time the program is
run. The purpose of the Randomize function is to initialize the internal pseudorandom
number generator so that each run of the program produces a different sequence, which is
what you want if you are writing a program that plays a game.
At first, it may seem hard to understand why a random number package should return
the same values on each run. After all, deterministic behavior of this sort seems to defeat
Libraries and Interfaces – 92 –
the whole purpose of the package. There is, however, a good reason behind this
behavior: programs that behave deterministically are easier to debug. To illustrate this
fact, suppose you have just written a program to play an intricate game, such as
Monopoly™. As is always the case with newly written programs, the odds are good that
your program has a few bugs. In a complex program, bugs can be relatively obscure, in
the sense that they only occur in rare situations. Suppose you are playing the game and
discover that the program is starting to behave in a bizarre way. As you begin to debug
the program, it would be very convenient if you could regenerate the same state and take
a closer look at what is going on. Unfortunately, if the program is running in a
nondeterministic way, a second run of the program will behave differently from the first.
Bugs that showed up the first time may not occur on the second pass.
In general, it is extremely difficult to reproduce the conditions that cause a program to
fail if the program is behaving in a truly random fashion. If, on the other hand, the
program is operating deterministically, it will do the same thing each time it is run. This
behavior makes it possible for you to recreate the conditions under which the problem
occurred. When you write a program that works with random numbers, it is usually best
to leave out the call to Randomize during the debugging phase. When the program seems
to be working well, you can insert a call to Randomize at the beginning of the main
program to make the program change its behavior from one run to the next.
int rand();
Libraries and Interfaces – 93 –
/*
* File: craps.cpp
* ---------------
* This program plays the casino game called craps, which is
* played using a pair of dice. At the beginning of the game,
* you roll the dice and compute the total. If your first roll
* is 7 or 11, you win with what gamblers call a "natural."
* If your first roll is 2, 3, or 12, you lose by "crapping
* out." In any other case, the total from the first roll
* becomes your "point," after which you continue to roll
* the dice until one of the following conditions occurs:
*
* a) You roll your point again. This is called "making
* your point," which wins.
*
* b) You roll a 7, which loses.
*
* Other rolls, including 2, 3, 11, and 12, have no effect
* during this phase of the game.
*/
#include "genlib.h"
#include "random.h"
#include <iostream>
/* Function prototypes */
/* Main program */
int main() {
Randomize();
cout << "This program plays a game of craps." << endl;
int point = RollTwoDice();
switch (point) {
case 7: case 11:
cout << "That's a natural. You win." << endl;
break;
case 2: case 3: case 12:
cout << "That's craps. You lose." << endl;
break;
default:
cout << "Your point is " << point << "." << endl;
if (TryToMakePoint(point)) {
cout << "You made your point. You win." << endl;
} else {
cout << "You rolled a seven. You lose." << endl;
}
}
return 0;
}
Libraries and Interfaces – 94 –
/*
* Function: TryToMakePoint
* Usage: flag = TryToMakePoint(point);
* ------------------------------------
* This function is responsible for the part of the game
* during which you roll the dice repeatedly until you either
* make your point or roll a 7. The function returns true if
* you make your point and false if a 7 comes up first.
*/
/*
* Function: RollTwoDice
* Usage: total = RollTwoDice();
* -----------------------------
* This function rolls two dice and both prints and returns their sum.
*/
int RollTwoDice() {
cout << "Rolling the dice . . ." << endl;
int d1 = RandomInteger(1, 6);
int d2 = RandomInteger(1, 6);
int total = d1 + d2;
cout << "You rolled " << d1 << " and " << d2 << " - that's "
<< total << endl;
return total;
}
Unlike most functions, rand returns a different result each time it is called. The result of
rand is guaranteed to be nonnegative and no larger than the constant RAND_MAX, which is
also defined in the cstdlib interface. Thus, each time rand is called, it returns a
different integer between 0 and RAND_MAX, inclusive.
The value of RAND_MAX depends on the computer system. When you write programs
that work with random numbers, you should not make any assumptions about the precise
value of RAND_MAX. Instead, your programs should be prepared to use whatever value of
RAND_MAX the system defines.
You can get a sense of how rand behaves on your own system by running the program
const int N_TRIALS = 10;
int main() {
cout << "On this computer, RAND_MAX is " << RAND_MAX << endl;
cout << "The first " << N_TRIALS << " calls to rand:" << endl;
for (int i = 0; i < N_TRIALS; i++) {
cout << setw(10) << rand() << endl;
}
return 0;
}
Libraries and Interfaces – 95 –
RandTest
On this computer, RAND_MAX is 2147483647
The first 10 calls to rand:
16807
282475249
1622650073
984943658
1144108930
470211272
101027544
1457850878
1458777923
2007237709
You can see that the program is generating integers, all of which are positive and none of
which is greater than 2147483647, which the sample run shows as the value of RAND_MAX
for this machine. Although this number itself seems rather arbitrary, it happens to be
231 – 1, which is the largest value of type int on my computer. Because the numbers are
pseudorandom, you know that there must be some pattern, but it is unlikely that you can
discern one. From your point of view, the numbers appear to be random, because you
don’t know what the underlying pattern is.
The rand function generates each new random value by applying a set of mathematical
calculations to the last value it produced. Because you don’t know what those
calculations are, it is best to think of the entire operation as a black box where old
numbers go in on one side and new pseudorandom numbers pop out on the other. Since,
the first call to rand produces the number 16807, the second call to rand corresponds to
putting 16807 into one end of the black box and having 282475249 appear on the other:
black
16807 282475249
box
Similarly, on the next call to rand, the implementation puts 282475249 into the black
box, which returns 1622650073:
black
282475249 1622650073
box
This same process is repeated on each call to rand. The computation inside the black box
is designed so that (1) the numbers are uniformly distributed over the legal range, and (2)
the sequence goes on for a long time before it begins to repeat.
But what about the first call to rand—the one that returns 16838? The implementation
must have a starting point. There must be an integer, s0 , that goes into the black box and
produces 16807:
black
s0 16807
box
This initial value—the value that is used to get the entire process started—is called a seed
for the random number generator. The ANSI library implementation sets the initial seed
Libraries and Interfaces – 96 –
to a constant value every time a program is started, which is why the library always
generates the same sequence of values. To change the sequence, you need to set the seed
to a different value, which is done by calling the function srand(seed).
The srand function is essential to the implementation of Randomize, which resets the
seed so that the sequence of random numbers is different each time. The usual strategy is
to use the value of the internal system clock as the initial seed. Because the time keeps
changing, the random number sequence will change as well. You can retrieve the current
value of the system clock by calling the function time, which is defined in the library
interface ctime, and then converting the result to an integer. This technique allows you
to write the following statement, which has the effect of initializing the pseudorandom
number generator to some unpredictable point:
srand(int(time(NULL)));
Although it requires only a single line, the operation to set the random seed to an
unpredictable value based on the system clock is relatively obscure. If this line were to
appear in the client program, the client would have to understand the concept of a random
number seed, along with the functions srand and time. To make things simpler for the
client, it is much better to give this operation a simple name like Randomize and make it
part of the random number library. By doing so, the client simply needs to call
Randomize();
/*
* File: random.cpp
* -----------------
* This file implements the random.h interface.
*/
#include <cstdlib>
#include <ctime>
#include "random.h"
/*
* Function: RandomInteger
* -----------------------
* This function begins by using rand to select an integer
* in the interval [0, RAND_MAX] and then converts it to the
* desired range by applying the following steps:
*
* 1. Normalize the value to a real number in the interval [0, 1)
* 2. Scale the resulting value to the appropriate range size
* 3. Truncate the scaled value to an integer
* 4. Translate the integer to the appropriate starting point
*/
/*
* Function: RandomReal
* --------------------
* The implementation of RandomReal is similar to that
* of RandomInteger, without the truncation step.
*/
/*
* Function: RandomChance
* ----------------------
* This function uses RandomReal to generate a real number
* in the interval [0, 1) and then compares that value to p.
*/
bool RandomChance(double p) {
return RandomReal(0, 1) < p;
}
Libraries and Interfaces – 98 –
/*
* Function: Randomize
* -------------------
* This function operates by setting the random number
* seed to the current time. The srand function is
* provided by the <cstdlib> library and requires an
* integer argument. The time function is exported by
* the <ctime> interface.
*/
void Randomize() {
srand(int(time(NULL)));
}
• Normalization. The first step in the process is to convert the integer result from rand
into a floating-point number d in the half-open interval [0, 1). To do so, all you need to
do is convert the result of rand to a double and then divide it by the number of
elements in the range. Because RAND_MAX is often the largest integer the machine can
hold, it is important to convert it to a double before adding the constant 1, which
ensures that the division produces a value that is strictly less than 1.
• Scaling. The second step consists of multiplying the value d by the size of the desired
range, so that it spans the correct number of integers. Because the desired range
includes both the endpoints, low and high, the number of integers in the range is given
by the expression high - low + 1.
• Truncation. The third step consists of using a type cast to convert the number back to
an integer by throwing away any fraction. This step gives you a random integer with a
lower bound of 0.
• Translation. The final step consists of adding the value low so that the range begins at
the desired lower bound.
The steps in this process are illustrated by the diagram in Figure 3-4, which shows how a
call to RandomInteger(1, 6) converts the result of rand into an integer in the desired
range of 1 to 6.
3.3 Strings
In any programming language, strings are one of the most important data types because
they come up so frequently in applications. Conceptually, a string is just a sequence of
characters. For example, the string "hello, world" is a sequence of 12 characters
including ten letters, a comma, and a space. In C++, the string data type and its
associated operations are defined in the <string> interface, and you must therefore
include this interface in any source file that manipulates string data.
In many ways, string is an ideal example of an abstract data type, which is the topic
of the following chapter. However, given that strings are essential to many applications
and that they are more deeply integrated into the syntax of C++ than the classes described
in Chapter 4, it makes sense to introduce them before the others. In this chapter, you will
look at strings only from a client perspective, which means that you will be able to use
them as a tool without having to understand how their underlying implementation.
The data type string
In Chapter 1, you learned that a data type is defined by two properties: a domain and a set
of operations. If you think about strings as a separate data type, the domain is easy to
Libraries and Interfaces – 99 –
Initial call to r a n d
0 9768 RAND_MAX
Normalization
0 0.3 1
Scaling
0 1.8 6
Truncation
0 1 2 3 4 5 6
Translation
0 1 2 3 4 5 6
identify; the domain of type string is the set of all sequences of characters. The more
interesting problem is to identify an appropriate set of operations. Early versions of C++
and its predecessor language C did not have much support for manipulating strings. The
only facilities provided were fairly low-level operations that required you to be very
familiar with the precise representation of strings and work at a detailed level. The C++
standard introduced the standard string type that presents an abstract view of string and
a richer set of facilities for operating on strings. This allows us to focus on manipulating
strings using their published interface without concern for how strings might be internally
represented.
You can also create strings by concatenating existing strings using the + operator:
string str2 = str + "World";
The addition operator has been overloaded, or given multiple meanings. When + is
applied to numbers, it performs addition, when applied to strings, it performs string
concatenation. It is an error to attempt to add two operands of incompatible type such as a
double and a string.
The shorthand += form can be used to append onto an existing string. Both + and +=
allow concatenation of another string or a single character:
string str = "Stanford";
str += '!';
Libraries and Interfaces – 100 –
This assignment overwrites any previous contents of str2 with a copy of the characters
contained in str1 . The variables str1 and str2 remain independent. Changing the
characters in str1 would not cause any changes to str2.
When passing a string as parameter, a copy is made, just as with a primitive type.
Changes to the parameter made within a function are not reflected in the calling function
unless the string parameter is explicitly passed by reference.
Two strings can be compared using the relational operators, ==, !=, <, >, <=, and >=.
These operators compare strings lexicographically, which follows the order given by the
character codes. This ordering means case is significant, so "abc" is not equal to "ABC".
if (str == "quit") ...
You can retrieve the number of characters contained in a string by invoking the
lengthfunction on the string using the dot operator:
int numChars = str.length();
The syntax for calling the length function is different from what you have seen so far.
If length were like the functions in the random.h, you would expect to call it like this:
What makes length different is that it is an integral part of the string class and must
therefore be applied to a particular string object. In the expression
str.length()
the object is the variable str. In the language of the object-oriented paradigm, this object
to the left of the dot is called the receiver, and the syntax is intended to emphasize that
the object stored in str is receiving a request to perform the length operation.
Informally, it makes sense to think of this operation as sending a message to the object
asking for its length and having it respond by providing the requested information.
In C++, functions that are directed to a specific objects were originally called member
functions, but that designation is gradually giving way to the term method, which is
more common in other object-oriented languages. Functions that are independent of an
object—such as those you’ve seen up to now—are called free functions. Other than the
use of dot notation to identify the receiver, the mechanics of calling a method and calling
a free function are pretty much the same.
It is possible to access the ith character from a string str using the notation like that
of array selection, as follows:
str[i]
As with arrays, index numbers in a string begin at 0. Thus, if str contains the string
"Hello", then str[0] has the value 'H', str[1] has the value 'e', and so on.
Libraries and Interfaces – 101 –
The standard idiom for processing every character in a string looks like this:
for (int i = 0; i < str.length(); i++) {
. . . body of loop that manipulates str[i] . . .
}
On each loop cycle, the selection expression str[i] refers to the i th character in the
string. Because the purpose of the loop is to process every character, the loop continues
until i reaches the length of the string. Thus, you can count the number of spaces in a
string using the following function:
int CountSpaces(string str) {
int nSpaces = 0;
for (int i = 0; i < str.length(); i++) {
if (str[i] == ' ') nSpaces++;
}
return nSpaces;
}
As with array selection, selecting a character position that is out of range for the string is
not automatically recognized as an error but will typically lead to incorrect results.
The string interface exports a large number of methods, many of which come up only
in relatively specialized applications. Table 3-1 lists several of the more useful methods.
The code in Figure 3-5 provides a more extensive example of how you can use the
string interface to perform simple string manipulation. The principal function is
PigLatin, which converts an English word to
Pig Latin by applying the following rules:
• If the word contains no vowels, no translation is done, which means that the translated
word is the same as the original.
• If the word begins with a vowel, the function adds the string "way" to the end of the
original word. Thus, the Pig Latin equivalent of alley is alleyway.
• If the word begins with a consonant, the function extracts the string of consonants up
to the first vowel, moves that collection of consonants to the end of the word, and adds
the string "ay". For example, the Pig Latin equivalent of trash is ashtray.
The implementation of PigLatin uses the substr function to extract pieces of the
original word and string concatenation to reassemble them. The FindFirstVowel
function returns the integer index of the first vowel, or –1 if no vowel appears.
Figure 3-5 Implementation of Pig Latin translation using the string interface
/*
* Function: PigLatin
* Usage: translation = PigLatin(word);
* ------------------------------------
* This function translates a word from English to Pig Latin using
* the rules specified in Chapter 3. The translated word is
* returned as the value of the function.
*/
/*
* Function: FindFirstVowel
* Usage: k = FindFirstVowel(word);
* --------------------------------
* This function returns the index position of the first vowel
* in word. If word does not contain a vowel, FindFirstVowel
* returns -1. The code for IsVowel appears in Chapter 1.
*/
The principal advantage of the string interface is that strings are treated as abstract
values. When a function needs to return a string to its caller, it does so by returning a
string as its value. Any operations on that string are performed using the operations
exported by the library. The client is free from having to worry about the details of string
representation and allocation.
Even though this text relies extensively on the functions in the string interface, it is
not necessary to understand that code from the implementation side. The whole point of
interfaces is that they protect clients from the complexity of the implementation. As you
continue with your programming career, you will often make use of libraries even though
you have no understanding of their implementation, so it is best to become comfortable
with that process as early as you can.
/*
* File: strutils.h
* --------------
* The strutils.h file defines the interface for a library of string
* utilities.
*/
#ifndef _strutils_h
#define _strutils_h
#include "genlib.h"
/*
* Function: ConvertToLowerCase
* Usage: s = ConvertToLowerCase(s);
* ---------------------------------
* This function returns a new string with all
* alphabetic characters converted to lower case.
*/
/*
* Function: ConvertToUpperCase
* Usage: s = ConvertToUpperCase(s);
* ---------------------------------
* This function returns a new string with all
* alphabetic characters converted to upper case.
*/
/*
* Function: IntegerToString
* Usage: s = IntegerToString(n);
* ------------------------------
* This function converts an integer into the corresponding
* string of digits. For example, IntegerToString(123)
* returns "123" as a string.
*/
/*
* Function: StringToInteger
* Usage: n = StringToInteger(s);
* ------------------------------
* This function converts a string of digits into an integer.
* If the string is not a legal integer or contains extraneous
* characters, StringToInteger signals an error condition.
*/
/*
* Function: RealToString
* Usage: s = RealToString(d);
* ---------------------------
* This function converts a floating-point number into the
* corresponding string form. For example, calling
* RealToString(23.45) returns "23.45".
*/
/*
* Function: StringToReal
* Usage: d = StringToReal(s);
* ---------------------------
* This function converts a string representing a real number
* into its corresponding value. If the string is not a
* legal floating-point number or if it contains extraneous
* characters, StringToReal signals an error condition.
*/
#endif
arrays of characters with a sentinel value, the null character, used to mark the end of the
string. You can recognize older programs that operate on these C-style strings by their
use of the data type char* or char[]. Working with C-style strings is error-prone
because of the exposed-pointer implementation and issues of allocation. Using the C++
string type frees the programmer from managing string storage and decreases the
probability of difficult pointer bugs. Thus, you should use C++ strings wherever possible.
That said, there are some facilities in the standard libraries that predate the introduction of
the C++ string type and require the use of the older C-style strings. You can obtain the
C-style equivalent from a C++ string using the method c_str:
Libraries and Interfaces – 105 –
Some of the legacy of C++ is demonstrated by the fact that string literals are in fact C-
style strings. However, they are automatically converted to C++ strings as needed in most
contexts, so you can use a string literal in most places where a C++ string is expected.
Where needed, you can explicitly convert a string literal to a C++ string using a typecast-
like notation:
string str = string("Hello");
Data files
Whenever you want to store information on the computer for longer than the running
time of a program, the usual approach is to collect the data into a logically cohesive
whole and store it on a permanent storage medium as a file. Ordinarily, a file is stored
using magnetic or optical media, such as on a removable floppy disk, a compact disc, or a
hard disk. The important point is that the permanent data objects you store on the
computer—documents, games, executable programs, source code, and the like—are all
stored in the form of files.
On most systems, files come in a variety of types. For example, in the programming
domain, you work with source files, object files, and executable files, each of which has a
distinct representation. When you use a file to store data for use by a program, that file
usually consists of text and is therefore called a text file. You can think of a text file as a
sequence of characters stored in a permanent medium and identified by a file name. The
name of the file and the characters it contains have the same relationship as the name of a
variable and its contents.
As an example, the following text file contains the first stanza of Lewis Carroll’s
nonsense poem “Jabberwocky,” which appears in Through the Looking Glass:
jabberwocky.txt
'Twas brillig, and the slithy toves
Did gyre and gimble in the wabe;
All mimsy were the borogoves,
And the mome raths outgrabe.
the data. A string is stored temporarily in the computer’s memory during the time that a
program runs; a file is stored permanently on a long-term storage device until it is
explicitly deleted. There is also a difference in the way you use data in strings and files.
The individual characters in a string may be accessed in any order by specifying the
appropriate index. The characters in a text file are usually accessed in a sequential
fashion, with a program starting at the beginning of the file and either reading or writing
characters from the start to the end in order.
2. Open the file. Before you can use a stream variable, you need to establish an
association between that variable and an actual file. This operation is called opening
the file and is performed by calling the stream method open. Like the methods seen
previously on string, you invoke it using dot notation on the stream. For example, if
you wanted to read the text of the jabberwocky.txt file, you would execute the
statement
infile.open("jabberwocky.txt");
One minor glitch to note is that the open method expects a C-style string as the
argument. A string literal is acceptable as is, but if you have the filename in a C++
string variable, you will need to pass its C-style equivalent as shown:
string str = ...
infile.open(str.c_str());
If a requested input file is missing, the open operation will fail. You can test the
current state of a stream by using the fail method. As a programmer, you have a
responsibility to check for this error and report it to the user.
if (infile.fail()) Error("Could not open file.");
In some cases, you may want to recover from such an input file failure (for example,
if the user accidentally typed a non-existent filename), and try to open the input
stream once again. In such cases, you must first clear the "fail state" that the input
stream variable will be in after such a failure. You can do this by calling the clear
method on the stream, as exemplified below.
infile.clear();
3. Transfer the data. Once you have opened the data files, you then use the appropriate
stream operations to perform the actual I/O operations. For an input file, these
operations read data from the file into your program; for an output file, the operations
transfer data from the program to the file. To perform the actual transfers, you can
choose any of several strategies, depending on the application. At the simplest level,
you can read or write files character by character. In some cases, however, it is more
convenient to process files line by line. At a still higher level, you can choose to read
Libraries and Interfaces – 107 –
and write formatted data. Doing so allows you to intermix numeric data with strings
and other data types.
4. Close the file. When you have finished all data transfers, you need to indicate that
fact to the file system by calling the stream method close. This operation, called
closing the file, breaks the association between a stream variable and the actual file.
infile.close();
Standard streams
The standard I/O library defines three special identifiers—cin, cout, and cerr—that act
as stream variables and are available to all programs. These variables are referred to as
standard streams. The constant cin designates the standard input stream, which is the
source for user input. The constant cout indicates the standard output stream and
represents the device on which output data is written to the user. The constant cerr
represents the standard error stream and is used to report any error messages the user
should see. Typically, the standard streams all refer to the computer console. When you
read data from cin, the input comes from the keyboard; when you write data to cout or
cerr, the output appears on the screen. You do not open or close these streams; they are
handled automatically.
Formatted stream output
Stream output is usually accomplished by using the insertion operator <<. The operand on
the left is the output stream; the operand on the right is the data being inserted into the
stream. Thus far, you have only written to cout, but any open output stream can be used
as the destination.
outfile << "some text " << num << endl;
The insertion operator will accept any primitive data type on the right. Arrays are
treated as pointers in this context and only the base address is printed. Strings print the
entire sequence of characters. By default, complex types such as structs cannot be printed
with a single insertion operation, you must output each of the struct members one by one.
Several insertions can be chained together by multiple uses of the insertion operator. The
manipulator endl is used to output a newline.
Values are formatted according to the stream’s default rules unless you specify
otherwise. For explicit control, you insert I/O manipulators to set the field width,
alignment, precision, and other features on a per-stream basis. A few common output
manipulators options are described in the section on “Simple input and output” in
Chapter 1. Although the mechanisms for formatted I/O in any programming language can
be quite useful, they also tend to be detail-ridden. I recommend having a reference on
hand for looking up details on as-needed basis rather than memorizing the entirety of the
options.
The operand on the left is the input stream; the operand on the right is the variable that
will store the value read from the stream. The previous value of the variable is
overwritten by the next integer read from the stream.
The default setting for an input stream is to skip characters that appear as blank space,
such as the space, tab, and newline characters. When reading the next value, the insertion
operator will skip over any leading blank space and start reading from the first non-blank
character. When extracting a string from an input stream, a sequence of non-blank
characters is read, stopping at the first blank. To illustrate how blank space is handled,
consider the a text file with the following contents:
data.txt
3 45
some text
The code below attempts to extract two integers, a string, and character from this file:
int num1, num2;
string str;
char ch;
infile >> num1 >> num2 >> str >> ch;
After executing this code, num1 would hold the value 3, num2 the value 45, str would be
"some" , and ch would be 't'.
The extraction operator will fail if there is no input remaining or if the next input is not
compatible with the type you are attempting to extract. The stream method fail can be
used to test whether an extraction operation was successful.
if (infile.fail()) ...
If you were attempting to read and sum integers from a file until you reached the end, you
could use a loop such as this one:
int total, num;
total = 0;
while (true) {
infile >> num;
if (infile.fail()) break;
total += num;
}
For a program to be robust, it typically must take care to handle malformed input. This
is especially important when reading from cin, where the human user is prone to typing
errors at the console. To avoid cluttering the code with error-handling, this text does not
use the extraction operator on cin and relies instead on the facilities provided by the
simpio.h interface described in Chapter 1 that have error-handling built-in.
At first glance, the result type seems odd. The prototype indicates that COMMON PITFALLS
get returns an integer, even though conceptually the function returns a
character. The reason for this design decision is that returning a Remember that get
returns an int, not a
character would make it impossible for a program to detect the end-of- char. If you use a
file mark. There are only 256 possible character codes, and a data file variable of type char to
might contain any of those values. There is no value—or at least no store the result of get,
value of type char—that you could use as a sentinel to indicate the your program will be
end-of-file condition. By extending the definition so that get returns unable to detect the end-
an integer, the implementation can return a value outside the range of of-file condition.
legal character codes to indicate the end-of-file condition. That value
is given the symbolic name of EOF.
For output streams, the stream method put takes just one argument, a single character,
and writes that character to the stream:
outfile.put(ch);
As an example of the use of get and put, you can copy one file to another by calling
the following function:
void CopyFile(istream & infile, ostream & outfile) {
int ch;
while ((ch = infile.get()) != EOF) {
outfile.put(ch);
}
}
The while loop in CopyFile is highly idiomatic and deserves some consideration.
The test expression for the while loop uses embedded assignment to combine the
operations of reading in a character and testing for the end-of-file condition. When the
program evaluates the while condition, it begins by evaluating the subexpression
ch = infile.get()
which reads a character and assigns it to ch . Before executing the loop body, the
program then goes on to make sure the result of the assignment is not EOF . The
parentheses around the assignment are required; without them, the expression would
incorrectly assign to ch the result of comparing the character against EOF.
Note that both stream parameters are passed by reference to the function CopyFile.
Reading from and writing to a stream changes its internal state, and it is essential to pass
streams by reference so that the stream state is consistently maintained throughout the
context of the entire program.
should not copy it to the output file. On the other hand, it might be the division operator.
The only way to determine which of these cases applies is to look at the next character. If
it is an asterisk, you need to ignore both characters and make note of the fact that a
comment is in progress. If it not, however, what you would most like to do is forget that
you ever read that character and then treat it normally on the next cycle of the loop.
The stream interface provides a function that allows you to do just that. The method is
called unget and has the following form:
infile.unget();
The effect of this call is to “push” the last character read back into the input stream so
that it is returned on the next call to get. The C++ libraries only guarantee the ability to
push back one character into the input file, so you should not rely on being able to read
several characters ahead and then push them all back. Fortunately, being able to push
back one character is sufficient in the vast majority of cases.
An implementation of a function CopyRemovingComments that uses unget is shown in
Figure 3-7.
Line-oriented I/O
Because files are usually subdivided into individual lines, it is often useful to read an
entire line of data at a time. The stream function that performs this operation is called
getline . (not to be confused with the similarly-named GetLine function from the
simpio.h interface). Unlike the other stream operations we’ve discussed, getline is not
a method and is not invoked using dot notation. getline takes two arguments, the input
stream to read from, and a string; both are reference parameters.
getline(infile, str);
The effect of this function is to copy the next line of the file into the string parameter.
getline removes the newline character used to signal the end of the line, so that the
string contains simply the characters on the line. The string will be the empty string if the
next character coming up in the stream is a newline. The getline function will fail if
there are no more lines to be read from the file. As always, you can test whether the
stream is in failure state using the fail method
Some of the most common operations exported by the iostream and fstream
interfaces are summarized in Table 3-3.
Table 3-3 Common operations for the iostream and fstream classes
Call Operations for all streams
file.open(filename) This method attempts to open the named file and attach it to the
receiver stream file. Note that the filename parameter is a C-style
string, not a C++ string object. You can convert a C++ string to
its C-style equivalent with the string method c_str . You can
check whether open fails by calling the fail method.
file.close() This method closes the file attached to the stream file.
file.fail() This method returns a boolean indicating the error state of the
stream file. A true result means that a previous operation on this
stream failed for some reason. Once an error occurs, the error state
must be cleared before any further operations will succeed.
file.clear() This method clears the error state of the stream file. After an error,
you must clear the stream before executing subsequent operations.
Operations for input streams
infile.get() This method reads and returns the next character from the input
stream infile. If there are no more characters, get returns the
constant EOF. Note that the return value is of type int, not char.
infile.unget() This method pushes the last character read back onto the input
stream infile .
getline(infile, str) This function reads the next line from the input stream infile into
the reference parameter str , discarding the newline. Note this is not
a method, but an ordinary free function. (This is a different
function than GetLine from simpio.h.)
infile >> var The stream extraction operation reads a value into var from the
input stream infile. By default, leading whitespace is skipped. If
there is no input remaining or the next input is not compatible
with the type of var, the stream is set into an error state.
Operations for output streams
outfile.put(ch) This method writes the character ch to the output stream outfile.
outfile << expr This stream insertion operations writes the value of expr to the
output stream outfile. The expression can evaluate to any type that
has a defined stream insertion behavior, generally this means all
primitive types and string.
Libraries and Interfaces – 112 –
In some cases, the functions in these interfaces are easy to implement on your own.
Even so, it is good programming practice to use the library functions instead of writing
your own. There are three principal reasons for doing so:
1. Because the library functions are standard, programs you write will be easier for other
programmers to read. Assuming that the programmers are at all experienced in C++,
they will recognize these functions and know exactly what they mean.
2. It is easier to rely on library functions for correctness than on your own. Because the
C++ libraries are used by millions of client programmers, there is considerable
pressure on the implementers to get the functions right. If you rewrite library
functions yourself, the chance of introducing a bug is much larger.
3. The library implementations of functions are often more efficient than those you can
write yourself. Because these libraries are standard and their performance affects
many clients, the implementers have a large incentive to optimize the performance of
the libraries as much as possible.
Summary
In this chapter, you have learned about interfaces, which are the points of connection
between the client of a library abstraction and the corresponding implementation.
Interfaces are one of the central themes of modern programming and will be used
extensively throughout the rest of this text. You have also learned how to use several
specific interfaces including random.h, string, fstream, cctype, and cmath.
Important points in this chapter include:
Review questions
1. Define the following terms: interface, package, abstraction, implementation, client.
Libraries and Interfaces – 114 –
24. What is the result of calling each of the following functions from the string
interface?
string s = "ABCDE", t = "";
a. s.length();
b. t.length();
c. s[2]
d. s + t
e. t += 'a'
f. s.replace(0, 2, "Z")
g. s.substr(0, 3)
h. s.substr(4)
i. s.substr(3, 9)
j. s.substr(3, 3)
26. What is the purpose of the types ifstream and ofstream? Is understanding the
underlying structure of these types important to most programmers?
27. The argument to open must be a C-style string. What is the significance of this
requirement?
28. How can you determine if an open operation on a stream was unsuccessful?
29. The iostream interface automatically defines three standard streams. What are their
names? What purpose does each one serve?
30. When you are using the get method, how do you detect the end of a file?
31. Why is the return type of get declared as int instead of char?
32. What is the purpose of the unget method?
33. How can you determine whether an extraction operation on a stream was successful?
34. What are the differences between the functions GetLine and getline?
Libraries and Interfaces – 116 –
35. True or false: It is very worthwhile to memorize all the features of the standard I/O
library since they are used so extensively.
36. What is the result of each of the following calls from cctype:
a. isdigit(7)
b. isdigit('7')
c. isalnum('7')
d. toupper('7')
e. toupper('A')
f. tolower('A')
37. When using the trigonometric functions in the cmath interface, how can you convert
an angle from degrees to radians?
Programming exercises
1. Write a program that repeatedly generates a random real number between 0 and 1
and then displays the average after a certain number of runs, as illustrated by the
following sample run:
AverageRand
This program averages a series of random numbers
between 0 and 1.
How many trials: 10000
The average value after 10000 trials is 0.501493
If the random number generator is working well, the average should get closer to 0.5
as the number of trials increases.
2. Heads. . . .
Heads. . . .
Heads. . . .
A weaker man might be moved to re-examine his faith, if in nothing
else at least in the law of probability.
— Tom Stoppard, Rosencrantz and Guildenstern Are Dead, 1967
Write a program that simulates flipping a coin repeatedly and continues until three
consecutive heads are tossed. At that point, your program should display the total
number of coin flips that were made. The following is one possible sample run of
the program:
ConsecutiveHeads
tails
heads
heads
tails
tails
heads
tails
heads
heads
heads
It took 10 flips to get 3 consecutive heads.
Libraries and Interfaces – 117 –
3. In casinos from Monte Carlo to Las Vegas, one of the most common gambling
devices is the slot machine—the “one-armed bandit.” A typical slot machine has
three wheels that spin around behind a narrow window. Each wheel is marked with
the following symbols: CHERRY, LEMON, ORANGE, PLUM, BELL, and BAR. The window,
however, allows you to see only one symbol on each wheel at a time. For example,
the window might show the following configuration:
If you put a dollar into a slot machine and pull the handle on its side, the wheels spin
around and eventually come to rest in some new configuration. If the configuration
matches one of a set of winning patterns printed on the front of the slot machine, you
get back some money. If not, you’re out a dollar. The following table shows a
typical set of winning patterns, along with their associated payoffs:
The notation BELL/BAR means that either a BELL or a BAR can appear in that position,
and the dash means that any symbol at all can appear. Thus, getting a CHERRY in the
first position is automatically good for $2, no matter what appears on the other
wheels. Note that there is never any payoff for the LEMON symbol, even if you
happen to line up three of them.
Write a program that simulates playing a slot machine. Your program should
provide the user with an initial stake of $50 and then let the user play until the money
runs out or the user decides to quit. During each round, your program should take
away a dollar, simulate the spinning of the wheels, evaluate the result, and pay the
user any appropriate winnings. For example, a user might be lucky enough to see the
following sample run:
Slots
Would you like instructions? no
You have $50. Would you like to play? yes
PLUM LEMON LEMON -- You lose
You have $49. Would you like to play? yes
PLUM BAR LEMON -- You lose
You have $48. Would you like to play? yes
BELL LEMON ORANGE -- You lose
You have $47. Would you like to play? yes
CHERRY CHERRY ORANGE -- You win $5
You have $51. Would you like to play? yes
BAR BAR BAR -- You win $250
You have $300. Would you like to play? no
Even though it’s not realistic (and would make the slot machine unprofitable for the
casino), you should assume that the six symbols are equally likely on each wheel.
Libraries and Interfaces – 118 –
7. One of the simplest types of codes used to make it harder for someone to read a
message is a letter-substitution cipher, in which each letter in the original message
is replaced by some different letter in the coded version of that message. A
particularly simple type of letter-substitution cipher is a cyclic cipher, in which each
letter is replaced by its counterpart a fixed distance ahead in the alphabet. The word
cyclic refers to the fact that if the operation of moving ahead in the alphabet would
take you past Z, you simply circle back to the beginning and start over again with A.
Using the string functions provided by the string interface, implement a function
EncodeString with the prototype
string EncodeString(string str, int key);
The function returns the new string formed by shifting every letter in str forward
the number of letters indicated by key, cycling back to the beginning of the alphabet
if necessary. For example, if key has the value 4, the letter A becomes E, B becomes
F, and so on up to Z, which becomes D because the coding cycles back to the
beginning. If key is negative, letter values should be shifted toward the beginning of
the alphabet instead of the end.
After you have implemented EncodeString, write a test program that duplicates
the examples shown in the following sample run:
CyclicCipher
This program encodes messages using a cyclic cipher.
To stop, enter 0 as the key.
Enter the key: 4
Enter a message: ABCDEFGHIJKLMNOPQRSTUVWXYZ
Encoded message: EFGHIJKLMNOPQRSTUVWXYZABCD
Enter the key: 13
Enter a message: This is a secret message.
Encoded message: Guvf vf n frperg zrffntr.
Enter the key: -1
Enter a message: IBM-9000
Encoded message: HAL-9000
Enter the key: 0
Note that the coding operation applies only to letters; any other character is included
unchanged in the output. Moreover, the case of letters is unaffected: lowercase
letters come out as lowercase, and uppercase letters come out as uppercase.
Libraries and Interfaces – 119 –
9. Write a program wc.cpp that reads a file and reports how many lines, words, and
characters appear in it. For the purposes of this program, a word consists of a
consecutive sequence of any characters except whitespace characters. For example,
if the file twinkle.txt contains the following verse from Alice in Wonderland,
10. In the 1960s, entertainer Steve Allen often played a game called madlibs as part of
his comedy routine. Allen would ask the audience to supply words that fit specific
categories—a verb, an adjective, or a plural noun, for example—and then use these
words to fill in blanks in a previously prepared text that he would then read back to
the audience. The results were usually nonsense, but often very funny nonetheless.
In this exercise, your task is to write a program that plays madlibs with the user.
The text for the story comes from a text file that includes occasional placeholders
enclosed in angle brackets. For example, suppose the input file carroll.txt
contains the following excerpt from Lewis Carroll’s poem “The Walrus and the
Carpenter,” with a few key words replaced by placeholders as shown:
Your program must read this file and display it on the console, giving the user the
chance to fill in the placeholders with new strings. If Carroll himself had used the
program, he would likely have obtained the following sample run:
Libraries and Interfaces – 120 –
MadLibs
Input file: carroll.txt
animal: Walrus
plural noun: shoes
sticky substance: wax
plural vegetable name: cabbages
body of water: sea
plural animal name: pigs
Note that the user must provide all the substitutions before any of the text is
displayed. This design complicates the program structure slightly because it is
impossible to display the output text as you go. The simplest strategy is to write the
output to a temporary file first and then copy the contents of the temporary file back
to the screen.
11. Write a program that plays the game of hangman. In hangman, the computer begins
by selecting a secret word at random from a list of possibilities. It then prints out a
row of dashes—one for each letter in the secret word—and asks the user to guess a
letter. If the user guesses a letter that appears in the word, the word is redisplayed
with all instances of that letter shown in the correct positions, along with any letters
guessed correctly on previous turns. If the letter does not appear in the word, the
player is charged with an incorrect guess. The player keeps guessing letters until
either (1) the player has correctly guessed all the letters in the word or (2) the player
has made eight incorrect guesses. A sample run of the hangman program is shown in
Figure 3-8.
To separate the process of choosing a secret word from the rest of the game,
define and implement an interface called randword.h that exports two functions:
InitDictionary and ChooseRandomWord. InitDictionary should take the name
of a data file containing a list of words, one per line, and read it into an array
declared as a static global variable in the implementation. ChooseRandomWord takes
no arguments and returns a word chosen at random from the internally maintained
array.
12. Design and implement an interface called card.h that exports the following interface
entries:
• A type rankT that allows you to represent the rank of a card. The values of type
rankT include the integers between 2 and 10 but should also include the constants
Ace, Jack, Queen, and King.
• A type suitT consisting of the four suits: Clubs, Diamonds, Hearts, and Spades.
• A type cardT that combines a rank and a suit.
• A function NewCard(rank, suit) that creates a cardT from the rank and suit values.
• Two functions, Rank(card) and Suit(card), that allow the client to select the rank
and suit of a cardT value. These functions could easily be replaced by code that
selected the appropriate components of the card, but defining them as functions
means that the client need not pay attention to the underlying structure of the type.
Libraries and Interfaces – 121 –
• A function CardName(card) that returns a string identifying the card. The result of
CardName begins with a rank indicator (which is one of A, 2, 3, 4, 5, 6, 7, 8, 9, 10,
J, Q, or K), followed by a one-character suit (C, D, H, or S). Note that the result
is usually a two-character string, but contains three characters if the rank is a 10.
13. Using the card.h interface from the preceding exercise, write a program that
initializes a complete deck of 52 cards, shuffles it, and then displays the shuffled
values, as shown in the following sample run:
ShuffleDeck
This program initializes, shuffles, and displays
a deck of playing cards.
AH 10C 5D 4H JS AD KH 3C 4C 2D 6C AC JD
2H KS 9H 5S AS 6S 6D 8S KD 2S 7H 8H 5C
8C QH 4S 9S QS 9D 6H 7S 9C 7D 3H JH 10D
KC 10H 8D 2C 7C QD JC 5H QC 4D 10S 3D 3S
One of the easiest ways to shuffle the contents of an array is to adopt the strategy
represented by the following pseudocode:
for (each position p1 in the array) {
Pick a random position p2 between p1 and the end of the array.
Exchange the values at positions p 1 and p2 .
}
Chapter 4
Using Abstract Data Types
As you know from your programming experience, data structures can be assembled to
form hierarchies. The atomic data types—such as int, char, double, and enumerated
types—occupy the lowest level in the hierarchy. To represent more complex
information, you combine the atomic types to form larger structures. These larger
structures can then be assembled into even larger ones in an open-ended process.
Collectively, these assemblages of information into more complex types are called data
structures.
As you learn more about programming, however, you will discover that particular data
structures are so useful that they are worth studying in their own right. Moreover, it is
usually far more important to know how those structures behave than it is to understand
their underlying representation. For example, even though a string might be represented
inside the machine as an array of characters, it also has an abstract behavior that
transcends its representation. A type defined in terms of its behavior rather than its
representation is called an abstract data type, which is often abbreviated to ADT.
Abstract data types are central to the object-oriented style of programming, which
encourages thinking about data structures in a holistic way.
In this chapter, you will have a chance to learn about seven classes—Vector, Grid,
Stack , Queue , Map , Lexicon , and Scanner —each of which represents an important
abstract data type. For the moment, you will not need to understand how to implement
those classes. In subsequent chapters, you’ll have a chance to explore how each of these
classes can be implementated and to learn about the algorithms and data structures
necessary to make those implementations efficient.
Being able to separate the behavior of a class from its underlying implementation is a
fundamental precept of object-oriented programming. As a design strategy, it offers the
following advantages:
• Simplicity. Hiding the internal representation from the client means that there are
fewer details for the client to understand.
• Flexibility. Because a class is defined in terms of its public behavior, the programmer
who implements one is free to change its underlying private representation. As with
any abstraction, it is appropriate to change the implementation as long as the interface
remains the same.
• Security. The interface boundary acts as a wall that protects the implementation and
the client from each other. If a client program has access to the representation, it can
change the values in the underlying data structure in unexpected ways. Making the
data private in a class prevents the client from making such changes.
The ADT classes used in this book are inspired by and draw much of their structure
from a more advanced set of classes available for C++ called the Standard Template
Library, or STL for short. Although the STL is extremely powerful and provides some
capabilities beyond the somewhat simplified class library covered in this book, it is also
more difficult to understand from both the client and implementation perspectives. One
of the primary advantages of using the simplified class library is that you can easily
understand the entire implementation by the time you finish this book. Understanding the
implementation gives you greater insight into how classes work in general and what
libraries like the Standard Template Library are doing for you behind the scenes.
Experience has shown, however, that you will be able to understand the implementation
of a class more easily if you have first had a chance to use with that class as a client.
Using Abstract Data Types – 125 –
Arrays are a fundamental type in almost all programming languages and have been
part of programming language designs since the beginnings of the field. Arrays,
however, have a number of weaknesses that can make using them difficult, such as the
following:
• Arrays are allocated with a particular size that doesn’t change after the array is
allocated.
• Even though arrays have a fixed size, C++ does not in fact make that size available to
the programmer. In most applications, you need to keep track of the effective size of
the array, as discussed in Chapter 2.
• It is impossible to insert new elements into an array or to delete elements without
writing a fair amount of code to shift the existing elements to new index positions.
• Many languages, including both C and C++, make no effort to ensure that the elements
you select are actually present in the array. For example, if you create an array with 25
elements and then try to select the value at index position 50, C++ will not ordinarily
detect this as an error. Instead, the program will blithely go on and look at the memory
addresses at which element 50 would appear if the array were long enough. It would
be far better if arrays in C++ (as they do in Java) implemented bounds checking,
which means that every array access checks to see whether the index is valid.
The Vector class solves each of these problems by reimplementing the array concept
in the form of an abstract data type. You can use the Vector class in place of arrays in
any application, usually with surprisingly few changes in the source code and only a
minor reduction in efficiency. In fact, once you have the Vector class, it’s unlikely that
you will have much occasion to use arrays at all, unless you actually have to implement
classes like Vector, which, not surprisingly, uses arrays in its underlying structure. As a
client of the Vector class, however, you are not interested in that underlying structure
and can leave the array mechanics to the programmers who implement the abstract data
type.
As a client of the Vector class, you are concerned with a different set of issues and
need to answer the following questions:
1. How is it possible to specify the type of object contained in a Vector?
2. How does one create an object that is an instance of the Vector class?
3. What methods are available in the Vector class to implement its abstract behavior?
The next three sections explore the answers to each of these questions in turn.
Using Abstract Data Types – 126 –
In C++, that is precisely what you do. That declaration introduces a new variable named
vec, which is—as the template marker in angle brackets indicates—a vector of integers.
As it happens, however, there is more going on in that declaration than meets the eye.
Unlike declarations of a primitive type, declarations of a new class instance automatically
initialize the object by invoking a special method called a constructor. The constructor
for the Vector class initializes the underlying data structures so that they represent a
vector with no elements, which is called an empty vector, to which you can later add any
elements you need. As a client, however, you have no idea what those underlying data
structures are. From your point of view, the constructor simply creates the Vector object
and leave it ready for you to use.
vec.add(10);
vec.add(20);
vec.add(30);
would create a three-element vector containing the values 10, 20, and 30. Conceptually,
you could diagram the resulting structure just as if it were an array:
vec
10 20 30
0 1 2
The major difference between the vector and the array is that you can add additional
elements to the vector. For example, if you subsequently called
vec.add(40);
the vector would expand to make room for the new element, like this:
vec
10 20 30 40
0 1 2 3
The insertAt method allows you to add new elements in the middle of a vector. The
first argument to insertAt is an index number, and the new element is inserted before
that position. For example, if you call
vec.insertAt(2, 25);
Internally, the implementation of the Vector class has to take care of moving the values
30 and 40 over one position to make room for the 25. From your perspective as a client,
all of that is handled magically by the class.
The Vector class also lets you remove elements. For example, calling
vec.removeAt(0);
Once again, the implementation takes care of shifting elements to close the hole left by
the deleted value.
Now that you have a way of getting elements into a vector, it would be useful to know
how to examine them once they are there. The counterpart to array selection in the
Vector class is the getAt method, which takes an index number and returns the value in
that index position. For example, given the most recent of vec, calling vec.getAt(2)
would return the value 30. If you were to call vec.getAt(5), the bounds-checking code
in the Vector implementation would signal an error because no such element exists.
Symmetrically, you can change the value of an element by calling the setAt method.
Calling
vec.setAt(3, 35);
Even though the getAt and setAt methods are relatively simple to use, hardly anyone
in fact calls these methods directly. One of the characteristics of C++ that sets it apart
from most other languages is that classes can override the definition of the standard
operators In particular, C++ allows classes to override the selection operator used to
select elements in an array. This feature makes it possible for the Vector class to support
exactly the same selection syntax as arrays. To select the element at position i, all you
need to write is
vec[i];
To change an element, all you need to do is assign to the selected element. Thus, you can
set element 3 in vec to 35 by writing
vec[3] = 35;
The resulting syntax is marginally shorter but considerably more evocative of the array
operations that the Vector class tries to emulate.
Inside the loop body, you can refer to the current element as vec[i].
As an example, the following code writes out the contents of the vector vec as a
comma-separated list enclosed in square brackets:
cout << "[";
for (int i = 0; i < vec.size(); i++) {
if (i > 0) cout << ", ";
cout << vec[i];
}
cout << "]" << endl;
If you were to execute this code given the most recent contents of vec, you would see the
following output on the screen:
PrintVector
[20, 25, 30, 35]
The header line, however, involves one subtlety that you absolutely have to understand
before you can use the library classes effectively. As described in Chapter 1, the & before
the parameter name indicates that the argument to PrintVector is passed by reference,
which means that the vector in the caller is shared with the vector in the function.
Passing by reference is more efficient than C++’s default model of passing by value,
which specifies that the entire contents of the argument vector must be copied before
passing it along to the function. More importantly, passing by reference makes it
possible for you to write functions that change the contents of a vector. As an example,
the following function adds the elements of an integer array to a vector:
void AddArrayToVector(Vector<int> & vec, int array[], int n) {
for (int i = 0; i < n; i++) {
vec.add(array[i]);
}
}
Using Abstract Data Types – 130 –
If you had left out the ampersand in this header line, the function COMMON PITFALLS
would have no effect at all. The code would happily add the first n
elements from array to a vector, but that vector would be a copy of When you are using the
classes in the template
the one the caller supplied. As soon as AddArrayToVector returned, library, you should always
that copy would go away, leaving the original value unchanged. This pass them by reference.
kind of error is easy to make, and you should learn to look for it when The C++ compiler won’t
your programs go awry. notice if you don’t, but the
results are unlikely to be
The revfile.cpp program in Figure 4-1 shows a complete C++ what you intend.
program that uses V e c t o r to reverse the lines in a file. The
AskUserForInputFile and ReadTextFile in this example will
/*
* File: revfile.cpp
* -----------------
* This program reads in a text file and then displays the lines of
* the file in reverse order.
*/
#include "genlib.h"
#include "simpio.h"
#include "vector.h"
#include <string>
#include <iostream>
#include <fstream>
/* Function prototypes */
void ReadTextFile(ifstream & infile, Vector<string> & lines);
void AskUserForInputFile(string prompt, ifstream & infile);
void PrintReversed(Vector<string> & lines);
/* Main program */
int main() {
ifstream infile;
AskUserForInputFile("Input file: ", infile);
Vector<string> lines;
ReadTextFile(infile, lines);
infile.close();
PrintReversed(lines);
return 0;
}
/*
* Reads an entire file into the Vector<string> supplied by the user.
*/
void ReadTextFile(ifstream & infile, Vector<string> & lines) {
while (true) {
string line;
getline(infile, line);
if (infile.fail()) break;
lines.add(line);
}
}
Using Abstract Data Types – 131 –
/*
* Opens a text file whose name is entered by the user. If the file
* does not exist, the user is given additional chances to enter a
* valid file. The prompt string is used to tell the user what kind
* of file is required.
*/
void AskUserForInputFile(string prompt, ifstream & infile) {
while (true) {
cout << prompt;
string filename = GetLine();
infile.open(filename.c_str());
if (!infile.fail()) break;
cout << "Unable to open " << filename << endl;
infile.clear();
}
}
/*
* Prints the lines from the Vector<string> in reverse order.
*/
void PrintReversed(Vector<string> & lines) {
for (int i = lines.size() - 1; i >= 0; i--) {
cout << lines[i] << endl;
}
}
probably come in handy in a variety of applications, and you might want to keep a copy
of this program around so that you can cut-and-paste these functions into your own code.
Even though the elements of the matrix are created by the constructor, they may not be
initialized in any helpful way. If the elements of the grid are objects, they will be
initialized by calling the default constructor for that class, which is simply the
constructor that takes no arguments. If the elements, however, are of a primitive type like
double, C++ does not initialize them, and their values depend on whatever happened be
in the memory locations to which those variables were assigned. It is therefore a good
programming practice to initialize the elements of a Grid explicitly before you use them.
To initialize the elements of a grid, you need to know what methods are available to
manipulate the values the grid contains. The most common methods in the Grid class are
shown in Table 4-2. As you can see from the table, the Grid class does include getAt
and setAt methods that allow you to work with individual elements, but it is far more
common to use the more familiar bracket-selection syntax. For example, if you want to
set every element in the matrix grid to 0.0, you could do so with the following code:
for (int i = 0; i < matrix.numRows(); i++) {
for (int j = 0; j < matrix.numCols(); j++) {
matrix[i][j] = 0.0;
}
}
Players take turns placing the letters X and O in the empty squares, trying to line up three
identical symbols horizontally, vertically, or diagonally.
If you want to represent a tic-tac-toe board using the classes provided in this chapter,
the obvious approach is to use a Grid with three rows and three columns. Given that
each of the elements contains a character—an X, an O, or a space—the declaration of a
board will presumably look like this:
Grid<char> board(3, 3);
You will have a chance to see an program that plays tic-tac-toe in Chapter 7, but for now,
it is sufficient to look at how you might manipulate a tic-tac-toe board declared in this
way. Figure 4-2, for example, contains the code for checking to see whether a player has
won the game by looking to see whether the same character appears in every cell of a
row, a column, or a diagonal.
Figure 4-2 Program to check whether a player has won a tic-tac-toe game
/*
* Checks to see whether the specified player identified by mark
* ('X' or 'O') has won the game. To reduce the number of special
* cases, this implementation uses the helper function CheckLine.
*/
bool CheckForWin(Grid<char> & board, char mark) {
for (int i = 0; i < 3; i++) {
if (CheckLine(board, mark, i, 0, 0, 1)) return true;
if (CheckLine(board, mark, 0, i, 1, 0)) return true;
}
if (CheckLine(board, mark, 0, 0, 1, 1)) return true;
return CheckLine(board, mark, 2, 0, -1, 1);
}
/*
* Checks a line extending across the board in some direction. The
* starting coordinates are given by the row and col parameters.
* The direction of motion is specified by dRow and dCol, which
* show how to adjust the row and col values on each cycle. For
* rows, dRow is always 0; for columns, dCol is 0. For diagonals,
* these values will be +1 or -1 depending on the direction.
*/
bool CheckLine(Grid<char> & board, char mark, int row, int col,
int dRow, int dCol) {
for (int i = 0; i < 3; i++) {
if (board[row][col] != mark) return false;
row += dRow;
col += dCol;
}
return true;
}
Using Abstract Data Types – 134 –
When a dishwasher adds a new plate, it goes on the top of the stack, pushing the others
down slightly as the spring is compressed, as shown:
Customers can only take plates from the top of the stack. When they do, the remaining
plates pop back up. The last plate added to the stack is the first one a customer takes.
The primary reason that stacks are important in programming is that nested function
calls behave in a stack-oriented fashion. For example, if the main program calls a
function named F, a stack frame for F gets pushed on top of the stack frame for main.
main
F
If F calls G, a new stack frame for G is pushed on top of the frame for F.
main
F
G
When G returns, its frame is popped off the stack, restoring F to the top of the stack as
shown in the original diagram.
on an RPN calculator, you would enter the operations in the following order:
When the ENTER button is pressed, the calculator takes the previous value and pushes it
on a stack. When an operator button is pressed, the calculator first checks whether the
user has just entered a value and, if so, automatically pushes it on the stack. It then
computes the result of applying the operator by
• Popping the top two values from the stack
• Applying the arithmetic operation indicated by the button to these values
• Pushing the result back on the stack
Except when the user is actually typing in a number, the calculator display shows the
value at the top of the stack. Thus, at each point in the operation, the calculator display
Display 50.0 50.0 1.5 75.0 3.8 3.8 2.0 1.9 76.9
To implement the RPN calculator described in the preceding section in C++ requires
making some changes in the user-interface design. In a real calculator, the digits and
operations appear on a keypad. In this implementation, it is easier to imagine that the
user enters lines on the console, where those lines take one of the following forms:
• A floating-point number
• An arithmetic operator chosen from the set +, -, *, and /
• The letter Q, which causes the program to quit
• The letter H, which prints a help message
• The letter C, which clears any values left on the stack
A sample run of the calculator program might therefore look like this:
RPNCalc
RPN Calculator Simulation (type H for help)
> 50.0
> 1.5
> *
75
> 3.8
> 2.0
> /
1.9
> +
76.9
> Q
Because the user enters each number on a separate line terminated with the RETURN key,
there is no need for any counterpart to the calculator’s ENTER button, which really serves
only to indicate that a number is complete. The calculator program can simply push the
numbers on the stack as the user enters them. When the calculator reads an operator, it
pops the top two elements from the stack, applies the operator, displays the result, and
then pushes the result back on the stack.
The complete implementation of the calculator application appears in Figure 4-3.
/*
* File: rpncalc.cpp
* -----------------
* This program simulates an electronic calculator that uses
* reverse Polish notation, in which the operators come after
* the operands to which they apply.
*/
#include <iostream>
#include <cctype>
#include "genlib.h"
#include "simpio.h"
#include "strutils.h"
#include "stack.h"
/* Main program */
int main() {
Stack<double> operandStack;
cout << "RPN Calculator Simulation (type H for help)" << endl;
while (true) {
cout << "> ";
string line = GetLine();
char ch = toupper(line[0]);
if (ch == 'Q') {
break;
} else if (ch == 'C') {
ClearStack(operandStack);
} else if (ch == 'H') {
HelpCommand();
} else if (isdigit(ch)) {
operandStack.push(StringToReal(line));
} else {
ApplyOperator(ch, operandStack);
}
}
return 0;
}
Using Abstract Data Types – 138 –
/*
* Function: ApplyOperator
* Usage: ApplyOperator(op, operandStack);
* ---------------------------------------
* This function applies the operator to the top two elements on
* the operand stack. Because the elements on the stack are
* popped in reverse order, the right operand is popped before
* the left operand.
*/
/*
* Function: HelpCommand
* Usage: HelpCommand();
* ---------------------
* This function generates a help message for the user.
*/
void HelpCommand() {
cout << "Enter expressions in Reverse Polish Notation," << endl;
cout << "in which operators follow the operands to which" << endl;
cout << "they apply. Each line consists of a number, an" << endl;
cout << "operator, or one of the following commands:" << endl;
cout << " Q -- Quit the program" << endl;
cout << " H -- Display this help message" << endl;
cout << " C -- Clear the calculator stack" << endl;
}
/*
* Function: ClearStack
* Usage: ClearStack(stack);
* -------------------------
* This function clears the stack by popping elements until empty.
*/
In real-world situations, however, its usefulness is more limited. In human society, our
collective notion of fairness assigns some priority to being first, as expressed in the
maxim “first come, first served.” In programming, the usual phrasing of this ordering
strategy is “first in, first out,” which is traditionally abbreviated as FIFO.
A data structure that stores items using a FIFO discipline is called a queue. The
fundamental operations on a queue—which are analogous to the push and pop operations
for stacks—are called enqueue and dequeue . The enqueue operation adds a new
element to the end of the queue, which is traditionally called its tail. The dequeue
operation removes the element at the beginning of the queue, which is called its head.
The conceptual difference between these structures can be illustrated most easily with
a diagram. In a stack, the client must add and remove elements from the same end of the
internal data structure, as follows:
Push
Stack:
base of top of
stack stack Pop
In a queue, the client adds elements at one end and removes them from the other, like this:
Enqueue
Queue:
head of tail of
D e q u e u e queue queue
As you might expect from the fact that the conceptual are so similar, the structure of
the Queue class looks very much like its Stack counterpart. The list of methods in the
Queue class shown in Table 4-4 bears out that supposition. The only differences are in
the terminology, which reflects the difference in the ordering of the elements.
The queue data structure has many applications in programming. Not surprisingly,
queues turn up in many situations in which it is important to maintain a first-in/first-out
discipline in order to ensure that service requests are treated fairly. For example, if you
are working in an environment in which a single printer is shared among several
computers, the printing software is usually designed so that all print requests are entered
in a queue. Thus, if several users decide to enter print requests, the queue structure
ensures that each user’s request is processed in the order received.
Queues are also common in programs that simulate the behavior of waiting lines. For
example, if you wanted to decide how many cashiers you needed in a supermarket, it
might be worth writing a program that could simulate the behavior of customers in the
store. Such a program would almost certainly involve queues, because a checkout line
operates in a first-in/first-out way. Customers who have completed their purchases arrive
in the checkout line and wait for their turn to pay. Each customer eventually reaches the
front of the line, at which point the cashier totals up the purchases and collects the
money. Because simulations of this sort represent an important class of application
programs, it is worth spending a little time understanding how such simulations work.
Simulations and models
Beyond the world of programming, there are an endless variety of real-world events and
processes that—although they are undeniably important—are nonetheless too
complicated to understand completely. For example, it would be very useful to know
how various pollutants affect the ozone layer and how the resulting changes in the ozone
layer affect the global climate. Similarly, if economists and political leaders had a more
complete understanding of exactly how the national economy works, it would be possible
to evaluate whether a cut in the capital-gains tax would spur investment or whether it
would exacerbate the existing disparities of wealth and income.
When faced with such large-scale problems, it is usually necessary to come up with an
idealized model, which is a simplified representation of some real-world process. Most
problems are far too complex to allow for a complete understanding. There are just too
many details. The reason to build a model is that, despite the complexity of a particular
problem, it is often possible to make certain assumptions that allow you to simplify a
complicated process without affecting its fundamental character. If you can come up
with a reasonable model for a process, you can often translate the dynamics of the model
into a program that captures the behavior of that model. Such a program is called a
simulation.
It is important to remember that creating a simulation is usually a two-step process.
The first step consists of designing a conceptual model for the real-world behavior you
are trying to simulate. The second consists of writing a program that implements the
conceptual model. Because errors can occur in both steps of the process, maintaining a
certain skepticism about simulations and their applicability to the real world is probably
wise. In a society conditioned to believe the “answers” delivered by computers, it is
critical to recognize that the simulations can never be better than the models on which
they are based.
The waiting-line model
Suppose that you want to design a simulation that models the behavior of a supermarket
waiting line. By simulating the waiting line, you can determine some useful properties of
waiting lines that might help a company make such decisions as how many cashiers are
needed, how much space needs to be reserved for the line itself, and so forth.
The first step in the process of writing a checkout-line simulation is to develop a model
for the waiting line, detailing the simplifying assumptions. For example, to make the
initial implementation of the simulation as simple as possible, you might begin by
assuming that there is one cashier who serves customers from a single queue. You might
then assume that customers arrive with a random probability and enter the queue at the
Using Abstract Data Types – 141 –
end of the line. Whenever the cashier is free and someone is waiting in line, the cashier
begins to serve that customer. After an appropriate service period—which you must also
model in some way—the cashier completes the transaction with the current customer, and
is free to serve the next customer in the queue.
Discrete time
Another assumption often required in a model is some limitation on the level of accuracy.
Consider, for example, the time that a customer spends being served by the cashier. One
customer might spend two minutes; another might spend six. It is important, however, to
consider whether measuring time in minutes allows the simulation to be sufficiently
precise. If you had a sufficiently accurate stopwatch, you might discover that a customer
actually spent 3.14159265 minutes. The question you need to resolve is how accurate
you need to be.
For most models, and particularly for those intended for simulation, it is useful to
introduce the simplifying assumption that all events within the model happen in discrete
integral time units. Using discrete time assumes that you can find a time unit that—for
the purpose of the model—you can treat as indivisible. In general, the time units used in
a simulation must be small enough that the probability of more than one event occurring
during a single time unit is negligible. In the checkout-line simulation, for example,
minutes may not be accurate enough; two customers could easily arrive in the same
minute. On the other hand, you could probably get away with using seconds as the time
unit and discount the possibility that two customers arrive in precisely the same second.
Although the checkout-line example assumes that simulation time is measured in
seconds, in general, there is no reason you have to measure time in conventional units.
When you write a simulation, you can define the unit of time in any way that fits the
structure of the model. For example, you could define a time unit to be five seconds and
then run the simulation as a series of five-second intervals.
Events in simulated time
The real advantage of using discrete time units is not that it makes it possible to work
with variables of type int instead of being forced to use type double . The most
important property of discrete time is that it allows you to structure the simulation as a
loop in which each time unit represents a single cycle. When you approach the problem
in this way, a simulation program has the following form:
for (int time = 0; time < SIMULATION_TIME; time++) {
Execute one cycle of the simulation.
}
Within the body of the loop, the program performs the operations necessary to advance
through one unit of simulated time.
Think for a moment about what events might occur during each time unit of the
checkout-line simulation. One possibility is that a new customer might arrive. Another
is that the cashier might finish with the current customer and go on the serve the next
person in line. These events bring up some interesting issues. To complete the model,
you need to say something about how often customers arrive and how much time they
spend at the cash register. You could (and probably should) gather approximate data by
watching a real checkout line in a store. Even if you collect that information, however,
you will need to simplify it to a form that (1) captures enough of the real-world behavior
to be useful and (2) is easy to understand in terms of the model. For example, your
surveys might show that customers arrive at the line on average once every 20 seconds.
This average arrival rate is certainly useful input to the model. On the other hand, you
Using Abstract Data Types – 142 –
would not have much confidence in a simulation in which customers arrived exactly once
every 20 seconds. Such an implementation would violate the real-world condition that
customer arrivals have some random variability and that they sometimes bunch together.
For this reason, the arrival process is usually modeled by specifying the probability
that an arrival takes place in any discrete time unit instead of the average time between
arrivals. For example, if your studies indicated that a customer arrived once every 20
seconds, the average probability of a customer arriving in any particular second would be
1/20 or 0.05. If you assume that arrivals occur randomly with an equal probability in
each unit of time, the arrival process forms a pattern that mathematicians call a Poisson
distribution.
You might also choose to make simplifying assumptions about how long it takes to
serve a particular customer. For example, the program is easier to write if you assume
that the service time required for each customer is uniformly distributed within a certain
range. If you do, you can use the RandomInteger function from the random.h interface
to pick the service time.
1. Determine whether a new customer has arrived and, if so, add that person to the
queue.
2. If the cashier is busy, note that the cashier has spent another second with the current
customer. Eventually, the required service time will be complete, which will free the
cashier.
3. If the cashier is free, serve the next customer in the waiting line.
The waiting line itself is represented, naturally enough, as a queue. The value stored in
the queue is the time at which that customer arrived in the queue, which makes it possible
to determine how many seconds that customer spent in line before reaching the head of
the queue.
The simulation is controlled by the following parameters:
• SIMULATION_TIME—This parameter specifies the duration of the simulation.
• ARRIVAL_PROBABILITY—This parameter indicates the probability that a new customer
will arrive at the checkout line during a single unit of time. In keeping with standard
statistical convention, the probability is expressed as a real number between 0 and 1.
• MIN_SERVICE_TIME, MAX_SERVICE_TIME—These parameters define the legal range of
customer service time. For any particular customer, the amount of time spent at the
cashier is determined by picking a random integer in this range.
When the simulation is complete, the program reports the simulation parameters along
with the following results:
• The number of customers served
• The average amount of time customers spent in the waiting line
• The average length of the waiting line
Using Abstract Data Types – 143 –
/*
* File: checkout.cpp
* ------------------
* This program simulates a checkout line, such as one you
* might encounter in a grocery store. Customers arrive at
* the checkout stand and get in line. Those customers wait
* in the line until the cashier is free, at which point
* they are served and occupy the cashier for a randomly
* chosed period of time. After the service time is complete,
* the cashier is free to serve the next customer in the line.
*
* The waiting line is represented by a Queue<int> in which the
* integer value stored in the queue is the time unit in which
* that customer arrived. Storing this time makes it possible
* to determine the average waiting time for each customer.
*
* In each unit of time, up to the parameter SIMULATION_TIME,
* the following operations are performed:
*
* 1. Determine whether a new customer has arrived.
* New customers arrive randomly, with a probability
* determined by the parameter ARRIVAL_PROBABILITY.
*
* 2. If the cashier is busy, note that the cashier has
* spent another minute with that customer. Eventually,
* the customer's time request is satisfied, which frees
* the cashier.
*
* 3. If the cashier is free, serve the next customer in line.
* The service time is taken to be a random period between
* MIN_SERVICE_TIME and MAX_SERVICE_TIME.
*
* At the end of the simulation, the program displays the
* parameters and the following computed results:
*
* o The number of customers served
* o The average time spent in line
* o The average number of customers in the line
*/
#include "genlib.h"
#include "random.h"
#include "queue.h"
#include <iostream>
#include <iomanip>
/* Simulation parameters */
void RunSimulation();
void ReportResults(int nServed, long totalWait, long totalLength);
/* Main program */
int main() {
Randomize();
RunSimulation();
return 0;
}
/*
* Function: RunSimulation
* Usage: RunSimulation();
* -----------------------
* This function runs the actual simulation. In each time unit,
* the program first checks to see whether a new customer arrives.
* Then, if the cashier is busy (indicated by a nonzero value for
* serviceTimeRemaining), the program decrements that variable to
* indicate that one more time unit has passed. Finally, if the
* cashier is free, the simulation serves another customer from
* the queue after recording the waiting time for that customer.
*/
void RunSimulation() {
Queue<int> queue;
int serviceTimeRemaining = 0;
int nServed = 0;
long totalWait = 0;
long totalLength = 0;
for (int t = 0; t < SIMULATION_TIME; t++) {
if (RandomChance(ARRIVAL_PROBABILITY)) {
queue.enqueue(t);
}
if (serviceTimeRemaining > 0) {
serviceTimeRemaining--;
if (serviceTimeRemaining == 0) nServed++;
} else if (!queue.isEmpty()) {
totalWait += t - queue.dequeue();
serviceTimeRemaining =
RandomInteger(MIN_SERVICE_TIME, MAX_SERVICE_TIME);
}
totalLength += queue.size();
}
ReportResults(nServed, totalWait, totalLength);
}
Using Abstract Data Types – 145 –
/*
* Function: ReportResults
* Usage: ReportResults(nServed, totalWait, totalLength);
* ------------------------------------------------------
* This function reports the results of the simulation.
*/
For example, the following sample run shows the results of the simulation for the
indicated parameter values:
CheckoutLine
Simulation results given the following parameters:
SIMULATION_TIME: 2000
ARRIVAL_PROBABILITY: 0.05
MIN_SERVICE_TIME: 5
MAX_SERVICE_TIME: 15
Customers served: 93
Average waiting time: 4.97
Average queue length: 0.23
The behavior of the simulation depends significantly on the values of its parameters.
Suppose, for example, that the probability of a customer arriving increases from 0.05 to
0.10. Running the simulation with these parameters gives the following results:
CheckoutLine
Simulation results given the following parameters:
SIMULATION_TIME: 2000
ARRIVAL_PROBABILITY: 0.10
MIN_SERVICE_TIME: 5
MAX_SERVICE_TIME: 15
As you can see, doubling the probability of arrival causes the average waiting time to
grow from approximately 5 seconds to over a minute and a half, which is obviously a
dramatic increase. The reason for the poor performance is that the arrival rate in the
second run of the simulation means that new customers arrive at the same rate at which
they are served. When this arrival level is reached, the length of the queue and the
average waiting time begin to grow very quickly. Simulations of this sort make it
possible to experiment with different parameter values. Those experiments, in turn, make
it possible to identify potential sources of trouble in the corresponding real-world
systems.
These definitions create empty maps that contain no keys and values. In either case, you
would subsequently need to add key/value pairs to the map. In the case of the dictionary,
you could read the contents from a data file. For the symbol table, you would add new
associations whenever an assignment statement appeared.
It is important to note that the parameter for the Map class specifies the type of the
value, and not the type of the key. In many implementations of collection classes—
including, for example, the one in the Standard Template Library and its counterpart in
the Java collection classes—you can specify the type of the key as well. The Map class
used in this book avoid considerable complexity by insisting that all keys be strings.
Strings are certainly the most common type for keys, and it is usually possible to convert
other types to strings if you want to use them as map keys. For example, if you want to
use integers as keys, you can simply call the IntegerToString function on the integer
version of the key and then use the resulting string for all map operations.
The most common methods used with the Map class appear in Table 4-5. Of these, the
ones that implement the fundamental behavior of the map concept are put and get. The
Using Abstract Data Types – 147 –
put method creates an association between a key and a value. Its operation is analogous
to assigning a value to a variable in C++: if there is a value already associated with the
key, the old value is replaced by the new one. The get method retrieves the value most
recently associated with a particular key and therefore corresponds to the act of using a
variable name to retrieve its value. If no value appears in the map for a particular key,
calling get with that key generates an error condition. You can check for that condition
by calling the containsKey method, which returns true or false depending on whether
the key exists in the map.
A few simple diagrams may help to illustrate the operation of the Map class in more
detail. Suppose that you have declared the symbolTable variable to be a Map<double>
as you saw earlier in the section. That declaration creates an empty map with no
associations, which can be represented as the following empty box:
symbolTable
Once you have the map, you can use put to establish new associations. For example, if
you were to call
symbolTable.put("pi", 3.14159);
the conceptual effect would be to add an association inside the box between the key "pi"
and the value 3.14159, as follows:
symbolTable
pi = 3.14159
a new association would be added between the key "e" and the value 2.71828, like this:
symbolTable
pi = 3.14159
e = 2.71828
You can then use get to retrieve these values. Calling symbolTable.get("pi") would
return the value 3.14159, and calling symbolTable.get("pi") would return 2.71828.
Although it hardly makes sense in the case of mathematical constants, you could
change the values in the map by making additional calls to put. You could, for example,
reset the value associated with "pi" (as an 1897 bill before the Indiana State General
Assembly sought to do) by calling
symbolTable.put("pi", 3.2);
/*
* File: airports.cpp
* ------------------
* This program looks up a three-letter airport code in a Map object.
*/
#include "genlib.h"
#include "simpio.h"
#include "strutils.h"
#include "map.h"
#include <iostream>
#include <fstream>
#include <string>
/* Main program */
int main() {
Map<string> airportCodes;
ReadCodeFile(airportCodes);
while (true) {
cout << "Airport code: ";
string code = ConvertToUpperCase(GetLine());
if (code == "") break;
if (airportCodes.containsKey(code)) {
cout << code << " is in " << airportCodes.get(code) << endl;
} else {
cout << "There is no such airport code" << endl;
}
}
return 0;
}
and the expression map[key] returns the value from map associated with key in exactly
the same way that map.get(key) does. While these shorthand forms of the put and get
methods are certainly convenient, using array notation for maps is initially somewhat
surprising, given that maps and arrays seem to be rather different in their structure. If
you think about maps and arrays in the right way, however, they turn out to be more alike
than you might at first suspect.
The insight necessary to unify these two seemingly different structures is that you can
think of arrays as structures that map index positions to elements. For example, the array
scores
9.2 9.9 9.7 9.0 9.5
0 1 2 3 4
used as an example in Chapter 2 maps the key 0 into the value 9.2, the key 1 into 9.9, the
key 2 into 9.7, and so forth. Thus, an array is in some sense just a map with integer keys.
Conversely, you can think of a map as an array that uses strings as index positions, which
is precisely what the overloaded selection syntax for the Map class suggests.
Using array syntax to perform map-like operations is becoming increasingly common
in programming languages beyond the C++ domain. Many popular scripting languages
implement all arrays internally as maps, making it possible use index values that are not
necessarily integers. Arrays implemented using maps as their underlying representation
are called associative arrays.
The implementation of the Lexicon class allows these data files to be in either of two
formats:
1. A text file in which the words appear in any order, one word per line.
Using Abstract Data Types – 152 –
2. A precompiled data file that mirrors the internal representation of the lexicon. Using
precompiled files (such as EnglishWords.dat) is more efficient, both in terms of
space and time.
Unlike the classes presented earlier in this chapter, Lexicon does not require a type
parameter, because a lexicon doesn’t contain any values. It does, of course, contain a set
of words, but the words are always strings.
The methods available in the Lexicon class appear in Table 4-6. The most commonly
used method is containsWord, which checks to see if a word is in the lexicon. Assuming
that you have initialized the variable english so that it contains a lexicon of all English
words, you could see if a particular word exists by writing a test such as the following:
if (english.containsWord(word)) . . .
And because it is useful to make such tests in a variety of applications, you can also
determine whether any English words begin with a particular substring by calling
if (english.containsPrefix(prefix)) . . .
/*
* File: twoletters.cpp
* --------------------
* This program generates a list of the two-letter words.
*/
#include "genlib.h"
#include "lexicon.h"
#include <iostream>
int main() {
Lexicon english("EnglishWords.dat");
string word = "xx";
for (char c0 = 'a'; c0 <= 'z'; c0++) {
word[0] = c0;
for (char c1 = 'a'; c1 <= 'z'; c1++) {
word[1] = c1;
if (english.containsWord(word)) {
cout << word << endl;
}
}
}
return 0;
}
successive calls to the scanner package would return those ten individual tokens as shown
by the boxes on the following line:
Because it is often easier to check for a sentinel value, the nextToken method returns
the empty string if you call it after the last token has been read.
You can use the same scanner instance many times by calling setInput for each string
you want to split into tokens, so you don’t need to declare a separate scanner for each
string that you have.
Figure 4-8 offers a simple example of how to use the scanner to create a program that
reports all words in a text file that aren’t in the English lexicon.
/*
* File: spellcheck.cpp
* --------------------
* This program checks the spelling of words in an input file.
*/
#include "genlib.h"
#include "simpio.h"
#include "lexicon.h"
#include "scanner.h"
#include <string>
#include <cctype>
#include <iostream>
#include <fstream>
/* Function prototypes */
bool IsAllAlpha(string & str);
void AskUserForInputFile(string prompt, ifstream & infile); (see page 131)
/* Main program */
int main() {
ifstream infile;
Lexicon english("EnglishWords.dat");
Scanner scanner;
AskUserForInputFile("Input file: ", infile);
scanner.setInput(infile);
while (scanner.hasMoreTokens()) {
string word = scanner.nextToken();
if (IsAllAlpha(word) && !english.containsWord(word)) {
cout << word << " is not in the dictionary" << endl;
}
}
infile.close();
return 0;
}
The names of the constants used to set each option are described in Table 4-7 along with
the method to which those constants apply.
The Scanner class also exports a method called saveToken that comes in handy in a
variety of applications. This method solves the problem that arises from the fact that you
often don’t know that you want to stop reading a sequence of tokens until you’ve read the
token that follows that sequence. Unless your application is prepared to deal with the
new token at that point in the code, it is convenient to put that token back in the scanner
stream where it can be read again when the program is ready to do so.
4.8 Iterators
The twoletter.cpp program introduced in Figure 4-7 earlier in this chapter computes a
list of all two-letter words by generating every possible combination of two letters and
then looking up each one to see whether that two-letter string appears in the lexicon of
English words. Another strategy that accomplishes the same result is to go through every
word in the lexicon and display the words whose length is equal to 2. To do so, all you
need is some way of stepping through each word in a Lexicon object, one at a time.
Stepping through the elements of a collection class is a fundamental operation that
each class must provide through its interface. Moreover, if the package of collection
classes is well designed, clients should be able to use the same strategy to perform that
operation, no matter whether they are cycling through all elements in a vector or a grid,
all keys in a map, or all words in a lexicon. In most modern software packages, including
the library ADTs used in this book and the Standard Template Library on which those
classes are based, the process of cycling through the elements of a collection is provided
through a class called an iterator. Each abstract collection class in the library—with the
exception of Stack and Queue, for which being able to process the elements out of order
would violate the LIFO or FIFO discipline that defines those type—exports its own
Iterator class, but defines that class so that all iterators behave in the same way. Once
you learn how to use an iterator for one class, you can easily transfer that knowledge to
any of the other classes.
Using Abstract Data Types – 157 –
The iterator method in the Lexicon class returns an iterator that provides each word in
the lexicon, one at a time. The iterator class itself is defined as a nested subclass within
Lexicon, so its full name is Lexicon::Iterator. The first line in this example therefore
applies the iterator method to the lexicon stored in the variable english and then
stores the resulting iterator object in the variable iter, which has been suitably declared
with the full name of its type.
Once you have the iterator variable, you then enter a loop that continues as long as the
iterator has more elements to process. The hasNext method returns a Boolean value that
indicates whether any additional elements remain, which is exactly what you need for the
condition in the while loop. Inside the loop, the next method returns the next element in
the collection. In this example, calling iter.next() returns the next word from the
English language lexicon, which is then stored in the string variable word.
The code that needs to go into the body of the loop depends, of course, on what you’re
trying to do. If, for example, you want to list all two-letter English words using the
iterator model, the code to do so will look like this:
Lexicon::Iterator iter = english.iterator();
while (iter.hasNext()) {
string word = iter.next();
if (word.length() == 2) {
cout << word << endl;
}
}
The type of value produced by the next method depends on the class in which the iterator
is created. In the Map and Lexicon classes, next always returns a value of type string.
In the Array and Grid classes, next returns a value whose type matches the base type of
that collection. Thus, an iterator for an Array<int> will produce values of type int, and
an iterator for a Grid<char> will produce values of type char.
Some languages, most notably C# and Java, define a new syntactic form that expresses
precisely that idea. Unfortunately, the syntax of C++ does not such a facility.
The good news, however, is that it is possible to use the macro-definition capabilities
of the C++ preprocessor to achieve exactly what you would like to see in the language.
Although the implementation details are beyond the scope of this text, the collection
classes that support iteration also define a foreach macro that has the following form:
foreach (string word in english) {
if (word.length() == 2) {
cout << word << endl;
}
}
The advantage of the foreach syntax is not that the code is a couple of lines shorter,
but rather that the revised code tells the reader exactly what is going on. If you compare
the two versions of this loop, I’m sure you’ll immediately recognize just how much
clearer the foreach version is. In my experience, once students have been given the
opportunity to use foreach in their code, they never go back to using the iterator form.
Even so, it is useful to know that the iterator form exists and that the iterator mechanism
is in fact what is going on inside the implementation of foreach.
Iteration order
When you work with iterators or the foreach macro, it is often useful to understand the
order in which the iterator generates each of the individual values. There is no universal
rule. Each container class defines its own policy about iteration order, usually based on
considerations of efficiency. The classes you’ve already seen make the following
guarantees about the order of values:
• The iterator for the Vector class generates the elements in the order of the index
position, so that the element in position 0 comes first, followed by the element in
position 1, and so on, up to the end of the vector. The order in which elements are
returned by the iterator is therefore the same as the order in which elements are
processed by the standard for loop pattern for iterating through an array:
for (int i = 0; i < vec.size(); i++) {
code to process vec[i]
}
• The iterator for the Grid class steps through the elements of row 0 in order, then the
elements of row 1, and so forth. This order is iteration strategy for Grid is thus
analogous to using the following for loop pattern:
for (int row = 0; row < grid.numRows(); row++) {
for (int col = 0; col < grid.numCols(); col++) {
code to process grid[row][col]
}
}
This order, in which the row subscript appears in the outer loop, is called row-major
order.
• The iterator for the Map class makes no guarantees about the order in which the keys
are returned. As you will discover in Chapter 12, the most efficient representation for
storing keys in a map is incompatible with, for example, keeping them in alphabetical
order.
Using Abstract Data Types – 160 –
• The iterator for the Lexicon class always returns words in alphabetical order, with all
words converted to lower case. The ability to process words alphabetically is one of
the principal advantages of the Lexicon class.
When you use an iterator, it is important that you do not modify the contents of the
collection object over which the iteration is performed, because such changes may
invalidate the data structures stored within the iterator. If, for example, you are iterating
over the keys in a map, deleting the current key may make it impossible for the iterator to
figure out how to get to the next key. The implementations of the iterators used in this
text check that the structure has not changed as the iterator proceeds through it, but that
may not be the case for iterators that exist in other packages.
An example of the foreach mechanism
In the discussion of Pig Latin in section 3.3, the words used to illustrate the rules for
forming Pig Latin words were alley and trash. These words have the interesting property
that their Pig Latin forms—alleyway and ashtray—happen to be other English words.
Such words are not all that common; in the lexicon stored in the file EnglishWords.dat,
there are only 27 words with that property out of over 100,000 English words. Given
iterators and the PigLatin function from Figure 3-5, it is easy to write a program that
lists them all:
int main() {
cout << "This program finds words that remain words when "
<< "translated to Pig Latin." << endl;
Lexicon english("EnglishWords.dat");
foreach (string word in english) {
string pig = PigLatin(word);
if (pig != word && english.containsWord(pig)) {
cout << word << " -> " << pig << endl;
}
}
return 0;
}
If you are trying to determine the relative frequency of words in Shakespeare’s writing,
you need to have a program that counts how many times each word appears in the data
Using Abstract Data Types – 161 –
file. Thus, given the file macbeth.txt , your would like your program to produce
something like the following output:
WordFrequency
and 2
creeps 1
day 2
from 1
in 1
pace 1
petty 1
this 1
to 1
tomorrow 3
The code for the word frequency program appears in Figure 4-9. Given the tools you
have at your disposal from the earlier sections in this chapter, the code required to
tabulate word frequencies is quite straightforward. The Scanner class is clearly the right
mechanism for going through the words in the file, just as it was for the spelling checker
in Figure 4-8. To keep track of the mapping between words and their associated counts, a
Figure 4-9 Program to keep track of the frequency of words in a text file
/*
* File: wordfreq.cpp
* ------------------
* This program computes the frequency of words in a text file.
*/
#include "genlib.h"
#include "simpio.h"
#include "map.h"
#include "scanner.h"
#include <string>
#include <cctype>
#include <iostream>
#include <fstream>
#include <iomanip>
/*
* Creates a frequency table that reads through the input file
* and counts how often each word appears. The client supplies
* both the input file stream and the map used to keep track of
* the word count.
*/
void CreateFrequencyTable(ifstream & infile, Map<int> & wordCounts) {
Scanner scanner;
scanner.setInput(infile);
scanner.setSpaceOption(Scanner::IgnoreSpaces);
while (scanner.hasMoreTokens()) {
string word = ConvertToLowerCase(scanner.nextToken());
if (IsAllAlpha(word)) {
if (wordCounts.containsKey(word)) {
wordCounts[word]++;
} else {
wordCounts[word] = 1;
}
}
}
}
/*
* Displays the count for each word in the frequency table.
*/
void DisplayWordCounts(Map<int> & wordCounts) {
foreach (string word in wordCounts) {
cout << left << setw(15) << word
<< right << setw(5) << wordCounts[word] << endl;
}
}
Map<int> is precisely what you need. And when you need to go through the entries in
the map to list the word counts, Iterator provides just the right tool.
The only minor problem with this implementation is that the words don’t appear in
alphabetical order as they did in the proposed sample run created during the design phase.
Because the iterator for the Map class is allowed to produce the keys in any order, they
will ordinarily come out in some jumbled fashion. Given the implementation of the Map
class as it exists, the program happens to produce the output
WordFrequency
pace 1
to 1
day 2
tomorrow 3
petty 1
and 2
creeps 1
from 1
in 1
this 1
It’s not hard to get the output to come out in alphabetical order. In fact, as you will have
a chance to discover in exercise 16, the library classes in this chapter make it possible to
display this list alphabetically with just a few additional lines of code. It might, however,
be even more useful to present the list in descending order of frequency. To do that, it
will be useful to understand the sorting algorithms presented in Chapter 8.
Summary
This chapter introduced seven C++ classes—Vector, Grid, Stack, Queue, Map, Lexicon,
and Scanner—that form a powerful collection of programming tools. For the moment,
you have looked at these classes only as a client. In subsequent chapters, you will have a
chance to learn more about how they are implemented. Important points in this chapter
include:
• Data structures that are defined in terms of their behavior rather their representation are
called abstract data types. Abstract data types have several important advantages over
more primitive data structures such as arrays and records. These advantages include:
1. Simplicity. The representation of the underlying data representation is not
accessible, which means that there are fewer details for the client to understand.
2. Flexibility. The implementer is free to enhance the underlying representation as
long as the methods in the interface continue to behave in the same way.
3. Security. The interface barrier prevents the client from making unexpected
changes in the internal structure.
• Classes that contain other objects as elements of an integral collection are called
container classes or, equivalently, collection classes. In C++, container classes are
usually defined using a template or parameterized type, in which the type name of the
element appears in angle brackets after the name of the container class. For example,
the class Vector<int> signifies a vector containing values of type int.
• The Vector class is an abstract data type that behaves in much the same fashion as a
one-dimensional array but is much more powerful. Unlike arrays, a Vector can grow
dynamically as elements are added and removed. They are also more secure, because
the implementation of Vector checks to make sure that selected elements exist.
• The Grid class provides a convenient abstraction for working with two-dimensional
arrays.
• The Stack class represents a collection of objects whose behavior is defined by the
property that items are removed from a stack in the opposite order from which they
were added: last in, first out (LIFO). The fundamental operations on a stack are push,
which adds a value to the stack, and pop, which removes and returns the value most
recently pushed.
• The Queue class is similar to the Stack class except for the fact that elements are
removed from a queue in the same order in which they were added: first in, first out
(FIFO). The fundamental operations on a queue are enqueue, which adds a value to
the end of a queue, and dequeue, which removes and returns the value from the front.
• The Map class makes it possible to associate keys with values in a way that makes it
possible to retrieve those associations very efficiently. The fundamental operations
on a map are put , which adds a key/value pair, and get , which returns the value
associated with a particular key.
• The Lexicon class represents a word list. The fundamental operations on a map are
add , which stores a new word in the list, and containsWord, which checks to see
whether a word exists in the lexicon.
Using Abstract Data Types – 164 –
• The Scanner class simplifies the problem of breaking up a string or an input file into
tokens that have meaning as a unit. The fundamental operations on an scanner are
hasMoreTokens, which determines whether more tokens can be read from the scanner,
and nextToken, which returns the next token from the input source.
• Most collection classes define an internal class named Iterator that makes it easy to
cycle through the contents of the collection. The fundamental operations on an iterator
are hasNext, which determines whether more elements exist, and next, which returns
the next element from the collection.
Review questions
1. True or false: An abstract data type is one defined in terms of its behavior rather than
its representation.
2. What three advantages does this chapter cite for separating the behavior of a class
from its underlying implementation?
3. What is the STL?
4. If you want to use the Vector class in a program, what #include line do you need to
add to the beginning of your code?
5. List at least three advantages of the Vector class over the more primitive array
mechanism available in C++.
6. What is meant by the term bounds-checking?
7. What type name would you use to store a vector of Boolean values?
8. True or false: The default constructor for the Vector class creates a vector with ten
elements, although you can make it longer later.
9. What method do you call to determine the number of elements in a Vector?
10. If a Vector object has N elements, what is the legal range of values for the first
argument to insertAt? What about for the first argument to removeAt?
11. What feature of the Vector class makes it possible to avoid explicit use of the getAt
and setAt methods?
12. Why is it important to pass vectors and other collection object by reference?
13. What declaration would you use to initialize a variable called chessboard to an 8 x 8
grid, each of whose elements is a character?
14. Given the chessboard variable from the preceding exercise, how would you assign
the character 'R' (which stands for a white rook in standard chess notation) to the
squares in the lower left and lower right corners of the board?
15. What do the acronyms LIFO and FIFO stand for? How do these terms apply to
stacks and queues?
16. What are the names of the two fundamental operations for a stack?
17. What are the names for the corresponding operations for a queue?
Using Abstract Data Types – 165 –
18. What does the peek operation do in each of the Stack and Queue classes?
19. What are the names for the corresponding operations for a queue?
20. Describe in your own words what is meant by the term discrete time in the context of
a simulation program.
21. True or false: In the Map class used in this book, the keys are always strings.
22. True or false: In the Map class used in this book, the values are always strings.
23. What happens if you call get for a key that doesn’t exist in a map?
24. What are the syntactic shorthand forms for get and put that allow you to treat a map
as an associative array?
25. Why do the libraries for this book include a separate Lexicon class even though it is
easy to implement the fundamental operations of a lexicon using the Map class?
26. What are the two kinds of data files supported by the constructor for the Lexicon
class?
27. What is the purpose of the Scanner class?
28. What options are available for controlling the definition of the tokens recognized by
the Scanner class?
29. What is an iterator?
30. What reason is offered for why there is no iterator for the Stack and Queue class?
31. If you use the iterator method explicitly, what is the standard idiom for using an
iterator to cycle through the elements of a collection?
32. What is the foreach version of ths standard iterator idiom?
33. What is the principal advantage of using foreach in preference to the explicit
iterator-based code?
34. True or false: The iterator for the Map class guarantees that individual keys will be
delivered in alphabetical order.
35. True or false: The iterator for the Lexicon class guarantees that individual words
will be delivered in alphabetical order.
36. What would happen if you removed the call to scanner.setSpaceOption in the
implementation of createFrequencyTable in Figure 4-9? Would the program still
work?
Programming exercises
1. In Chapter 2, exercise 8, you were askd to write a function RemoveZeroElements
that eliminated any zero-valued elements from an integer array. That operation is
much easier in the context of a vector, because the Vector class makes it possible to
add and remove elements dynamically. Rewrite RemoveZeroElements so that the
function header looks like this:
Using Abstract Data Types – 166 –
2. Write a function
bool ReadVector(ifstream & infile, Vector<double> & vec);
that reads lines from the data file specified by infile, each of which consists of a
floating-point number, and adds them to the vector vec . The end of the vector is
indicated by a blank line or the end of the file. The function should return true if it
successfully reads the vector of numbers; if it encounters the end of the data file
before it reads any values, the function should return false.
To illustrate the operation of this function, suppose that you have the data file
SquareAndCubeRoots.txt
1.0000
1.4142
1.7321
2.0000
1.0000
1.2599
1.4422
1.5874
1.7100
1.8171
1.9129
2.0000
and that you have opened infile as an ifstream on that file. In addition, suppose
that you have declares the variable roots as follows:
Vector<double> roots;
The first call to ReadVector(infile, roots) should return true after initializing
roots so that it contains the four elements shown at the beginning of the file. The
second call would also return true and change the value of roots to contain the
eight elements shown at the bottom of the file. Calling ReadVector a third time
would return false.
3. Given that it is possible to insert new elements at any point, it is not difficult to keep
elements in order as you create a Vector. Using ReadTextFile as a starting point,
write a function
void SortTextFile(ifstream & infile, Vector<string> & lines);
that reads the lines from the file into the vector lines, but keeps the elements of the
vector sorted in lexicographic order instead of the order in which they appear in the
file. As you read each line, you need to go through the elements of the vector you
have already read, find out where this line belongs, and then insert it at that position.
4. The code in Figure 4-2 shows how to check the rows, columns, and diagonals of a
tic-tac-toe board using a single helper function. That function, however, is coded in
such a way that it only works for 3 x 3 boards. As a first step toward creating a
program that can play tic-tac-toe on larger grids, reimplement the CheckForWin and
CheckLine functions so that they work for square grids of any size.
Using Abstract Data Types – 167 –
5. A magic square is a two-dimensional grid of Figure 4-10 Dürer etching with a magic square
integers in which the rows, columns, and
diagonals all add up to the same value. One
of the most famous magic squares appears in
the 1514 engraving “Melencolia I” by
Albrecht Dürer shown in Figure 4-10, in
which a 4 x 4 magic square appears in the
upper right, just under the bell. In Dürer’s
square, which can be read more easily as
16 3 2 13
5 10 11 8
9 6 7 12
4 15 14 1
all four rows, all four columns, and both
diagonals add up to 34.
A more familiar example is the following
3 x 3 magic square in which each of the rows,
columns, and diagonals add up to 15, as
shown:
=15
=15
=15
5
=1
8 1 6 =15 8 1 6 8 1 6
3 5 7 =15 3 5 7 3 5 7
4 9 2 =15 4 9 2 4 9 2
=1
5
Implement a function
bool IsMagicSquare(Grid<int> & square);
that tests to see whether the grid contains a magic square. Note that your program
should work for square grids of any size. If you call IsMagicSquare with a grid in
which the number of rows and columns are different, it should simply return false.
6. In the last several years, a new logic puzzle called Sudoku has become quite popular
throughout the world. In Sudoku, you start with a 9 x 9 grid of integers in which
some of the cells have been filled in with digits between 1 and 9. Your job in the
puzzle is to fill in each of the empty spaces with a digit between 1 and 9 so that each
digit appears exactly once in each row, each column, and each of the smaller 3 x 3
squares. Each Sudoku puzzle is carefully constructed so that there is only one
solution. For example, given the puzzle shown on the left of the following diagram,
the unique solution is shown on the right:
Using Abstract Data Types – 168 –
2 4 5 8 3 9 2 4 6 5 8 1 7
4 1 8 2 7 4 1 8 9 3 6 2 5
6 7 3 9 6 8 5 2 7 1 4 3 9
2 3 9 6 2 5 4 1 3 8 7 9 6
9 6 7 1 8 3 9 6 2 7 1 5 4
1 7 5 3 1 7 6 9 5 4 2 8 3
9 6 8 1 9 6 7 5 8 2 3 4 1
2 9 5 6 4 2 3 7 1 9 5 6 8
8 3 6 9 5 1 8 3 4 6 9 7 2
Although you won’t have learned the algorithmic strategies you need to solve
Sudoku puzzles until later in this book, you can easily write a method that checks to
see whether a proposed solution follows the Sudoku rules against duplicating values
in a row, column, or outlined 3 x 3 square. Write a function
bool CheckSudokuSolution(Grid<int> puzzle);
that performs this check and returns true if the puzzle is a valid solution. Your
program should check to make sure that puzzle contains a 9 x 9 grid of integers and
report an error if this is not the case.
7. Write a program that uses a stack to reverse a sequence of integers read in one per
line from the console, as shown in the following sample run:
ReverseList
Enter a list of integers, ending with 0:
> 10
> 20
> 30
> 40
> 0
Those integers in reverse order are:
40
30
20
10
8. Write a C++ program that checks whether the bracketing operators (parentheses,
brackets, and curly braces) in a string are properly matched. As an example of
proper matching, consider the string
{ s = 2 * (a[2] + 3); x = (1 + (2)); }
If you go through the string carefully, you discover that all the bracketing operators
are correctly nested, with each open parenthesis matched by a close parenthesis, each
open bracket matched by a close bracket, and so on. On the other hand, the
following strings are all unbalanced for the reasons indicated:
(([]) The line is missing a close parenthesis.
)( The close parenthesis comes before the open parenthesis.
{(}) The bracketing operators are improperly nested.
Using Abstract Data Types – 169 –
The reason that this exercise fits in this chapter is that one of the simplest strategies
for implementing this program is to store the unmatched operators on a stack.
9. Bob Dylan’s 1963 song “The Times They Are A-Changin’” contains the following
lines, which are themselves paraphrased from Matthew 19:30:
And the first one now
Will later be last
For the times they are a-changin’
In keeping with this revolutionary sentiment, write a function
void ReverseQueue(Queue<string> & queue);
that reverses the elements in the queue. Remember that you have no access to the
internal representation of the queue and will need to come up with an algorithm,
presumably involving other structures, that accomplishes the task.
10. The checkout-line simulation in Figure 4-4 can be extended to investigate important
practical questions about how waiting lines behave. As a first step, rewrite the
simulation so that there are several independent queues, as is usually the case in
supermarkets. A customer arriving at the checkout area finds the shortest checkout
line and enters that queue. Your revised simulation should calculate the same results
as the simulation in the chapter.
11. As a second extension to the checkout-line simulation, change the program from the
previous exercise so that there is a single waiting line served by multiple cashiers—a
practice that has become more common in recent years. In each cycle of the
simulation, any cashier that becomes idle serves the next customer in the queue. If
you compare the data produced by this exercise and the preceding one, what can you
say about the relative advantages of these two strategies?
12. If waiting lines become too long, customers can easily become frustrated and may
decide to take their business elsewhere. Simulations may make it possible to reduce
the risk of losing customers by allowing managers to determine how many cashiers
are required to reduce the average waiting time below a predetermined threshold.
Rewrite the checkout-line simulation from exercise 11 so that the program itself
determines how many cashiers are needed. To do so, your program must run the
complete simulation several times, holding all parameters constant except the
number of cashiers. When it finds a staffing level that reduces the average wait to an
acceptable level, your program should display the number of cashiers used on that
simulation run.
13. Write a program to simulate the following experiment, which was included in the
1957 Disney film, Our Friend the Atom, to illustrate the chain reactions involved in
nuclear fission. The setting for the experiment is a large cubical box, the bottom of
which is completely covered with an array of 625 mousetraps, arranged to form a
square grid 25 mousetraps on a side. Each of the mousetraps is initially loaded with
two ping-pong balls. At the beginning of the simulation, an additional ping-pong
ball is released from the top of the box and falls on one of the mousetraps. That
mousetrap springs and shoots its two ping-pong balls into the air. The ping-pong
balls bounce around the sides of the box and eventually land on the floor, where they
are likely to set off more mousetraps.
In writing this simulation, you should make the following simplifying
assumptions:
Using Abstract Data Types – 170 –
• Every ping-pong ball that falls always lands on a mousetrap, chosen randomly by
selecting a random row and column in the grid. If the trap is loaded, its balls are
released into the air. If the trap has already been sprung, having a ball fall on it
has no effect.
• Once a ball falls on a mousetrap—whether or not the trap is sprung—that ball
stops and takes no further role in the simulation.
• Balls launched from a mousetrap bounce around the room and land again after a
random number of simulation cycles have gone by. That random interval is
chosen independently for each ball and is always between one and four cycles.
Your simulation should run until there are no balls in the air. At that point, your
program should report how many time units have elapsed since the beginning, what
percentage of the traps have been sprung, and the maximum number of balls in the
air at any time in the simulation.
14. In May of 1844, Samuel F. B. Morse sent the message “What hath God wrought!” by
telegraph from Washington to Baltimore, heralding the beginning of the age of
electronic communication. To make it possible to communicate information using
only the presence or absence of a single tone, Morse designed a coding system in
which letters and other symbols are represented as coded sequences of short and long
tones, traditionally called dots and dashes. In Morse code, the 26 letters of the
alphabet are represented by the following codes:
A • J • S •••
B ••• K • T
C • • L • •• U ••
D •• M V •••
E • N • W •
F •• • O X ••
G • P • • Y •
H •••• Q • Z ••
I •• R • •
If you want to convert from letters to Morse code, you can store the strings for each
letter in an array with 26 elements; to convert from Morse code to letters, the easiest
approach is to use a map.
Write a program that reads in lines from the user and translates each line either to
or from Morse code depending on the first character of the line:
• If the line starts with a letter, you want to translate it to Morse code. Any
characters other than the 26 letters should simply be ignored.
• If the line starts with a period (dot) or a hyphen (dash), it should be read as a
series of Morse code characters that you need to translate back to letters. Each
sequence of dots and dashes is separated by spaces, but any other characters
should be ignored. Because there is no encoding for the space between words, the
characters of the translated message will be run together when your program
translates in this direction.
The program should end when the user enters a blank line. A sample run of this
program (taken from the messages between the Titanic and the Carpathia in 1912)
might look like this:
Using Abstract Data Types – 171 –
MorseCode
Morse code translator
> SOS TITANIC
... --- ... - .. - .- -. .. -.-.
> WE ARE SINKING FAST
.-- . .- .-. . ... .. -. -.- .. -. --. ..-. .- ... -
> .... . .- -.. .. -. --. ..-. --- .-. -.-- --- ..-
HEADINGFORYOU
>
15. In Chapter 3, exercise 6, you were asked to write a function IsPalindrome that
checks whether a word is a palindrome, which means that it reads identically
forward and backward. Use that function together with the lexicon of English words
to print out a list of all words in English that are palindromes.
16. As noted in the chapter, it is actually rather easy to change the wordfreq.cpp
program from Figure 4-8 so that the words appear in alphabetical order. The only
thing you need to do is think creatively about the tools that you already have. Make
the necessary modifications to the program to accomplish this change.
17. As noted in section 4.5, a map is often called a symbol table when it is used in the
context of a programming language, because it is precisely the structure you need to
store variables and their values. For example, if you are working in an application in
which you need to assign floating-point values to variable names, you could do so
using a map declared as follows:
Map<double> symbolTable;
Write a C++ program that declares such a symbol table and then reads in
command lines from the user, which must be in one of the following forms:
• A simple assignment statement of the form
var = number
This statement should store the value represented by the token number in the
symbol table under the name var. Thus, if the user were to enter
pi = 3.14159
the string pi should be assigned a value of 3.14159 in symbolTable.
• The name of a variable alone on a line. When your program reads in such a line,
it should print out the current value in the symbol table associated with that name.
Thus, if pi has been defined as shown in the preceding example, the command
pi
should display the value 3.14159.
• The command list, which is interpreted by the program as a request to display
all variable/value pairs currently stored in the symbol table, not necessarily in any
easily discernable order.
• The command quit, which should exit from the program.
Once you have implemented each of these command forms, your program should be
able to produce the following sample run:
Using Abstract Data Types – 172 –
SymbolTableTest
> pi = 3.14159
> e = 2.71828
> x = 2.00
> pi
3.14159
> e
2.71828
> list
e = 2.71828
x = 2
pi = 3.14159
> x = 42
> list
e = 2.71828
x = 42
pi = 3.14159
> a = 1.5
> list
e = 2.71828
x = 42
pi = 3.14159
a = 1.5
> quit
18. Rewrite the RPN calculator from Figure 4-3 so that it uses the Scanner class to read
its input tokens from a single line, as illustrated by the following sample run:
RPNCalc
RPN Calculator Simulation (type H for help)
> 1 2 3 * +
7
> 50.0 1.5 * 3.8 2.0 / +
76.9
> quit
Chapter 5
Introduction to Recursion
Before you can solve many sophisticated programming tasks, however, you will have
to learn to use a powerful problem-solving strategy that has few direct counterparts in the
real world. That strategy, called recursion, is defined as any solution technique in which
large problems are solved by reducing them to smaller problems of the same form. The
italicized phrase is crucial to the definition, which otherwise describes the basic strategy
of stepwise refinement. Both strategies involve decomposition. What makes recursion
special is that the subproblems in a recursive solution have the same form as the original
problem.
If you are like most beginning programmers, the idea of breaking a problem down into
subproblems of the same form does not make much sense when you first hear it. Unlike
repetition or conditional testing, recursion is not a concept that comes up in day-to-day
life. Because it is unfamiliar, learning how to use recursion can be difficult. To do so,
you must develop the intuition necessary to make recursion seem as natural as all the
other control structures. For most students of programming, reaching that level of
understanding takes considerable time and practice. Even so, learning to use recursion is
definitely worth the effort. As a problem-solving tool, recursion is so powerful that it at
times seems almost magical. In addition, using recursion often makes it possible to write
complex programs in simple and profoundly elegant ways.
If you express this fundraising strategy in pseudocode, it has the following structure:
void CollectContributions(int n) {
if (n <= 100) {
Collect the money from a single donor.
} else {
Find 10 volunteers.
Get each volunteer to collect n/10 dollars.
Combine the money raised by the volunteers.
}
}
The most important thing to notice about this pseudocode translation is that the line
is simply the original problem reproduced at a smaller scale. The basic character of the
task—raise n dollars—remains exactly the same; the only difference is that n has a
smaller value. Moreover, because the problem is the same, you can solve it by calling the
original function. Thus, the preceding line of pseudocode would eventually be replaced
with the following line:
CollectContributions(n / 10);
It’s important to note that the CollectContributions function ends up calling itself if
the contribution level is greater than $100. In the context of programming, having a
function call itself is the defining characteristic of recursion.
The structure of the CollectContributions procedure is typical of recursive
functions. In general, the body of a recursive function has the following form:
This structure provides a template for writing recursive functions and is therefore called
the recursive paradigm. You can apply this technique to programming problems as
long as they meet the following conditions:
1. You must be able to identify simple cases for which the answer is easily determined.
2. You must be able to identify a recursive decomposition that allows you to break any
complex instance of the problem into simpler problems of the same form.
The CollectContributions example illustrates the power of recursion. As in any
recursive technique, the original problem is solved by breaking it down into smaller
subproblems that differ from the original only in their scale. Here, the original problem is
to raise $1,000,000. At the first level of decomposition, each subproblem is to raise
$100,000. These problems are then subdivided in turn to create smaller problems until
the problems are simple enough to be solved immediately without recourse to further
subdivision. Because the solution depends on dividing hard problems into simpler ones,
recursive solutions are often called divide-and-conquer strategies.
Introduction to Recursion – 176 –
product = 1;
for (int i = 1; i <= n; i++) {
product *= i;
}
return product;
}
This implementation uses a for loop to cycle through each of the integers between 1 and
n. In the recursive implementation this loop does not exist. The same effect is generated
instead by the cascading recursive calls.
Implementations that use looping (typically by using for and while statements) are
said to be iterative. Iterative and recursive strategies are often seen as opposites because
they can be used to solve the same problem in rather different ways. These strategies,
however, are not mutually exclusive. Recursive functions sometimes employ iteration
internally, and you will see examples of this technique in Chapter 6.
n! = n x (n – 1)!
Thus, 4! is 4 x 3!, 3! is 3 x 2!, and so on. To make sure that this process stops at some
point, mathematicians define 0! to be 1. Thus, the conventional mathematical definition
of the factorial function looks like this:
Introduction to Recursion – 177 –
1 if n = 0
n! =
n x (n – 1)! otherwise
This definition is recursive, because it defines the factorial of n in terms of the factorial of
n – 1. The new problem—finding the factorial of n – 1—has the same form as the
original problem, which is the fundamental characteristic of recursion. You can then use
the same process to define (n – 1)! in terms of (n – 2)!. Moreover, you can carry this
process forward step by step until the solution is expressed in terms of 0!, which is equal
to 1 by definition.
From your perspective as a programmer, the practical impact of the mathematical
definition is that it provides a template for a recursive implementation. In C++, you can
implement a function Fact that computes the factorial of its argument as follows:
int Fact(int n) {
if (n == 0) {
return 1;
} else {
return n * Fact(n - 1);
}
}
If n is 0, the result of Fact is 1. If not, the implementation computes the result by calling
Fact(n - 1) and then multiplying the result by n. This implementation follows directly
from the mathematical definition of the factorial function and has precisely the same
recursive structure.
f = Fact(4);
as part of the function main. When main calls Fact, the computer creates a new stack
frame and copies the argument value into the formal parameter n. The frame for Fact
temporarily supersedes the frame for main, as shown in the following diagram:
Introduction to Recursion – 178 –
main
Fact
→ if (n == 0) {
n return (1);
4 } else {
return (n * Fact(n - 1));
}
In the diagram, the code for the body of Fact is shown inside the frame to make it easier
to keep track of the current position in the program, which is indicated by an arrow. In
the current diagram, the arrow appears at the beginning of the code because all function
calls start at the first statement of the function body.
The computer now begins to evaluate the body of the function, starting with the if
statement. Because n is not equal to 0, control proceeds to the else clause, where the
program must evaluate and return the value of the expression
n * Fact(n - 1)
main
Fact
if (n == 0) {
n return (1);
4 } else {
return (n * Fact(n - 1));
}
↵
As soon as the call to Fact(n - 1) returns, the result is substituted for the expression
underlined in the diagram, allowing computation to proceed.
The next step in the computation is to evaluate the call to Fact(n - 1), beginning with
the argument expression. Because the current value of n is 4, the argument expression
n - 1 has the value 3. The computer then creates a new frame for Fact in which the
formal parameter is initialized to this value. Thus, the next frame looks like this:
main
Fact
Fact
→ if (n == 0) {
n return (1);
3 } else {
return (n * Fact(n - 1));
}
Introduction to Recursion – 179 –
There are now two frames labeled Fact . In the most recent one, the computer is just
starting to calculate Fact(3). In the preceding frame, which the newly created frame
hides, the Fact function is awaiting the result of the call to Fact(n - 1).
The current computation, however, is the one required to complete the topmost frame.
Once again, n is not 0, so control passes to the else clause of the if statement, where the
computer must evaluate Fact(n - 1) . In this frame, however, n is equal to 3, so the
required result is that computed by calling Fact(2). As before, this process requires the
creation of a new stack frame, as shown:
main
Fact
Fact
Fact
→ if (n == 0) {
n return (1);
2 } else {
return (n * Fact(n - 1));
}
Following the same logic, the program must now call Fact(1), which in turn calls
Fact(0), thereby creating two new stack frames. The resulting stack configuration looks
like this:
main
Fact
Fact
Fact
Fact
Fact
→ if (n == 0) {
n return (1);
0 } else {
return (n * Fact(n - 1));
}
At this point, however, the situation changes. Because the value of n is 0, the function
can return its result immediately by executing the statement
return 1;
The value 1 is returned to the calling frame, which resumes its position on top of the
stack, as shown:
Introduction to Recursion – 180 –
main
Fact
Fact
Fact
Fact
→ if (n == 0) {
n return (1);
1 } else {
return (n * Fact(n - 1));
}
↵
1
From this point, the computation proceeds back through each of the recursive calls,
completing the calculation of the return value at each level. In this frame, for example,
the call to Fact(n - 1) can be replaced by the value 1, so that the result at this level can
be expressed as follows:
return n * 1 );
In this stack frame, n has the value 1, so the result of this call is simply 1. This result gets
propagated back to its caller, which is represented by the top frame in the following
diagram:
main
Fact
Fact
Fact
→ if (n == 0) {
n return (1);
2 } else {
return (n * Fact(n - 1));
}
↵
Because n is now 2, evaluating the return statement causes the value 2 to be passed back
to the previous level, as follows:
main
Fact
Fact
→ if (n == 0) {
n return (1);
3 } else {
return (n * Fact(n - 1));
}
↵
At this stage, the program returns 3 x 2 to the previous level, so that the frame for the
initial call to Fact looks like this:
Introduction to Recursion – 181 –
main
Fact
→ if (n == 0) {
n return (1);
4 } else {
return (n * Fact(n - 1));
}
↵
6
The final step in the calculation process consists of calculating 4 x 6 and returning the
value 24 to the main program.
n * Fact(n - 1)
By substituting the current value of n into the expression, you know that the result is
4 * Fact(3)
Stop right there. Computing Fact(3) is simpler than computing Fact(4). Because it is
simpler, the recursive leap of faith allows you to assume that it works. Thus, you should
assume that the call to Fact(3) will correctly compute the value of 3!, which is 3 x 2 x 1,
or 6. The result of calling Fact(4) is therefore 4 x 6, or 24.
As you look at the examples in the rest of this chapter, try to focus on the big picture
instead of the morass of detail. Once you have made the recursive decomposition and
identified the simple cases, be satisfied that the computer can handle the rest.
population biology—a field that has become increasingly important in recent years.
Fibonacci’s problem concerns how the population of rabbits would grow from generation
to generation if the rabbits reproduced according to the following, admittedly fanciful,
rules:
• Each pair of fertile rabbits produces a new pair of offspring each month.
• Rabbits become fertile in their second month of life.
• Old rabbits never die.
If a pair of newborn rabbits is introduced in January, how many pairs of rabbits are there
at the end of the year?
You can solve Fibonacci’s problem simply by keeping a count of the rabbits at each
month during the year. At the beginning of January, there are no rabbits, since the first
pair is introduced sometime in that month, which leaves one pair of rabbits on February
1. Since the initial pair of rabbits is newborn, they are not yet fertile in February, which
means that the only rabbits on March 1 are the original pair of rabbits. In March,
however, the original pair is now of reproductive age, which means that a new pair of
rabbits is born. The new pair increases the colony’s population—counting by pairs—to
two on April 1. In April, the original pair goes right on reproducing, but the rabbits born
in March are as yet too young. Thus, there are three pairs of rabbits at the beginning of
May. From here on, with more and more rabbits becoming fertile each month, the rabbit
population begins to grow more quickly.
t0 t1 t2 t3 t4
0 1 1 2 3
You can simplify the computation of further terms in this sequence by making an
important observation. Because rabbits in this problem never die, all the rabbits that were
around in the previous month are still around. Moreover, all of the fertile rabbits have
produced a new pair. The number of fertile rabbit pairs capable of reproduction is simply
the number of rabbits that were alive in the month before the previous one. The net effect
is that each new term in the sequence must simply be the sum of the preceding two.
Thus, the next several terms in the Fibonacci sequence look like this:
The number of rabbit pairs at the end of the year is therefore 144.
From a programming perspective, it helps to express the rule for generating new terms
in the following, more mathematical form:
tn = tn–1 + tn–2
Introduction to Recursion – 183 –
The recurrence relation alone is not sufficient to define the Fibonacci sequence.
Although the formula makes it easy to calculate new terms in the sequence, the process
has to start somewhere. In order to apply the formula, you need to have at least two
terms in hand, which means that the first two terms in the sequence—t0 and t1—must be
defined explicitly. The complete specification of the terms in the Fibonacci sequence is
therefore
n if n is 0 or 1
tn =
tn–1 + tn–2 otherwise
At this point, the computer calculates the result of Fib(4) , adds that to the result of
calling Fib(3), and returns the sum as the value of Fib(5).
But how does the computer go about evaluating Fib(4) and Fib(3)? The answer, of
course, is that it uses precisely the same strategy. The essence of recursion is to break
problems down into simpler ones that can be solved by calls to exactly the same function.
Those calls get broken down into simpler ones, which in turn get broken down into even
simpler ones, until at last the simple cases are reached.
On the other hand, it is best to regard this entire mechanism as irrelevant detail.
Remember the recursive leap of faith. Your job at this level is to understand how the call
to Fib(5) works. In the course of walking though the execution of that function, you
have managed to transform the problem into computing the sum of Fib(4) and Fib(3).
Because the argument values are smaller, each of these calls represents a simpler case.
Applying the recursive leap of faith, you can assume that the program correctly computes
each of these values, without going through all the steps yourself. For the purposes of
validating the recursive strategy, you can just look the answers up in the table. Fib(4) is
3 and Fib(3) is 2, so the result of calling Fib(5) is 3 + 2, or 5, which is indeed the
correct answer. Case closed. You don’t need to see all the details, which are best left to
the computer.
Introduction to Recursion – 184 –
/*
* File: fib.cpp
* -------------
* This program lists the terms in the Fibonacci sequence with
* indices ranging from MIN_INDEX to MAX_INDEX.
*/
#include "genlib.h"
#include <iostream>
/*
* Constants
* ---------
* MIN_INDEX -- Index of first term to generate
* MAX_INDEX -- Index of last term to generate
*/
/* Main program */
int main() {
cout << "This program lists the Fibonacci sequence." << endl;
for (int i = MIN_INDEX; i <= MAX_INDEX; i++) {
cout << "Fib(" << i << ")";
if (i < 10) cout << " ";
cout << " = " << Fib(i) << endl;
}
return 0;
}
/*
* Function: Fib
* Usage: t = Fib(n);
* ------------------
* This function returns the nth term in the Fibonacci sequence
* using a recursive implementation of the recurrence relation
*
* Fib(n) = Fib(n - 1) + Fib(n - 2)
*/
int Fib(int n) {
if (n < 2) {
return n;
} else {
return Fib(n - 1) + Fib(n - 2);
}
}
Introduction to Recursion – 185 –
Fib(5)
Fib(4) Fib(3)
1 1 0 1 0
Fib(1) Fib(0)
1 0
Introduction to Recursion – 186 –
If you had such a function, it would be easy to implement Fib using it. All you would
need to do is supply the correct values of the first two terms, as follows:
int Fib(int n) {
return AdditiveSequence(n, 0, 1);
}
The body consists of a single line of code that does nothing but call another function,
passing along a few extra arguments. Functions of this sort, which simply return the
result of another function, often after transforming the arguments in some way, are called
wrapper functions. Wrapper functions are extremely common in recursive
programming. In most cases, a wrapper function is used—as it is here—to supply
additional arguments to a subsidiary function that solves a more general problem.
From here, the only remaining task is to implement the function AdditiveSequence.
If you think about this more general problem for a few minutes, you will discover that
additive sequences have an interesting recursive character of their own. The simple case
for the recursion consists of the terms t0 and t 1 , whose values are part of the definition of
the sequence. In the C++ implementation, the value of these terms are passed as
arguments. If you need to compute t0, for example, all you have to do is return the
argument t0.
But what if you are asked to find a term further down in the sequence? Suppose, for
example, that you want to find t6 in the additive sequence whose initial terms are 3 and 7.
By looking at the list of terms in the sequence
t0 t1 t2 t3 t4 t5 t6 t7 t8 t9
3 7 10 17 27 44 71 115 186 301 ...
you can see that the correct value is 71. The interesting question, however, is how you
can use recursion to determine this result.
Introduction to Recursion – 187 –
The key insight you need to discover is that the nth term in any additive sequence is
simply the n–1st term in the additive sequence which begins one step further along. For
example, t6 in the sequence shown in the most recent example is simply t5 in the additive
sequence
t0 t1 t2 t3 t4 t5 t6 t7 t8
7 10 17 27 44 71 115 186 301 ...
that begins with 7 and 10.
This discovery makes it possible to implement the function AdditiveSequence as
follows:
int AdditiveSequence(int n, int t0, int t1) {
if (n == 0) return t0;
if (n == 1) return t1;
return AdditiveSequence(n - 1, t1, t0 + t1);
}
If you trace through the steps in the calculation of Fib(5) using this technique, you
will discover that the calculation involves none of the redundant computation that
plagued the earlier recursive formulation. The steps lead directly to the solution, as
shown in the following diagram:
Fib(5)
= AdditiveSequence(5, 0, 1)
= AdditiveSequence(4, 1, 1)
= AdditiveSequence(3, 1, 2)
= AdditiveSequence(2, 2, 3)
= AdditiveSequence(1, 3, 5)
= 5
Detecting palindromes
A palindrome is a string that reads identically backward and forward, such as "level"
or "noon". Although it is easy to check whether a string is a palindrome by iterating
through its characters, palindromes can also be defined recursively. The insight you need
to do so is that any palindrome longer than a single character must contain a shorter
palindrome in its interior. For example, the string "level" consists of the palindrome
"eve" with an "l" at each end. Thus, to check whether a string is a palindrome—
assuming the string is sufficiently long that it does not constitute a simple case—all you
need to do is
Introduction to Recursion – 188 –
1. Check to see that the first and last characters are the same.
2. Check to see whether the substring generated by removing the first and last characters
is itself a palindrome.
The only other question you must consider before writing a recursive solution to the
palindrome problem is what the simple cases are. Clearly, any string with only a single
character is a palindrome because reversing a one-character string has no effect. The
one-character string therefore represents a simple case, but it is not the only one. The
empty string—which contains no characters at all—is also a palindrome, and any
recursive solution must operate correctly in this case as well.
Figure 5-3 contains a recursive implementation of the predicate function
IsPalindrome(str) that returns true if and only if the string str is a palindrome. The
function first checks to see whether the length of the string is less than 2. If it is, the
string is certainly a palindrome. In not, the function checks to make sure that the string
meets both of the criteria listed earlier.
This implementation in Figure 5-3 is somewhat inefficient, even though the recursive
decomposition is easy to follow. You can write a more efficient implementation of
IsPalindrome by making the following changes:
• Calculate the length of the argument string only once. The initial implementation
calculates the length of the string at every level of the recursive decomposition, even
though the structure of the solution guarantees that the length of the string decreases by
two on every recursive call. By calculating the length of the string at the beginning
and passing it down through each of the recursive calls, you can eliminate many calls
to the length method. To avoid changing the prototype for IsPalindrome, you need
Figure 5-3 Recursive implementation of IsPalindrome
/*
* Function: IsPalindrome
* Usage: if (IsPalindrome(str)) . . .
* -----------------------------------
* This function returns true if and only if the string is a.
* palindrome. This implementation operates recursively by noting
* that all strings of length 0 or 1 are palindromes (the simple
* case) and that longer strings are palindromes only if their first
* and last characters match and the remaining substring is a
* palindrome.
*/
Binary search
When you work with arrays or vectors, one of the most common algorithmic operations
consists of searching the array for a particular element. For example, if you were
working with arrays of strings, it would be extremely useful to have a function
/*
* Function: IsPalindrome
* Usage: if (IsPalindrome(str)) . . .
* -----------------------------------
* This function returns true if and only if the character string
* str is a palindrome. This level of the implementation is
* just a wrapper for the CheckPalindrome function, which
* does the real work.
*/
/*
* Function: CheckPalindrome
* Usage: if (CheckPalindrome(str, firstPos, lastPos)) . . .
* ----------------------------------------------------------
* This function returns true if the characters from firstPos
* to lastPos in the string str form a palindrome. The
* implementation uses the recursive insight that all
* strings of length 0 or 1 are palindromes (the simple
* case) and that longer strings are palindromes only if
* their first and last characters match and the remaining
* substring is a palindrome. Recursively examining the
* interior substring is performed by adjusting the indexes
* of the range to examine. The interior substring
* begins at firstPos+1 and ends at lastPos-1.
*/
that searches through each of the n elements of array, looking for an element whose
value is equal to key. If such an element is found, FindStringInArray returns the index
at which it appears (if the key appears more than once in the array, the index of any
matching is fine). If no matching element exists, the function returns –1.
If you have no specific knowledge about the order of elements within the array, the
implementation of FindStringInArray must simply check each of the elements in turn
until it either finds a match or runs out of elements. This strategy is called the linear
search algorithm, which can be time-consuming if the arrays are large. On the other
hand, if you know that the elements of the array are arranged in alphabetical order, you
can adopt a much more efficient approach. All you have to do is divide the array in half
and compare the key you’re trying to find against the element closest to the middle of the
array, using the order defined by the ASCII character codes, which is called
lexicographic order. If the key you’re looking for precedes the middle element, then the
key—if it exists at all—must be in the first half. Conversely, if the key follows the
middle element in lexicographic order, you only need to look at the elements in the
second half. This strategy is called the binary search algorithm. Because binary search
makes it possible for you to discard half the possible elements at each step in the process,
it turns out to be much more efficient than linear search for sorted arrays.
The binary search algorithm is also a perfect example of the divide-and-conquer
strategy. It is therefore not surprising that binary search has a natural recursive
implementation, which is shown in Figure 5-5. Note that the function
FindStringInSortedArray is implemented as a wrapper, leaving the real work to the
recursive function BinarySearch, which takes two indices—low and high—that limit
the range of the search.
The simple cases for BinarySearch are
1. There are no elements in the active part of the array. This condition is marked by the
fact that the index low is greater than the index high, which means that there are no
elements left to search.
2. The middle element (or an element to one side of the middle if the array contains an
even number of elements) matches the specified key. Since the key has just been
found, FindStringInSortedArray can simply return the index of the middle value.
If neither of these cases applies, however, the implementation can simplify the problem
by choosing the appropriate half of the array and call itself recursively with an updated
set of search limits.
Mutual recursion
In each of the examples considered so far, the recursive functions have called themselves
directly, in the sense that the body of the function contains a call to itself. Although most
of the recursive functions you encounter are likely to adhere to this style, the definition of
recursion is actually somewhat broader. To be recursive, a function must call itself at
some point during its evaluation. If a function is subdivided into subsidiary functions, the
recursive call can actually occur at a deeper level of nesting. For example, if a function ƒ
calls a function g, which in turn calls ƒ, the function calls are still considered to be
recursive. Because the functions ƒ and g call each other, this type of recursion is called
mutual recursion.
Introduction to Recursion – 191 –
/*
* Function: FindStringInSortedArray
* Usage: index = FindStringInSortedArray(key, array, n);
* ------------------------------------------------------
* This function searches the array looking for the specified
* key. The argument n specifies the effective size of the
* array, which must be sorted according to lexicographic
* order. If the key is found, the function returns the
* index in the array at which that key appears. (If the key
* appears more than once in the array, any of the matching
* indices may be returned). If the key does not exist in
* the array, the function returns -1. In this implementation,
* FindStringInSortedArray is simply a wrapper; all the work
* is done by the recursive function BinarySearch.
*/
/*
* Function: BinarySearch
* Usage: index = BinarySearch(key, array, low, high);
* ---------------------------------------------------
* This function does the work for FindStringInSortedArray.
* The only difference is that BinarySearch takes both the
* upper and lower limit of the search.
*/
As a simple example, let’s investigate how to use recursion to test whether a number is
even or odd. If you limit the domain of possible values to the set of natural numbers,
which are defined simply as the set of nonnegative integers, the even and odd numbers
can be characterized as follows:
Even though these rules seem simplistic, they constitute the basis of an effective, if
inefficient, strategy for distinguishing odd and even numbers. A mutually recursive
implementation of the predicate functions IsEven and IsOdd appears in Figure 5-6.
Introduction to Recursion – 192 –
/*
* Function: IsEven
* Usage: if (IsEven(n)) . . .
* ---------------------------
* This function returns true if n is even. The number 0
* is considered even by definition; any other number is
* even if its predecessor is odd. Note that this function
* is defined to take an unsigned argument and is therefore
* not applicable to negative integers.
*/
/*
* Function: IsOdd
* Usage: if (IsOdd(n)) . . .
* --------------------------
* This function returns true if n is odd, where a number
* is defined to be odd if it is not even. Note that this
* function is defined to take an unsigned argument and is
* therefore not applicable to negative integers.
*/
Whenever you are writing a recursive program or trying to understand the behavior of
one, you must get to the point where you ignore the details of the individual recursive
calls. As long as you have chosen the right decomposition, identified the appropriate
simple cases, and implemented your strategy correctly, those recursive calls will simply
work. You don’t need to think about them.
Unfortunately, until you have had extensive experience working with recursive
functions, applying the recursive leap of faith does not come easily. The problem is that
it requires to suspend your disbelief and make assumptions about the correctness of your
programs that fly in the face of your experience. After all, when you write a program, the
odds are good—even if you are an experienced programmer—that your program won’t
work the first time. In fact, it is quite likely that you have chosen the wrong
decomposition, messed up the definition of the simple cases, or somehow messed things
up trying to implement your strategy. If you have done any of these things, your
recursive calls won’t work.
When things go wrong—as they inevitably will—you have to remember to look for the
error in the right place. The problem lies somewhere in your recursive implementation,
not in the recursive mechanism itself. If there is a problem, you should be able to find it
by looking at a single level of the recursive hierarchy. Looking down through additional
levels of recursive calls is not going to help. If the simple cases work and the recursive
decomposition is correct, the subsidiary calls will work correctly. If they don’t, there is
something you need to fix in the definition of the recursive function itself.
Avoiding the common pitfalls
As you gain experience with recursion, the process of writing and debugging recursive
programs will become more natural. At the beginning, however, finding out what you
need to fix in a recursive program can be difficult. The following is a checklist that will
help you identify the most common sources of error.
• Does your recursive implementation begin by checking for simple cases? Before you
attempt to solve a problem by transforming it into a recursive subproblem, you must
first check to see if the problem is so simple that such decomposition is unnecessary.
In almost all cases, recursive functions begin with the keyword if. If your function
doesn’t, you should look carefully at your program and make sure that you know what
you’re doing.1
• Have you solved the simple cases correctly? A surprising number of bugs in recursive
programs arise from having incorrect solutions to the simple cases. If the simple cases
are wrong, the recursive solutions to more complicated problems will inherit the same
mistake. For example, if you had mistakenly defined Fact(0) as 0 instead of 1,
calling Fact on any argument would end up returning 0.
• Does your recursive decomposition make the problem simpler? For recursion to work,
the problems have to get simpler as you go along. More formally, there must be some
metric—a standard of measurement that assigns a numeric difficulty rating to the
problem—that gets smaller as the computation proceeds. For mathematical functions
like Fact and Fib , the value of the integer argument serves as a metric. On each
recursive call, the value of the argument gets smaller. For the IsPalindrome function,
the appropriate metric is the length of the argument string, because the string gets
shorter on each recursive call. If the problem instances do not get simpler, the
1 At times, as in the case of the IsPalindrome implementation, it may be necessary to perform some
calculations prior to making the simple-case test. The point is that the simple-case test must precede any
recursive decomposition.
Introduction to Recursion – 194 –
decomposition process will just keep making more and more calls, giving rise to the
recursive analogue of the infinite loop, which is called nonterminating recursion.
• Does the simplification process eventually reach the simple cases, or have you left out
some of the possibilities? A common source of error is failing to include simple case
tests for all the cases that can arise as the result of the recursive decomposition. For
example, in the IsPalindrome implementation presented in Figure 5-3, it is critically
important for the function to check the zero-character case as well as the one-character
case, even if the client never intends to call IsPalindrome on the empty string. As the
recursive decomposition proceeds, the string arguments get shorter by two characters
at each level of the recursive call. If the original argument string is even in length, the
recursive decomposition will never get to the one-character case.
• Do the recursive calls in your function represent subproblems that are truly identical
in form to the original? When you use recursion to break down a problem, it is
essential that the subproblems be of the same form. If the recursive calls change the
nature of the problem or violate one of the initial assumptions, the entire process can
break down. As several of the examples in this chapter illustrate, it is often useful to
define the publicly exported function as a simple wrapper that calls a more general
recursive function which is private to the implementation. Because the private
function has a more general form, it is usually easier to decompose the original
problem and still have it fit within the recursive structure.
• When you apply the recursive leap of faith, do the solutions to the recursive
subproblems provide a complete solution to the original problem? Breaking a
problem down into recursive subinstances is only part of the recursive process. Once
you get the solutions, you must also be able to reassemble them to generate the
complete solution. The way to check whether this process in fact generates the
solution is to walk through the decomposition, religiously applying the recursive leap
of faith. Work through all the steps in the current function call, but assume that every
recursive call generates the correct answer. If following this process yields the right
solution, your program should work.
Summary
This chapter has introduced the idea of recursion, a powerful programming strategy in
which complex problems are broken down into simpler problems of the same form. The
important points presented in this chapter include:
• To use recursion, you must be able to identify simple cases for which the answer is
easily determined and a recursive decomposition that allows you to break any complex
instance of the problem into simpler problems of the same type.
Introduction to Recursion – 195 –
• Recursive functions are implemented using exactly the same mechanism as any other
function call. Each call creates a new stack frame that contains the local variables for
that call. Because the computer creates a separate stack frame for each function call,
the local variables at each level of the recursive decomposition remain separate.
• Before you can use recursion effectively, you must learn to limit your analysis to a
single level of the recursive decomposition and to rely on the correctness of all simpler
recursive calls without tracing through the entire computation. Trusting these simpler
calls to work correctly is called the recursive leap of faith.
• Mathematical functions often express their recursive nature in the form of a recurrence
relation, in which each element of a sequence is defined in terms of earlier elements.
• Although some recursive functions may be less efficient than their iterative
counterparts, recursion itself is not the problem. As is typical with all types of
algorithms, some recursive strategies are more efficient than others.
• In order to ensure that a recursive decomposition produces subproblems that are
identical in form to the original, it is often necessary to generalize the problem. As a
result, it is often useful to implement the solution to a specific problem as a simple
wrapper function whose only purpose is to call a subsidiary function that handles the
more general case.
• Recursion need not consist of a single function that calls itself but may instead involve
several functions that call each other in a cyclical pattern. Recursion that involves
more than one function is called mutual recursion.
• You will be more successful at understanding recursive programs if you can maintain a
holistic perspective rather than a reductionistic one.
Thinking about recursive problems in the right way does not come easily. Learning to
use recursion effectively requires practice and more practice. For many students,
mastering the concept takes years. But because recursion will turn out to be one of the
most powerful techniques in your programming repertoire, that time will be well spent.
Review questions
1. Define the terms recursive and iterative. Is it possible for a function to employ both
strategies?
if (n <= 100)
Why is it important to use the <= operator instead of simply checking whether n is
exactly equal to 100?
5. What two properties must a problem have for recursion to make sense as a solution
strategy?
7. What is meant by the recursive leap of faith? Why is this concept important to you
as a programmer?
8. In the section entitled “Tracing the recursive process,” the text goes through a long
analysis of what happens internally when Fact(4) is called. Using this section as a
model, trace through the execution of Fib(4) , sketching out each stack frame
created in the process.
9. Modify Fibonacci’s rabbit problem by introducing the additional rule that rabbit
pairs stop reproducing after giving birth to three litters. How does this assumption
change the recurrence relation? What changes do you need to make in the simple
cases?
10. How many times is Fib(1) called when calculating Fib(n) using the recursive
implementation given in Figure 5-1?
11. What would happen if you eliminated the if (n == 1) check from the function
AdditiveSequence, so that the implementation looked like this:
12. What is a wrapper function? Why are they often useful in writing recursive
functions?
13. Why is it important that the implementation of IsPalindrome in Figure 5-3 check
for the empty string as well as the single character string? What would happen if the
function didn’t check for the single character case and instead checked only whether
the length is 0? Would the function still work correctly?
16. What would happen if you defined IsEven and IsOdd as follows:
Which of the errors explained in the section “Avoiding the common pitfalls” is
illustrated in this example?
Introduction to Recursion – 197 –
17. The following definitions of IsEven and IsOdd are also incorrect:
bool IsEven(unsigned int n) {
if (n == 0) {
return true;
} else {
return IsOdd(n - 1);
}
}
Programming exercises
1. Spherical objects, such as cannonballs, can be stacked to form a pyramid with one
cannonball at the top, sitting on top of a square composed of four cannonballs, sitting
on top of a square composed of nine cannonballs, and so forth. Write a recursive
function Cannonball that takes as its argument the height of the pyramid and returns
the number of cannonballs it contains. Your function must operate recursively and
must not use any iterative constructs, such as while or for.
2. Unlike many programming languages, C++ does not include a predefined operator
that raises a number to a power. As a partial remedy for this deficiency, write a
recursive implementation of a function
int RaiseIntToPower(int n, int k)
that calculates n k. The recursive insight that you need to solve this problem is the
mathematical property that
1 if k = 0
nk =
n x n k–1 otherwise
3. The greatest common divisor (g.c.d.) of two nonnegative integers is the largest
integer that divides evenly into both. In the third century B. C ., the Greek
mathematician Euclid discovered that the greatest common divisor of x and y can
always be computed as follows:
• If x is evenly divisible by y, then y is the greatest common divisor.
• Otherwise, the greatest common divisor of x and y is always equal to the greatest
common divisor of y and the remainder of x divided by y.
Use Euclid’s insight to write a recursive function GCD(x, y) that computes the
greatest common divisor of x and y.
4. Write an iterative implementation of the function Fib(n).
Introduction to Recursion – 198 –
5. For each of the two recursive implementations of the function Fib(n) presented in
this chapter, write a recursive function (you can call these CountFib1 and
CountFib2 for the two algorithms) that counts the number of function calls made
during the evaluation of the corresponding Fibonacci calculation. Write a main
program that uses these functions to display a table showing the number of calls
made by each algorithm for various values of n, as shown in the following sample
run:
FibCount
This program compares the performance of two
algorithms to compute the Fibonacci sequence.
Number of calls:
N Fib1 Fib2
-- ---- ----
0 1 2
1 1 3
2 3 4
3 5 5
4 9 6
5 15 7
6 25 8
7 41 9
8 67 10
9 109 11
10 177 12
11 287 13
12 465 14
6. Write a recursive function DigitSum(n) that takes a nonnegative integer and returns
the sum of its digits. For example, calling DigitSum(1729) should return
1 + 7 + 2 + 9, which is 19.
The recursive implementation of DigitSum depends on the fact that it is very easy
to break an integer down into two components using division by 10. For example,
given the integer 1729, you can divide it into two pieces as follows:
1729
172 9
n / 10 n % 10
Each of the resulting integers is strictly smaller than the original and thus represents
a simpler case.
7. The digital root of an integer n is defined as the result of summing the digits
repeatedly until only a single digit remains. For example, the digital root of 1729
can be calculated using the following steps:
Step 1: 1 + 7 + 2 + 9 → 19
Step 2: 1 + 9 → 10
Step 3: 1 + 0 → 1
Introduction to Recursion – 199 –
Because the total at the end of step 3 is the single digit 1, that value is the digital
root.
Write a function DigitalRoot(n) that returns the digital root of its argument.
Although it is easy to implement DigitalRoot using the DigitSum function from
exercise 6 and a while loop, part of the challenge of this problem is to write the
function recursively without using any explicit loop constructs.
8. The mathematical combinations function C(n, k) is usually defined in terms of
factorials, as follows:
n!
C(n, k) =
k! x (n–k)!
The values of C(n, k) can also be arranged geometrically to form a triangle in which
n increases as you move down the triangle and k increases as you move from left to
right. The resulting structure,, which is called Pascal’s Triangle after the French
mathematician Blaise Pascal, is arranged like this:
C(0, 0)
C(1, 0) C(1, 1)
C(2, 0) C(2, 1) C(2, 2)
C(3, 0) C(3, 1) C(3, 2) C(3, 3)
C(4, 0) C(4, 1) C(4, 2) C(4, 3) C(4, 4)
Pascal’s Triangle has the interesting property that every entry is the sum of the two
entries above it, except along the left and right edges, where the values are always 1.
Consider, for example, the circled entry in the following display of Pascal’s
Triangle:
1
1 1
1 2 1
1 3 3 1
1 4 6 4 1
1 5 10 10 5 1
1 6 15 20 15 6 1
This entry, which corresponds to C(6, 2), is the sum of the two entries—5 and 10—
that appear above it to either side. Use this relationship between entries in Pascal’s
Triangle to write a recursive implementation of the Combinations function that uses
no loops, no multiplication, and no calls to Fact.
9. Write a recursive function that takes a string as argument and returns the reverse of
that string. The prototype for this function should be
string Reverse(string str);
and the statement
cout << Reverse("program") << endl;
Introduction to Recursion – 200 –
should display
ReverseString
margorp
Your solution should be entirely recursive and should not use any iterative constructs
such as while or for.
10. The strutils.h library contains a function IntegerToString,. You might have
wondered how the computer actually goes about the process of converting an integer
into its string representation. As it turns out, the easiest way to implement this
function is to use the recursive decomposition of an integer outlined in exercise 6.
Rewrite the IntegerToString implementation so that it operates recursively without
using use any of the iterative constructs such as while and for.
Chapter 6
Recursive Procedures
In the great temple at Benares beneath the dome which marks the
center of the world, rests a brass plate in which are fixed three
diamond needles, each a cubit high and as thick as the body of a bee.
On one of these needles, at the creation, God placed sixty-four disks
of pure gold, the largest disk resting on the brass plate and the others
getting smaller and smaller up to the top one. This is the Tower of
Brahma. Day and night unceasingly, the priests transfer the disks
from one diamond needle to another according to the fixed and
immutable laws of Brahma, which require that the priest on duty
must not move more than one disk at a time and that he must place
this disk on a needle so that there is no smaller disk below it. When
all the sixty-four disks shall have been thus transferred from the
needle on which at the creation God placed them to one of the other
needles, tower, temple and Brahmins alike will crumble into dust,
and with a thunderclap the world will vanish.
Over the years, the setting has shifted from India to Vietnam, but the puzzle and its
legend remain the same.
Recursive Procedures – 203 –
As far as I know, the Tower of Hanoi puzzle has no practical use except one: teaching
recursion to computer science students. In that domain, its value is unquestioned because
the solution involves almost nothing besides recursion. In contrast to most practical
examples of recursion, the Tower of Hanoi problem has no extraneous complications that
might interfere with your understanding and keep you from seeing how the recursive
solution works. Because it works so well as an example, the Tower of Hanoi is included
in most textbooks that treat recursion and has become part of the cultural heritage that
computer programmers share.
In most commercial versions of the puzzle, the 64 golden disks of legend are replaced
with eight wooden or plastic ones, which makes the puzzle considerably easier to solve,
not to mention cheaper. The initial state of the puzzle looks like this:
A B C
At the beginning, all eight disks are on spire A. Your goal is to move these eight disks
from spire A to spire B, but you must adhere to the following rules:
The number of disks to move is clearly an integer, and the fact that the spires are labeled
with the letters A, B, and C suggests the use of type char to indicate which spire is
involved. Knowing the types allows you to write a prototype for the operation that
moves a tower, as follows:
This function call corresponds to the English command “Move a tower of size 8 from
spire A to spire B using spire C as a temporary.” As the recursive decomposition
proceeds, MoveTower will be called with different arguments that move smaller towers in
various configurations.
1. There must be a simple case. In this problem, there is an obvious simple case.
Because the rules of the puzzle require you to move only one disk at a time, any
tower with more than one disk must be moved in pieces. If, however, the tower only
contains one disk, you can go ahead and move it, as long as you obey the other rules
of the game. Thus, the simple case occurs when n is equal to 1.
2. There must be a way to break the problem down into a simpler problem in such a way
that solving the smaller problem contributes to solving the original one. This part of
the problem is harder and will require closer examination.
To see how solving a simpler subproblem helps solve a larger problem, it helps to go
back and consider the original example with eight disks.
A B C
The goal here is to move eight disks from spire A to spire B. You need to ask yourself
how it would help if you could solve the same problem for a smaller number of disks. In
particular, you should think about how being able to move a stack of seven disks would
help you to solve the eight-disk case.
If you think about the problem for a few moments, it becomes clear that you can solve
the problem by dividing it into these three steps:
1. Move the entire stack consisting of the top seven disks from spire A to spire C.
2. Move the bottom disk from spire A to spire B.
3. Move the stack of seven disks from spire C to spire B.
A B C
Once you have gotten rid of the seven disks on top of the largest disk, the second step is
simply to move that disk from spire A to spire B, which results in the following
configuration:
A B C
All that remains is to move the tower of seven disks back from spire C to spire B, which
is again a smaller problem of the same form. This operation is the third step in the
recursive strategy, and leaves the puzzle in the desired final configuration:
A B C
That’s it! You’re finished. You’ve reduced the problem of moving a tower of size
eight to one of moving a tower of size seven. More importantly, this recursive strategy
generalizes to towers of size N, as follows:
1. Move the top N–1 disks from the start spire to the temporary spire.
2. Move a single disk from the start spire to the finish spire.
3. Move the stack of N–1 disks from the temporary spire back to the finish spire.
At this point, it is hard to avoid saying to yourself, “Okay, I can reduce the problem to
moving a tower of size N–1, but how do I accomplish that?” The answer, of course, is
that you move a tower of size N–1 in precisely the same way. You break that problem
down into one that requires moving a tower of size N–2, which further breaks down into
Recursive Procedures – 206 –
the problem of moving a tower of size N–3, and so forth, until there is only a single disk
to move. Psychologically, however, the important thing is to avoid asking that question
altogether. The recursive leap of faith should be sufficient. You’ve reduced the scale of
the problem without changing its form. That’s the hard work. All the rest is
bookkeeping, and it’s best to let the computer take care of that.
Once you have identified the simple cases and the recursive decomposition, all you
need to do is plug them into the standard recursive paradigm, which results in the
following pseudocode procedure:
void MoveTower(int n, char start, char finish, char temp) {
if (n == 1) {
Move a single disk from start to finish.
} else {
Move a tower of size n - 1 from start to temp.
Move a single disk from start to finish.
Move a tower of size n - 1 from temp to finish.
}
}
To trace how this call computes the steps necessary to transfer a tower of size 3, all you
need to do is keep track of the operation of the program, using precisely the same strategy
as in the factorial example from Chapter 5. For each new function call, you introduce a
stack frame that shows the values of the parameters for that call. The initial call to
MoveTower, for example, creates the following stack frame:
MoveTower
n start finish temp
3 A B C
→ if (n == 1) {
MoveSingleDisk(start, finish);
} else {
MoveTower(n - 1, start, temp, finish);
MoveSingleDisk(start, finish);
MoveTower(n - 1, temp, finish, start);
}
Recursive Procedures – 208 –
As the arrow in the code indicates, the function has just been called, so execution begins
with the first statement in the function body . The current value of n is not equal to 1, so
the program skips ahead to the else clause and executes the statement
As with any function call, the first step is to evaluate the arguments. To do so, you
need to determine the values of the variables n, start, temp, and finish. Whenever you
need to find the value of a variable, you use the value as it is defined in the current stack
frame. Thus, the MoveTower call is equivalent to
This operation, however, indicates another function call, which means that the current
operation is suspended until the new function call is complete. To trace the operation of
the new function call, you need to generate a new stack frame and repeat the process. As
always, the parameters in the new stack frame are initialized by copying the calling
arguments in the order in which they appear. Thus, the new stack frame looks like this:
MoveTower
MoveTower
n start finish temp
2 A C B
→ if (n == 1) {
MoveSingleDisk(start, finish);
} else {
MoveTower(n - 1, start, temp, finish);
MoveSingleDisk(start, finish);
MoveTower(n - 1, temp, finish, start);
}
As the diagram illustrates, the new stack frame has its own set of variables, which
temporarily supersede the variables in frames that are further down on the stack. Thus, as
long as the program is executing in this stack frame, n will have the value 2, start will
be 'A', finish will be 'C', and temp will be 'B'. The old values in the previous frame
will not reappear until the subtask represented by this call is created and the function
returns.
The evaluation of the recursive call to MoveTower proceeds exactly like the original
one. Once again, n is not 1, which requires another call of the form
Because this call comes from a different stack frame, however, the value of the individual
variables are different from those in the original call. If you evaluate the arguments in the
context of the current stack frame, you discover that this function call is equivalent to
MoveTower
MoveTower
MoveTower
n start finish temp
1 A B C
→ if (n == 1) {
MoveSingleDisk(start, finish);
} else {
MoveTower(n - 1, start, temp, finish);
MoveSingleDisk(start, finish);
MoveTower(n - 1, temp, finish, start);
}
This call to MoveTower, however, does represent the simple case. Since n is 1, the
program calls the MoveSingleDisk function to move a disk from A to B, leaving the
puzzle in the following configuration:
A B C
At this point, the most recent call to MoveTower is complete and the function returns.
In the process, its stack frame is discarded, which brings the execution back to the
previous stack frame, having just completed the first statement in the else clause:
MoveTower
MoveTower
n start finish temp
2 A C B
if (n == 1) {
MoveSingleDisk(start, finish);
} else {
MoveTower(n - 1, start, temp, finish);
→ MoveSingleDisk(start, finish);
MoveTower(n - 1, temp, finish, start);
}
The call to MoveSingleDisk again represents a simple operation, which leaves the
puzzle in the following state:
Recursive Procedures – 210 –
A B C
With the MoveSingleDisk operation completed, the only remaining step required to
finish the current call to MoveTower is the last statement in the function:
Evaluating these arguments in the context of the current frame reveals that this call is
equivalent to
Once again, this call requires the creation of a new stack frame. By this point in the
process, however, you should be able to see that the effect of this call is simply to move a
tower of size 1 from B to C, using A as a temporary repository. Internally, the function
determines that n is 1 and then calls M o v e S i n g l e D i s k to reach the following
configuration:
A B C
This operation again completes a call to MoveTower, allowing it to return to its caller
having completed the subtask of moving a tower of size 2 from A to C. Discarding the
stack frame from the just-completed subtask reveals the stack frame for the original call
to MoveTower, which is now in the following state:
MoveTower
n start finish temp
3 A B C
if (n == 1) {
MoveSingleDisk(start, finish);
} else {
MoveTower(n - 1, start, temp, finish);
→ MoveSingleDisk(start, finish);
MoveTower(n - 1, temp, finish, start);
}
The next step is to call MoveSingleDisk to move the largest disk from A to B, which
results in the following position:
Recursive Procedures – 211 –
A B C
with the arguments from the current stack frame, which are
MoveTower(2, 'C', 'B', 'A');
If you’re still suspicious of the recursive process, you can draw the stack frame created
by this function call and continue tracing the process to its ultimate conclusion. At some
point, however, it is essential that you trust the recursive process enough to see that
function call as a single operation having the effect of the following command in English:
If you think about the process in this holistic form, you can immediately see that
completion of this step will move the tower of two disks back from C to B, leaving the
desired final configuration:
A B C
ListPermutations("ABC");
ListPermutations
ABC
ACB
BAC
BCA
CBA
CAB
Recursive Procedures – 212 –
The order of the output is unimportant, but each of the possible arrangements should
appear exactly once.
How would you go about implementing the ListPermutations function? If you are
limited to iterative control structures, finding a general solution that works for strings of
any length is difficult. Thinking about the problem recursively, on the other hand, leads
to a relatively straightforward solution.
As is usually the case with recursive programs, the hard part of the solution process is
figuring out how to divide the original problem into simpler instances of the same
problem. In this case, to generate all permutations of a string, you need to discover how
being able to generate all permutations of a shorter string might contribute to the solution.
Stop and think about this problem for a few minutes. When you are first learning
about recursion, it is easy to look at a recursive solution and believe that you could have
generated it on your own. Without trying it first, however, it is hard to know whether you
would have come up with the same insight.
To give yourself more of a feel for the problem, you need to consider a concrete case.
Suppose you want to generate all permutations of a five-character string, such as
"ABCDE" . In your solution, you can apply the recursive leap of faith to generate all
permutations of any shorter string. Just assume that the recursive calls work and be done
with it. Once again, the critical question is how being able to permute shorter strings
helps you solve the problem of permuting the original five-character string.
The recursive insight
The key to solving the permutation problem is recognizing that the permutations of the
five-character string "ABCDE" consist of the following strings:
• The character 'A' followed by every possible permutation of "BCDE"
• The character 'B' followed by every possible permutation of "ACDE"
• The character 'C' followed by every possible permutation of "ABDE"
• The character 'D' followed by every possible permutation of "ABCE"
• The character 'E' followed by every possible permutation of "ABCD"
More generally, to display all permutations of a string of length n, you can take each of
the n characters in turn and display that character followed by every possible permutation
of the remaining n – 1 characters.
The only difficulty with this solution strategy is that the recursive subproblem does not
have exactly the same form as the original. The original problem requires you to display
all permutations of a string. The subproblem requires you to display a character from a
string followed by all permutations of the remaining letters. As the recursion proceeds,
the character in front will become two characters, then three, and so forth. The general
subproblem, therefore, is to generate all permutations of a string, with some characters at
the beginning of the string already fixed in their positions.
As discussed in Chapter 5, the easiest way to solve the problem of asymmetry between
the original problem and its recursive subproblems is to define ListPermutations as a
simple wrapper function that calls a subsidiary function to solve the more general case.
In this example, the general problem can be solved by a new procedure
RecursivePermute, which generates all permutations of the remaining characters in a
string having already chosen some characters as the prefix. The prefix starts empty and
Recursive Procedures – 213 –
all the original letters still remain to be examined, which gives you the original problem.
As the prefix grows and there are fewer characters remaining, the problem becomes
simpler. When there are no characters remaining to be permuted, all characters have been
placed in the prefix, and it can be displayed exactly as it appears. The definition of
ListPermutations itself looks like this:
Translating this function from pseudocode to C++ is reasonably simple. The full
definition of RecursivePermute looks like this:
void RecursivePermute(string prefix, string rest) {
if (rest == "") {
cout << prefix << endl;
} else {
for (int i = 0; i < rest.length(); i++) {
string newPrefix = prefix + rest[i];
string newRest = rest.substr(0, i) + rest.substr(i+1);
RecursivePermute(newPrefix, newRest);
}
}
}
1 Note that the C-based graphics library uses a very different drawing model from the acm.graphics
package available in Java. We’re working on a new graphics library for C++ that looks like the Java one.
Recursive Procedures – 214 –
• Absolute coordinates specify a point in the window by giving its coordinates with
respect to the origin. For example, the solid dot in Figure 6-1 is at absolute
coordinates (2.0, 1.5).
• Relative coordinates specify a position in the window by indicating how far away that
point is along each axis from the last position specified. For example, the open dot in
Figure 6-1 has absolute coordinates (2.5, 1.5). If, however, you express its coordinates
in relation to the solid dot, this point is shifted by the relative coordinates (0.5, 0.0). If
you want to connect these dots with a line, the standard approach is to specify the first
point in absolute coordinates and the endpoint of the line in relative coordinates.
Figure 6-1 Coordinates in the graphics library
3
0
0 1 2 3
Recursive Procedures – 215 –
The best mental model to use for the drawing process is to imagine that there is a pen
positioned over a piece of transparent graph paper covering the screen. You can move
the pen to any location on the screen by specifying the absolute coordinates. You then
draw a straight line by moving the pen to a new point specified using relative coordinates,
making sure that the pen continuously touches the graph paper as you draw the line.
From there, you can start another line beginning where the last one ended.
The functions exported by the graphics.h interface are shown in Table 6-1. Graphics
applications begin by calling InitGraphics, after which the graphical image itself is
created by calls to MovePen , DrawLine , and DrawArc . The remaining functions—
GetWindowWidth , GetWindowHeight , GetCurrentX , and GetCurrentY —make it
possible to retrieve information about the dimensions and state of the graphics window.
These functions come up less frequently, but are nonetheless useful enough that it makes
sense to include them in the interface.
To get a better sense of how the graphics library works, consider the following
program, which draws a simple archway:
int main() {
InitGraphics();
MovePen(2.0, 0.5);
DrawLine(1.0, 0.0);
DrawLine(0.0, 1.0);
DrawArc(0.5, 0, 180);
DrawLine(0.0, -1.0);
return 0;
}
The program begins, like all graphics programs, with a call to InitGraphics , which
creates an empty graphics window. The next two statements then move the pen to the
point (2.0, 0.5) and draw a line with the relative coordinates (1.0, 0.0). The effect of
these statements is to draw a 1-inch horizontal line near the bottom of the window. The
next call to DrawLine adds a vertical line that begins where the first line ended. Thus, at
this point, the graphics window contains two lines in the following configuration:
draws a circular arc with a radius of 0.5 inches. Because the second argument is 0, the
arc begins at the 0 degree mark, which corresponds to the 3 o’clock position. From there,
the third argument indicates that the arc runs in the positive direction (counterclockwise)
for a total of 180 degrees, or halfway around the circle. Adding this semicircle to the line
segments generated earlier makes the graphics window look like this:
The last line in the program draws a 1-inch vertical line in the downward direction,
which completes the archway, as shown:
Recursive Procedures – 217 –
How would you go about designing a general strategy to create such a figure using the
graphics library?
Figure 6-2 Grid pattern from Piet Mondrian, “Composition with Grid 6,” 1919
Recursive Procedures – 218 –
To understand how a program might produce such a figure, it helps to think about the
process as one of successive decomposition. At the beginning, the canvas was simply an
empty rectangle that looked like this:
If you want to subdivide the canvas using a series of horizontal and vertical lines, the
easiest way to start is by drawing a single line that divides the rectangle in two:
If you’re thinking recursively, the thing to notice at this point is that you now have two
empty rectangular canvases, each of which is smaller in size. The task of subdividing
these rectangles is the same as before, so you can perform it by using a recursive
implementation of the same procedure. Since the new rectangles are taller than they are
wide, you might choose to use a horizontal dividing line, but the basic process remains
the same.
At this point, the only thing needed for a complete recursive strategy is a simple case.
The process of dividing up rectangles can’t go on indefinitely. As the rectangles get
smaller and smaller, at some point the process has to stop. One approach is to look at the
area of each rectangle before you start. Once the area of a rectangle falls below some
threshold, you needn’t bother to subdivide it any further.
The mondrian.cpp program shown in Figure 6-3 implements the recursive algorithm,
using the entire graphics window as the initial canvas.
Recursive Procedures – 219 –
/*
* File: mondrian.cpp
* ------------------
* This program creates a random line drawing in a style reminiscent
* of the Dutch painter Piet Mondrian. The picture is generated by
* recursively subdividing the canvas into successively smaller
* rectangles with randomly chosen horizontal and vertical lines.
*/
#include "genlib.h"
#include "graphics.h"
#include "random.h"
/*
* Constants
* ---------
* MIN_AREA -- Smallest square that will be split
* MIN_EDGE -- Minimum fraction on each side of dividing line
*/
/* Main program */
int main() {
InitGraphics();
Randomize();
SubdivideCanvas(0, 0, GetWindowWidth(), GetWindowHeight());
return 0;
}
/*
* Function: SubdivideCanvas
* Usage: SubdivideCanvas(x, y, width, height);
* --------------------------------------------
* This function decomposes a canvas by recursive subdivision. The
* lower left corner of the canvas is the point (x, y), and the
* dimensions are given by the width and height parameters. The
* function first checks for the simple case, which is obtained
* when the size of the rectangular canvas is too small to subdivide
* (area < MIN_AREA). In the simple case, the function does nothing.
* If the area is larger than the minimum, the function first
* decides whether to split the canvas horizontally or vertically,
* choosing the larger dimension. The function then chooses a
* random dividing line, making sure to leave at least MIN_EDGE on
* each side. The program then uses a divide-and-conquer strategy
* to subdivide the two new rectangles.
*/
Recursive Procedures – 220 –
In mondrian.cpp , the recursive function SubdivideCanvas does all the work. The
arguments give the position and dimensions of the current rectangle on the canvas. At
each step in the decomposition, the function simply checks to see whether the rectangle is
large enough to split. If it is, the function checks to see which dimension—width or
height—is larger and accordingly divides the rectangle with a vertical or horizontal line.
In each case, the function draws only a single line; all remaining lines in the figure are
drawn by subsequent recursive calls.
Fractals
In the late 1970s, a researcher at IBM named Benoit Mandelbrot generated a great deal of
excitement by publishing a book on fractals, which are geometrical structures in which
the same pattern is repeated at many different scales. Although mathematicians have
known about fractals for a long time, there was a resurgence of interest in the subject
during the 1980s, partly because the development of computers made it possible to do so
much more with fractals than had ever been possible before.
One of the earliest examples of fractal figures is called the Koch snowflake after its
inventor, Helge von Koch. The Koch snowflake begins with an equilateral triangle like
this:
This triangle, in which the sides are straight lines, is called the Koch fractal of order 0.
The figure is then revised in stages to generate fractals of successively higher orders. At
each stage, every straight-line segment in the figure is replaced by one in which the
middle third consists of a triangular bump protruding outward from the figure. Thus, the
first step is to replace each line segment in the triangle with a line that looks like this:
Recursive Procedures – 221 –
Applying this transformation to each of the three sides of the original triangle generates
the Koch fractal of order 1, as follows:
If you then replace each line segment in this figure with a new line that again includes
a triangular wedge, you create the following order-2 Koch fractal:
Replacing each of these line segments gives the order-3 fractal shown in the following
diagram, which has started to resemble a snowflake:
Because figures like the Koch fractal are much easier to draw by computer than by
hand, it makes sense to write a program that uses the graphics library to generate this
design. Before designing the program itself, however, it helps to introduce a new
procedure that will prove useful in a variety of graphical applications. The DrawLine
primitive in the graphics library requires you to specify the relative coordinates of the
new endpoint as a pair of values, dx and dy. In many graphical applications, it is much
easier to think of lines as having a length and a direction. For example, the solid line in
the following diagram can be identified by its length (r) and its angle from the x-axis (θ):
Recursive Procedures – 222 –
θ
x-axis
In mathematics, the parameters r and θ are called the polar coordinates of the line.
Converting from polar coordinates to the more traditional Cartesian coordinates used in
the graphics library requires a little trigonometry, as shown in the following
implementation of the procedure DrawPolarLine, which draws a line of length r in the
direction theta, measured in degrees counterclockwise from the x-axis:
const double PI = 3.1415926535;
void DrawPolarLine(double r, double theta) {
double radians = theta / 180 * PI;
DrawLine(r * cos(radians), r * sin(radians));
}
If you don’t understand trigonometry, don’t worry. You don’t need to understand the
implementation of DrawPolarLine to use it. If you have had a trigonometry course, most
of this implementation should be straightforward; the only complexity comes from the
fact that the library functions sin and cos are defined to take their arguments in radian
measure, which means that the implementation must convert the theta parameter from
degrees to radians prior to calling the trigonometric functions.
Given DrawPolarLine, it is very easy to draw the equilateral triangle that represents
the Koch snowflake of order 0. If size is the length of one side of the triangle, all you
need to do is position the pen at the lower left corner of the figure and make the following
calls:
DrawPolarLine(size, 0);
DrawPolarLine(size, 120);
DrawPolarLine(size, 240);
But how would you go about drawing a more complicated Koch fractal, that is, one of
a higher order? The first step is simply to replace each of the calls to DrawPolarLine
with a call to a new procedure that draws a fractal line of a specified order. Thus, the
three calls in the main program look like this:
DrawFractalLine(size, 0, order);
DrawFractalLine(size, 120, order);
DrawFractalLine(size, 240, order);
The next task is to implement DrawFractalLine, which is easy if you think about it
recursively. The simple case for DrawFractalLine occurs when order is 0, in which
case the function simply draws a straight line with the specified length and direction. If
order is greater than 0, the fractal line is broken down into four components, each of
which is itself a fractal line of the next lower order. Thus, the implementation of
DrawFractalLine looks like this:
Recursive Procedures – 223 –
/*
* File: koch.cpp
* ---------------
* This program draws a Koch fractal.
*/
#include <iostream>
#include <cmath>
#include "simpio.h"
#include "graphics.h"
#include "genlib.h"
/* Constants */
/* Main program */
int main() {
InitGraphics();
cout << "Program to draw Koch fractals" << endl;
cout << "Enter edge length in inches: ";
double size = GetReal();
cout << "Enter order of fractal: ";
int order = GetInteger();
KochFractal(size, order);
return 0;
}
/*
* Function: KochFractal
* Usage: KochFractal(size, order);
* --------------------------------
* This function draws a Koch fractal snowflake centered in
* the graphics window of the indicated size and order.
*/
Recursive Procedures – 224 –
/*
* Function: DrawFractalLine
* Usage: DrawFractalLine(len, theta, order);
* ------------------------------------------
* This function draws a fractal line of the given length, starting
* from the current point and moving in direction theta. If order
* is 0, the fractal line is a straight line. If order is greater
* than zero, the line is divided into four line segments, each of
* which is a fractal line of the next lower order. These segments
* connect the same endpoints as the straight line, but include
* a triangular wedge replacing the center third of the segment.
*/
void DrawFractalLine(double len, double theta, int order) {
if (order == 0) {
DrawPolarLine(len, theta);
} else {
DrawFractalLine(len/3, theta, order - 1);
DrawFractalLine(len/3, theta - 60, order - 1);
DrawFractalLine(len/3, theta + 60, order - 1);
DrawFractalLine(len/3, theta, order - 1);
}
}
/*
* Function: DrawPolarLine
* Usage: DrawPolarLine(r, theta);
* -------------------------------
* This function draws a line of length r in the direction
* specified by the angle theta, measured in degrees.
*/
void DrawPolarLine(double r, double theta) {
double radians = theta / 180 * PI;
DrawLine(r * cos(radians), r * sin(radians));
}
Summary
Except for the discussion of the graphics library in the section entitled “Graphical
applications of recursion” earlier in this chapter, relatively few new concepts have been
introduced in Chapter 6. The fundamental precepts of recursion were introduced in
Chapter 5. The point of Chapter 6 is to raise the sophistication level of the recursive
examples to the point at which the problems become difficult to solve in any other way.
Because of this increase in sophistication, beginning students often find these problems
much harder to comprehend than those in the preceding chapter. Indeed, they are harder,
but recursion is a tool for solving hard problems. To master it, you need to practice with
problems at this level of complexity.
Recursive Procedures – 225 –
Review questions
1. In your own words, describe the recursive insight necessary to solve the Tower of
Hanoi puzzle.
2. What is wrong with the following strategy for solving the recursive case of the
Tower of Hanoi puzzle:
a. Move the top disk from the start spire to the temporary spire.
b. Move a stack of N–1 disks from the start spire to the finish spire.
c. Move the top disk now on the temporary spire back to the finish spire.
3. If you call
MoveTower(16, 'A', 'B', 'C')
what line is displayed by MoveSingleDisk as the first step in the solution? What is
the last step in the solution?
4. What is a permutation?
5. In your own words, explain the recursive insight necessary to enumerate the
permutations of the characters in a string.
6. How many permutations are there of the string "WXYZ"?
7. Why is it necessary to define both ListPermutations and RecursivePermute in
the permutation problem?
8. Where is the origin located in the graphics window?
9. What is the difference between absolute and relative coordinates?
10. What are the eight functions exported by the graphics.h interface?
11. What simple case is used to terminate the recursion in mondrian.cpp?
Recursive Procedures – 226 –
Programming exercises
1. Following the logic of the MoveTower function, write a recursive function
NHanoiMoves(n) that calculates the number of individual moves required to solve
the Tower of Hanoi puzzle for n disks.
2. To make the operation of the program somewhat easier to explain, the
implementation of MoveTower in this chapter uses
if (n == 1)
as its simple case test. Whenever you see a recursive program use 1 as its simple
case, it pays to be a little skeptical; in most applications, 0 is a more appropriate
choice. Rewrite the Tower of Hanoi program so that the MoveTower function checks
whether n is 0 instead. What happens to the length of the M o v e T o w e r
implementation?
3. Rewrite the Tower of Hanoi program so that it uses an explicit stack of pending tasks
instead of recursion. In this context, a task can be represented most easily as a
structure containing the number of disks to move and the names of the spires used
for the start, finish, and temporary repositories. At the beginning of the process, you
push onto your stack a single task that describes the process of moving the entire
tower. The program then repeatedly pops the stack and executes the task found there
until no tasks are left. Except for the simple cases, the process of executing a task
results in the creation of more tasks that get pushed onto the stack for later execution.
4. As presented in the text, the function RecursivePermute takes two strings, which
indicate how far the permutation process has progressed. You could also design the
program so that RecursivePermute takes a string and an integer. where the string is
the concatenation of the fixed prefix with a suffix whose characters can still be
permuted. The integer indicates the number of characters in the prefix and thus the
index at which the remaining characters begin within the string. For example, if you
call the redesigned RecursivePermute function on the arguments "ABCD" and 2, the
output should be
LPEX1
ABCD
ABDC
which is all strings beginning with "AB" followed by some permutation of "CD".
Rewrite the permutation program so that it uses this new design.
5. Update the permutation algorithm from the text to generate the correct list of
permutations even if the string contains repeated letters. For example, if you call
ListPermutations on the string "AABB" , your program should not generate as
many permutations as it does for the string "ABCD" because some of the strings
Recursive Procedures – 227 –
ABC DEF
1 2 3
* 0 #
In order to make their phone numbers more memorable, service providers like to find
numbers that spell out some word (called a mnemonic) appropriate to their business
that makes that phone number easier to remember. For example, the phone number
for a recorded time-of-day message in some localities is 637-8687 (NERVOUS).
Imagine that you have just been hired by a local telephone company to write a
function ListMnemonics that will generate all possible letter combinations that
correspond to a given number, represented as a string of digits. For example, the call
ListMnemonics("723")
should generate the following 36 possible letter combinations that correspond to that
prefix:
PAD PBD PCD QAD QBD QCD RAD RBD RCD SAD SBD SCD
PAE PBE PCE QAE QBE QCE RAE RBE RCE SAE SBE SCE
PAF PBF PCF QAF QBF QCF RAF RBF RCF SAF SBF SCF
7. Rewrite the program from exercise 6 so that it uses the Lexicon class and the
EnglishWords.dat file from Chapter 4 so that the program only lists mnemonics
that are valid English words.
Recursive Procedures – 228 –
ListSubsets("ABC");
Subsets
This program lists all subsets of a set.
Enter a string representing a set: ABC
{ABC}
{AB}
{AC}
{A}
{BC}
{B}
{C}
{}
000 → 0
001 → 1
010 → 2
011 → 3
100 → 4
101 → 5
110 → 6
111 → 7
Each entry in the left side of the table is written in its standard binary representation,
in which each bit position counts for twice as much as the position to its right. For
instance, you can demonstrate that the binary value 110 represents the decimal
number 6 by following the logic shown in the following diagram:
place value 4 2 1
x x x
binary digits 1 1 0
=
4 + 2 + 0 = 6
Recursive Procedures – 229 –
10. Although the binary coding used in exercise 7 is ideal for most applications, it has
certain drawbacks. As you count in standard binary notation, there are some points
in the sequence at which several bits change at the same time. For example, in the
three-bit binary code, the value of every bit changes as you move from 3 (011) to 4
(100).
In some applications, this instability in the bit patterns used to represent adjacent
numbers can lead to problems. Imagine for the moment that you are using some
hardware measurement device that produces a three-bit value from some real-world
phenomenon that happens to be varying between 3 and 4. Sometimes, the device
will register 011 to indicate the value 3; at other times, it will register 100 to indicate
4. For this device to work correctly, the transitions for each of the individual bits
must occur simultaneously. If the first bit changes more quickly than the others, for
example, there may be an intermediate state in which the device reads 111, which
would be a highly inaccurate reading.
It is interesting to discover that you can avoid this problem simply by changing
the numbering system. If instead of using binary representation in the traditional
way, you can assign three-bit values to each of the numbers 0 through 7 with the
highly useful property that only one bit changes in the representation between every
pair of adjacent integers. Such an encoding is called a Gray code (after its inventor,
the mathematician Frank Gray) and looks like this:
000 → 0
001 → 1
011 → 2
010 → 3
110 → 4
111 → 5
101 → 6
100 → 7
Note that, in the Gray code representation, the bit patterns for 3 and 4 differ only in
their leftmost bit. If the hardware measurement device used Gray codes, a value
oscillating between 3 and 4 would simply turn that bit on and off, eliminating any
problems with synchronization.
The recursive insight that you need to create a Gray code of N bits is summarized
in the following informal procedure:
Recursive Procedures – 230 –
0 0 0
0 0 1
0 1 1 0 0
0 1 0 0 1 0
1 1 0 1 1 reversed
1
1 1 1 reversed 1 0
1 0 1
1 0 0
Write a recursive function GenerateGrayCode(nBits) that generates the Gray
code patterns for the specified number of bits.
11. Given a set of numbers, the partition problem is to find a subset of the numbers that
add up to a specific target number. For example, there are two ways to partition the
set {1, 3, 4, 5} so that the remaining elements add up to 5:
• Select the 1 and the 4
• Select just the 5
By contrast, there is no way to partition the set {1, 3, 4, 5} to get 11.
Write a function NumberOfPartitions that takes an array of integers, the length
of that array, and a target number, and returns the number of partitions of that set of
integers which add up to the target. For example, suppose that the array sampleSet
has been initialized as follows:
NumberOfPartitions(sampleSet, 4, 5);
should return 2 (there are two ways to make 5), and calling
NumberOfPartitions(sampleSet, 4, 11)
In order to see the recursive nature of this problem, think about any specific element
in the set, such as the first element. If you think about all the partitions of a
particular target number, some of them will include the first element and some
won’t. If you count those that do include the first element and then add that total to
the number of those which leave out that element, you get the total number of
partitions. Each of these two computations, however, can be expressed as a problem
in the same form as the outer partition problem and can therefore be solved
recursively.
12. I am the only child of parents who weighed, measured, and priced
everything; for whom what could not be weighed, measured, and
priced had no existence.
—Charles Dickens, Little Dorrit, 1857
In Dickens’s time, merchants measured many commodities using weights and a two-
pan balance—a practice that continues in many parts of the world today. If you are
using a limited set of weights, however, you can only measure certain quantities
accurately.
For example, suppose that you have only two weights: a 1-ounce weight and a 3-
ounce weight. With these you can easily measure out 4 ounces, as shown:
1 3
It is somewhat more interesting to discover that you can also measure out 2 ounces
by shifting the 1-ounce weight to the other side, as follows:
1 3
that determines whether it is possible to measure out the desired target amount with a
given set of weights. The available weights are stored in the array weights, which
has nWeights as its effective size. For instance, the sample set of two weights
illustrated above could be represented using the following pair of variables:
int sampleWeights[] = { 1, 3 };
int nSampleWeights = 2;
The longest tick mark falls at the half-inch position, two smaller tick marks indicate
the quarter inches, and even smaller ones are used to mark the eighths and sixteenths.
Write a recursive program that draws a 1-inch line at the center of the graphics
window and then draws the tick marks shown in the diagram. Assume that the
length of the tick mark indicating the half-inch position is given by the constant
definition
and that each smaller tick mark is half the size of the next larger one.
14. One of the reasons that fractals have generated so much interest is that they turn out
to be useful in some surprising practical contexts. For example, the most successful
techniques for drawing computer images of mountains and certain other landscape
features involve using fractal geometry.
As a simple example of where this issue comes up, consider the problem of
connecting two points A and B with a fractal that looks like a coastline on a map.
The simplest possible strategy would be to draw a straight line between the two
points:
A B
This is the order 0 coastline and represents the base case of the recursion.
Of course, a real coastline will have small peninsulas or inlets somewhere along
its length, so you would expect a realistic drawing of a coastline to jut in or out
occasionally like a real one. As a first approximation, you could replace the straight
Recursive Procedures – 233 –
line with precisely the same fractal line used to create the Koch snowflake in the
program described in the section on “Fractals” earlier in the chapter, as follows:
A B
This process gives the order 1 coastline. However, in order to give the feeling of a
traditional coastline, it is important for the triangular wedge in this line sometimes to
point up and sometimes down, with equal probability.
If you then replace each of the straight line segments in the order 1 fractal with a
fractal line in a random direction, you get the order 2 coastline, which might look
like this:
A B
15. Recursive decomposition can also be used to draw a stylized representation of a tree.
The tree begins as a simple trunk indicated by a straight vertical line, as follows:
Recursive Procedures – 234 –
The trunk may branch at the top to form two lines that veer off at an angle, as shown:
These branches may themselves split to form new branches, which split to form new
ones, and so on. If the decision to branch is made randomly at each step of the
process, the tree will eventually become unsymmetrical and will end up looking a
little more like trees in nature, as illustrated by the following diagram:
If you think about this process recursively, however, you can see that all trees
constructed in this way consist of a trunk, optionally topped by two trees that veer
off at an angle. If the probability of branching is a function of the length of the
current branch, the process will eventually terminate as the branches get
progressively shorter.
Write a program drawtree.cpp that uses this recursive strategy and the graphics
library to draw a stylized line drawing of a tree.
Chapter 7
Backtracking Algorithms
For many real-world problems, the solution process consists of working your way
through a sequence of decision points in which each choice leads you further along some
path. If you make the correct set of choices, you end up at the solution. On the other
hand, if you reach a dead end or otherwise discover that you have made an incorrect
choice somewhere along the way, you have to backtrack to a previous decision point and
try a different path. Algorithms that use this approach are called backtracking
algorithms.
If you think about a backtracking algorithm as the process of repeatedly exploring
paths until you encounter the solution, the process appears to have an iterative character.
As it happens, however, most problems of this form are easier to solve recursively. The
fundamental recursive insight is simply this: a backtracking problem has a solution if and
only if at least one of the smaller backtracking problems that results from making each
possible initial choice has a solution. The examples in this chapter are designed to
illustrate this process and demonstrate the power of recursion in this domain.
As you walk, the requirement that you keep your right hand touching the wall may force
you to turn corners and occasionally retrace your steps. Even so, following the right-
hand rule guarantees that you will always be able to find an opening to the outside of any
maze.
To visualize the operation of the right-hand rule, imagine that Theseus has successfully
dispatched the Minotaur and is now standing in the position marked by the first character
in Theseus’s name, the Greek letter theta (Θ):
Backtracking Algorithms – 237 –
If Theseus puts his right hand on the wall and then follows the right-hand rule from there,
he will trace out the path shown by the dashed line in this diagram:
Θ
Finding a recursive approach
As the while loop in its pseudocode form makes clear, the right-hand rule is an iterative
strategy. You can, however, also think about the process of solving a maze from a
recursive perspective. To do so, you must adopt a different mindset. You can no longer
think about the problem in terms of finding a complete path. Instead, your goal is to find
a recursive insight that simplifies the problem, one step at a time. Once you have made
the simplification, you use the same process to solve each of the resulting subproblems.
Let’s go back to the initial configuration of the maze shown in the illustration of the
right-hand rule. Put yourself in Theseus’s position. From the initial configuration, you
have three choices, as indicated by the arrows in the following diagram:
The exit, if any, must lie along one of those paths. Moreover, if you choose the correct
direction, you will be one step closer to the solution. The maze has therefore become
Backtracking Algorithms – 238 –
simpler along that path, which is the key to a recursive solution. This observation
suggests the necessary recursive insight. The original maze has a solution if and only if it
is possible to solve at least one of the new mazes shown in Figure 7-1. The × in each
diagram marks the original starting square and is off-limits for any of the recursive
solutions because the optimal solution will never have to backtrack through this square.
By looking at the mazes in Figure 7-1, it is easy to see—at least from your global
vantage point—that the submazes labeled (a) and (c) represent dead-end paths and that
the only solution begins in the direction shown in the submaze (b). If you are thinking
recursively, however, you don’t need to carry on the analysis all the way to the solution.
You have already decomposed the problem into simpler instances. All you need to do is
rely on the power of recursion to solve the individual subproblems, and you’re home free.
You still have to identify a set of simple cases so that the recursion can terminate, but the
hard work has been done.
× ×
Θ ×
×
At this point, you’ve run out of room to maneuver. Every path from the new position is
either marked or blocked by a wall, which makes it clear that the maze has no solution
from this point. Thus, the maze problem has a second simple case in which every
direction from the current square is blocked, either by a wall or a marked square.
Θ
× × Θ ×
Θ
It is easier to code the recursive algorithm if, instead of checking for marked squares as
you consider the possible directions of motion, you go ahead and make the recursive calls
on those squares. If you check at the beginning of the procedure to see whether the
current square is marked, you can terminate the recursion at that point. After all, if you
find yourself positioned on a marked square, you must be retracing your path, which
means that the solution must lie in some other direction.
Thus, the two simple cases for this problem are as follows:
1. If the current square is outside the maze, the maze is solved.
2. If the current square is marked, the maze is unsolvable.
/*
* File: mazelib.h
* ---------------
* This interface provides a library of primitive operations
* to simplify the solution to the maze problem.
*/
#ifndef _mazelib_h
#define _mazelib_h
#include "genlib.h"
/*
* Type: directionT
* ----------------
* This type is used to represent the four compass directions.
*/
/*
* Type: pointT
* ------------
* The type pointT is used to encapsulate a pair of integer
* coordinates into a single value with x and y components.
*/
struct pointT {
int x, y;
};
/*
* Function: ReadMazeMap
* Usage: ReadMazeMap(filename);
* -----------------------------
* This function reads in a map of the maze from the specified
* file and stores it in private data structures maintained by
* this module. In the data file, the characters '+', '-', and
* '|' represent corners, horizontal walls, and vertical walls,
* respectively; spaces represent open passageway squares. The
* starting position is indicated by the character 'S'. For
* example, the following data file defines a simple maze:
*
* +-+-+-+-+-+
* | |
* + +-+ + +-+
* |S | |
* +-+-+-+-+-+
*
* Coordinates in the maze are numbered starting at (0,0) in
* the lower left corner. The goal is to find a path from
* the (0,0) square to the exit east of the (4,1) square.
*/
/*
* Function: GetStartPosition
* Usage: pt = GetStartPosition();
* -------------------------------
* This function returns a pointT indicating the coordinates of
* the start square.
*/
pointT GetStartPosition();
/*
* Function: OutsideMaze
* Usage: if (OutsideMaze(pt)) . . .
* ---------------------------------
* This function returns true if the specified point is outside
* the boundary of the maze.
*/
/*
* Function: WallExists
* Usage: if (WallExists(pt, dir)) . . .
* -------------------------------------
* This function returns true if there is a wall in the indicated
* direction from the square at position pt.
*/
/*
* Functions: MarkSquare, UnmarkSquare, IsMarked
* Usage: MarkSquare(pt);
* UnmarkSquare(pt);
* if (IsMarked(pt)) . . .
* ------------------------------
* These functions mark, unmark, and test the status of the
* square specified by the coordinates pt.
*/
#endif
Backtracking Algorithms – 242 –
The code for the SolveMaze function itself turns out to be extremely short and is
shown in Figure 7-3. The entire algorithm fits into approximately 10 lines of code with
the following pseudocode structure:
If the current square is outside the maze, return true to indicate that a solution has been found.
If the current square is marked, return false to indicate that this path has already been tried.
Mark the current square.
for (each of the four compass directions) {
if (this direction is not blocked by a wall) {
Move one step in the indicated direction from the current square.
Try to solve the maze from there by making a recursive call.
If this call shows the maze to be solvable, return true to indicate that fact.
}
}
Unmark the current square.
Return false to indicate that none of the four directions led to a solution.
The only function called by SolveMaze that is not exported by the mazelib.h
interface is the function AdjacentPoint(pt, dir), which returns the coordinates of the
square that is one step away from pt in the direction dir . The following is a simple
implementation of AdjacentPoint that copies the original point and then adjusts the
appropriate coordinate value:
/*
* Function: SolveMaze
* Usage: if (SolveMaze(pt)) . . .
* -------------------------------
* This function attempts to generate a solution to the current
* maze from point pt. SolveMaze returns true if the maze has
* a solution and false otherwise. The implementation uses
* recursion to solve the submazes that result from marking the
* current square and moving one step along each open passage.
*/
The code to unmark the current square at the end of the for loop is not strictly
necessary in this implementation and in fact can reduce the performance of the algorithm
if there are loops in the maze (see exercise 3). The principal advantage of including it is
that doing so means that the solution path ends up being recorded by a chain of marked
squares from the original starting position to the exit. If you are using a graphical
implementation of this algorithm, erasing the marks as you retreat down a path makes it
much easier to see the current path.
Θ
×
At this point, the same process occurs again. The program again tries to move north
and makes a new recursive call in the following position:
Backtracking Algorithms – 244 –
Θ
×
×
At this level of the recursion, moving north is no longer possible, so the for loop cycles
through the other directions. After a brief excursion southward, upon which the program
encounters a marked square, the program finds the opening to the west and proceeds to
generate a new recursive call. The same process occurs in this new square, which in turn
leads to the following configuration:
× ×
Θ ×
×
In this position, none of the directions in the for loop do any good; every square is
either blocked by a wall or already marked. Thus, when the for loop at this level exits at
the bottom, it unmarks the current square and returns to the previous level. It turns out
that all the paths have also been explored in this position, so the program once again
unmarks the square and returns to the next higher level in the recursion. Eventually, the
program backtracks all the way to the initial call, having completely exhausted the
possibilities that begin by moving north. The for loop then tries the eastward direction,
finds it blocked, and continues on to explore the southern corridor, beginning with a
recursive call in the following configuration:
×
Θ
From here on, the same process ensues. The recursion systematically explores every
corridor along this path, backing up through the stack of recursive calls whenever it
reaches a dead end. The only difference along this route is that eventually—after
Backtracking Algorithms – 245 –
descending through an additional recursive level for every step on the path—the program
makes a recursive call in the following position:
× × × ×
× × × ×
× × ×
× × ×
× × × × ×
× × × ×
× × ×
Θ
At this point, Theseus is outside the maze. The simple case kicks in and returns true to
its caller. This value is then propagated back through all 27 levels of the recursion, at
which point the original call to SolveMaze returns to the main program.
How would you go about writing a program to play a winning game of nim? The
mechanical aspects of the game—keeping track of the number of coins, asking the player
for a legal move, determining the end of the game, and so forth—are a straightforward
programming task. The interesting part of the program consists of figuring out how to
give the computer a strategy for playing the best possible game.
Finding a successful strategy for nim is not particularly hard, particularly if you work
backward from the end of the game. The rules of nim state that the loser is the player
who takes the last coin. Thus, if you ever find yourself with just one coin on the table,
you’re in a bad position. You have to take that coin and lose. On the other hand, things
look good if you find yourself with two, three, or four coins. In any of these cases, you
can always take all but one of the remaining coins, leaving your opponent in the
unenviable position of being stuck with just one coin. But what if there are five coins on
the table? What can you do then? After a bit of thought, it’s easy to see that you’re also
doomed if you’re left with five coins. No matter what you do, you have to leave your
opponent with two, three, or four coins—situations that you’ve just discovered represent
good positions from your opponent’s perspective. If your opponent is playing
intelligently, you will surely be left with a single coin on your next turn. Since you have
no good moves, being left with five coins is clearly a bad position.
This informal analysis reveals an important insight about the game of nim. On each
turn, you are looking for a good move. A move is good if it leaves your opponent in a
bad position. But what is a bad position? A bad position is one in which there is no good
move. Although these definitions of good move and bad position are circular, they
nonetheless constitute a complete strategy for playing a perfect game of nim. All you
have to do is rely on the power of recursion. If you have a function FindGoodMove that
takes the number of coins as its argument, all it has to do is try every possibility, looking
for one that leaves a bad position for the opponent. You can then assign the job of
determining whether a particular position is bad to the predicate function
IsBadPosition, which calls FindGoodMove to see if there is one. The two functions call
each other back and forth, evaluating all possible branches as the game proceeds.
The FindGoodMove function has the following pseudocode formulation:
Backtracking Algorithms – 247 –
The legal values returned by FindGoodMove are 1, 2, and 3. The sentinel indicating that
no good move exists can be any integer value outside that range. For example, you can
define the constant NO_GOOD_MOVE as follows:
The code for the IsBadPosition function is even easier. After checking for the
simple case that occurs when there is only a single coin to take, the function simply calls
FindGoodMove to see if a good move exists. The code for IsBadPosition is therefore
simply
The functions FindGoodMove and IsBadPosition provide all the strategy that the nim
program needs to play a perfect game. The rest of the program just takes care of the
mechanics of playing nim with a human player, as shown in Figure 7-5.
/*
* File: nim.cpp
* -------------
* This program simulates a simple variant of the game of nim.
* In this version, the game starts with a pile of 13 coins
* on a table. Players then take turns removing 1, 2, or 3
* coins from the pile. The player who takes the last coin
* loses. This simulation allows a human player to compete
* against the computer.
*/
#include "genlib.h"
#include "simpio.h"
#include <iostream>
/*
* Constants
* ---------
* N_COINS -- Initial number of coins
* MAX_MOVE -- The maximum number of coins a player may take
* NO_GOOD_MOVE -- Sentinel indicating no good move is available
*/
/*
* Type: playerT
* -------------
* This enumeration type distinguishes the turns for the human
* player from those for the computer.
*/
void GiveInstructions();
void AnnounceWinner(int nCoins, playerT whoseTurn);
int GetUserMove(int nCoins);
bool MoveIsLegal(int nTaken, int nCoins);
int ChooseComputerMove(int nCoins);
int FindGoodMove(int nCoins);
bool IsBadPosition(int nCoins);
Backtracking Algorithms – 249 –
/*
* Main program
* ------------
* This program plays the game of nim. In this implementation,
* the human player always goes first.
*/
int main() {
int nCoins, nTaken;
playerT whoseTurn;
GiveInstructions();
nCoins = N_COINS;
whoseTurn = Human;
while (nCoins > 1) {
cout << "There are " << nCoins << " coins in the pile."<<endl;
switch (whoseTurn) {
case Human:
nTaken = GetUserMove(nCoins);
whoseTurn = Computer;
break;
case Computer:
nTaken = ChooseComputerMove(nCoins);
cout << "I'll take " << nTaken << "." << endl;
whoseTurn = Human;
break;
}
nCoins -= nTaken;
}
AnnounceWinner(nCoins, whoseTurn);
return 0;
}
/*
* Function: GiveInstructions
* Usage: GiveInstructions();
* --------------------------
* This function explains the rules of the game to the user.
*/
void GiveInstructions() {
cout << "Hello. Welcome to the game of nim." << endl;
cout << "In this game, we will start with a pile of" << endl;
cout << N_COINS << " coins on the table. " << endl;
cout << "On each turn, you" << endl;
cout << "and I will alternately take between 1 and" << endl;
cout << MAX_MOVE << " coins from the table." << endl;
cout << "The player who" << endl;
cout << "takes the last coin loses." << endl;
cout << endl;
}
Backtracking Algorithms – 250 –
/*
* Function: AnnounceWinner
* Usage: AnnounceWinner(nCoins, whoseTurn);
* -----------------------------------------
* This function announces the final result of the game.
*/
/*
* Function: GetUserMove
* Usage: nTaken = GetUserMove(nCoins);
* ------------------------------------
* This function is responsible for the human player's turn.
* It takes the number of coins left in the pile as an argument,
* and returns the number of coins that the player removes
* from the pile. The function checks the move for legality
* and gives the player repeated chances to enter a legal move.
*/
/*
* Function: MoveIsLegal
* Usage: if (MoveIsLegal(nTaken, nCoins)) . . .
* ---------------------------------------------
* This predicate function returns true if it is legal to take
* nTaken coins from a pile of nCoins.
*/
/*
* Function: ChooseComputerMove
* Usage: nTaken = ChooseComputerMove(nCoins);
* -------------------------------------------
* This function figures out what move is best for the computer
* player and returns the number of coins taken. The function
* first calls FindGoodMove to see if a winning move exists.
* If none does, the program takes only one coin to give the
* human player more chances to make a mistake.
*/
/*
* Function: FindGoodMove
* Usage: nTaken = FindGoodMove(nCoins);
* -------------------------------------
* This function looks for a winning move, given the specified
* number of coins. If there is a winning move in that
* position, the function returns that value; if not, the
* function returns the constant NoWinningMove. This function
* depends on the recursive insight that a good move is one
* that leaves your opponent in a bad position and a bad
* position is one that offers no good moves.
*/
/*
* Function: IsBadPosition
* Usage: if (IsBadPosition(nCoins)) . . .
* ---------------------------------------
* This function returns true if nCoins is a bad position.
* A bad position is one in which there is no good move.
* Being left with a single coin is clearly a bad position
* and represents the simple case of the recursion.
*/
One of the principal ideas in this text is the notion of abstraction, which is the process
of separating out the general aspects of a problem so that they are no longer obscured by
the details of a specific domain. You may not be terribly interested in a program that
plays nim; after all, nim is rather boring once you figure it out. What you would probably
enjoy more is a program that is general enough to be adapted to play nim, or tic-tac-toe,
or any other two-player strategy game you choose.
The first step in creating such a generalization lies in recognizing that there are several
concepts that are common to all games. The most important such concept is state. For
any game, there is some collection of data that defines exactly what is happening at any
point in time. In the nim game, for example, the state consists of the number of coins on
the table and whose turn it is to move. For a game like chess, the state would instead
include what pieces were currently on which squares. Whatever the game, however, it
should be possible to combine all the relevant data together into a single record structure
and then refer to it using a single variable. Another common concept is that of a move.
In nim, a move consists of an integer representing the number of coins taken away. In
chess, a move might consist of a pair indicating the starting and ending coordinates of the
piece that is moving, although this approach is in fact complicated by the need to
represent various esoteric moves like castling or the promotion of a pawn. In any case, a
move can also be represented by a single structure that includes whatever information is
appropriate to that particular game. The process of abstraction consists partly of defining
these concepts as general types, with names like stateT and moveT, that transcend the
details of any specific game. The internal structure of these types will be different for
different games, but the abstract algorithm can refer to these concepts in a generic form.
Consider, for example, the following main program, which comes from the tic-tac-toe
example introduced in Figure 7-6 at the end of this chapter:
int main() {
GiveInstructions();
stateT state = NewGame();
moveT move;
while (!GameIsOver(state)) {
DisplayGame(state);
switch (WhoseTurn(state)) {
case Human:
move = GetUserMove(state);
break;
case Computer:
move = ChooseComputerMove(state);
DisplayMove(move);
break;
}
MakeMove(state, move);
}
AnnounceResult(state);
return 0;
}
At this level, the program is easy to read. It begins by giving instructions and then calls
NewGame to initialize a new game, storing the result in the variable state. It then goes
into a loop, taking turns for each side until the game is over. On the human player’s
turns, it calls a function GetUserMove to read in the appropriate move from the user. On
its own turns, the program calls ChooseComputerMove, which has the task of finding the
best move in a particular state. Once the move has been determined by one of these two
functions, the main program then calls MakeMove, which updates the state of the game to
Backtracking Algorithms – 253 –
show that the indicated move has been made and that it is now the other player’s turn. At
the end, the program displays the result of the game and exits.
It is important to notice that the main program gives no indication whatsoever about
what the actual game is. It could just as easily be nim or chess as tic-tac-toe. Each game
requires its own definitions for stateT , moveT , and the various functions like
GiveInstructions, MakeMove, and GameIsOver . Even so, the implementation of the
main program as it appears here is general enough to work for many different games.
The minimax strategy
The main program, however, is hardly the most interesting part of a game. The real
challenge consists of providing the computer with an effective strategy. In the general
program for two-player games, the heart of the computer’s strategy is the function
FindBestMove , which is called by the function ChooseComputerMove in the main
program. Given a particular state of the game, the role of FindBestMove is to return the
optimal move in that position.
From the discussion of nim earlier in this chapter, you should already have some sense
of what constitutes an optimal move. The best move in any position is simply the one
that leaves your opponent in the worst position. The worst position is likewise the one
that offers the weakest best move. This idea—finding the position that leaves your
opponent with the worst possible best move—is called the minimax strategy because the
goal is to find the move that minimizes your opponent’s maximum opportunity.
The best way to visualize the operation of the minimax strategy is to think about the
possible future moves in a game as forming a branching diagram that expands on each
turn. Because of their branching character, such diagrams are called game trees. The
current state is represented by a dot at the top of the game tree. If there are, for example,
three possible moves from this position, there will be three lines emanating down from
the current state to three new states that represent the results of these moves, as shown in
the following diagram:
For each of these new positions, your opponent will also have options. If there are again
three options from each of these positions, the next generation of the game tree looks like
this:
Which move do you choose in the initial position? Clearly, your goal is to achieve the
best outcome. Unfortunately, you only get to control half of the game. If you were able
to select your opponent’s move as well as your own, you could select the path to the state
two turns away that left you in the best position. Given the fact that your opponent is also
Backtracking Algorithms – 254 –
trying to win, the best thing you can do is choose the initial move that leaves your
opponent with as few winning chances as possible.
In order to get a sense of how you should proceed, it helps to add some quantitative
data to the analysis. Determine whether a particular move is better than some alternative
is much easier if it is possible to assign a numeric score to each possible move. The
higher the numeric score, the better the move. Thus, a move that had a score of +7, for
example, is better than a move with a rating of –4. In addition to rating each possible
move, it makes sense to assign a similar numeric rating to each position in the game.
Thus, one position might have a rating of +9 and would therefore be better than a position
with a score of only +2.
Both positions and moves are rated from the perspective of the player having the
move. Moreover, the rating system is designed to be symmetric around 0, in the sense
that a position that has a score of +9 for the player to move would have a score of –9
from the opponent’s point of view. This interpretation of rating numbers captures the
idea that a position that is good for one player is therefore a bad position for the
opponent, as you saw in the discussion of the Nim game earlier in this chapter. More
importantly, defining the rating system in this way makes it easy to express the
relationship between the scores for moves and positions. The score for any move is
simply the negative of the score for the resulting position when rated by your opponent.
Similarly, the rating of any position can be defined as the rating of its best move.
To make this discussion more concrete, let’s consider a simple example. Suppose that
you have looked two steps ahead in the game, covering one move by you and the possible
responses from your opponent. In computer science, a single move for a single player is
called a ply to avoid the ambiguity associated with the words move and turn, which
sometimes imply that both players have a chance to play. If you rate the positions at the
conclusion of the two-ply analysis, the game tree might look like this:
+7 +6 –9 –5 +9 –4 –1 +1 –2
Because the positions at the bottom of this tree are again positions in which—as at the top
of the tree—you have to move, the rating numbers in those positions are assigned from
your perspective. Given these ratings of the potential positions, what move should you
make from the original configuration? At first glance, you might be attracted by the fact
that the leftmost branch has the most positive total score or that the center one contains a
path that leads to a +9, which is an excellent outcome for you. Unfortunately, none of
these considerations matter much if your opponent is playing rationally. If you choose
the leftmost branch, your opponent will surely take the rightmost option from there,
which leaves you with a –9 position. The same thing happens if you choose the center
branch; your opponent finds the worst possible position, which has a rating of –5. The
best you can do is choose the rightmost branch, which only allows your opponent to end
up with a –2 rating. While this position is hardly ideal, it is better for you than the other
outcomes.
Backtracking Algorithms – 255 –
The situation becomes easier to follow if you add the ratings for each of your
opponent’s responses at the second level of the tree. The rating for a move—from the
perspective of the player making it—is the negative of the resulting position. Thus, the
move ratings from your opponent’s point of view look like this:
–7 +9 +5 +4 +1 +2
–6 –9 –1
In these positions, your opponent will seek to play the move with the best score. By
choosing the rightmost path, you minimize the maximum score available to your
opponent, which is the essence of the minimax strategy.
• It must be possible to limit the depth of the recursive search. For games that involve
any significant level of complexity, it is impossible to search the entire game tree in a
reasonable amount of time. If you try to apply this approach to chess, for example, a
program running on the fastest computers available would require many times the
lifetime of the universe to make the first move. As a result, a practical implementation
of the minimax algorithm must include a provision for cutting off the search at a
certain point. One possible approach is to limit the depth of the recursion to a certain
number of moves. You could, for example, allow the recursion to proceed until each
player had made three moves and then evaluate the position at that point using some
nonrecursive approach.
• It must be possible to assign ratings to moves and positions. Every position in nim is
either good or bad; there are no other options. In a more complex game, it is
necessary—particularly if you can’t perform a complete analysis—to assign ratings to
positions and moves so that the algorithm has a standard for comparing them against
other possibilities. The rating scheme used in this implementation assigns integers to
positions and moves. Those integers extend in both the positive and the negative
direction and are centered on zero, which means that a rating of –5 for one player is
equivalent to a rating of +5 from the opponent’s point of view. Zero is therefore the
neutral rating and is given the name NeutralPosition. The maximum positive rating
is the constant WinningPosition , which indicates a position in which the player
whose turn it is to move will invariably win; the corresponding extreme in the negative
direction is LosingPosition, which indicates that the player will always lose.
Taking these general considerations into account requires some changes in the design
of the mutually recursive functions that implement the minimax algorithm, which are
called FindBestMove and EvaluatePosition. Both functions take the state of the game
Backtracking Algorithms – 256 –
as an argument, but each also requires the current depth of the recursion so that the
recursive search can be restricted if necessary. Moreover, in order to avoid a
considerable amount of redundant calculation, it is extremely useful if FindBestMove can
return a rating along with the best move, so it uses a reference parameter along with the
return value to return the two pieces of information.. Given these design decisions, the
prototypes for FindBestMove and EvaluatePosition look like this:
The strategy for FindBestMove can be expressed using the following pseudocode:
The corresponding implementation, which follows this pseudocode outline, looks like
this:
minRating = WinningPosition + 1;
which initializes the value of minRating to a number large enough to guarantee that this
value will be replaced on the first cycle through the for loop, and the line
Backtracking Algorithms – 257 –
rating = -minRating;
which stores the rating of the best move in the reference parameter. The negative sign is
included because the perspective has shifted: the positions were evaluated from the point-
of-view of your opponent, whereas the ratings express the value of a move from your
own point of view. A move that leaves your opponent with a negative position is good
for you and therefore has a positive value.
The EvaluatePosition function is considerably simpler. The simple cases that allow
the recursion to terminate occur when the game is over or when the maximum allowed
recursive depth has been achieved. In these cases, the program must evaluate the current
state as it exists without recourse to further recursion. This evaluation is performed by
the function EvaluateStaticPosition, which is coded separately for each game. In the
general case, however, the rating of a position is simply the rating of the best move
available, given the current state. Thus, the following code is sufficient to the task:
int EvaluatePosition(stateT state, int depth) {
int rating;
if (GameIsOver(state) || depth >= MAX_DEPTH) {
return EvaluateStaticPosition(state);
}
FindBestMove(state, depth, rating);
return rating;
}
1 2 3
4 5 6
7 8 9
a move can be represented as a single integer, which means that the appropriate definition
for the type moveT is simply
typedef int moveT;
Backtracking Algorithms – 258 –
/*
* File: tictactoe.cpp
* -------------------
* This program plays a game of tic-tac-toe with the user. The
* code is designed to make it easy to adapt the general structure
* to other games.
*/
#include "genlib.h"
#include "simpio.h"
#include "vector.h"
#include "grid.h"
#include <iostream>
/*
* Constants: WINNING_POSITION, NEUTRAL_POSITION, LOSING_POSITION
* --------------------------------------------------------------
* These constants define a rating system for game positions. A
* rating is an integer centered at 0 as the neutral score: ratings
* greater than 0 are good for the current player, ratings less than
* 0 are good for the opponent. The constants WINNING_POSITION and
* LOSING_POSITION are opposite in value and indicate a position that
* is a forced win or loss, respectively. In a game in which the
* analysis is complete, no intermediate values ever arise. If the
* full tree is too large to analyze, the EvaluatePosition function
* returns integers that fall between the two extremes.
*/
const int WINNING_POSITION = 1000;
const int NEUTRAL_POSITION = 0;
const int LOSING_POSITION = -WINNING_POSITION;
/*
* Type: playerT
* -------------
* This type is used to distinguish the human and computer
* players and keep track of who has the current turn.
*/
enum playerT { Human, Computer };
/*
* Type: moveT
* -----------
* For any particular game, the moveT type must keep track of the
* information necessary to describe a move. For tic-tac-toe,
* a moveT is simply an integer identifying the number of one of
* the nine squares, as follows:
*
* 1 | 2 | 3
* ---+---+---
* 4 | 5 | 6
* ---+---+---
* 7 | 8 | 9
*/
typedef int moveT;
Backtracking Algorithms – 259 –
/*
* Type: stateT
* ------------
* For any game, the stateT structure records the current state of
* the game. As in Chapter 4, the tic-tac-toe board is represented
* using a Grid<char>; the elements must be either 'X', 'O', or ' '.
* In addition to the board array, the code stores a playerT value
* to indicate whose turn it is. In this game, the stateT structure
* also contains the total number of moves so that functions can
* find this value without counting the number of occupied squares.
*/
struct stateT {
Grid<char> board;
playerT whoseTurn;
int turnsTaken;
};
/*
* Constant: MAX_DEPTH
* -------------------
* This constant indicates the maximum depth to which the recursive
* search for the best move is allowed to proceed.
*/
const int MAX_DEPTH = 10000;
/*
* Constant: FIRST_PLAYER
* ----------------------
* This constant indicates which player goes first.
*/
const playerT FIRST_PLAYER = Computer;
/*
* Main program
* ------------
* The main program, along with the functions FindBestMove and
* EvaluatePosition, are general in their design and can be
* used with most two-player games. The specific details of
* tic-tac-toe do not appear in these functions and are instead
* encapsulated in the stateT and moveT data structures and a
* a variety of subsidiary functions.
*/
int main() {
GiveInstructions();
stateT state = NewGame();
moveT move;
while (!GameIsOver(state)) {
DisplayGame(state);
switch (WhoseTurn(state)) {
case Human:
move = GetUserMove(state);
break;
case Computer:
move = ChooseComputerMove(state);
DisplayMove(move);
break;
}
MakeMove(state, move);
}
AnnounceResult(state);
return 0;
}
/*
* Function: GiveInstructions
* Usage: GiveInstructions();
* --------------------------
* This function gives the player instructions about how to
* play the game.
*/
void GiveInstructions() {
cout << "Welcome to tic-tac-toe. The object of the game" << endl;
cout << "is to line up three symbols in a row," << endl;
cout << "vertically, horizontally, or diagonally." << endl;
cout << "You'll be " << PlayerMark(Human) << " and I'll be "
<< PlayerMark(Computer) << "." << endl;
}
Backtracking Algorithms – 261 –
/*
* Function: NewGame
* Usage: state = NewGame();
* -------------------------
* This function starts a new game and returns a stateT that
* has been initialized to the defined starting configuration.
*/
stateT NewGame() {
stateT state;
state.board.resize(3, 3);
for (int i = 0; i < 3; i++) {
for (int j = 0; j < 3; j++) {
state.board[i][j] = ' ';
}
}
state.whoseTurn = FIRST_PLAYER;
state.turnsTaken = 0;
return state;
}
/*
* Function: DisplayGame
* Usage: DisplayGame(state);
* --------------------------
* This function displays the current state of the game.
*/
/*
* Function: DisplayMove
* Usage: DisplayMove(move);
* -------------------------
* This function displays the computer's move.
*/
/*
* Function: FindBestMove
* Usage: move = FindBestMove(state, depth, pRating);
* --------------------------------------------------
* This function finds the best move for the current player, given
* the specified state of the game. The depth parameter and the
* constant MAX_DEPTH are used to limit the depth of the search
* for games that are too difficult to analyze in full detail.
* The function returns the best move by storing an integer in
* the variable to which pRating points.
*/
/*
* Function: EvaluatePosition
* Usage: rating = EvaluatePosition(state, depth);
* -----------------------------------------------
* This function evaluates a position by finding the rating of
* the best move in that position. The depth parameter and the
* constant MAX_DEPTH are used to limit the depth of the search.
*/
/*
* Function: NewGame
* Usage: state = NewGame();
* -------------------------
* This function starts a new game and returns a stateT that
* has been initialized to the defined starting configuration.
*/
stateT NewGame() {
stateT state;
/*
* Function: DisplayGame
* Usage: DisplayGame(state);
* --------------------------
* This function displays the current state of the game.
*/
/*
* Function: DisplayMove
* Usage: DisplayMove(move);
* -------------------------
* This function displays the computer's move.
*/
/*
* Function: PlayerMark
* Usage: mark = PlayerMark(player);
* ---------------------------------
* This function returns the mark used on the board to indicate
* the specified player. By convention, the first player is
* always X, so the mark used for each player depends on who
* goes first.
*/
/*
* Function: GetUserMove
* Usage: move = GetUserMove(state);
* ---------------------------------
* This function allows the user to enter a move and returns the
* number of the chosen square. If the user specifies an illegal
* move, this function gives the user the opportunity to enter
* a legal one.
*/
/*
* Function: ChooseComputerMove
* Usage: move = ChooseComputerMove(state);
* ----------------------------------------
* This function chooses the computer's move and is primarily
* a wrapper for FindBestMove. This function also makes it
* possible to display any game-specific messages that need
* to appear at the beginning of the computer's turn. The
* rating value returned by FindBestMove is simply discarded.
*/
/*
* Function: GenerateMoveList
* Usage: GenerateMoveList(state, moveList);
* -----------------------------------------
* This function generates a list of the legal moves available in
* the specified state. The list of moves is returned in the
* vector moveList, which must be allocated by the client.
*/
/*
* Function: MoveIsLegal
* Usage: if (MoveIsLegal(move, state)) . . .
* ------------------------------------------
* This function returns true if the specified move is legal.
*/
/*
* Function: MakeMove
* Usage: MakeMove(state, move);
* -----------------------------
* This function changes the state by making the indicated move.
*/
/*
* Function: RetractMove
* Usage: RetractMove(state, move);
* --------------------------------
* This function changes the state by "unmaking" the indicated move.
*/
/*
* Function: GameIsOver
* Usage: if (GameIsOver(state)) . . .
* -----------------------------------
* This function returns true if the game is complete.
*/
/*
* Function: AnnounceResult
* Usage: AnnounceResult(state);
* -----------------------------
* This function announces the result of the game.
*/
/*
* Function: WhoseTurn
* Usage: player = WhoseTurn(state);
* ---------------------------------
* This function returns whose turn it is, given the current
* state of the game. The reason for making this a separate
* function is to ensure that the common parts of the code do
* not need to refer to the internal components of the state.
*/
/*
* Function: Opponent
* Usage: opp = Opponent(player);
* ------------------------------
* This function returns the playerT value corresponding to the
* opponent of the specified player.
*/
/*
* Function: EvaluateStaticPosition
* Usage: rating = EvaluateStaticPosition(state);
* ----------------------------------------------
* This function gives the rating of a position without looking
* ahead any further in the game tree. Although this function
* duplicates much of the computation of GameIsOver and therefore
* introduces some runtime inefficiency, it makes the algorithm
* somewhat easier to follow.
*/
/*
* Function: CheckForWin
* Usage: if (CheckForWin(state, player)) . . .
* --------------------------------------------
* This function returns true if the specified player has won
* the game. The check on turnsTaken increases efficiency,
* because neither player can win the game until the fifth move.
*/
/*
* Checks to see whether the specified player identified by mark
* ('X' or 'O') has won the game. To reduce the number of special
* cases, this implementation uses the helper function CheckLine
* so that the row, column, and diagonal checks are the same.
*/
/*
* Checks a line extending across the board in some direction.
* The starting coordinates are given by the row and col
* parameters. The direction of motion is specified by dRow
* and dCol, which show how to adjust the row and col values
* on each cycle. For rows, dRow is always 0; for columns,
* dCol is 0. For diagonals, the dRow and dCol values will
* be +1 or -1 depending on the direction of the diagonal.
*/
bool CheckLine(Grid<char> & board, char mark, int row, int col,
int dRow, int dCol) {
for (int i = 0; i < 3; i++) {
if (board[row][col] != mark) return false;
row += dRow;
col += dCol;
}
return true;
}
Backtracking Algorithms – 269 –
The state of the tic-tac-toe game is determined by the symbols on the nine squares of
the board and whose turn it is to move. Thus, you can represent the essential components
of the state as follows:
struct stateT {
char board[(3 * 3) + 1];
playerT whoseTurn;
};
Summary
In this chapter, you have learned to solve problems that require making a sequence of
choices as you search for a goal, as illustrated by finding a path through a maze or a
winning strategy in a two-player game. The basic strategy is to write programs that can
backtrack to previous decision points if those choices lead to dead ends. By exploiting
the power of recursion, however, you can avoid coding the details of the backtracking
process explicitly and develop general solution strategies that apply to a wide variety of
problem domains.
Important points in this chapter include:
• You can solve most problems that require backtracking by adopting the following
recursive approach:
If you are already at a solution, report success.
for (every possible choice in the current position ) {
Make that choice and take one step along the path.
Use recursion to solve the problem from the new position.
If the recursive call succeeds, report the success to the next higher level.
Back out of the current choice to restore the state at the beginning of the loop.
}
Report failure.
• The complete history of recursive calls in a backtracking problem—even for relatively
simple applications—is usually too complex to understand in detail. For problems that
involve any significant amount of backtracking, it is essential to accept the recursive
leap of faith.
• You can often find a winning strategy for two-player games by adopting a recursive-
backtracking approach. Because the goal in such games involves minimizing the
winning chances for your opponent, the conventional strategic approach is called the
minimax algorithm.
• It is possible to code the minimax algorithm in a general way that keeps the details of
any specific game separate from the implementation of the minimax strategy itself.
This approach makes it easier to adapt an existing program to new games.
Backtracking Algorithms – 270 –
Review questions
1. What is the principal characteristic of a backtracking algorithm?
2. Using your own words, state the right-hand rule for escaping from a maze. Would a
left-hand rule work equally well?
3. What is the insight that makes it possible to solve a maze by recursive backtracking?
4. What are the simple cases that apply in the recursive implementation of SolveMaze?
5. Why is important to mark squares as you proceed through the maze? What would
happen in the SolveMaze function if you never marked any squares?
6. What is the purpose of the UnmarkSquare call at the end of the for loop in the
SolveMaze implementation? Is this statement essential to the algorithm?
–4 –9 + 4 –3 –2 –4 –3 + 2 –5 +1 0 –5
If you adopt the minimax strategy, what is the best move to make in this position?
What is the rating of that move from your perspective?
13. Why is it useful to develop an abstract implementation of the minimax algorithm?
14. What two data structures are used to make the minimax implementation independent
of the specific characteristics of a particular game?
15. What is the role of each of the three arguments to the FindBestMove function?
16. Explain the role of the EvaluateStaticPosition function in the minimax
implementation.
Backtracking Algorithms – 271 –
Programming exercises
1. The SolveMaze function shown in Figure 7-3 implements a recursive algorithm for
solving a maze but is not complete as it stands. The solution depends on several
functions exported by the mazelib.h interface, which is specified in Figure 7-2 but
never actually implemented.
Write a file mazelib.cpp that implements this interface. Your implementation
should store the data representing the maze as part of the private state of the module.
This design requires you to declare static global variables within the implementation
that are appropriate to the data you need to implement the operations. If you design
the data structure well, most of the individual function definitions in the interface are
quite simple. The hard parts of this exercise are designing an appropriate internal
representation and implementing the function ReadMapFile, which initializes the
internal structures from a data file formatted as described in the interface
documentation.
2. In many mazes, there are multiple paths. For example, the diagrams below show
three solutions for the same maze:
Θ × × × Θ Θ
× × × × ×
× × × × × × × ×
× × × × × × ×
× × × × ×
× × × × × × × × × ×
length = 13 length = 15 length = 13
None of these solutions, however, is optimal. The shortest path through the maze
has a path length of 11:
Θ
×
× ×
× ×
×
× × × ×
Write a function
int ShortestPathLength(pointT pt);
that returns the length of the shortest path in the maze from the specified position to
any exit. If there is no solution to the maze, ShortestPathLength should return the
constant NO_SOLUTION, which is defined to have a value larger than the maximum
permissible path length, as follows:
const int NO_SOLUTION = 10000;
Backtracking Algorithms – 272 –
Run your program again, this time without the call to UnmarkSquare. What happens
to the number of recursive calls?
4. As the result of the preceding exercise makes clear, the idea of keeping track of the
path through a maze by using the MarkSquare facility in mazelib.h has a substantial
cost. A more practical approach is to change the definition of the recursive function
so that it keeps track of the current path as it goes. Following the logic of
SolveMaze, write a function
bool FindPath(pointT pt, Vector<pointT> path);
that takes, in addition to the coordinates of the starting position, a vector of pointT
values called path. Like SolveMaze, FindPath returns a Boolean value indicating
whether the maze is solvable. In addition, FindPath initializes the elements of the
path vector to a sequence of coordinates beginning with the starting position and
ending with the coordinates of the first square that lies outside the maze. For
example, if you use FindPath with the following main program
int main() {
ReadMazeMap(MazeFile);
Vector<pointT> path;
if (FindPath(GetStartPosition(), path)) {
cout << "The following path is a solution:" << endl;
for (int i = 0; i < path.size(); i++) {
cout << "(" << path[i].x << ", "
<< path[i].y << ")" << endl;
}
} else {
cout << "No solution exists." << endl;
}
return 0;
}
it will display the coordinates of the points in the solution path on the screen.
Backtracking Algorithms – 273 –
For this exercise, it is sufficient for FindPath to find any solution path. It need
not find the shortest one.
5. If you have access to the graphics library described in Chapter 6, extend the
maze.cpp program so that, in addition to keeping track of the internal data structures
for the maze, it also displays a diagram of the maze on the screen and shows the final
solution path.
6. Most drawing programs for personal computers make it possible to fill an enclosed
region on the screen with a solid color. Typically, you invoke this operation by
selecting a paint-bucket tool and then clicking the mouse, with the cursor somewhere
in your drawing. When yo