Search for notes by fellow students, in your own course and all over the country.

Browse our notes for titles which look like what you need, you can preview any of the notes via a sample of the contents. After you're happy these are the notes you're after simply pop them into your shopping cart.

My Basket

You have nothing in your shopping cart yet.

Title: Beginner's Guide to C++
Description: 96 pages to guide you to learn C++ successfully

Document Preview

Extracts from the notes are below, to see the PDF you'll receive please use the links above


C++ Without Fear
Second Edition

This page intentionally left blank

C++ Without Fear
Second Edition

A Beginner’s Guide That
Makes You Feel Smart

Brian Overland

Upper Saddle River, NJ • Boston • Indianapolis • San Francisco
New York • Toronto • Montreal • London • Munich • Paris • Madrid
Capetown • Sydney • Tokyo • Singapore • Mexico City

Many of the designations used by manufacturers and sellers to distinguish their products are
claimed as trademarks
...

The author and publisher have taken care in the preparation of this book, but make no expressed
or implied warranty of any kind and assume no responsibility for errors or omissions
...

The publisher offers excellent discounts on this book when ordered in quantity for bulk purchases
or special sales, which may include electronic versions and/or custom covers and content particular to your business, training goals, marketing focus, and branding interests
...
S
...
com
For sales outside the United States please contact:
International Sales
international@pearson
...
com/ph
Library of Congress Cataloging-in-Publication Data
Overland, Brian R
...
—2nd ed
...
cm
...

ISBN 978-0-13-267326-6 (pbk
...
paper)
1
...
Title
...
73
...
13'3—dc22
2011004218
Copyright © 2011 Pearson Education, Inc
...
Printed in the United States of America
...
For information regarding permissions, write to:
Pearson Education, Inc
...

Third printing, August 2012

For Colin

This page intentionally left blank

Contents
Preface
About This Book: How It’s Different
Onward to the Second Edition
“Where Do I Begin?”
Icons, Icons, Who’s Got the Icons?
What Is Not Covered?
Getting Started with C++: A Free Compiler
A Final Note: Have Fun!

xxiii
xxiv
xxv
xxv
xxvi
xxvii
xxvii

Acknowledgments
About the Author
Chapter 1

xxiii

xxix
xxxi

Your First C++ Programs

1

Thinking Like a Programmer
Computers Do Only What You Tell Them
Determine What the Program Will Do
Write the Equivalent C++ Statements
Interlude How “Smart” Are Computers, Really?
Some Nerdy Definitions—A Review
What’s Different About C++?
Building a C++ Program
Enter the Program Statements
Build the Program (Compile and Link)

1
1
1
2
4
4
7
8
8
8

vii

viii

Contents

Test the Program
Revise as Needed
Installing Your Own C++ Compiler
Example 1
...
Print a Message
If You’re Using the Dev-C++ Environment
If You’re Using Microsoft Visual Studio
How It Works
Exercises
Interlude What about the #include and using?
Advancing to the Next Print Line
Example 1
...
Print Multiple Lines
How It Works
Exercises
Interlude What Is a String?
Storing Data: C++ Variables
Introduction to Data Types
Interlude Why Double Precision, Not Single?
Example 1
...
Convert Temperatures
How It Works
Optimizing the Program
Exercises
A Word about Variable Names and Keywords
Exercise
Chapter 1 Summary
Chapter 2

9
9
10
11
12
12
13
15
15
16
16
17
18
18
19
20
22
22
24
26
28
28
29
30

Decisions, Decisions

33

But First, a Few Words about Data Types
Decision Making in Programs
Interlude What about Artificial Intelligence (AI)?
if and if-else
Interlude Why Two Operators (= and ==)?
Example 2
...
Odd or Even?
How It Works
Optimizing the Code
Exercise
Introducing Loops
Interlude Infinite Loopiness
Example 2
...
Print 1 to N

33
34
35
35
38
39
40
42
42
43
46
46

Contents

ix

How It Works
Optimizing the Program
Exercises
True and False in C++
Interlude The bool Data Type
The Increment Operator (++)
Statements vs
...
3
...
4
...
5
...
1
...
2
...
1
...
2
...
3
...
4
...
5
...
6
...


117

A First Look at C++ Arrays
Initializing Arrays

117
119

Contents

xi

Zero-Based Indexing
Interlude Why Use Zero-Based Indexes?
Example 5
...
Print Out Elements
How It Works
Exercises
Example 5
...
How Random Is Random?
How It Works
Exercises
Strings and Arrays of Strings
Example 5
...
Card Dealer #1
How It Works
Exercise
Example 5
...
Card Dealer #2
How It Works
Exercise
Example 5
...
Card Dealer #3
How It Works
Optimizing the Program
Exercise
A Word to the Wise
2-D Arrays: Into the Matrix
Chapter 5 Summary
Chapter 6

119
120
121
121
122
123
125
127
128
129
131
132
132
134
135
136
138
140
141
141
142
143

Pointers: Getting a Handle on Data

145

What the Heck Is a Pointer, Anyway?
The Concept of Pointer
Interlude What Do Addresses Look Like?
Declaring and Using Pointers
Example 6
...
Print Out Addresses
Example 6
...
The double_it Function
How It Works
Exercises
Swap: Another Function Using Pointers
Example 6
...
Array Sorter
How It Works
Exercises
Pointer Arithmetic

145
146
147
148
151
152
153
154
155
156
160
161
161

xii

Contents

Pointers and Array Processing
Example 6
...
Zero Out an Array
How It Works
Writing More Compact Code
Exercises
Chapter 6 Summary
Chapter 7

163
165
166
166
167
168

Strings: Analyzing the Text

169

Text Storage on the Computer
Interlude How Does the Computer Translate Programs?
It Don’t Mean a Thing If It Ain’t Got That String
String-Manipulation Functions
Example 7
...
Building Strings
How It Works
Exercises
Interlude What about Escape Sequences?
Reading String Input
Example 7
...
Get a Number
How It Works
Exercise
Example 7
...
Convert to Uppercase
How It Works
Exercises
Individual Characters vs
...
4
...
5
...
1
...
2
...
“Binary” Files
Interlude Are “Binary Files” Really More Binary?
Introducing Binary Operations
Example 8
...
Random-Access Write
How It Works
Exercises
Example 8
...
Random-Access Read
How It Works
Exercises
Chapter 8 Summary

Chapter 8

197
199
200
201
203
203
204
205
206
208
208
211
213
214
214
216
217
217

Some Advanced Programming Techniques

221

Command-Line Arguments
Example 9
...
Display File from Command Line
How It Works
Improving the Program
Interlude The Virtue of Predefined Constants
Exercises
Function Overloading
Interlude Overloading and Object Orientation
Example 9
...
Printing Different Types of Arrays
How It Works
Exercise
The do-while Loop
The switch-case Statement
Multiple Modules
Exception Handling: I Take Exception to That!
Say Hello to Exceptions

221
223
224
225
226
226
227
228
228
230
230
230
232
234
237
237

xiv

Contents

Handling Exceptions: A First Attempt
Introducing try-catch Exception Handling
Chapter 9 Summary

Chapter 11

New Features of C++0x

243

Overview of C++0x Features
The long long Type (not long long long)
Interlude Why a “Natural” Integer?
Working with 64-Bit Literals (Constants)
Accepting long long Input
Formatting long long Numbers
Example 10
...
Fibonacci: A 64-Bit Example
How It Works
Exercises
Localizing Numbers
Interlude Who Was Fibonacci?
Range-Based “for” (For Each)
Example 10
...
Setting an Array with Range-Based “for”
How It Works
Exercises
The auto and decltype Keywords
The nullptr Keyword
Strongly Typed Enumerations
enum Classes in C++0x
Extended enum Syntax: Controlling Storage
Example 10
...
Rock, Paper, Scissors Game
How It Works
A More Interesting Game
Exercises
Raw String Literals
Chapter 10 Summary

Chapter 10

238
238
240

243
244
246
246
247
248
250
253
254
254
255
256
258
260
260
261
262
263
265
266
267
269
271
272
273
273

Introducing Classes: The Fraction Class

277

Object Orientation: Quasi-Intelligent Data Types
Interlude OOP…Is It Worth It?
Point: A Simple Class
Interlude Interlude for C Programmers: Structures and Classes

277
278
279
281

Contents

xv

Private: Members Only (Protecting the Data)
Exmple 11
...
Testing the Point Class
How It Works
Exercises
Introducing the Fraction Class
Inline Functions
Find the Greatest Common Factor
Find the Lowest Common Denominator
Example 11
...
Fraction Support Functions
How It Works
Exercises
Example 11
...
Testing the Fraction Class
How It Works
Interlude A New Kind of #include?
Exercise
Example 11
...
Fraction Arithmetic: add and mult
How It Works
Exercises
Chapter 11 Summary
Chapter 12

281
284
286
286
286
289
291
292
293
294
296
296
299
299
300
300
304
305
305

Constructors: If You Build It…

307

Introducing Constructors
Multiple Constructors (Overloading)
C++0x Only: Initializing Members within a Class
The Default Constructor—and a Warning
Interlude Is C++ Out to Trick You with the Default Constructor?
C++0x Only: Delegating Constructors
C++0x Only: Consistent Initialization
Example 12
...
Point Class Constructors
How It Works
Exercises
Example 12
...
Fraction Class Constructors
How It Works
Exercises
Reference Variables and Arguments (&)
The Copy Constructor
Interlude The Copy Constructor and References

307
309
309
310
312
313
314
315
316
317
317
320
320
321
323
325

xvi

Contents

Example 12
...
Fraction Class Copy Constructor
How It Works
Exercises
A Constructor from String to Fract
Chapter 12 Summary

Chapter 14

Operator Functions: Doing It with Class

333

Introducing Class Operator Functions
Operator Functions as Global Functions
Improve Efficiency with References
Example 13
...
Point Class Operators
How It Works
Exercises
Example 13
...
Fraction Class Operators
How It Works
Optimizing the Code
Exercises
Working with Other Types
The Class Assignment Function (=)
The Test-for-Equality Function (==)
A Class “Print” Function
Example 13
...
The Completed Fraction Class
How It Works
Exercises
C++0x Only: User-Defined Literals
Defining a Raw-String Literal
Defining a Cooked Literal
Chapter 13 Summary

Chapter 13

325
328
329
329
331

333
336
338
340
342
343
343
346
347
348
348
349
350
351
352
355
356
357
358
359
360

Dynamic Memory and the String Class

363

Dynamic Memory: The “new” Keyword
Objects and “new”
Allocating Multiple Data
Interlude Dealing with Problems in Memory Allocation
Example 14
...
Dynamic Memory in Action

363
365
366
368
368

Contents

xvii

How It Works
Exercise
Introducing Class Destructors
Example 14
...
A Simple String Class
How It Works
Exercises
“Deep” Copying and the Copy Constructor
The “this” Keyword
Revisiting the Assignment Operator
Writing a Concatenation Function
Example 14
...
The Complete String Class
How It Works
Exercises
Chapter 14 Summary

Chapter 16

Two Complete OOP Examples

389

Introducing Linked Lists
Node Design
Implementing a Simple Linked List
An Alphabetical List
Example 15
...
Names in Alpha Order
How It Works
Dealing with Memory Leaks
C++ Only: Using Smart Pointers to Clean Up
Interlude Recursion vs
...
2
...
Iterators
Example 16
...
STL Ordered List
How It Works
A Continually Sorted List
Exercises
Designing an RPN Calculator
Interlude A Brief History of Polish Notation
Using a Stack for RPN
Introducing the Generalized STL Stack Class
Example 16
...
Reverse Polish Calculator
How It Works
Exercises
Correct Interpretation of Angle Brackets
Chapter 16 Summary

Chapter 18

Inheritance: What a Legacy

435

How to Subclass
Interlude Why “public” Base Classes?
Example 17
...
The FloatFraction Class
How It Works
Exercises
Problems with the FloatFraction Class
C++ Only: Inheriting Base-Class Constructors
Example 17
...
The Completed FloatFraction Class
How It Works
Exercises
Protected Members
Object Containment
Safe Inheritance Through Class Hierarchies
Chapter 17 Summary

Chapter 17

415
416
418
418
419
420
421
422
422
424
424
427
428
429
431
432
432

435
437
438
439
440
440
441
442
444
445
445
447
448
451

Polymorphism: Object Independence

453

A Different Approach to the FloatFraction Class
Virtual Functions to the Rescue!

453
454

Contents

Interlude

xix

What Is the Virtual Penalty?
Example 18
...
The Revised FloatFraction Class
How It Works
Exercise
C++ Only: Requiring Explicit Overrides
“Pure Virtual” and Other Abstract Matters
Abstract Classes and Interfaces
Object Orientation and I/O
cout Is Endlessly Extensible
But cout Is Not Polymorphic
Example 18
...
True Polymorphism: The Printable Class
How It Works
Exercise
A Final Word (or Two)
A Final, Final Word
Chapter 18 Summary

Appendix B

Operators

475

The Scope (::) Operator
The sizeof Operator
Old and New Style Type Casts
Integer vs
...
errors that you are sure to
make in learning C
...
” Instead, I had to
sweat and groan through every error a person could make
...
Each of those is rare enough
...

It’s hard to find such a person
...

Later, at Microsoft, I started in tech support and testing and worked my way
into management
...
I was sometimes the second or third person in the world to see a new feature of a programming language, and my job was to turn a cryptic spec into
readable prose for the rest of the universe to understand
...


About This Book: How It’s Different
What’s different about this book is that I’m an advocate for you, the reader
...
I’m aware of all the ways you are “supposed” to program and why they are supposed to be better (and I do discuss
those issues), but I’m mostly concerned about telling you what works
...
For those of you
more knowledgeable, you’ll want to breeze through the first few chapters
...
But although C
and C++ are great languages, there are some features that beginners (and even
relatively advanced programmers) never find uses for, at least not for the first
few years
...
At the same time, I’m also eager to tell you
about the elegant features of C++ that can save you time and energy
...
It’s also a book about having fun! The
great majority of examples in this book either are useful and practical or—by
using puzzles and games—are intrinsically entertaining
...
At the same time, there are some terms—object
orientation and polymorphism—that you will want to know, and I provide concrete, practical contexts for understanding and using them
...
I believe that’s a testament to the variety of learning paths it supplied: complete examples, exercises,
and generous use of conceptual art
...
Compiler vendors
either have brought their versions of C++ up to this standard or are in the
process of doing so
...

◗ Examples galore, featuring puzzles and games: By the end of Chapter 2, you’ll
learn how to enter a program, barely a page long, that not only is a complete
game but even has an optimal strategy for the computer
...
This edition features puzzles and
games, much more so than the first edition
...
This edition
has substantially more of these
...
by
taking apart an example that works, analyzing it, and figuring out how to modify
it to make it do your own thing
...
The syntax diagrams in this
book, accompanied by loads of examples, clarify exactly how the language
works, statement by statement and keyword by keyword
...

◗ Expanded reference: The appendixes in the back are intended as a mini desk reference to use in writing C++ programs
...

◗ Essays, or “interludes” for the philosophically inclined: Throughout the book, I
detour into areas related to C++ but that impact the larger world, such as computer science, history of programming, mathematics, philosophy, and artificial
intelligence
...
You can read them at your leisure
...
If
you can turn on a computer and use a menu system, keyboard, and mouse, you
can begin on page 1
...

If you already know a lot about C or C++ and are mainly interested in the new
features of C++0x, you may want to go straight to Chapter 10, “New Features of
C++0x
...


Icons, Icons, Who’s Got the Icons?
Building on the helpful icons used in the first edition, this edition provides even
more—as signposts on the pages to help you find what you need
...


xxvi

Preface

These sections take apart program examples and explain, line by line, how and
why the examples work
...
I do that for you! (Or rather, we go through the examples together
...
These encourage you to alter
and extend the programming code you’ve just seen
...

The answers can be found on the book’s Web site (www
...
com/title/
9780132673266)
...

As with “Optimizing,” these sections take the example in new directions, helping
you learn by showing how the example can be varied or modified to do other
things
...

C++0x ᮣ This icon is used to indicate sections that apply only to versions of C++
compliant with the new C++0x specification
...
If your version is
not C++0x-compliant, you’ll generally want to skip these sections
...
The two features not covered at all are bit fields
and unions
...
Of course, I encourage you
to learn about them on your own later
...
Without a doubt,
the ability to write new template classes is one of the most amazing features of
state-of-the-art C++, but it is a very advanced and complex topic
...

Josuttis; STL Tutorial and Reference Guide: C++ Programming with the Standard
Template Library, Second Edition, by David R
...
Derge, and Atul
Saini; and Effective STL: 50 Specific Ways to Improve Your Use of the Standard
Template Library, by Scott Meyers
...


Getting Started with C++: A Free Compiler
Although this edition doesn’t come with a CD with a free compiler on it, that is
no longer necessary
...
And they install easily
...
informit
...

As mentioned earlier, you will also find downloadable copies of all the full
program examples in the book, as well as answers to exercises
...
Yes, there are those nasty potholes I started out discussing, but remember, I’m going to steer you around
them
...
But it doesn’t have to be intimidating
...
This
is a book about learning and about taking a road to new knowledge, but more
than that, it’s a book about enjoying the ride
...
The book’s editor, Peter Gordon, not only took the initiative
in arranging for the new edition but did a lovely job of nursing the book through
all its stages along with the author’s ego
...
I’d also like to extend a special
thanks to Kim Wimpsett and Anna Popick, who unexpectedly have been an
absolute delight to work with in getting the book through its final tense stages
...
Bennett and Matt Greig, who provided
superb insights about the latest directions of C++
...


xxix

This page intentionally left blank

About the Author
Brian Overland published his first article in a professional math journal at age 14
...
He also tutored students in math,
computer programming, and writing, as well as
lecturing to classes at Microsoft and at the community-college level
...
His
qualifications as an author of technical books are
nearly unique because they involve so much real programming and teaching
experience, as well as writing
...
As a technical writer, he became an expert on advanced utilities, such as the
linker and assembler, and was the “go-to” guy for writing about new technology
...
0 and having a leading role in teaching the “object-based” way
of programming that was so new at the time
...
0 team
...
He is currently working on a novel
...
A function is a
group of related statements that accomplish a specific task
...

Understanding functions is a crucial step to programming in C++: Without
functions, it would be a practical impossibility to engage in serious programming
projects
...
Functions make this possible
...

double sqrt_of_n = sqrt(n);

This is not far removed from the mathematical concept of function
...
Here’s another example
...
0, 4
...
By calling a
function, you transfer execution of the program to the function-definition code,
which runs until it is finished or until it encounters a return statement; execution then is transferred back to the caller
...
It’s easy to see in
a conceptual diagram
...
(The values of a and b are passed to x
and y, respectively
...
2;
double b = 2
...
Then, 4) execution resumes normally inside main, and the program
continues until it ends
...
2;
double b = 2
...
Other functions run only as
called
...
For example, main can
call a function A, which in turn calls B and C, which in turn calls D
...

2 Somewhere in your program, define the function
...


Step 1: Declare (Prototype) the Function
return_type

function_name (argument_list);

The return_type is a data type indicating what kind of value the function
returns (what it passes back)
...

The argument_list is a list of zero or more argument names—separated by
commas if there are more than one—each preceded by the corresponding type
...
) For example, the following statement declares a function
named avg, which takes two arguments of type double and returns a double value
...


Step 2: Define the Function
The function definition tells what the function does
...
The only thing that’s different is that the
semicolon is replaced by zero or more statements between two braces ({})
...
For example:
double avg(double x, double y) {
return (x + y) / 2;
}

4

A function declaration (or prototype) provides type information only
...
Functions with no return value can still use the
return statement but only to exit early
...
For example:
n = avg(9
...
5);
n = avg(5, 25);
n = avg(27, 154
...
For example:
z = x + y + avg(a, b) + 25
...
Here’s how a call to the avg function works,
with sample values 9
...
5 as input
...
When the function returns, the value in this case is assigned to z
...
5, 11
...
5 + 11
...
0 / 2
10
...
(Because these are integer values, they are implicitly converted, or promoted,
to type double
...
1
...
0 + 26
...
0 / 2
16
...

It demonstrates all three steps: declare a function, define it, and call it
...
cpp
#include
using namespace std;
// Function must be declared before being used
...
0;
double b = 0
...

cout << "Average is: " << avg(a, b) << endl;
▼ continued on next page

88

Chapter 4

avg
...


Functions: Many Are Called

system("PAUSE");
return 0;
}
// Average-number function definition
//
double avg(double x, double y) {
return (x + y)/2;
}

How I

t Works

How It Works
This code is a very simple program, but it demonstrates the three steps I outlined
earlier:
1 Declare (that is, prototype) the function at the beginning of the program
...

3 Call the function from within another function (in this case, main)
...
The general
rule is that functions must be declared before being called
...
)
double avg(double x, double y);

The function definition for the avg function is extremely simple, containing
only one statement
...

double avg(double x, double y) {
return (x + y)/2;
}

The main function calls avg as part of a larger expression
...

cout << "Average is: " << avg(a, b) << endl;

The Basics of Using Functions

89

Vari

ation

Function Call a Function!
A program can have any number of functions
...
Lines
that are new or changed are in bold
...
cpp
#include
using namespace std;
// Functions must be declared before being used
...
0;
double b = 0
...

print_results(a, b);
system("PAUSE");
return 0;
}
// print_results function definition
//
void print_results(double a, double b) {
cout << "Average is: " << avg(a, b) << endl;
}
▼ continued on next page

90

Chapter 4

avg2
...


Functions: Many Are Called

// Average-number function definition
//
double avg(double x, double y) {
return (x + y)/2;
}

This version is a little less efficient, but it illustrates an important principle:
You are not limited to only one or two functions
...
The factorial of a number is the product of all whole numbers from 1 to N
...
(Hint: Use a for loop as described in
Chapter 3
...
1
...


Write a function named print_out that prints all the whole numbers
from 1 to N
...
The print_out
function should have type void; it does not return a value
...
1
...


print_out(n);

Example 4
...


Prime-Number Function
Chapter 2 included an example that was actually useful: determining whether a
specified number was a prime number
...

The following program uses the prime-number example from Chapters 2 and
3 but places the relevant C++ statements into their own function, is_prime
...
cpp
#include
#include
using namespace std;

The Basics of Using Functions
prime2
...


91

// Function must be declared before being used
...

// Otherwise, evaluate n from prime-ness
...
Test divisors from
// 2 to sqrt of n
...

bool prime(int n) {
int i;
for (i = 2; i <= sqrt(n); i++) {
if (n % i == 0)
// If i divides n evenly,
return false;
// n is not prime
...

}

4

while (true) {
cout << "Enter num (0 = exit) and press ENTER: ";
cin >> i;
if (i == 0)
// If user entered 0, EXIT
break;
if (prime(i))
// Call prime(i)
cout << i << " is prime" << endl;
else
cout << i << " is not prime" << endl;
}
system("PAUSE");
return 0;

92

Chapter 4

Functions: Many Are Called

How I

t Works

How It Works
As always, the program adheres to the pattern of 1) declaring function type
information at the beginning of the program (prototyping the function), 2)
defining the function somewhere in the program, and 3) calling the function
...
(Note: If you have a really
old compiler, you may have to use the int type instead of bool
...
If you compare the code here to Example 3
...

bool prime(int n) {
int i;
for (i = 2; i <= sqrt(n); i++) {
if (n % i == 0)
// If i divides n evenly,
return false;
// n is not prime
...

}

Another difference is that instead of setting a Boolean variable, is_prime, this
version returns a Boolean result
...

Remember that the modulus operator (%) carries out division and returns
the remainder
...

The action of the return statement here is key
...
There’s no need to use break to get out of the loop
...
The use of a break
statement here provides an exit mechanism, so the loop isn’t really infinite
...
Here I’ve
put the exit lines in bold
...
Declare a local variable sqrt_of_n of
type double
...
) Then
use this variable in the loop condition
...
2
...


Rewrite main so that it tests all the numbers from 2 to 20 and prints
out the results, each on a separate line
...
)

Exercise 4
...
2
...


Exercise 4
...
3
...


Exercise 4
...
4
...
As long as
two functions mind their own data, as it were, they won’t interfere with each
other
...
2)
...
If i were not local—that is, if it was
shared between functions—then consider what could happen
...
Note that the prime function, in this case, returns a
true/false value, and so the call to prime(i) can be used as an if/else condition
...

Let’s say that i has the value 24
...

// Assume i is not declared here, but is global
...

}

// If no divisor found, n is

Look what this function does
...
This test passes—because 2 does divide into 24
evenly—and the function returns
...

Upon returning, the program executes
cout << i << " is not prime" << endl;

which prints the following:
2 is not prime

This is not what was wanted, since we were testing the number 24!
So, to avoid this problem, declare variables local unless there is a good reason
not to do so
...
3, you’ll see that i is local; main and
prime each declare their own version of i
...

You can declare global—that is, nonlocal—variables by declaring them outside of any function definition
...
A variable is recognized
only from the point it is declared, to the end of the file
...
Because this
variable is global, there is only one copy of it; if one function changes the value of
status, this reflects the value of status that other functions see
...
Habitual use of global variables can cause shocks to a program, because
changes performed by one function cause unexpected effects in another
...
Global variables are often the
best way to communicate information between functions; otherwise, you
might need a long series of argument lists that transfer all the program
information back and forth
...


Recursive Functions
So far, I’ve only shown the use of main calling other functions defined in the
program, but in fact, any function can call any function
...
And as you’ll see, it’s less crazy than it sounds
...
The obvious problem is the same one for
infinite loops: If a function calls itself, when does it ever stop? The problem is
easily solved, however, by putting in some mechanism for stopping
...
1
...
Eventually, the function factorial(1) is called, and the cycle
stops
...
The stack is a special area of memory
maintained by the computer: It is a last-in-first-out (LIFO) mechanism that
keeps track of information for all pending function calls
...

You can picture how to call a factorial(4) this way
...
But does it always make sense to use that approach?
No
...
This approach is not efficient
...


Example 4
...


Prime Factorization
The prime-number examples we’ve looked at so far are fine, but they have a limitation
...
Wouldn’t it be more useful to know what
numbers divide into 12,001?
It’d be more useful to generate the prime factorization for any requested number
...

For example, if the number 36 was input, we’d get this:
2, 2, 3, 3

If 99 was input, we’d get this:
3, 3, 11

For all whole numbers from 2 to the square root of n,
If n is evenly divisible by the loop variable (i),
Print i followed by a comma, and
Rerun the function on n / i, and
Exit the current function
If no divisors found, print n itself
This logic is a recursive solution, which we can implement in C++ by having
the function get_divisors call itself
...
cpp
#include
#include
using namespace std;
void get_divisors(int n);
int main() {
int n = 0;
cout << "Enter a number and press ENTER: ";
cin >> n;
▼ continued on next page

4

And if a prime number was input, the result would be the number itself
...

We have almost all the programming code to do this already
...
To get prime-factorization,
first get the lowest divisor, and then factor the remaining quotient
...
cpp, cont
...

void get_divisors(int n) {
int i;
double sqrt_of_n = sqrt(n);
for (i = 2; i <= sqrt_of_n; i++)
if (n % i == 0) {
// If i divides n evenly,
cout << i << ", ";
//
Print i,
get_divisors(n / i); //
Factor n/i,
return;
//
and exit
...

cout << n;
}

How I

t Works

How It Works
As always, the program begins by declaring functions—in this case, there is one
function other than main
...

Also, the beginning of the program includes iostream and cmath, because the
program uses cout, cin, and sqrt
...

#include
#include
void get_divisors(int n);

Recursive Functions

99

The main function just gets a number from the user and calls get_divisors
...

}
// If no divisor is found, then n is prime;
// Print n and make no further calls
...

for (i = 2; i <= sqrt_of_n; i++)
if (n % i == 0) { // If i divides n evenly,
cout << i << ", ";
//
Print i,
get_divisors(n / i); //
Factor n/i,
return;
//
and exit
...
It has a void
return value, meaning that it doesn’t pass back a value
...


100

Chapter 4

Functions: Many Are Called

If the expression n % i == 0 is true, that means the loop variable i divides
evenly into n
...

The function calls itself with the value n/i
...

If no divisors are found, that means the number being tested is prime
...

cout << n;

For example, suppose that 30 is input
...
The function prints the number 2 and then reruns itself on
the remaining quotient, 15 (because 30 divided by 2 is 15)
...
This is 3, so it
prints 3 and then reruns itself on the remaining quotient, 5 (because 15 divided
by 3 is 5)
...
Each call to get_divisors gets the lowest divisor and
then makes another call unless the number being tested is prime
...

Suppose we test a positive whole number and that A is the lowest divisor but
is not a prime
...

But if B divides evenly into A and A is a divisor of the target number, then
B must also be a divisor of the target number
...

Therefore, the hypothesis that the lowest divisor is not prime results in a
contradiction
...
Any number divisible by 4 (a nonprime) is
also divisible by 2 (a prime)
...


Exerci

ses

EXERCISES

Rewrite the main function for Example 4
...
” The program
should call get_divisors to show the prime factorization and then prompt the
user again, until he or she enters 0
...
2, on page 90
...
3
...


Modify Example 4
...
You will
end up having to write more code
...
The main function should call
get_all_divisors, which in turn has a loop: get_all_divisors calls get_lowest_divisor
repeatedly, each time replacing n with n/i, where i is the divisor that was found
...
)

Exercise 4
...
3
...
4
...
For example, the greatest common factor of 15 and 25 is 5
...

Wouldn’t it be nice to have a computer figure this out for you? We’ll focus just
on GCF, because as I’ll show in Chapter 11, if you can figure out the CGF of two
numbers, you can easily compute the lowest common multiple (LCM)
...

To get CGF: For whole two numbers A and B:
If B equals 0,
The answer is A
...
A triangle number is the sum of all whole numbers from 1 to N, in
which N is the number specified
...


Exercise 4
...
2
...
A%B
means this:
Divide A by B and produce the remainder
...
A result of 0 means that B
divides A evenly
...
This solution works for two reasons:
◗ The terminal case (B equals 0) is valid
...

◗ The general case is valid: GCF(A, B) equals CGF(B, A%B), so the function calls
itself with new arguments B and A%B
...
You
can see that A divides evenly into both itself and 0, but nothing larger can divide
into A
...
)
For example, 997 is the greatest common factor for the pair (997, 0)
...

The general case is valid if the following is true:
The greatest common factor of the pair (B, A%B) is also the greatest common factor of the pair (A, B)
...
This is the general idea of recursion:
Pass the problem along to a simpler case involving smaller numbers
...
Therefore, during each recursive call, the algorithm uses successively smaller numbers until B is zero
...
Here is a
complete program for computing greatest common factors:

gcf
...
cpp, cont
...

cout << "Enter a: ";
cin >> a;
cout << "Enter b: ";
cin >> b;
cout << "GCF = " << gcf(a, b) << endl;

}
int gcf(int a, int b) {
if (b == 0)
return a;
else
return gcf(b, a%b);
}

How I

t Works

How It Works
All that main does in this case is to prompt for two input variables a and b, call
the greatest-common-factor function (gcf), and print results:
cout << "GCF = " << gcf(a, b) << endl;

As for the gcf function, it implements the algorithm discussed earlier:
int gcf(int a, int b) {
if (b == 0)
return a;
else
return gcf(b, a%b);
}

The algorithm keeps assigning the old value of B to A and the value A%B to B
...
They get smaller until B equals 0
...
(This always happens if B is larger
...

If the initial value of A is larger than B, the algorithm produces an answer
even sooner
...


VALUE OF A

VALUE OF A%B
(DIVIDE AND GET REMAINDER)

35
25
10
5

Interlude

VALUE OF B
25
10
5
0

10
5
0
Terminal case: answer is 5

Who Was Euclid?
Who was this Euclid guy? Wasn’t he the Greek who wrote about geometry?
(Something like “The shortest distance between two points is a straight
line”?)
Indeed he was
...
For almost 2,500 years it was used as a standard textbook in schools
...
In
fact, he invented the whole idea of proof
...


Recursive Functions

Interlude

105

▼ continued

It was Euclid who (according to legend) said to King Ptolemy of Alexandria, “Sire, there is no royal road to geometry
...

Although its focus is on geometry, Euclid’s book has results in number
theory as well
...
Euclid
expressed the problem geometrically, finding the biggest length commensurable with two sides of a rectangle
...


Exerci

ses

EXERCISES

GCF(500,
GCF(300,
GCF(200,
GCF(100,
100

300) =>
200) =>
100) =>
0) =>

For experts: Revise the gcf function so that it uses an iterative (loopbased) approach
...
You’ll need a temporary
variable—temp—to hold the old value of B for a couple of lines: temp=b,
b=a%b, and a=temp
...
4
...


Interlude

Interlude for Math Junkies: Rest of the Proof
Earlier, I worked out some of a proof of Euclid’s algorithm
...
This is true if we can show the
following:
◗ If a number is a factor of both A and B, it is also a factor of A%B
...

▼ continued on next page

4

Revise the program so that it prints out all the steps involved in the
algorithm
...
4
...


106

Interlude

Chapter 4

Functions: Many Are Called

▼ continued

If these are true, then all the common factors of one pair are common
factors of the other pair
...
Since the two sets are identical, they have the greatest member—therefore, they share the greatest common factor
...
It implies the following,
where m is a whole number:
A = mB + A%B

A%B is equal or less than A, so the general tendency of the algorithm is to
get progressively smaller numbers
...
In that case:
A = cn
B = dn

where c and d are whole numbers
...
By similar reasoning, we can show that if n is a factor of both B and
A%B, it is also a factor of A
...
Therefore, GCF(A, B) equals GCF(B, A%B)
...


Example 4
...


Beautiful Recursion: Tower of Hanoi
Strictly speaking, the earlier examples don’t require recursion
...
But there is a problem
that illustrates recursion beautifully, solving a problem that would be very difficult to solve otherwise
...
Each ring is
smaller than the one it sits on
...

◗ You can place a ring only on top of a larger ring, never a smaller
...
Then, to move N rings from a source stack to a destination stack, do the
following:
1 Move N–1 rings from the source stack to the (currently) unused, or “other,” stack
...

3 Move N–1 rings from the “other” stack to the destination stack
...
Move N–1 rings from source to “other
...

This top ring is then moved: This is a simple action, moving one ring from
source to destination
...
Move one ring from source to destination, directly
...


4

This is easier to envision graphically
...
In this case, N is 4 and N–1 is 3,
but these numbers will vary
...
Move N–1 rings from “other” to destination
...
Assume the problem has already been
solved for the case N–1, although this may require many steps
...
The program magically does the rest
...
But that’s trivial
...


Source

Destination

The following program shows the C++ code that implements this algorithm:
tower
...
cpp, cont
...
In this example, I’ve set the stack
size to just three rings, although it can be any positive integer:
int n = 3;

// Stack is 3 rings high

The call to the move_rings function says that three rings should be moved
from stack 1 to stack 3; these are determined by the second and third arguments,
respectively
...

move_rings(n, 1, 3, 2); // Move stack 1 to stack
3

This small example—moving only three rings—produces the following output
...

Move
Move
Move
Move
Move
Move
Move

from
from
from
from
from
from
from

1
1
3
1
2
2
1

to
to
to
to
to
to
to

3
2
2
3
1
3
3

Try setting n to 4, and you’ll get a list of moves more than twice as long
...
Remember, this recursive approach
assumes the N–1 case has already been solved
...

move_rings(n - 1, src, other, dest);
cout << "Move from " << src << " to " << dest
<< endl;
move_rings(n - 1, other, dest, src);

Notice how the functional role of the three stacks is continually switched
between source (where to move a group of rings from), destination (where the
group is going), and other (the intermediate stack, which is not used now but
will be at the next level)
...
Ideally, you should test the input to see whether it is greater than 0
...
5
...


Instead of printing the “Move” message directly on the screen, have
the move_ring function call yet another function, which you give the name
exec_move
...
Because this is a separate function, you can use as
many lines of code as you need to print a message
...
5
...


Move the top ring from stack 1 to stack 3
...
6
...
It’s time to move on to another,
highly practical example
...

The test program here simulates any number of dice rolls
...
For example, if the user inputs the number 6, this program simulates dice rolls:
3 4 6 2 5 3 1 1 6

Here is the program code:

Recursive Functions

111

dice
...

// Generate a random integer from 0 to N–1, with each
// integer an equal probability
...


112

Chapter 4

Functions: Many Are Called

#include
#include
#include
#include
using namespace std;

Make sure you include the last three here—cmath, cstdlib, and ctime—whenever you use random-number generation
...

The solution is to generate what’s called a pseudorandom sequence by taking a
number and performing a series of complex transformations on it
...
So, we’re back where we started, aren’t we?
Well, fortunately no
...

srand(time(NULL));

NULL is a predefined value that means a data address set to nothing
...
The effect in this case is simply to get the
current time
...

A program that uses random numbers should call srand first
...
This is a practical application of what chaos theorists call the Butterfly Effect
...
A for loop makes repeated calls to rand_0toN1, a function that returns a random number from 0 to n – 1:
for (i = 1; i <= n; i++) {
r = rand_0toN1(6) + 1;
cout << r << " ";
}

// Get num from 1 to 6
// Print it out

Here is the function definition for the rand_0toN1 function:
int rand_0toN1(int n) {
return rand() % n;
}

Games and More Games

113

This is one of the simplest functions we’ve seen yet! Calling rand produces a
number anywhere in the range of the int type, which, on 32-bit systems, can be
anywhere in the range of roughly plus or minus two billion
...

The solution is to use your old friend, the remainder-division operator (%),
to divide by n and return the remainder
...

In this case, the function is called with the argument 6, so it returns a value
from 0 to 5
...

Exerci

ses

EXERCISES

Write a random-number generator that returns a random floatingpoint number between 0
...
0
...
) Make sure you declare the function with the double
return type
...
4
...


Games and More Games
Now that we know how to write functions and generate random numbers, it’s
possible to enhance some game programs
...

Right now, when the user plays optimal strategy, the computer responds by
choosing 1
...
The following program makes the necessary
changes, putting altered lines in bold:

nim2
...


Exercise 4
...
1
...
cpp, cont
...

cout << "Welcome to NIM
...

if ((total % 3) == 2) {
total = total - 2;
cout << "I am subtracting 2
...
" << endl;
} else {
n = 1 + rand_0toN1(2); // n = 1 or 2
...
" << endl;
}
cout << "New total is " << total << endl;
if (total == 0) {
cout << "I win!" << endl;
break;
}
// Get user’s response; must be 1 or 2
...
" << endl;
cout << "Re-enter: ";
cin >> n;
}

Summary
nim2
...


115

total = total - n;
cout << "New total is " << total << endl;
if (total == 0) {
cout << "You win!" << endl;
break;
}
}
system("PAUSE");
return 0;
}

Chapter 2 presented an exercise: Alter this program so that it permits any
number from 1 to N to be subtracted each time, where N is set at the beginning
...
(You can even prompt
the end user for this value before the game starts
...
)
The last full example in Chapter 10 presents a game of Rock, Paper, Scissors
that can be programmed even with C++ compilers that are not fully C++0x
compliant
...
3) with weak, rather
than strong, enumerations, replace this line in Chapter 10:
enum class Choice { rock, paper, scissors };

with this:
enum Choice { rock, paper, scissors };

Also, remove the using statement:
using namespace Choice;

Chapter 4

Summary
Here are the main points of Chapter 4:
◗ In C++, you can use functions to define a specific task, just as you might use a
subroutine or procedure in another language
...


4

int rand_0toN1(int n) {
return rand() % n;
}

116

Chapter 4

Functions: Many Are Called

◗ You need to declare all your functions (other than main) at the beginning of the
program so that C++ has the type information required
...
Function definitions use this syntax:
type function_name (argument_list) {
statements
}

◗ A function runs until it ends or until the return statement is executed
...
If a variable is
local, it is not shared with other functions; two functions can each have a variable named i (for example) without interfering with each other
...
It’s a good policy
not to make a variable global unless there’s a clear need to do so
...
For example:
n += 50;

// n = n + 50

◗ C++ functions can use recursion—meaning they call themselves
...
) This technique is valid as
long as there is a case that terminates the calls
...
See
Greater than or equal to (>=) operator
!= (inequality) operator, 47, 477
, (join) operator
associativity, precedence, and syntax of,
477
as delimiters in text, 187
uses of, 482
<<= (left shift and assign) operator, 477
<= (less than or equal to) operator, 47, 477
*= (multiply and assign) operator, 477

...
(access class member) operator, 476
/= (divide and assign) operator, 477
/ (divide) operator, 476
// (double slashes), in comment syntax, 23–24
:: (scope) operator, 476, 478
; (semicolon)
class or data declaration ending with, 280
compound statements and, 36
termination of function prototypes, 119
termination of statements, 52–53
use in program syntax, 14
\ (backslash), 177
| (bitwise OR) operator, 477, 480
|| (logical OR) operator, 477
+ (addition) operator
...
See Increment (++)
operator
= (assignment) operator
...
See Equality operator
(==)
& (address) operator, 160, 321, 476
&= (bitwise AND and assign) operator, 477
! (logical negation) operator
associativity, precedence, and syntax
of, 476
swap function and, 161
types of Boolean operators, 54

553

554

Index

&& (bitwise AND) operator
...
See Braces ({})
~ (bitwise negation) operator, 476, 481
< > (angle brackets)
correct interpretation of, 432
#include syntax, 299–300, 510–511
i
<< (bitwise left shift or stream op) operator,
476, 481
< (less than) operator
...
481
> (greater than) operator, 47, 477
>> (stream input) operator, 180

Numbers
16-bit integers (short), 244–245
2-D arrays, 142–143
32-bit
addresses, 148
integers (long), 244–245
64-bit
addresses, 148

Fibonacci numbers as 64-bit example,
250–254
integers (long long), 244–245
l
literals (constants), in C++Ox
specification, 246–247

A
Abstract classes
declaring an abstract Printable class, 465
defined, 537
as a pattern for subclasses, 463
specifying and enforcing a set of services
(as an interface), 463–464
stream classes demonstrating
extensibility of OOP, 464–466
virtual functions in, 462
Access array element ([ ]) operator, 476
Access class member (->) operator, 476
Access levels
defined, 537
public, protected, and private, 446
ACK (acknowledgement signal), 513–514
Add and assign (+=) operator, 477
add function
adding arithmetic functions to Fraction
class, 300–305
refining in Fraction class, 347–348
Addition (+) operator
adding to Point class, 342–343
associativity, precedence, and syntax of,
476
declaring, 334
overloading in Fraction class, 348–349
using with references, 338–339
Address operator (&), 160, 476
Addresses
32-bit and 64-bit, 148
arr constant, 161–163
comparing address expressions to each
other, 163

Index

CPUs determining location by, 145
defined, 537
doubling variable whose address is
passed via pointer, 152–155
pointers and, 146
printing, 151–152
Advanced programming
...
"binary" files, 206
Assignment operator (=)
copy constructors compared with, 380
equality operator (==) compared with,
36, 38–39
in expression syntax, 491–492
overview of, 349–350
precedence of, 166
return *this statement as last statement
in, 379–380
in statements, 25–26
Associativity
defined, 538
in evaluation of expressions, 166–167
of operators, 475–477
atof function, 183
atoi function, 183, 206
atoll function, 247–248
auto keyword
uses of, 261–262
variable modifiers, 499
working with exotic types and, 243
Avg(), 87–88

B
Backslash (\), indicating special meaning, 177
Backward compatibility
with C language, 281
defined, 538
issues with C, 312–313
Base 10 numbers
...
See Hexadecimal notation
(base 16)
Base 2 numbers
...
L
...
, 206–208
writing data to, 211–214
Binary notation (base 2)
Fibonacci and, 255
floating-point data type and, 33
hexadecimal and decimal equivalents, 147
Bits, 538
Bitwise left shift or stream op (<<) operator,
476
Bitwise negation (~) operator, 476, 481
Bitwise operators
associativity, precedence, and syntax of,
476
logical operators compared with, 55
operating on integers, 480
uses of, 481
Bitwise right shift or stream op (>>) operator,
476, 481

Index

Bitwise XOR and assign (^=) operator, 477
Bitwise XOR (^) operator, 477, 480
Blocks
...
See also Control
structures, 493
break statements
interrupting loops, 46, 60
syntax of control structures, 496
transferring control out of loop or
function, 231
BS (backspace), 513–514
Bubble sort algorithm, 156–157
Bytes
defined, 539
one byte per character in ASCII code,
170

C
C language

...
See Strings (C-strings)
Callback, 539
Calling functions
arguments in, 227–228
avg() example, 87–88
as expression, 86–87
implementation of, 325

558

Index

Calling functions (continued)
object member functions, 179
overview of, 83
prototypes and, 235
Card dealer array examples
Card Dealer #1, 129–132
Card Dealer #2, 132–136
Card Dealer #3, 136–140
Case
case-sensitivity in compiling code, 11
Convert to Uppercase program
(example), 183–185
switch case statements, 232–234
Casts
associativity, precedence, and syntax of
cast operator, 476
defined, 539
new vs
...
See CPUs (central
processing units)
cerr, 526
Change sign of (-) operator, 333, 476
char*
converting to long long integers, 247–248
format of string literals, 273, 486
for string variables, 128–129
char type
...
See Abstract classes
arithmetic functions added to, 300–305
constructors for, 317–320
copy constructors for, 324–329
declaring, 279–280, 502–503
defined, 540
destructors, 370–371
encapsulation and, 236
enum class, 265–266
exception class, 240
finding GCF of, 291–292
finding LCM of, 292
Fraction class example
...
See Inheritance
initializing members within (C++Ox
only), 309–310
inline functions of, 289–291
lists
...
See Point class
polymorphism
...
See Streams
strings
...
See Subclasses
summary, 305–306
support functions of, 293–296
syntax of class keyword, 279
testing, 284–286, 296–300
clog, 526
close( )
closing files, 199
description of file I/O functions, 529
cmath library
accessing, 57
functions in, 520
including, 181
Code
defined, 5, 540
packaging with data in classes, 277–278
as program instructions, 1
Code reuse
inheritance and, 435
object containment and, 447–448
Command-line
arguments, 221–222
displaying files from, 223–226
Commas (,)
...
See Streams
const keyword
in declaring copy constructors, 324
function modifiers, 501
preventing changes to arguments while
passing, 340
variable modifiers, 499
Constants
64-bit literals, 246–247
advantages of predefined, 225–226
all literals are constants, 485

560

Index

Constants (continued)
automating assignment of symbolic,
264–265
defined, 540
end line constant, 16
list of predefined, 512
Constructors
for base classes (C++Ox only), 441–442
cannot be virtual, 455
consistent initialization of (C++Ox
only), 314–315
copy constructors, 323–325
copy constructors for Fraction class,
325–329
default constructors, 310–313
defined, 540
delegating (C++Ox only), 313–314, 452
for Fraction class, 317–320
initializing members within a class
(C++Ox only), 309–310
initializing objects from strings,
329–331
for linked lists, 390–391
multiple (overloading), 309
overview of, 307–309
for Point class, 315–317
reference variables and arguments and,
321–323
for String class, 374
subclasses not inheriting, 440
summary, 331–332
Containers
range-based for (for each), 257
templates creating, 413
continue statements, 496
Control structures
defined, 540
do while, 231–232
else
...
See for
if
...
See while
Convert to Uppercase program (example),
183–185
Cooked literals, 359
Copy constructors
assignment operator compared with, 380
deep copying, 377
defined, 541
for Fraction class, 325–329
member functions automatically
supplied by compiler, 349
overview of, 323
references and, 325
shallow copying, 376–377
syntax of, 324
Counting, loops used for, 67–68
cout
console output object, 14
description of stream objects, 526
file streams as alternative to, 197
polymorphism and extensibility of,
464–466
print function interacting with, 351–352
string type and, 191
use of data objects in C++, 7–8
CPUs (central processing units)
addresses of locations, 145
defined, 541
translating statements into machine code
prior to execution, 170–171
CR (carriage return), 513–514
cstdlib, 181
ctemp variable, for holding Celsius values,
19–20, 24–25

D
Data
arrays, 117

Index

conversion functions in standard library,
518
defined, 5
linking data structures using addresses,
146
packaging with code in classes, 277–278
pointers for sending large amounts of, 146
programs and, 1
storing via variables, 19–20
string data, 19
Data declaration
classes, 502–503
enumerations, 503–504
functions, 500–501
semicolon terminating, 280
variables, 498–500
Data members
...
accepting
default, 310–313

562

Index

#define directive
d
localizing numbers, 254–255
overview of, 505–506
placing predefined constants with,
225–226
defined function, preprocessor directives, 507
Defining functions
avg() example, 87–88
defined, 541
overview of, 85–86
DEL (delete), 513–514
Delegating constructors (C++Ox only),
313–314, 452
delete operator
associativity, precedence, and syntax of,
476
class destructors and, 370–371
pointers to objects and, 365–366
releasing allocated memory, 364–365,
367, 370
Delimiters, in text, 186
Deprecate
defined, 541
setting null pointers without nullptr
keyword, 263
Dereference, 542
Derived classes
...
W
...
See Preprocessor directives
Directories, referencing disk files in, 199–200
Displaying text files, 203–206
Divisors, lowest divisor as prime number,
100–101
do while statements
as loop, 230

statement and conditions, 232
syntax of, 231, 494
Double-precision types
...
See Users
#endif directive, 508
e

Index

endl stream manipulator
description of, 527
for end line constant, 16
ends stream manipulator, 527
Enumerations
automating assignment of symbolic
constants, 264–265
enum classes, 265–266
enum declarations, 503–504
extended enum syntax, 266–267
Rock, Paper, Scissors game, 267–272
strongly typed, 244, 263–265
eof (end of file) function, file I/O functions,
205, 529
Equality operator (==)
associativity, precedence, and syntax of,
476
compared with assignment operator (=),
36, 38–39
in Fraction class, 355–356
ordered lists and, 419
overview of, 350–351
precedence of, 166
in String class, 374
types of relational operators, 47
#error directive, 508
e
Errors
...
double quotes in syntax
of, 186
statements compared with, 52–53
syntax of, 491–492
Extensibility, of OOP, 464–466
extern declaration
sharing variables and, 235
for variable modifiers, 499–500

F
F suffix, representing float format, 486
Factorial function
overview of, 90
rewriting as recursive function, 96
Factorization, of prime numbers, 96–100
Fahrenheit, converting to/from Celsius, 22–26
False/true
...
"binary" files, 206–208
writing binary data to, 211–214
writing text to, 200–203
fill( ) function, output streams, 528
fixed, 237–240
fixed stream manipulator, 527
Flags
file mode flags, 530
seek direction flags, 530
float data type
...
See also Control
structures, 37–38, 48
flush( ) function, streams, 528

flush stream manipulator, 527
Folders, referencing disk files in, 199–200
For each
...
See Operators
overloading, 227–230
overview of, 83–84
prime factorization, 96–100
prime number, 90–93
in programs, 89–90
random number generator, 110–113
randomized, 521
recursive, 95–96, 106–110
single-character, 519
strftime format, 523–524

565

string manipulation, 172–174
in Subtraction Game, 113–115
summary, 115–116
support functions of Fraction class,
296–300
time functions, 521–523
virtual
...
See GCFs (greatest
common factors)
GUIs (graphical-user interfaces)
OOP and, 279
safe inheritance and, 448–451

H

...
See also Constructors
of arrays, 119
assigning variable values during, 49
consistency of, 314–315
of Fraction objects from strings, 329–331
initializer values in for loops, 68–69
of types while declaring, 307
Inline functions
addition (+) operator as, 340
cannot be virtual, 455

567

constructors as, 308
defined, 544
of Fraction class, 289–291
function modifiers, 501
Input stream functions
...
See also Integer data
comparing pointer values with int
variables, 151–152
converting strings to, 183
"cooked" literals and, 359
description and range of, 484
natural integer type, 245–246
pointer to, 148
range compared with double, 127
reading binary data, 209–210
storing numbers with, 485
swapping values of two int variables,
155–156
syntax of, 34
Integer data
address expressions and, 162
char type and, 171
comparing with floating point data,
33–34
converting strings to, 183
data types, 20–21
defined, 544
division of, 480
get_int function, 214
reading binary data, 209–210
short, long, and long long, 244–245
signed and unsigned, 245
suffixes in representation of, 486
two's complement format for signed
integers, 487–489

568

Index

Interfaces
abstract classes for specifying and
enforcing a set of services, 463–464
defined, 544
implementing through class inheritance,
462
relationship between GUIs and OOP, 279
safe inheritance in GUIs, 448–451
ios::app, file mode flags, 530
ios::ate, file mode flags, 530
ios::beg, seek direction flags, 530
ios::binary, file mode flags, 213, 530
ios::cur, seek direction flags, 530
ios::end, seek direction flags, 530
ios::in, file mode flags, 216, 530
ios::out, file mode flags, 213, 530
ios::trunc, file mode flags, 530
is_open( ), description of file I/O functions, 529
Iteration
...
See LIFO (last-in-first-out)
Late binding, resolving address of virtual
functions at runtime, 472
LCM (lowest common multiple)
adding LCM function to Fraction class,
292
computing from greatest common
factors (GCFs), 101
defined, 545
Left shift and assign (<<=) operator, 477
left stream manipulator, 527
Less than (<) operator
associativity, precedence, and syntax of,
477
ordered lists and, 419
types of relational operators, 47
Less than or equal to (<=) operator, 47, 477
LF (linefeed), 513–514
Libraries, C++
math library, 57
standard library, 15
STL (Standard Template Library)
...
See for loops
increment operator (++) used in, 51–52
infinite, 46, 205
in prime factorization, 99–100
print 1 to N example, 46–49
testing randomness with, 126–127
using strtok function with, 188
using swap function for sorting, 157–161
using with arrays, 117, 121–123
while loops, 43–45
Lowest common multiple
...
returning
new objects, 382
sort, 421
in Stack classes (), 536
in string class (), 532–533
syntax of, 283
Members
assigning values to class data fields, 280
defined, 541, 546
initializing within a class (C++Ox only),
309–310
private, 281–284
protected, 445–446
public, 279
relationship with objects and classes, 284
restricting access to, 287
structures and, 281

Memory
allocating blocks of, 366–367
defined, 546
dynamic allocation
...
See Change sign of (-)
operator
Modules
advantages of multiple, 235–236
defined, 546
overview of, 234
source files as, 241
Modulus or remainder operator (%)
associativity, precedence, and syntax of, 476
declaring, 335–336
prime number function and, 92
random number generation and, 113
using in Odd-or-Even program, 41–42
mult function
adding arithmetic functions to Fraction
class, 300–305
refining in Fraction class, 347–348
Multi-dimensional arrays, 142–143
Multiple constructors (overloading), 309
Multiple modules, 234–236
Multiply and assign (*=) operator, 477
Multiply (*) operator, 476
MyStack class, Tower of Hanoi example
creating, 403–404
using, 404–405

N
NAK (no acknowledgment), 513–514
Namespaces, std namespace, 414
Nesting
defined, 546
nested loops, 160

Index

new operator
allocating memory blocks with, 366–367
associativity, precedence, and syntax of,
476
creating node with, 391
dealing with problems in memory
allocation, 368
dynamic memory allocation and,
363–364
example allocating array of any size,
369–370
pointers to objects and, 365–366
syntax of, 315
Newline character
for advancing to next print line, 16–18
defined, 546
NIM (Subtraction Game)
decision making example, 60–63
function for enhancing, 113–115
noboolalpha stream manipulator, 527
Nodes, designing for linked lists, 390–391
Normalize function
adding support functions to Fraction
class, 293–296
overriding, 453–454, 457, 459–460
set function calling, 350
noshowbase stream manipulator, 527
noshowpoint stream manipulator, 527
NOT (!) operator
...
See Decimal notation (base 10)
base 16
...
See Binary notation (base 2)
converting numeric values into text
characters, 169–170
counting, 67–68
Fibonacci numbers, 250–254
function for prime factorization, 96–100
function for prime numbers, 90–93
Get a Number program (example),
180–183
get_number function, 181
localizing, 254–255
lowest divisor as prime number, 100–101
numeric data types, 20–21
numeric expressions in single quotes,
186
printing from 1 to N with for loop,
72–73
printing from 1 to N with while loop,
46–49
random number generator, 110–113
storing, 485
testing for prime numbers with for
loops, 75–79
testing for prime numbers with while
loops, 57–60

O
Object containment, as alternative to
inheritance, 447–448

572

Index

Object independence
...
See Linked lists
multiple modules and, 236
object independence
...
See
Tower of Hanoi, animated
using objects without knowing type or
what function it calls, 470–471
open( ), file I/O function, 529
Operand, 547

operator+ function, writing for String class,
381–386
Operators
...
See also I/O
(input/output), 528
Overloading
constructors, 309
defined, 547
functions, 227–228
object orientation and, 228
operators, 335, 348–349
print_array function (example), 228–230
override keyword, 461
Overriding
member functions, 453–454
normalize function, 453–454, 457,
459–460
requiring explicit (C++Ox only),
460–461

Index

P
Pascal
adding OOP extensions to, 279
purpose of high-level languages, 7
Pathnames, in referencing disk files, 200
peek( ), stream input function, 528
Performance penalty, in use of virtual
functions, 455–456
Persistent memory
defined, 547
nonpersistence of RAM, 197
polymorphism and, 459–460
Placeholders, program syntax and, 3
Point class
constructors for, 315–317
copy constructors for, 324
declaring, 279–280
operators for, 340–343
private members of, 281–284
testing, 284–286
Pointer arithmetic, 162
Pointer indirection (*), 149, 166
Pointer-to-member (->*) operator, 476
Pointer-to-member (
...
See also RPN (Reverse Polish
Notation), 424
Polymorphism
abstract classes, 462–464
benefits of OOP, 278
defined, 548
incomplete type information and, 228
making a floating point value persistent
and recalculating as needed, 459–460
overriding member functions and,
453–454
Printable class example, 466–470
pure virtual functions, 461–462
requiring explicit overrides (C++Ox
only), 460–461
revised FloatFraction class using virtual
functions, 456–458
stream classes demonstrating
extensibility of OOP, 464–466
summary, 472–473
system orientation of OOP and, 472
trade offs in use of virtual function calls,
455–456
using object without knowing type or
what function it calls, 470–471
virtual functions in FloatFraction class,
454–455
Precedence
defined, 548
in evaluation of expressions, 166–167
of operators, 54, 476
Precision of data types, 484
precision( ), output stream function, 528

574

Index

Predefined constants
advantages of, 226
list of, 512
use of, 225
Preprocessor directives
## (concatenation) operator, 507
#define
...
See #include
i
i
#line, 511
l
overview of, 505
#undef, 511
u
Prime factorization function, 96–100
Prime numbers
function for, 90–93
lowest divisor as, 100–101
testing for with for loops, 75–79
testing for with while loops, 57–60
Print function, as class operator, 351–352
Printable class example, true polymorphism
in, 466–470
Print_array function, example of function
overloading, 228–230
Printing
advancing to next print line (newline),
16–18
array elements, 121–123
building ability to print into objects, 465
multiple line programs, 16–18
names in alpha order, 395–399
numbers from 1 to N with for loop,
72–73
numbers from 1 to N with while loop,
46–49
printing a message (example), 11–14

private keyword
access levels in C++, 446
in class declaration, 502
Private members
access levels in C++, 446
of Fraction class, 287
friend functions and, 337–338
of Point class, 281–284
Private/public distinction, encapsulation and,
236
Procedures
...
See CPUs (central processing
units)
Program-logic errors
exception handling, 237
testing for, 9–10
Programming
computer do only what you tell them, 1
determining what a program will do, 1–2
exercises, 15
printing a message (example), 11–14
writing C++ statements, 2–3
Programming, advanced
advantages of predefined constants, 226
command-line arguments, 221–222
displaying files from command line,
223–226
do_while loops, 230–232
exception handling, 237–240
multiple modules, 234–236
overloading functions, 227–228
overview of, 221
print_array function (example), 228–230
summary, 240–242
switch case statements, 232–234
Programs
building a C++ program, 8–10
comments in, 23–24
compared with applications and code, 5
decision making in, 34–35
defined, 6, 548

Index

determining what a program will do, 1–2
as list of things for computer to do, 1
optimization of, 26–27
printing multiple line programs, 16–18
Projects, Microsoft Visual Studio, 12–13
protected keyword
in class declaration, 502
overriding functions and, 455
Protected members, of FloatFraction class,
445–446
Prototypes
avg() example, 87–88
calling functions and, 235
declaring functions, 85
declaring global functions, 336
defined, 548
ending with semicolon, 119
of Fraction class, 288–289
syntax of, 501
Pseudocode, 3
Pseudorandom sequences, 112
public keyword
access levels in C++, 446
in class declaration, 502
specifying access level for base classes,
437–438
Public members
access levels in C++, 446
declaring classes and, 280
of Fraction class, 287
of structures, 281
Public/private distinction, encapsulation and,
236
Pure virtual functions
...
See Fraction class
Raw string literals
in C++Ox specification, 273
defining, 358
overview of, 244
read( )
description of input stream functions,
528
input and output of binary data and, 210
readfile commands, 224

576

Index

Reading
binary data from files, 214–217
string input, 178–180
Records, finding by number, 213–214
Recursion
applying to Fibonacci numbers, 250
defined, 548
function calling itself, 95–96
iteration compared with, 401–402
prime factorization, 96–100
Tower of Hanoi puzzle, 106–110, 408
References
copy constructors and, 325
defined, 548–549
operators used with, 338–340
reference arguments, 322–323
reference variables, 321–322
register variable modifier, 499–500
reinterpret_cast operator, 209
Relational operators
Boolean operators, 50
precedence of, 54
returning true or false values, 47
return statements
returning values with, 18
syntax of control structures, 497
transferring control out of loop or
function, 231
Return *this statement, 379–380
Return values
compared with pointers, 321
declaring functions, 85
defining functions, 85–86
from functions, 83
Reusable code
inheritance and, 435
object containment and, 447–448
Reverse Polish Notation
...
See float
Single quotes (' '), distinguishing strings from
individual characters, 185
sizeof operator
associativity, precedence, and syntax of,
476
returning size of specified type, variable,
or array, 211
uses of, 478–479
Smart pointers (C++Ox only), 400–401
sort
as power member function, 421
sorting lists, 421–422
Source code
compiling as machine code, 5
defined, 6
storing as text file, 170
Source files
defined, 549
modules and, 235, 241
Space penalty, in use of virtual functions,
455–456
Spaces, as delimiters in text, 187
Spaghetti code, 497
sqrt function
in math library, 57
testing for prime numbers with for
loops, 75–79
testing for prime numbers with while
loops, 57–60
Square roots, Get a Number program
(example), 180–183
Stack classes (), in STL, 425, 427–428,
535–536
Stacks
defined, 549
of function calls, 96

577

Standard (infix) notation, 423
Standard library
character conversion functions, 519
character-testing functions, 519
data-conversion functions, 518
math functions, 520
overview of, 15
randomized functions, 521
single-character functions, 519
str functions, 175
strftime function, formats of, 523–524
strtok (string token) function, 186–188
time functions, 521–523
Statements
...
See Compound statements
(blocks)
defined, 6, 549
entering program statements, 8
expressions compared with, 52–53
functions grouping related, 83
replacing control structures with
statement blocks, 231
switch case statements, 232–234
syntax of, 492
translating into machine code, 170–171
writing C++ statements, 2–3
static
function modifiers, 501
variable modifiers, 499–500
Static storage class, 549
Static_cast conversion, 265–266
std namespace, 414
STL (Standard Template Library)
continual sorting of list, 421–422
creating iterators for list, 416–418
creating List class, 415–416
defined, 549
List classes (), 533–534
list template, 413–414
object-orientation of, 279

578

Index

STL (Standard Template Library) (continued )
overview of, 413
range-based for (for each) used in place
of iterators, 418
Reverse Polish Notation (RPN)
calculator, 422–424
RPN program, 428–432
stack classes (), 425, 427–428,
535–536
string (C-strings) functions, 517–518
string class (), 531–533
substream (substr) class, 248–249
summary, 432–433
writing ordered list program, 419–421
writing templates, 414–415
Storage
controlling using enum classes, 266–267
of data in files, 197
Storage classes, 550
strcat function, concatenation of stings,
172–173
strcmp function, comparing strings, 375
strcpy
building strings, 176
copying strings, 172–173
Stream classes
demonstrating extensibility of OOP,
464–466
Printable class example, 466–470
Stream input operator (>>), 180
Streams
console input
...
See cout
console stream objects, 525–526
file I/O functions, 529–530
input stream functions, 528
manipulators, 526–527
output stream functions, 528
substream (substr) class, 248–249
Strftime function, in standard library, 523–524

String class (C-strings)
complete version of, 382–386
deep copying, 377
shallow copying, 376–377
summary, 387–388
writing concatenation function for,
380–382
writing own, 371–376
String class (), 189–191, 531–533
String concatenation
defined, 551
strcat and strncat functions for, 172–174
working with string type and, 193
writing concatenation function for string
class, 380–382
String literals
defined, 550
format and escape sequences, 486–487
raw string literals, 244, 273
String objects, as container for range-based
for, 257
Strings (C-strings)
arrays in Card Dealer #1, 129–132
arrays of, 128–129
based on char type, 171–172
building, 174–177
building with STL string type, 191–193
comparing (strcmp), 375
s
Convert to Uppercase program
(example), 183–185
defined, 539, 550
distinguished from individual characters,
185–186
escape sequences, 177–178
format and escape sequences, 486–487
functions for manipulating, 172–174
functions in standard library, 517
Get a Number program (example),
180–183
including, 175, 181

Index

initializing Fraction objects from, 329–331
overview of, 169
reading string input, 178–180
storing text on computers, 169–170
string literals and string variables, 128
strtok function for breaking up input,
186–188
summary, 194–195
of text, 18–19
text string data, 20–21
Strings ()
building strings with, 191–193
declaring variables of, 189–190
input and output and, 191
new in C++, 189
new STL string class, 189–191
other operations on, 193–194
other operations on STL string type,
193–194
working with variables of, 190–191
strlen function, returning string length, 172
strncat function, concatenation of strings,
172, 174
strncpy function, copying strings, 172, 174
Strongly typed enumerations, 244, 263–265
Strousup, Bjarne, 243, 279
strtok (string token) function
for breaking up text input, 186–188
returning null pointer, 330
setting using nullptr keyword, 263
struct keyword
declaring structures, 281
issues with, 312–313
Structures, classes compared with, 281
Subclasses
...
See Functions
substream (substr) class, 248–249
Subtraction (-) operator
adding to Point class, 342–343
associativity, precedence, and syntax of,
476
Subtraction Game (NIM)
decision making example, 60–63
function for enhancing, 113–115
Suffixes
operators, 358–359
in representation of integer values, 486
Swap function
overloading, 227–228
sorting arrays with, 156–161
swapping values of two int variables,
155–156
switch-case statements
in advanced programming, 232–234
syntax of, 495–496
Symbols
automating assignment of symbolic
constants, 264–265
defined, 550
enum classes and, 266, 503
literals compared with, 485
Syntax
errors, 9–10, 237
summary of, 491-504
Systems
OOP and, 472
polymorphism and, 465

T
tellg( ) function, file I/O, 529
tellp( ) function, file I/O, 529
temp variable, 155–156

580

Index

Temperature, converting Celsius to/from
Fahrenheit, 22–26
Templates
...
binary files, 206–208
text files vs
...
See Strings (C-strings)
this keyword
as pointer to current object, 378
return *this statement as last statement
in assignment operator function,
379–380
throw statements
exception handling and, 239–240
syntax of control structures, 497
Time functions, in standard library, 521–523
Tokens, substrings, 186
tolower (c) function, 184–185
toupper (c) function, 184–185

Tower of Hanoi, animated version
building, 405–411
creating MyStack class, 403–404
overview of, 402–403
summary, 411–412
using MyStack class, 404–405
Tower of Hanoi, basic version, 106–110
Trigonometric functions, 520
True/false
...
See Casts
Type checking, in OOP, 471
Types
...
address of, 151–152
declaring, 498–500
declaring on the fly, 74–75
declaring prior to use, 20
declaring with auto keyword, 261–262
defined, 551
doubling with double_it function,
152–155
local and global variables, 93–95
naming rules and conventions, 28–29
sharing, 235
storing data with, 19–20
string variables, 128, 189–191
swapping values of two int variables,
155–156
Virtual functions
in abstract classes, 462–463
declaring member functions that might
be overridden v irtual, 454–455
defined, 551
late binding, 472
pure virtual functions, 461–462
restrictions on use of, 455
revised FloatFraction class using, 456–458
trade offs in use of, 455–456
virtual keyword, as function modifiers,
454–455, 501
Visual Basic, 7

W

Z
Zero-based indexes
arrays and, 119–120
defined, 551
Zero_out_array function, 165–16


Title: Beginner's Guide to C++
Description: 96 pages to guide you to learn C++ successfully