C++ 1
C++ 1
Allen B. Downey
November 2012
2
3 Function 21
3.1 Floating-point . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 21
3.2 Converting from double to int . . . . . . . . . . . . . . . . . . . 22
3.3 Math functions . . . . . . . . . . . . . . . . . . . . . . . . . . . . 23
3.4 Composition . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 24
3.5 Adding new functions . . . . . . . . . . . . . . . . . . . . . . . . 24
3.6 Definitions and uses . . . . . . . . . . . . . . . . . . . . . . . . . 26
3.7 Programs with multiple functions . . . . . . . . . . . . . . . . . . 27
3.8 Parameters and arguments . . . . . . . . . . . . . . . . . . . . . 28
i
ii CONTENTS
5 Fruitful functions 41
5.1 Return values . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 41
5.2 Program development . . . . . . . . . . . . . . . . . . . . . . . . 43
5.3 Composition . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 45
5.4 Overloading . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 46
5.5 Boolean values . . . . . . . . . . . . . . . . . . . . . . . . . . . . 47
5.6 Boolean variables . . . . . . . . . . . . . . . . . . . . . . . . . . . 47
5.7 Logical operators . . . . . . . . . . . . . . . . . . . . . . . . . . . 48
5.8 Bool functions . . . . . . . . . . . . . . . . . . . . . . . . . . . . 48
5.9 Returning from main . . . . . . . . . . . . . . . . . . . . . . . . . 49
5.10 More recursion . . . . . . . . . . . . . . . . . . . . . . . . . . . . 50
5.11 Leap of faith . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 52
5.12 One more example . . . . . . . . . . . . . . . . . . . . . . . . . . 53
5.13 Glossary . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 53
6 Iteration 55
6.1 Multiple assignment . . . . . . . . . . . . . . . . . . . . . . . . . 55
6.2 Iteration . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 56
6.3 The while statement . . . . . . . . . . . . . . . . . . . . . . . . . 56
6.4 Tables . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 58
6.5 Two-dimensional tables . . . . . . . . . . . . . . . . . . . . . . . 60
6.6 Encapsulation and generalization . . . . . . . . . . . . . . . . . . 60
6.7 Functions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 61
6.8 More encapsulation . . . . . . . . . . . . . . . . . . . . . . . . . . 62
6.9 Local variables . . . . . . . . . . . . . . . . . . . . . . . . . . . . 62
6.10 More generalization . . . . . . . . . . . . . . . . . . . . . . . . . 63
6.11 Glossary . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 65
CONTENTS iii
8 Structures 77
8.1 Compound values . . . . . . . . . . . . . . . . . . . . . . . . . . . 77
8.2 Point objects . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 77
8.3 Accessing instance variables . . . . . . . . . . . . . . . . . . . . . 78
8.4 Operations on structures . . . . . . . . . . . . . . . . . . . . . . . 79
8.5 Structures as parameters . . . . . . . . . . . . . . . . . . . . . . . 80
8.6 Call by value . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 80
8.7 Call by reference . . . . . . . . . . . . . . . . . . . . . . . . . . . 81
8.8 Rectangles . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 82
8.9 Structures as return types . . . . . . . . . . . . . . . . . . . . . . 84
8.10 Passing other types by reference . . . . . . . . . . . . . . . . . . 84
8.11 Getting user input . . . . . . . . . . . . . . . . . . . . . . . . . . 85
8.12 Glossary . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 87
9 More structures 89
9.1 Time . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 89
9.2 printTime . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 90
9.3 Functions for objects . . . . . . . . . . . . . . . . . . . . . . . . . 90
9.4 Pure functions . . . . . . . . . . . . . . . . . . . . . . . . . . . . 91
9.5 const parameters . . . . . . . . . . . . . . . . . . . . . . . . . . . 92
9.6 Modifiers . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 93
9.7 Fill-in functions . . . . . . . . . . . . . . . . . . . . . . . . . . . . 94
9.8 Which is best? . . . . . . . . . . . . . . . . . . . . . . . . . . . . 95
9.9 Incremental development versus planning . . . . . . . . . . . . . 95
9.10 Generalization . . . . . . . . . . . . . . . . . . . . . . . . . . . . 96
9.11 Algorithms . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 96
9.12 Glossary . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 97
iv CONTENTS
10 Vectors 99
10.1 Accessing elements . . . . . . . . . . . . . . . . . . . . . . . . . . 100
10.2 Copying vectors . . . . . . . . . . . . . . . . . . . . . . . . . . . . 101
10.3 for loops . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 101
10.4 Vector size . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 102
10.5 Vector functions . . . . . . . . . . . . . . . . . . . . . . . . . . . 103
10.6 Random numbers . . . . . . . . . . . . . . . . . . . . . . . . . . . 103
10.7 Statistics . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 105
10.8 Vector of random numbers . . . . . . . . . . . . . . . . . . . . . . 105
10.9 Counting . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 106
10.10Checking the other values . . . . . . . . . . . . . . . . . . . . . . 107
10.11A histogram . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 108
10.12A single-pass solution . . . . . . . . . . . . . . . . . . . . . . . . 108
10.13Random seeds . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 109
10.14Glossary . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 109
The goal of this book is to teach you to think like a computer scientist. I like
the way computer scientists think because they combine some of the best fea-
tures of Mathematics, Engineering, and Natural Science. Like mathematicians,
computer scientists use formal languages to denote ideas (specifically computa-
tions). Like engineers, they design things, assembling components into systems
and evaluating tradeoffs among alternatives. Like scientists, they observe the
behavior of complex systems, form hypotheses, and test predictions.
The single most important skill for a computer scientist is problem-solving.
By that I mean the ability to formulate problems, think creatively about solu-
tions, and express a solution clearly and accurately. As it turns out, the process
of learning to program is an excellent opportunity to practice problem-solving
skills. That’s why this chapter is called “The way of the program.”
Of course, the other goal of this book is to prepare you for the Computer
Science AP Exam. We may not take the most direct approach to that goal,
though. For example, there are not many exercises in this book that are similar
to the AP questions. On the other hand, if you understand the concepts in this
book, along with the details of programming in C++, you will have all the tools
you need to do well on the exam.
1
2 CHAPTER 1. THE WAY OF THE PROGRAM
Due to these advantages, almost all programs are written in high-level lan-
guages. Low-level languages are only used for a few special applications.
source
code interpreter
source object
code compiler code executor
The compiler ... and generates You execute the ... and the result
reads the object code. program (one way appears on
source code... or another)... the screen.
The next step is to run the program, which requires some kind of executor.
The role of the executor is to load the program (copy it from disk into memory)
and make the computer start executing the program.
Although this process may seem complicated, the good news is that in
most programming environments (sometimes called development environments),
these steps are automated for you. Usually you will only have to write a pro-
gram and type a single command to compile and run it. On the other hand, it
is useful to know what the steps are that are happening in the background, so
that if something goes wrong you can figure out what it is.
input: Get data from the keyboard, or a file, or some other device.
output: Display data on the screen or send data to a file or other device.
math: Perform basic mathematical operations like addition and multiplication.
testing: Check for certain conditions and execute the appropriate sequence of
statements.
repetition: Perform some action repeatedly, usually with some variation.
Believe it or not, that’s pretty much all there is to it. Every program you’ve
ever used, no matter how complicated, is made up of functions that look more or
less like these. Thus, one way to describe programming is the process of breaking
a large, complex task up into smaller and smaller subtasks until eventually the
subtasks are simple enough to be performed with one of these simple functions.
4 CHAPTER 1. THE WAY OF THE PROGRAM
Syntax rules come in two flavors, pertaining to tokens and structure. Tokens
are the basic elements of the language, like words and numbers and chemical
elements. One of the problems with 3=+6$ is that $ is not a legal token in
mathematics (at least as far as I know). Similarly, 2 Zz is not legal because
there is no element with the abbreviation Zz.
The second type of syntax error pertains to the structure of a statement;
that is, the way the tokens are arranged. The statement 3=+6$ is structurally
illegal, because you can’t have a plus sign immediately after an equals sign.
Similarly, molecular formulas have to have subscripts after the element name,
not before.
When you read a sentence in English or a statement in a formal language,
you have to figure out what the structure of the sentence is (although in a
natural language you do this unconsciously). This process is called parsing.
For example, when you hear the sentence, “The other shoe fell,” you under-
stand that “the other shoe” is the subject and “fell” is the verb. Once you have
parsed a sentence, you can figure out what it means, that is, the semantics of
the sentence. Assuming that you know what a shoe is, and what it means to
fall, you will understand the general implication of this sentence.
Although formal and natural languages have many features in common—
tokens, structure, syntax and semantics—there are many differences.
ambiguity: Natural languages are full of ambiguity, which people deal with
by using contextual clues and other information. Formal languages are
designed to be nearly or completely unambiguous, which means that any
statement has exactly one meaning, regardless of context.
redundancy: In order to make up for ambiguity and reduce misunderstand-
ings, natural languages employ lots of redundancy. As a result, they are
often verbose. Formal languages are less redundant and more concise.
literalness: Natural languages are full of idiom and metaphor. If I say, “The
other shoe fell,” there is probably no shoe and nothing falling. Formal
languages mean exactly what they say.
People who grow up speaking a natural language (everyone) often have a
hard time adjusting to formal languages. In some ways the difference between
formal and natural language is like the difference between poetry and prose, but
more so:
Poetry: Words are used for their sounds as well as for their meaning, and the
whole poem together creates an effect or emotional response. Ambiguity
is not only common but often deliberate.
Prose: The literal meaning of words is more important and the structure con-
tributes more meaning. Prose is more amenable to analysis than poetry,
but still often ambiguous.
Programs: The meaning of a computer program is unambiguous and literal,
and can be understood entirely by analysis of the tokens and structure.