C++ How To Program An Objects
C++ How To Program An Objects
C++ How To Program An Objects
https://deitel.com/pycds https://deitel.com/chtp9
https://deitel.com/jhtp11EOV https://deitel.com/jhtp11LOV
Content Management: Tracy Johnson
Content Production: Bob Engelhardt, Abhijeet Gope, K Madhusudhan
Product Marketing: Krista Clark
Rights and Permissions: Anjali Singh
Cover Designer: Paul Deitel, Harvey Deitel, Chuti Prasertsith
Cover Art: Paul Deitel (produced using Andreas Müller’s open-source Python library word_cloud—https://
github.com/amueller/word_cloud)
Microsoft and/or its respective suppliers make no representations about the suitability of the information contained in
the documents and related graphics published as part of the services for any purpose. All such documents and related
graphics are provided “as is” without warranty of any kind. Microsoft and/or its respective suppliers hereby disclaim
all warranties and conditions with regard to this information, including all warranties and conditions of merchantabi-
lity, whether express, implied or statutory, fitness for a particular purpose, title and non-infringement. In no event shall
Microsoft and/or its respective suppliers be liable for any special, indirect or consequential damages or any damages
whatsoever resulting from loss of use, data or profits, whether in an action of contract, negligence or other tortious
action, arising out of or in connection with the use or performance of information available from the services.
The documents and related graphics contained herein could include technical inaccuracies or typographical errors.
Changes are periodically added to the information herein. Microsoft and/or its respective suppliers may make improve-
ments and/or changes in the product(s) and/or the program(s) described herein at any time. Partial screen shots may
be viewed in full within the software version specified.
Microsoft® and Windows® are registered trademarks of the Microsoft Corporation in the U.S.A. and other countries.
This book is not sponsored or endorsed by or affiliated with the Microsoft Corporation.
Copyright © 2024 by Pearson Education, Inc. or its affiliates, 221 River Street, Hoboken, NJ 07030. All Rights
Reserved. Manufactured in the United States of America. This publication is protected by copyright, and permission
should be obtained from the publisher prior to any prohibited reproduction, storage in a retrieval system, or transmis-
sion in any form or by any means, electronic, mechanical, photocopying, recording, or otherwise. For information
regarding permissions, request forms, and the appropriate contacts within the Pearson Education Global Rights and
Permissions department, please visit www.pearsoned.com/permissions/.
Acknowledgments of third-party content appear on the appropriate page within the text.
PEARSON and REVEL are exclusive trademarks owned by Pearson Education, Inc. or its affiliates in the U.S. and/
or other countries.
Unless otherwise indicated herein, any third-party trademarks, logos, or icons that may appear in this work are the
property of their respective owners, and any references to third-party trademarks, logos, icons, or other trade dress are
for demonstrative or descriptive purposes only. Such references are not intended to imply any sponsorship, endorse-
ment, authorization, or promotion of Pearson’s products by the owners of such marks, or any relationship between
the owner and Pearson Education, Inc., or its affiliates, authors, licensees, or distributors.
Deitel and the double-thumbs-up bug are registered trademarks of Deitel and Associates, Inc.
ePub
ISBN-10: 0-13-809236-2
ISBN-13: 978-0-13809236-8
In memory of Gordon Moore, co-founder of Intel
and father of Moore’s Law:
While we work hard to present unbiased, fully accessible content, we want to hear from you about any
concerns or needs with this Pearson product so that we can investigate and address them.
• Please contact us with concerns about any potential bias at https://www.pearson.com/report-
bias.html.
• For accessibility-related issues, such as using assistive technology with Pearson products, alter-
native text requests, or accessibility documentation, email the Pearson Disability Support team
at [email protected].
Contents
Preface xxiii
1.13.6 Ethereum 47
1.13.7 Non-Fungible Tokens (NFTs) 47
1.13.8 Web3 47
1.14 Software Development Technologies 48
1.15 How Big Is Big Data? 49
1.15.1 Big-Data Analytics 52
1.15.2 Data Science and Big Data Are Making a Difference: Use Cases 53
1.16 AI—at the Intersection of Computer Science and Data Science 54
1.16.1 Artificial Intelligence (AI) 54
1.16.2 Artificial General Intelligence (AGI) 55
1.16.3 Artificial Intelligence Milestones 55
1.16.4 Machine Learning 56
1.16.5 Deep Learning 56
1.16.6 Reinforcement Learning 57
1.16.7 Generative AI—ChatGPT and Dall-E 2 57
1.17 Wrap-Up 59
4.12 Confusing the Equality (==) and Assignment (=) Operators 173
4.13 Structured-Programming Summary 175
4.14 Objects Natural Case Study: Precise Monetary Calculations with
the Boost Multiprecision Library 180
4.15 Wrap-Up 183
11 Operator Overloading,
Copy/Move Semantics and Smart Pointers 587
11.1 Introduction 588
11.2 Using the Overloaded Operators of Standard Library Class string 590
Contents xv
Index 1225
Preface
1 An Innovative Modern C++ Programming Textbook
Good programmers write code that humans can understand.1
—Martin Fowler
Welcome to C++ How to Program: An Objects-Natural Approach, 11/e. We present a
friendly, contemporary, code-intensive, case-study-oriented introduction to C++, the
world’s third most popular programming language according to the TIOBE Index.2
C++ is popular for building high-performance business-critical and mission-critical
computing systems—operating systems, real-time systems, embedded systems, game sys-
tems, banking systems, air-traffic-control systems, communications systems and more. This
book is an introductory- through intermediate-level college textbook presentation of the
C++20 version of C++ and its associated standard libraries, with a look toward C++23 and
C++26. In this Preface, we present the “soul of the book.”
1. Martin Fowler (with contributions by Kent Beck). Refactoring: Improving the Design of Existing Code.
Addison-Wesley Professional. 2018.
2. Tiobe Index for February 2023. Accessed March 8, 2023. https://www.tiobe.com/tiobe-index/.
xxiv Preface
2 Modern C++
We cover Modern C++—C++20, C++17, C++14 and C++11—with a look toward key fea-
tures coming in C++23 and anticipated for C++26. We employ industry best practices,
emphasizing Modern C++ idioms—which change how developers write C++ programs—
while focusing on performance, security and software engineering. We present rich treat-
ments of C++20’s “big four” features—ranges, concepts, modules and coroutines. We’ll say
more about these in Section 6 of this Preface.
3 Target Audiences
The book’s modular architecture (see the diagram on the next page) makes it appropriate
for several audiences:
• Introductory and intermediate college programming courses in Computer Sci-
ence, Computer Engineering, Information Systems, Information Technology,
Software Engineering and related disciplines.
• Science, technology, engineering and math (STEM) college courses with a pro-
gramming component.
• Professional industry training courses.
• Experienced professionals learning the latest Modern C++ idioms to prepare for
upcoming projects.
C++ How to Program: An Objects-Natural Approach, 11/e
by Paul Deitel & Harvey Deitel
PART 1 PART 2 PART 3 PART 5, Advanced Topics:
C++20 Fundamentals Quickstart Containers, C++20 Ranges, Modern Object-Oriented Modules, Parallel Algorithms,
& Procedural Programming Pointers, Strings & Files Programming & Exceptions Concurrency & Coroutines
1. Intro: Test-Driving Popular, 6. arrays, vectors, Ranges and 9. Custom Classes 16. C++20 Modules:
Free C++ Compilers Functional-Style Programming ON: Studying the Vigenère Secret- Large-Scale Development
Intro to Hardware, Software & Internet; Intro to functional-style programming. Key Cipher Implementation import, header units,
Test-Driving the Visual C++, GNU g++ ON: Class Template vector 10. OOP: Inheritance and module declarations,
and LLVM clang++ compilers. 7. (Downplaying) Runtime Polymorphism module fragments, partitions
2. Intro to C++20 Programming Pointers in Modern C++ Programming to an interface, 17. Parallel Algorithms &
C++ fundamentals. “Objects-Natural” Security & safe programming. 11. Operator Overloading, Concurrency: A High-Level View
(ON) approach intro—using libraries ON: C++20 spans Copy/Move Semantics, Smart Multi-core performance with C++17
to build powerful object-oriented 8. strings, string_views, Text Pointers and RAII parallel algorithms, concurrency,
applications with few lines of code. Files, CSV Files and Regex Crafting valuable classes: multithreading
ON: Manipulating string Objects ON: Reading and Analyzing Custom MyArray class, 18. C++20 Coroutines
3. Control Statements, Part 1 the Titanic Disaster Data (CSV) C++20 three-way comparison operator co_yield, co_await, co_return,
Intro to C++20 text formatting. ON: Intro to Regular Expressions <=>, resource management via RAII coroutines support libraries,
ON: Super-Sized Integers with the (Resource Acquisition Is Initialization) generators, executors and tasks
Boost Multiprecision Library 12. Exceptions and
4. Control Statements, Part 2 a Look Forward to Contracts PART 6
ON: Precise Monetary Calculations Miscellaneous Topics
with the Boost Multiprecision Library
19. Stream I/O and
5. Functions and an Intro to PART 4, Generic Programming:
C++20 Text Formatting
Function Templates Templates, Concepts &
Template Metaprogramming 20. Other Topics and a Look
ON: Lnfylun Lhqtomh Wjtz Qarcv: Toward C++23 and C++26
Qjwazkrplm xzz Xndmwwqhlz 13. Standard Library Containers
(encrypted title for our private-key 21. Computer Science Thinking:
and Iterators Searching, Sorting and Big O
cryptography case study) Manipulating standard data structures
14. Standard Library Algorithms • Programming tips: C++ Core
• ON = objects-natural case study. and C++20 Ranges & Views Guidelines, Software Engineering,
• C++20’s “Big Four” features: Ranges, Functional-style programming Performance, Security, Errors,
Concepts, Modules and Coroutines. C++20 Modules, C++20 Concepts,
• Live-code approach: 255 complete 15. Templates, C++20 Concepts Data Science.
programs with live outputs. and Metaprogramming • g++ & clang++ Docker containers.
• Communicate with the authors at Compile-time polymorphism, • A look toward C++23 and C++26.
[email protected]. • Static code-analysis tools. function templates, C++20 abbreviated • Blog: https://deitel.com/blog.
• Download source code at • Use developer resources: GitHub®, function templates, class templates,
https://deitel.com/cpphtp11. StackOverflow®, open-source, more. variadic templates, fold expressions
xxvi Preface
3. Intro to Python for Computer Science and Data Science: Learning to Program with AI, Big Data and the
Cloud (https://deitel.com/pycds).
4. “Boost 1.81.0 Library Documentation.” Accessed March 8, 2023. https://www.boost.org/doc/
libs/1_81_0/.
5. Kennytm, Answer to “Which Boost Features Overlap with C++11?” Accessed March 8, 2023.
https://stackoverflow.com/a/8852421.
5 Programming Wisdom and Key C++20 Features xxvii
We use the Boost Multiprecision library in our objects-natural case studies on super-sized
integers (Section 3.14) and precise monetary calculations (Section 4.14).
Whether you’re a student getting a sense of the textbook you’ll be using, an instructor
planning your course syllabus or a professional software developer deciding which chapters
to read as you prepare for a project, this detailed Tour of the Book will help you make the
best decisions.
6. We point out the few cases in which a compiler does not support a particular feature.
6 Tour of the Book xxix
Chapter 3, Algorithm Development and Control Statements: Part 1, is one of the most
important chapters for programming novices. It focuses on problem-solving and algorithm
development with C++’s control statements. You’ll develop algorithms through top-down,
stepwise refinement, using the if and if…else selection statements, the while iteration
statement for counter-controlled and sentinel-controlled iteration, and the increment, dec-
rement and assignment operators. The chapter presents three algorithm-development case
studies—Counter-Controlled Iteration, Sentinel-Controlled Iteration and Nested Con-
trol Statements. Section 3.14’s objects-natural case study demonstrates using the open-
source Boost Multiprecision library’s cpp_int class to create super-sized integers.
Chapter 4, Control Statements: Part 2, presents C++’s other control statements—for,
do…while, switch, break and continue—and the logical operators. A key feature of this
chapter is its structured-programming summary. We introduce C++20’s format func-
tion, which provides powerful new text-formatting capabilities. Pre-C++20 text format-
ting is complex and verbose. The format function greatly simplifies data formatting using
a concise syntax based on the Python programming language’s text formatting. We present
a few C++20 text-formatting features throughout the book, then take a deeper look in
Chapter 19. In introductory computer science courses, instructors may wish to present
Section 19.9 after C++20 text formatting is introduced in Chapter 4. Section 4.14’s
objects-natural case study demonstrates using the open-source Boost Multiprecision
library’s cpp_dec_float_50 class for precise monetary calculations.
Chapter 5, Functions and an Intro to Function Templates, introduces custom functions.
We introduce random-number generation and simulation techniques and use them in our
first of several Random-Number Simulation case studies throughout the book to imple-
ment a popular casino dice game. We discuss C++’s secure library of random-number Sec
capabilities that can produce “nondeterministic” random numbers—a set of random
numbers that can’t be predicted. Such random-number generators are used in simulations
and security scenarios where predictability is undesirable. We also discuss passing infor-
mation between functions and how the function-call stack and stack frames support the
function call/return mechanism. We begin our rich treatment of the powerful computer
science topic of recursion.
Section 5.19’s objects-natural case study title—Pqyoaf X Nylfomigrob Qwbbfmh
Mndogvk: Rboqlrut yua Boklnxhmywex—looks like gibberish. This is not a mistake!
This case study continues our security emphasis by introducing cryptography, which is
critically important in today’s connected world. Every day, cryptography is used behind
the scenes to ensure that your Internet-based communications are private and secure.
You’ll use our implementation of the Vigenère secret-key cipher7 algorithm to encrypt and
decrypt messages and to decrypt this section’s title. Then, in Chapter 9’s objects-natural
case study, you’ll study our class that implements the Vigenère secret-key cipher using
classes and array-processing techniques. In Chapter 9 case study exercises, you’ll also
explore far more secure public-key cryptography with the RSA algorithm.
Chapter 8, strings, string_views, Text Files, CSV Files and Regex, presents many of the
standard library string class’s features; shows how to write text to and read text from both
plain text files and comma-separated values (CSV) files (popular for representing data science DS
datasets); and introduces string pattern matching with the standard library’s regular-expres-
sion capabilities. C++ offers two types of strings—string objects and C-style pointer-based
strings. We use string objects to make programs more robust and eliminate many of the
security problems of C strings. In new development, you should favor string objects. We Sec
also present C++17’s string_views—a lightweight, flexible mechanism for passing any type
of string to a function. This chapter presents two objects-natural case studies:
• Section 8.19 introduces data analytics by reading and analyzing a CSV file con- DS
taining the Titanic Disaster dataset.
• Section 8.20 introduces regular-expression pattern matching and text replace-
ment.
This chapter includes three AI/Data Science case study exercises. In the first case study, DS
Machine Learning with Simple Linear Regression: Statistics Can Be Deceiving, you’ll
learn that an essential aspect of data analytics is “getting to know your data.” One way to do
this is via descriptive statistics—but these can be deceiving. To illustrate this, we’ll consider
visualizations of Anscombe’s Quartet8 (Exercise 8.40)—a famous example of four dramati-
cally different datasets containing x–y coordinate pairs with nearly identical descriptive sta-
tistics. You’ll then study a completely coded example in which we use the popular AI/
machine-learning statistical technique called simple linear regression that, given a collection
of x–y coordinate pairs representing an independent variable (x) and a dependent variable
(y), determines the equation of a straight line (y = mx + b) that most closely fits the data. This
equation describes the relationship between the dependent and independent variables,
enabling us to predict y’s value for any given x. It also allows us to plot a regression line.
You’ll see that the regression lines for Anscombe’s Quartet are visually identical for all four
dramatically different datasets. The code you’ll study uses the popular open-source gnuplot
package to create attractive visualizations of Anscombe’s Quartet. The gnuplot package uses
its own plotting language, different from C++, so we provide extensive code comments that
explain the gnuplot commands.
In the AI/Data Science case study exercise, Machine Learning with Simple Linear DS
Regression: Time Series Analysis (Exercise 8.41), you’ll use what you learned in the preced-
ing exercise to analyze a time series, a sequence of values (called observations) associated
with points in time. Time series examples include daily closing stock prices, hourly tem-
perature readings, the changing positions of a plane in flight, annual crop yields and quar-
terly company profits. You’ll run a simple linear regression on 126 years of New York City
average January temperature data (stored in a CSV file) and use gnuplot to plot the data
and the regression line so you can determine if there is a cooling or warming trend.
This chapter’s final AI/Data Science case study (Exercise 8.42) presents an intro to DS
similarity detection with very basic natural language processing (NLP)—an important
data science and artificial intelligence topic. NLP helps computers understand, analyze and
process text. While writing this book, we used the paid (NLP) tool Grammarly9 to help
tune the writing and ensure the text’s readability for a broad audience. Some people believe
that the works of William Shakespeare actually might have been penned by Christopher
Marlowe or Sir Francis Bacon, among others.10,11 In this exercise, you’ll use array-, string-
and file-processing techniques to perform simple similarity detection on Shakespeare’s
Romeo and Juliet and Marlowe’s Edward the Second. You’ll determine how alike they are
by comparing the statistics you calculate, such as the percentages of each unique word
among all words in each play. You may be surprised by the results.
9. Grammarly has free and paid versions (https://www.grammarly.com). They provide free plug-ins
you can use in several popular web browsers.
10. “Did Shakespeare Really Write His Own Plays?” Accessed November 13, 2020. https://www.his-
tory.com/news/did-shakespeare-really-write-his-own-plays.
11. “Shakespeare authorship question.” Accessed November 13, 2020. https://en.wikipedia.org/
wiki/Shakespeare_authorship_question.
6 Tour of the Book xxxiii
Chapter 11, Operator Overloading, Copy/Move Semantics and Smart Pointers, shows
how to enable C++’s existing operators to work with custom class objects and introduces
smart pointers and dynamic memory management. Smart pointers help you avoid dynamic Err
memory management errors and “resource leaks” by providing additional functionality
beyond that of built-in pointers. We discuss unique_ptr in this chapter and shared_ptr and
weak_ptr in Chapter 20, Other Topics and a Look Toward the Future of C++.
A key aspect of Chapter 11 is crafting valuable classes. We begin with a string class
test-drive, presenting an elegant use of operator overloading before you implement your
own customized class with overloaded operators. Then, in our Crafting Valuable Classes
case study—one of the book’s most important examples—you’ll build your own custom
MyArray class using overloaded operators and other capabilities to solve various problems
with C++’s native pointer-based arrays.12 We introduce and implement the five special
member functions you can define in each class—the copy constructor, copy assignment
operator, move constructor, move assignment operator and destructor. We discuss copy
semantics and move semantics, which enable a compiler to move resources from one Perf
object to another to avoid costly, unnecessary copies. We introduce C++20’s three-way
comparison operator (<=>; also called the “spaceship operator”) and show how to imple-
ment custom conversion operators. In Chapter 15, you’ll convert a portion of the MyArray
class into a class template that can store elements of a specified type. You will then have
truly “crafted valuable classes.”
Chapter 12, Exceptions and a Look Forward to Contracts, continues our exception- Err
handling discussion that began in Chapter 6. We’ve enhanced Chapter 12’s coverage with
discussions of when to use exceptions, exception safety guarantees, and using exceptions
in the context of constructors and destructors. We show how to handle dynamic memory
allocation failures. We discuss why some libraries provide dual interfaces, enabling devel-
opers to choose whether to use versions of functions that throw exceptions or versions that
set error codes. The chapter concludes with a case study that introduces contracts—a pos-
sible C++26 feature. One goal of contracts is to make most functions noexcept—mean-
ing they do not throw exceptions—which might enable the compiler to perform
additional optimizations and eliminate the overhead and complexity of exception han- Perf
dling. Another goal is to find errors faster, eliminate them during development and,
hopefully, create more robust code for deployment. We introduce preconditions, post-
conditions and assertions, and we discuss how they can be implemented as contracts that
are tested at execution time. We demonstrate the example code using GCC’s experimental
contracts implementation on https://godbolt.org.
12. In industrial-strength systems, you’ll use standard library classes for this, but this example enables us
to go “under the hood” to demonstrate many key Modern C++ concepts.
xxxiv Preface
We’ll discuss containers, container adaptors and near containers. You’ll see that the C++
standard library provides commonly used data structures, so you do not need to create
your own—the vast majority of your data structures needs can be fulfilled by reusing
these standard library capabilities. We demonstrate most standard library containers and
introduce how iterators enable algorithms to be applied to various container types. We
continue showing how C++20 ranges can simplify your code.
This chapter presents the second of our two systems programming case study exer-
cises—Building Your Own Compiler. In the context of several exercises, you’ll build a
simple compiler that translates programs written in a small high-level programming lan-
guage into our Simpletron Machine Language (SML). You’ll write programs in this small
new high-level language, compile them on the compiler you build, then run them on your
Simpletron virtual machine you built in Chapter 7’s systems programming case study
exercise—Building Your Own Computer. And with Chapter 8’s file-processing tech-
niques, your compiler can write the generated machine-language code into a file from
which your Simpletron computer can then read your SML program, load it into the Sim-
pletron’s memory and execute it! This is a nice end-to-end systems-programming exercise
sequence for novice computing students.
Chapter 14, Standard Library Algorithms and C++20 Ranges & Views, presents many of
the standard library’s 115 algorithms, focusing on the C++20 range-based algorithms,
which are easier to use than their pre-C++20 versions. As you’ll see, range-based algo-
Concepts C rithms specify their requirements using C++20 concepts—a C++20 “big four” feature that
makes generic programming with templates more convenient and powerful. We briefly
introduce C++20 concepts as needed for you to understand the requirements for working
with these algorithms—Chapter 15 discusses concepts in more depth. Algorithms we pres-
ent include filling containers with values, generating values, comparing elements or entire
containers, removing elements, replacing elements, mathematical operations, searching,
sorting, swapping, copying, merging, set operations, and calculating minimums and maxi-
mums. We discuss each algorithm’s minimum iterator requirements so you can determine
which containers can be used with each algorithm. We also continue our discussion of C++’s
functional-style programming features with C++20 ranges and views.
A feature of this chapter is the Crafting Valuable Classes case study—you’ll reimple-
ment Chapter 11’s MyArray case study as a class template with custom iterators that enable
most C++ standard library algorithms to manipulate MyArray objects. We also define a
custom algorithm that can process MyArray elements and standard library container class
objects. We show that you can use concepts to overload functions based on the type
requirements of their parameters. Finally, we introduce template metaprogramming for
performing compile-time calculations, enabling you to improve a program’s execution-
time performance, possibly reducing both execution time and memory consumption.
Chapter 16, C++20 Modules, presents another of C++20’s “big four” features. Modules Mod
provide a new way to organize your code, precisely control which declarations you expose
to client code and encapsulate implementation details. Modules help you be more produc-
tive, especially when building, maintaining and evolving large software systems. Modules
help such systems build faster and make them more scalable. C++ creator Bjarne Stroustrup Perf
says, “Modules offer a historic opportunity to improve code hygiene and compile times for C++
(bringing C++ into the 21st century).”13 You’ll see that, even in small systems, modules offer
immediate benefits in every program by eliminating the need for the C++ preprocessor. In SE
several Software Engineering case studies, you’ll learn several ways to separate interface
from implementation using modules.
Chapter 17, Parallel Algorithms and Concurrency: A High-Level View, is the first of two Perf
extensive chapters on concurrency and multi-core programming. Chapter 17 is one of the
most important chapters in the book, presenting C++’s features for building applications
that create and manage multiple tasks. These can significantly improve program perfor-
mance and responsiveness on today’s multi-core processors.
This chapter presents several multithreading and multicore systems performance
case studies. In the Profiling Sequential and Parallel Sorting Algorithms case study, we
show how to use prepackaged parallel algorithms to create multithreaded programs that
will run faster (often much faster) on today’s multi-core computer architectures. For
example, we sort 100 million values using a sequential sort, then a parallel sort. We use
timing operations from C++’s <chrono> library features to profile the performance
improvement we get on today’s popular multi-core systems, as we employ more cores.
You’ll see that the parallel sort runs 6.76 times faster than the sequential sort on our
computer with an 8-core Intel processor.
In the Producer–Consumer: Synchronizing Access to Shared Mutable Data case stud-
ies, we discuss the producer–consumer relationship and demonstrate various ways to imple-
ment it using low-level and high-level C++ concurrency primitives. We also present several
Coordinating Threads case studies using C++20’s new latch, barrier and semaphore capa-
bilities. We emphasize that concurrent programming is difficult to get right, so you should
prefer the easier-to-use, higher-level concurrency features. Lower-level features like sema-
phores and atomics can be used to implement higher-level features like latches.
Chapter 18, C++20 Coroutines, is the second of our chapters on concurrency and multi-
core programming. This chapter presents coroutines—the last of C++20’s “big four” fea-
tures. A coroutine is a function that can suspend its execution and be resumed later,
13. Bjarne Stroustrup, “Modules and Macros.” February 11, 2018. Accessed March 8, 2023. http://
www.open-std.org/jtc1/sc22/wg21/docs/papers/2018/p0955r0.pdf.
xxxvi Preface
and algorithms (Chapter 14) coverage provides nice content for a course emphasizing
Modern C++ data structures.
At the time of this writing, Apple’s Xcode integrated development environment (IDE) did
not support various key C++20 features we use. Once these features become available in
Xcode, we’ll post Xcode instructions on the preceding website.
Docker
Docker is a tool for packaging software into containers that bundle everything required to
execute that software conveniently and portably across platforms. Docker provides a sim-
ple way to help you get started with new technologies quickly, conveniently and econom-
ically on your desktop or notebook computers. We show how to install and execute
Docker containers preconfigured with
• the GNU Compiler Collection (GCC), which includes the g++ compiler, and
• the latest version of Clang’s clang++ compiler.
Each can run in Docker on Windows, macOS and Linux, enabling users to try the latest
versions of these compilers. Chapter 1 includes test-drives showing how to compile pro-
grams and run them in the context of cross-platform Docker containers.
• Microsoft’s C++ Core Guidelines static code analysis tools, which are built into
Visual Studio’s static code analyzer
We used these three tools on all the book’s code examples to check for
• adherence to the C++ Core Guidelines,
• adherence to coding standards,
• adherence to modern C++ idioms,
• possible security problems,
• common bugs,
• possible performance issues,
• code readability
• and more.
We also used the compiler flag -Wall in the GNU g++ and LLVM clang++ compilers to
enable all compiler warnings. Most of our programs compile without warning messages.
See the Before You Begin section that follows this Preface for information on configuring
the C++ Core Guidelines checker in Microsoft Visual C++.
You’ll work with such popular websites as GitHub and StackOverflow, and you’ll do lots
of Internet research.
• StackOverflow is one of the most popular programming question-and-answer
sites. Many problems you might encounter have already been discussed here. It’s
a great place to ask code-oriented questions. Many of our Google searches for var-
ious, often complex, issues throughout our writing effort returned StackOverflow
posts as their first results.
• GitHub is an excellent venue for finding free, open-source code to explore and
incorporate into your projects—and for you to contribute your code to the open-
source community if you like. One hundred million developers use GitHub.15
The site hosts over 330 million repositories for code in many programming lan-
guages16—developers made 413 million contributions to repositories in 2022.17
14. William Gates, quoted in Programmers at Work: Interviews With 19 Programmers Who Shaped the
Computer Industry by Susan Lammers. Microsoft Press, 1986, p. 83.
15. “Let’s build from here: The complete developer platform to build, scale, and deliver secure software.”
Accessed March 8, 2023. https://github.com/about.
16. “Let’s build from here: The complete developer platform to build, scale, and deliver secure software.”
Accessed March 8, 2023. https://github.com/about.
17. “OCTOVERSE 2022: The state of open source software.” Accessed March 8, 2023. https://oc-
toverse.github.com.
9 Computing and Data Science Curricula xxxix
Computing Curricula
• According to “CC2020: A Vision on Computing Curricula,”27 the curriculum
“needs to be reviewed and updated to include the new and emerging areas of
computing such as cybersecurity and data science.”28
11 Appendices on Deitel.com
On the textbook’s webpage at https://deitel.com/cpphtp11, we provide several appen-
dices to support the book:
27. A. Clear, A. Parrish, G. van der Veer and M. Zhang, “CC2020: A Vision on Computing Curricula,”
https://dl.acm.org/citation.cfm?id=3017690.
28. http://delivery.acm.org/10.1145/3020000/3017690/p647-clear.pdf.
29. This section is intended primarily for data science instructors but includes important information
for computer science instructors as well.
30. “Curriculum Guidelines for Undergraduate Programs in Data Science,” http://www.annualre-
views.org/doi/full/10.1146/annurev-statistics-060116-053930.
31. “Appendix—Detailed Courses for a Proposed Data Science Major,” http://www.annualre-
views.org/doi/suppl/10.1146/annurev-statistics-060116-053930/suppl_file/
st04_de_veaux_supmat.pdf.
12 C++ Core Guidelines xli
• Appendix A, Character Set, contains the letters, digits and symbols of the ASCII
character set.
• Appendix B, Number Systems, overviews the binary, octal, decimal and hexadec-
imal number systems.
• Appendix C, Preprocessor, discusses additional features of the C++ preprocessor.
Template metaprogramming (Chapter 15) and C++20 Modules (Chapter 16)
eliminate the need for many of this appendix’s features.
• Appendix D, Bit Manipulation, discusses bitwise operators for manipulating the
individual bits of integral operands and bit fields for compactly representing inte-
ger data.
Other Web-Based Materials on deitel.com
The book’s webpage also contains:
• Links to our GitHub repository containing the downloadable C++ source code
• Blog posts—https://deitel.com/blog
• Book updates
For more information about downloading the code examples and setting up your C++
development environment, see the Before You Begin section that follows this Preface.
are recommendations “to help people use modern C++ effectively.”32 They’re edited by
Bjarne Stroustrup (C++’s creator) and Herb Sutter (Convener of the ISO C++ Standards
Committee). According to the overview:
“The guidelines are focused on relatively high-level issues, such as interfaces,
resource management, memory management, and concurrency. Such rules affect
application architecture and library design. Following the rules will lead to code SE
that is statically type safe, has no resource leaks, and catches many more program-
Err
ming logic errors than is common in code today. And it will run fast—you can
afford to do things right.”33 Perf
Throughout this book, we adhere to these guidelines as appropriate. You’ll want to pay
close attention to their wisdom. We point out many C++ Core Guidelines recommenda- CG
tions with a CG icon. There are hundreds of core guidelines divided into scores of catego-
ries and subcategories. Though this might seem overwhelming, the static code analysis
tools we discussed earlier can check your code against the guidelines.
For your convenience, we include with the book’s code examples the version of this library
that we used in a few examples. Some GSL features have been incorporated into the C++
standard library.
Syntax Coloring
For readability, we syntax color all the code. Our e-book syntax-coloring conventions are:
comments appear in green
keywords appear in dark blue
constants and literal values appear in light blue
errors appear in red
all other code appears in black
Index
For convenient reference, we’ve included an extensive index, with defining occurrences of
key terms highlighted with a bold page number.
34. C++ Core Guidelines, “GSL: Guidelines Support Library.” Accessed March 8, 2023. https://iso-
cpp.github.io/CppCoreGuidelines/CppCoreGuidelines#S-gsl.
13 Pedagogic Features and Conventions xliii
• You’ll attack exciting and entertaining challenges in our larger case studies, such
as building a casino game, building your own computer (using simulation to
build a virtual machine), using AI/data-science technologies such as basic natural
language processing, building your own compiler, writing multithreaded code to
take advantage of today’s multicore computer architectures to get the best perfor-
mance from your computer and many more.
• Research and project exercises ask you to go deeper into what you’ve learned and
explore other technologies. We encourage you to use computers and the Internet
to solve significant problems. Projects are often more elaborate than the exer-
cises—some might require days or weeks of implementation effort. Many are
appropriate for class projects, term projects, directed-study courses, capstone-
course projects and thesis research. We do not provide solutions for the projects.
• We’ve enhanced existing case studies and added new ones focusing on AI and
DS data science, including simulations with random-number generation, Ans-
combe’s Quartet, natural language processing (NLP) and artificial intelligence via
heuristic programming.
• Instructors can tailor their courses to their audience’s unique requirements and
vary labs and exam questions each semester.
Extensive Videos
In the Pearson interactive eText and Revel versions of this book, we provide extensive vid-
eos in which Paul Deitel discusses the material in the Before You Begin section and
Chapters 1–10.
Glossary Items
In the Pearson interactive eText and Revel versions of the book, we added over 300 glos-
sary items for the core computer science chapters (1–12 and 21). These are also used in
student learning tools to create flashcards and matching exercises.
Perf Performance
Software developers prefer C++ (and C) for performance-intensive operating systems, real-
time systems, embedded systems, game systems and communications systems, so we focus
on performance issues.
Data Experiences DS
In Chapter 9, you’ll work with real-world text data. You’ll read and analyze the Titanic
Disaster dataset—popular for introducing data analytics. Datasets are often stored in CSV
(comma-separated values) files, which we introduce in Chapter 9. You’ll also download
and analyze Shakespeare’s play Romeo and Juliet and Christopher Marlowe’s play Edward
the Second from Project Gutenberg—a source of free downloadable texts for analysis. The
site contains over 60,000 e-books in various formats, including plain-text files—these are
out of copyright in the United States.
Privacy
The ACM/IEEE’s curricula recommendations36 for Computer Science, Information
Technology and Cybersecurity mention privacy over 200 times. Every programming stu-
dent and professional needs to be acutely aware of privacy issues and concerns. Students
research privacy in four exercises in Chapters 1 and 3. We also discuss cryptography, which
is critical in maintaining privacy, in Chapters 5 and 10.
In Chapter 1’s exercises, you’ll start thinking about these issues by researching ever-
stricter privacy laws such as HIPAA (Health Insurance Portability and Accountability
Act), the California Consumer Privacy Act (CCPA) in the United States and GDPR (Gen-
eral Data Protection Regulation) for the European Union.
Ethics
The ACM’s curricula recommendations37 for Computer Science, Information Technol-
ogy and Cybersecurity mention ethics more than 100 times. In several Chapter 1 exercises,
you’ll focus on ethics issues via Internet research. You’ll investigate privacy and ethical
issues surrounding intelligent assistants, such as Amazon Alexa, Apple Siri, Google Assis-
tant and Microsoft Cortana. And we’ll look at the excitement and controversy surround-
ing OpenAI’s ChatGPT38 and Dall-E 2.39
14 Instructor Supplements
The following supplements are available only to qualified instructors through Pearson
Education’s Instructor Resource Center (https://pearsonhighered.com/irc):
• The Instructor Solutions Manual contains solutions to most of the end-of-chap-
ter exercises. Solutions are not provided for “project” exercises.
• A Test Item File containing multiple-choice questions and answers.
• Lecture slides containing diagrams, tables and bulleted items summarizing key
points in the text.
The lecture slides do not include the source code—the source-code files40 for the hun-
dreds of live-code examples are available to instructors and students in the book’s GitHub
repository at
https://github.com/pdeitel/CPlusPlusHowToProgram11e
If you’re not a GitHub user, click the green Code button and select Download ZIP to down-
load a ZIP file containing the code. See the Before You Begin section for more information.
Please do not write to us requesting access to the Pearson Instructor’s Resource
Center. Access is restricted to college instructors who have adopted the book for their
courses. Instructors may obtain access only through their Pearson representatives. If
you’re not a registered faculty member, contact your Pearson representative or visit
https://pearson.com/replocator
The C++ standard committee’s evolving working draft (currently C++23) is available at:
https://eel.is/c++draft/
You may also find the following C++ resources helpful as you work through the book.
Documentation
• C++ Reference at https://cppreference.com/
• Microsoft’s C++ language documentation: https://docs.microsoft.com/en-us/
cpp/cpp/
• https://www.reddit.com/r/cpp/
• https://groups.google.com/g/comp.lang.c++
40. We recommend that instructors present source code in their favorite C++ integrated development
environments (IDEs) or code-oriented text editors. These typically provide customizable syntax
highlighting and adjustable font sizes for presentation purposes.
17 Join the Deitel & Associates, Inc. Social Media Communities xlvii
Also, vendors often provide forums for their tools and libraries. Many libraries are man-
aged and maintained at github.com. Some library maintainers provide support through
the Issues tab on a given library’s GitHub page.
20 Acknowledgments
We’d like to thank Barbara Deitel for long hours devoted to Internet research on this proj-
ect. We’re fortunate to have worked with the dedicated team of publishing professionals
at Pearson. We appreciate the guidance, wisdom, energy and editorial savvy of Tracy John-
son (Pearson Education, Global Content Manager, Computer Science)—on all our aca-
demic publications. She challenges us at every step of the process to “get it right” and make
the best books. Bob Engelhardt managed the book’s production. Erin Sullivan recruited
and managed the academic reviewers; Charvi Arora recruited and managed the profes-
sional reviewers. We selected the cover art, and Chuti Prasertsith designed the cover, add-
ing his special touch of graphics magic.
Reviewers
We were fortunate on this project to have 14 distinguished academics and professionals
review the manuscript. Most of the professional reviewers are either on the ISO C++ Stan-
dards Committee, have served on it or have a working relationship with it. Many have con-
tributed features to the language. They helped us make a better book—any remaining
flaws are our own.
Academic Review Team—Prof. Jeffrey Davis, School of Electrical and Computer
Engineering, Georgia Institute of Technology; M. Michael Hadavi, The MathWorks,
Inc., MET Computer Science at Boston University; Dr. Ningfang Mi, Associate Professor
20 Acknowledgments xlix
of Electrical and Computer Engineering, Northeastern University; Prof. Patrice Roy, Uni-
versité de Sherbrooke, ISO C++ Standards Committee Member.
Professional Review Team—Andreas Fertig, Independent C++ Trainer and Consul-
tant, Creator of cppinsights.io, Author of Programming with C++20; Marc Gregoire,
Software Architect, Nikon Metrology, Microsoft Visual C++ MVP and author of Profes-
sional C++, 5/e; Dr. Daisy Hollman, ISO C++ Standards Committee Member; Danny
Kalev, Ph.D. and Certified System Analyst and Software Engineer, Former ISO C++ Stan-
dards Committee Member; Dietmar Kühl, Senior Software Developer, Bloomberg L.P.,
ISO C++ Standard Committee Member; Inbal Levi, SolarEdge Technologies, ISO C++
Foundation director, ISO C++ SG9 (Ranges) chair, ISO C++ Standards Committee mem-
ber; Arthur O’Dwyer, C++ trainer, Chair of CppCon’s Back to Basics track, author of sev-
eral accepted C++17/20/23 proposals and the book Mastering the C++17 STL; Saar Raz,
Senior Software Engineer, Swimm.io and Implementor of C++20 Concepts in Clang; José
Antonio González Seco, Parliament of Andalusia; Anthony Williams, Member of the Brit-
ish Standards Institution C++ Standards Panel, Director of Just Software Solutions Ltd.,
Author of C++ Concurrency in Action, 2/e (Anthony is the author or co-author of many C++
Standard Committee papers that led to C++’s standardized concurrency features).
Google Search
Thanks to Google, whose search engine answers our constant stream of queries, each in a
fraction of a second, at any time—and at no charge. It’s the single best productivity
enhancement tool we’ve added to our research process in the last 20 years.
Grammarly
We use the paid version of Grammarly on all our manuscripts. They describe their tools
as helping you “compose bold, clear, mistake-free writing” with their “AI-powered writing
assistant.”41 Grammarly also provides free tools that you can integrate into several popular
web browsers, Microsoft® Office 365™ and Google Docs™.
As you read the book and work through the code examples, we’d appreciate your com-
ments, criticisms, corrections and suggestions for improvement. Please send all correspon-
dence, including questions, to
[email protected]
To learn more about Deitel virtual and on-site corporate training, visit
https://deitel.com/training
Bulk orders by corporations, the government, the military and academic institutions
should be placed directly with Pearson. For corporate and government sales, send an email
to
[email protected]
If you’re familiar with Git and GitHub, clone the repository to your system. If you’re not
a GitHub user, click the green Code button and select Download ZIP to download a ZIP
file containing the code. To extract the ZIP file’s contents:
• Windows: Right-click the ZIP file, select Extract All…, select your user account’s
Documentsfolder, then click Extract.
• macOS: Move the ZIP file to your user account’s Documents folder, then double-
click the ZIP file.
• Linux (varies by distribution): When you download the ZIP file on Ubuntu
Linux, you can choose to open the file with the Archive Manager or save it.
Choose Archive Manager, then click Extract in the window that appears. Select
your user account’s Documents folder, then click Extract again.
Throughout the book, our instructions assume the code examples reside in your user
account’s Documents folder in a subfolder named examples.
If you’re not familiar with Git and GitHub but are interested in learning about these
essential developer tools, check out
https://guides.github.com/activities/hello-world/
liv Before You Begin
Compilers We Use
Ensure that you have a recent C++ compiler installed. We tested the book’s code examples
using the following free compilers:
• For Microsoft Windows, we used Microsoft Visual Studio Community edition,
which includes the Visual C++ compiler and other Microsoft development tools.
• For Linux, we used the GNU C++ compiler (g++)1—part of the GNU Compiler
Collection (GCC). Typically, a version of GNU C++ is pre-installed on most
Linux systems. You might need to update the compiler to a more recent version.
GNU C++ also can be installed on macOS and Windows systems.
• For macOS, we used both the GNU C++ compiler (g++) and the Apple Xcode2
C++ compiler, which uses a version of the LLVM Clang C++ compiler (clang++).
• You can run the latest versions of GNU C++ (g++) and LLVM Clang C++
(clang++)3 conveniently on Windows, macOS and Linux via Docker containers.
See the “Docker and Docker Containers” section in this Before You Begin section.
At the time of this writing, Apple Xcode does not support several key C++20 features
we use throughout this book, so we recommend using the most recent version of g++.
When Xcode’s C++20 support changes, we’ll post updates at
https://deitel.com/cpphtp11
This Before You Begin describes installing the compilers and Docker. Section 1.11’s test-
drives demonstrate how to compile and run C++ programs using these compilers.
Next, go to
https://visualstudio.microsoft.com/downloads/
5. For this book’s examples, select the option Desktop Development with C++, which
includes the Visual C++ compiler and the C++ standard libraries.
6. Click Install. The installation process can take a significant amount of time.
Installing Docker
To use a Docker container, you must first install Docker. Windows and macOS users
should download and run the Docker Desktop installer from
https://www.docker.com/get-started
lvi Before You Begin
Then follow the on-screen instructions. Also, sign up for a Docker Hub account on this site,
which gives you access to the many containers at https://hub.docker.com. Linux users
should install Docker Engine from
https://docs.docker.com/engine/install/
Once Docker is installed and running, open a Command Prompt4 (Windows), Terminal
(macOS/Linux) or shell (Linux), then execute the command
docker pull gcc:latest
Docker downloads a container configured with the GNU Compiler Collection (GCC)’s
most current version—13.1 at the time of this writing. In one of Section 1.11’s test-drives,
we’ll demonstrate how to execute the container and use it to compile and run C++ programs.
Docker downloads a container configured with LLVM Clang’s most current version—16
at the time of this writing. In one of Section 1.11’s test-drives, we’ll demonstrate how to
execute the container and use it to compile and run C++ programs.
4. Windows users should choose Run as administrator when opening the Command Prompt.
Online C++ Documentation lvii
• cppcheck—https://cppcheck.sourceforge.io/
• Microsoft’s C++ Core Guidelines static code analysis tools, which are built into
Visual Studio’s static code analyzer
You can install clang-tidy on Linux with the following commands:
sudo apt-get update -y
sudo apt-get install -y clang-tidy
You can install cppcheck for various operating-system platforms by following the instruc-
tions at https://cppcheck.sourceforge.io/.
For Visual C++, once you learn how to create a project in Section 1.11’s test-drives,
you can configure Microsoft’s C++ Core Guidelines static code analysis tools as follows:
1. Right-click your project name in the Solution Explorer and select Properties.
2. In the dialog that appears, select Code Analysis > General in the left column, then
set Enable Code Analysis on Build to Yes in the right column.
3. Next, select Code Analysis > Microsoft in the left column. Then, in the right col-
umn, you can select a subset of the analysis rules from the drop-down list. We
used the option <Choose multiple rule sets…> to select all the rules that begin
with C++ Core Check. Click Save As…, give your custom rule set a name, click
Save, then click Apply.
This page intentionally left blank
Intro to Computers and C++ 1
Objectives
In this chapter, you’ll:
■ Learn computer hardware,
software and Internet basics.
■ Understand a data hierarchy
from bits to databases.
■ Understand the types of
programming languages.
■ Understand the strengths of
C++ and other languages.
■ Be introduced to the C++
standard library of reusable
components.
■ Compile and run a C++
application using our three
preferred compilers and
Docker containers.
■ Be introduced to object-
technology concepts used in
the objects-natural case studies
(Chapters 2–9) and discussed
in detail in the object-oriented
programming Chapters 9–11.
■ Understand how concurrent
programming helps maximize
performance on multi-core
processors.
■ Be introduced to big data and
data science.
■ Learn about exciting recent
developments in computing,
including the Metaverse,
artificial intelligence and
related technologies.
2 Chapter 1 Intro to Computers and C++
Outline
1.1 Introduction 1.12.1 The Internet: A Network of Networks
1.2 Hardware 1.12.2 The World Wide Web: Making the
Internet User-Friendly
1.2.1 Computer Organization
1.12.3 The Cloud
1.2.2 Moore’s Law, Multi-Core Processors
and Concurrent Programming 1.12.4 The Internet of Things (IoT)
1.12.5 Edge Computing
1.3 Data Hierarchies 1.12.6 Mashups
1.4 Machine Languages, Assembly 1.13 Metaverse
Languages and High-Level Languages 1.13.1 Virtual Reality (VR)
1.5 Operating Systems 1.13.2 Augmented Reality (AR)
1.6 C and C++ 1.13.3 Mixed Reality
1.13.4 Blockchain
1.7 C++ Standard Library and Open- 1.13.5 Bitcoin and Cryptocurrency
Source Libraries 1.13.6 Ethereum
1.8 Other Popular Programming 1.13.7 Non-Fungible Tokens (NFTs)
Languages 1.13.8 Web3
1.9 Introduction to Object Orientation 1.14 Software Development Technologies
1.10 Simplified View of a C++ 1.15 How Big Is Big Data?
Development Environment 1.15.1 Big-Data Analytics
1.15.2 Data Science and Big Data Are Making
1.11 Test-Driving a C++20 Application a Difference: Use Cases
Various Ways 1.16 AI—at the Intersection of Computer
1.11.1 Compiling and Running on Windows Science and Data Science
with Visual Studio Community Edition
1.16.1 Artificial Intelligence (AI)
1.11.2 Compiling and Running with GNU
C++ on Linux 1.16.2 Artificial General Intelligence (AGI)
1.11.3 Compiling and Running with g++ in 1.16.3 Artificial Intelligence Milestones
the GCC Docker Container 1.16.4 Machine Learning
1.11.4 Compiling and Running with 1.16.5 Deep Learning
clang++ in a Docker Container 1.16.6 Reinforcement Learning
1.11.5 Compiling and Running with Xcode 1.16.7 Generative AI—ChatGPT and Dall-E 2
on macOS 1.17 Wrap-Up
1.12 Internet, World Wide Web, the Exercises
Cloud and IoT
1.1 Introduction
Welcome to C++—one of the world’s most senior computer programming languages and,
according to various programming-language rankings, one of the world’s most popu-
lar.1,2,3 You’re probably familiar with many of the powerful tasks computers perform. This
textbook provides an intensive, hands-on experience in which you’ll write C++ instructions
that command computers to perform many of those and other tasks. Software—the C++
instructions you write, which also are called code—controls hardware (that is, computers
and related devices).
C++ is widely used in industry.4 Portions of today’s most popular desktop operating
systems—Windows5 and macOS6—are written in C++. Many applications and systems
are partially written in C++, including popular web browsers (e.g., Google Chrome7 and
Mozilla Firefox8), database management systems (e.g., Microsoft SQL Server9, Oracle10,
MySQL11), Adobe’s creative applications, Amazon.com, Bloomberg, Facebook, various
Microsoft apps (including Office and Visual Studio) and much more.12
The chapter introduces terminology and concepts that lay the groundwork for the
C++ programming you’ll learn, beginning in Chapter 2. We introduce hardware and soft-
ware concepts. We overview a sample data hierarchy—from bits (ones and zeros) to data-
bases, which store the massive amounts of data that organizations need to implement
contemporary applications such as Google Search, Netflix, Twitter, Waze, Uber, Airbnb
and a myriad of others.
We discuss the types of programming languages. We introduce the C++ standard
library and various C++ “open-source” libraries that help you avoid “reinventing the
wheel”—you’ll write only modest numbers of C++ instructions to make these libraries per-
form powerful tasks.
We overview additional technologies you’ll likely use as you build software in your
career. We discuss the Internet, the web, the cloud and the Internet of Things (IoT). We
introduce the Metaverse and its related technologies—blockchain, cryptocurrencies, NFTs,
Web3, augmented reality, virtual reality and mixed reality. Finally, we introduce big data,
data science and artificial intelligence (AI) technologies—machine learning, deep learning
and generative AIs like the recently introduced to much excitement ChatGPT and Dall-E 2.
Compilers
You can compile, build and run C++ applications in many development environments.
You’ll work through one or more of Section 1.11’s test-drives showing how to compile
and execute C++ code using:
• Microsoft Visual Studio Community edition for Windows.
• GNU g++ in a macOS Terminal window or Linux shell.
• LLVM clang++ in a macOS Terminal window or a Linux shell.
4. “C++.” Wikipedia. Wikimedia Foundation. Accessed March 18, 2023. https://en.wikipe-
dia.org/wiki/C%2B%2B.
5. “Windows 11.” Wikipedia. Wikimedia Foundation, Accessed March 18, 2023. https://en.wiki-
pedia.org/wiki/Windows_11.
6. “macOS.” Wikipedia. Wikimedia Foundation, Accessed March 18, 2023. https://en.wikipe-
dia.org/wiki/MacOS.
7. “Google Chrome.” Wikipedia. Wikimedia Foundation. Accessed March 18, 2023. https://
en.wikipedia.org/wiki/Google_Chrome.
8. “Firefox.” Wikipedia. Wikimedia Foundation. Accessed March 18, 2023. https://en.wikipe-
dia.org/wiki/Firefox.
9. “Microsoft SQL Server.” Wikipedia. Wikimedia Foundation. Accessed March 18, 2023. https://
en.wikipedia.org/wiki/Microsoft_SQL_Server.
10. “Oracle Database.” Wikipedia. Wikimedia Foundation. Accessed March 18, 2023. https://
en.wikipedia.org/wiki/Oracle_Database.
11. “MySQL.” Wikipedia. Wikimedia Foundation. Accessed March 18, 2023. https://en.wikipe-
dia.org/wiki/MySQL.
12. Bjarne Stroustrup, “C++ Applications.” Accessed March 18. 2023. https://www.stroustrup.com/
applications.html.
4 Chapter 1 Intro to Computers and C++
In addition, we’ll introduce Docker and show how to use g++ and clang++ in Docker con-
tainers that can execute on Windows, macOS or Linux. Docker is particularly important
for this book’s macOS users. Apple’s Xcode environment does not yet support several key
C++20 features we use throughout the book. Docker will enable macOS users (and Win-
dows and Linux users) to compile C++ programs with the latest g++ and clang++ versions.
You may want to read only the test-drive(s) required for your course or projects in industry.
• The preceding website also contains a concise introduction to the book, a bullet
list of its key features and testimonial comments from university professors and
C++ subject-matter experts who reviewed the prepublication manuscript.
• The Preface presents the “soul of the book” and our approach to Modern C++
programming. We introduce the early chapters’ “objects-natural approach,” in
which you’ll use small numbers of simple C++ statements to make powerful exist-
ing classes perform significant tasks—long before you learn how to create your
own custom classes in Chapter 9. Be sure to read the Tour of the Book, which
points out the key features of each chapter and enumerates the book’s 50 more
substantial case studies and case-study exercises. As you read the Tour, you might
also want to refer to the Table of Contents diagram.
1.2 Hardware
Computers process data under the control of instructions called programs. These guide
the computer through ordered actions specified by people called computer programmers.
A computer’s hardware consists of various physical devices, such as the keyboard,
screen, mouse, solid-state disks, memory and processing units. Computing costs are drop-
ping dramatically due to rapid developments in hardware and software technologies.
Computers that might have filled large rooms and cost millions of dollars decades ago are
now inscribed on silicon computer chips smaller than a fingernail, costing perhaps a few
dollars each. Ironically, silicon is one of the most abundant materials on Earth—it’s an
ingredient in ordinary sand. Silicon-chip technology has made computing so economical
that computers and computerized devices have become commodities.
Input Unit
This “receiving” section obtains information (data and computer programs) from input
devices and places it at the other units’ disposal for processing. Computers receive most user
input through keyboards, touch screens, mice and touchpads. Other forms of input include:
• receiving voice commands,
• scanning images, barcodes or QR codes,
• reading data from secondary storage devices (such as solid-state drives, Blu-ray
Disc™ drives and USB flash drives—also called “thumb drives” or “memory
sticks”),
• receiving video from a webcam,
• receiving information from the Internet (such as when you stream videos from
YouTube® or download e-books from Amazon),
• receiving position data from a GPS device,
• receiving motion and orientation information from an accelerometer (a device
that responds to up/down, left/right and forward/backward acceleration) in a
smartphone or wireless game controllers, such as those for Microsoft® Xbox®,
Nintendo Switch® and Sony® PlayStation®, and
• receiving voice input from intelligent assistants like Apple® Siri®, Amazon®
Alexa®, Microsoft® Cortana® and Google Home™.
Output Unit
This “shipping” section takes the information the computer has processed and places it on
various output devices to make it available outside the computer. Most information that’s
output from computers today is
• displayed on screens,
• printed on paper (“going green” discourages this),
• printed on 3D printers,
• played as audio or video on smartphones, tablets, PCs and giant screens in sports
stadiums,
• transmitted over the Internet, or
• used to control other devices, such as self-driving cars, robots and “intelligent”
appliances.
Information is also commonly output to secondary storage devices, such as solid-state
drives (SSDs), hard drives, USB flash drives and DVD drives. Popular recent forms of out-
put are smartphone and game-controller vibration, virtual reality devices like Meta
Quest® 2, Meta Quest® Pro, Sony® PlayStation® VR and Samsung Gear VR®, and
mixed reality devices like Magic Leap® 2 and Microsoft HoloLens® 2.
Memory Unit
This rapid-access, relatively low-capacity “warehouse” section retains information entered
through the input unit, making it immediately available for processing when needed. The
6 Chapter 1 Intro to Computers and C++
memory unit also retains processed information until the output unit can place it on output
devices. Information in the memory unit is volatile—it’s typically lost when the computer’s
power is turned off. The memory unit is often called either memory, primary memory or
RAM (Random Access Memory). Main memories on desktop and notebook computers
contain as much as 128 GB of RAM, though 8 to 32 GB is most common. GB stands for
gigabytes; a gigabyte is approximately one billion bytes. A byte is eight bits. A bit (short for
“binary digit”) is either a 0 or a 1.
13. “History of hard disk drives.” Wikipedia. Wikimedia Foundation. Accessed March 18, 2023. https://
en.wikipedia.org/wiki/History_of_hard_disk_drives.
14. Desire Athow. “Largest SSDs and hard drives of 2023.” Accessed March 18, 2023. https://
www.techradar.com/best/large-hard-drives-and-ssds.
1.2 Hardware 7
Checkpoint
1 (True/False) Information in the memory unit is persistent—it’s preserved even when
the computer’s power is turned off
Answer: False. Information in the memory unit is volatile—it’s typically lost when the
computer’s power is turned off.
2 (Fill-In) Most computers today have processors that implement multiple
processors on a single integrated-circuit chip. Such processors can perform many opera-
tions simultaneously.
Answer: multi-core.
Moore’s Law
You probably expect to pay at least a little more every year for most products and services.
The opposite has been the case in the computer and communications fields, especially
with regard to the hardware supporting these technologies. Over the years, hardware costs
have fallen rapidly.
For decades, computer processing power approximately doubled inexpensively every Perf
couple of years. This remarkable trend is called Moore’s law, named for Gordon Moore,
co-founder of Intel and the person who identified the trend in the 1960s. Intel is a leading
manufacturer of processors in today’s computers and embedded systems, such as smart
home appliances, home security systems, robots, intelligent traffic intersections and more.
Moore’s law and related observations apply especially to:
• the amount of memory that computers have for programs and data,
• the amount of secondary storage they have to hold programs and data, and
• their processor speeds—that is, the speeds at which computers execute programs
to do their work.
Key executives at computer-processor companies NVIDIA and ARM have indicated
that Moore’s Law no longer applies. However, Intel’s CEO says it is “alive and well”—
15. “Top 500.” Wikipedia. Wikimedia Foundation. Accessed March 18, 2023. https://en.wikipe-
dia.org/wiki/TOP500#TOP_500.
16. “Flops.” Wikipedia. Wikimedia Foundation. Accessed March 18, 2023. https://en.wikipe-
dia.org/wiki/FLOPS.
17. For perspective on how far computing performance has come, consider this: In his early computing
days in the 1960s, one of the authors, Harvey Deitel, used the Digital Equipment Corporation PDP-1
(https://en.wikipedia.org/wiki/PDP-1), which was capable of performing only 93,458 operations
per second, and the IBM 1401 (http://www.ibm-1401.info/1401GuidePosterV9.html), which per-
formed only 86,957 operations per second.
8 Chapter 1 Intro to Computers and C++
they are working on manufacturing advances that will enable more transistors on each
chip.18,19 Computer processing power continues to increase but relies on new processor
designs, such as multi-core processors (Section 1.2.1).
18. Esther Shein. “Moore’s Law turns 55: Is it still relevant?” April 17. 2020. Accessed March 18, 2023.
https://www.techrepublic.com/article/moores-law-turns-55-is-it-still-relevant.
19. Leswing, Kif. “Intel says Moore’s Law is still alive and well. Nvidia says it’s ended.” September 27,
2022. Accessed March 18, 2023. https://www.cnbc.com/2022/09/27/intel-says-moores-law-
is-still-alive-nvidia-says-its-ended.html.
20. “Apple unveils M2 Pro and M2 Max: next-generation chips for next-level workflows,” January 23,
2023. Accessed March 18, 2023. https://www.apple.com/newsroom/2023/01/apple-unveils-
m2-pro-and-m2-max-next-generation-chips-for-next-level-workflows/.
21. Anton Shilov, “Intel's Sapphire Rapids Could Have 72-80 Cores, According to New Die Shots.”
April 30, 2021. Accessed March 18, 2023. https://www.tomshardware.com/news/intel-sap-
phire-rapids-could-feature-80-cores.
22. Anthony Garreffa, “AMD EPYC 'Venice' CPU: Zen 6 with 256 cores, 512 threads... or MORE!”
May 22, 2022. Accessed March 18, 2023. https://www.tweaktown.com/news/85915/amd-epyc-
venice-cpu-zen-6-with-256-cores-512-threads-or-more/index.html.
23. “NVIDIA GeForce RTX 4090 Ti rumored to feature 18176 cores and 24GB/24Gbps memory.”
Accessed March 18, 2023. https://videocardz.com/newz/nvidia-geforce-rtx-4090-ti-
rumored-to-feature-18176-cores-and-24gb-24gbps-memory.
1.2 Hardware 9
Checkpoint
1 (Fill-In) For many decades, every year or two, computers’ capacities have approxi-
mately doubled inexpensively. This remarkable trend often is called .
Answer: Moore’s Law.
2 (Fill-In) Taking full advantage of multi-core architecture requires writing .
Answer: multithreaded applications.
24. “Top 500.” Wikipedia. Wikimedia Foundation. Accessed March 18, 2023. https://en.wikipe-
dia.org/wiki/TOP500#TOP_500.
25. “Frontier (supercomputer).” Wikipedia. Wikimedia Foundation. Accessed March 18, 2023. https://
en.wikipedia.org/wiki/Frontier_(supercomputer).
26. “Flops.” Wikipedia. Wikimedia Foundation. Accessed March 18, 2023. https://en.wikipe-
dia.org/wiki/FLOPS.
27. “A new supercomputing-powered weather model may ready us for Exascale.” Accessed March 18, 2023.
https://www.ibm.com/blogs/research/2017/06/supercomputing-weather-model-exascale/.
28. Norbert Biedrzycki, “Only God can count that fast — the world of quantum computing.” May 12,
2017. Accessed March 18, 2023. https://medium.com/@n.biedrzycki/only-god-can-count-
that-fast-the-world-of-quantum-computing-406a0a91fcf4.
29. “Blockchain.” Wikipedia. Wikimedia Foundation. Accessed March 18, 2023. https://en.wikipe-
dia.org/wiki/Blockchain.
30. Nathana Sharma, “Is Quantum Computing an Existential Threat to Blockchain Technology?”
November 5, 2017. Accessed March 18, 2023. https://singularityhub.com/2017/11/05/is-
quantum-computing-an-existential-threat-to-blockchain-technology/.
10 Chapter 1 Intro to Computers and C++
Matis Laurent
Edward Uwimana
Adriana Santos
Jacob Brown
J a z m i n Field
1 Bit
Bits
A bit is short for “binary digit”—a digit that can assume one of two values, 0 or 1—and is
a computer’s smallest data item. Remarkably, computers’ impressive functions involve
only the simplest manipulations of 0s and 1s—examining a bit’s value, setting a bit’s value
and reversing a bit’s value (from 1 to 0 or 0 to 1). Bits form the basis of the binary number
system, which we discuss in the “Number Systems” appendix at https://deitel.com/
cpphtp11.
Characters
Working with data in the low-level form of bits is tedious. Instead, people prefer to work
with decimal digits (0–9), letters (A–Z and a–z) and special symbols such as
$ @ % & * ing ( ) – + " : ; , ? /
Digits, letters and special symbols are known as characters. The computer’s character set
contains the characters used to write programs and represent data items. Computers pro-
cess only 1s and 0s, so a computer’s character set represents each character as a pattern of
1s and 0s. C++ uses the ASCII (American Standard Code for Information Interchange)
character set by default. C++ also supports Unicode® characters composed of one, two,
three or four bytes (8, 16, 24 or 32 bits, respectively).31
31. Victor Stinner, “Programming with Unicode.” Accessed March 18, 2023. https://unicode-
book.readthedocs.io/programming_languages.html.
1.3 Data Hierarchies 11
Unicode contains characters for many of the world’s languages. ASCII is a (tiny) sub-
set of Unicode representing letters (a–z and A–Z), digits and some common special char-
acters. You can view the ASCII subset of Unicode at
https://www.unicode.org/charts/PDF/U0000.pdf
For the lengthy Unicode charts for all languages, symbols, emojis and more, visit
http://www.unicode.org/charts/
Fields
Just as characters are composed of bits, fields are composed of characters or bytes. A field
is a group of characters or bytes that conveys meaning. For example, a field consisting of
uppercase and lowercase letters could represent a person’s name, and a field consisting of
decimal digits could represent a person’s age in years.
Records
Several related fields can be used to compose a record. In a payroll system, for example,
the record for an employee might consist of the following fields (possible types for these
fields are shown in parentheses):
• Employee identification number (a whole number).
• Name (a group of characters).
• Address (a group of characters).
• Hourly pay rate (a number with a decimal point).
• Year-to-date earnings (a number with a decimal point).
• Amount of taxes withheld (a number with a decimal point).
Thus, a record is a group of related fields. All the fields listed above belong to the same
employee. A company might have many employees and a payroll record for each.
Files
A file is a group of related records. More generally, a file contains arbitrary data in arbitrary
formats. Some operating systems view a file simply as a sequence of bytes—any organiza-
tion of the bytes in a file, such as into records, is a view created by the application pro-
grammer. You’ll see how to do that in Chapter 8. It’s not unusual for an organization to
have many files, some containing billions, or even trillions, of characters of information.
As we’ll see below, far larger file sizes are becoming increasingly common with big data.
Databases
A database is a collection of data organized for easy access and manipulation. The most
popular model is the relational database, in which data is stored in simple tables of rows
and columns. A table includes records and fields. For example, a table of students might
include first name, last name, major, year, student ID number and grade-point-average
fields. The data for each student is a record, and the individual pieces of information in
each record are the fields. You can search, sort and otherwise manipulate the data based
on its relationship to multiple tables or databases. For example, a university might use data
from the student database combined with data from databases of courses, on-campus
housing, meal plans, etc.
12 Chapter 1 Intro to Computers and C++
Big Data
The table below shows some common byte measures:
The amount of data produced worldwide is enormous, and its growth is accelerating. Big
data applications deal with massive amounts of data.
Checkpoint
1 (Fill-In) A(n) is short for “binary digit”—a digit that can assume one of two
values and is a computer’s smallest data item.
Answer: bit.
2 (Fill-In) A database is a collection of data organized for easy access and manipulation.
The most popular model is the database, in which data is stored in simple tables.
Answer: relational.
In our Building Your Own Computer case study (Exercises 7.9–7.11), you’ll “peel open” a
“made-up” computer and look at its internal structure. We’ll introduce machine-language
programming, and you’ll write several machine-language programs. To make this an espe-
cially valuable experience, you’ll then build a software simulation of a computer on which
you can execute your machine-language programs. This will give you a friendly introduc-
tion to the contemporary computer architecture concept of “virtual machines.”
Although such code is clearer to humans, it’s incomprehensible to computers until it’s
translated into machine language.
From the programmer’s standpoint, high-level languages are preferable to machine and
assembly languages. C++ is among the world’s most widely used high-level programming
languages.
In our Building Your Own Compiler case study (Exercises 13.29–13.34), you’ll build a
compiler that takes programs written in a simple “made-up” high-level programming lan-
guage and converts them to the Simpletron Machine Language that you learn in
Exercise 7.9. Exercises 13.29–13.34 “tie” together the entire programming process. You’ll
write programs in a simple high-level language, compile the programs on the compiler you
build, then run the programs on the Simpletron simulator virtual machine you build in
Exercise 7.10.
Interpreters
Compiling large high-level language programs into machine language can take consider-
able computer time. Interpreters execute high-level language programs directly, avoiding
compilation delays, but your code runs slower than compiled programs. Some program-
ming languages, such as Java34, Python35 and C#36, use a clever mixture of compilation
and interpretation to run programs.
Checkpoint
1 (Fill-In) programs, developed to execute high-level-language programs
directly, avoid compilation delays, although they run slower than compiled programs
Answer: Interpreter.
2 (True/False) High-level languages allow you to write instructions that look almost like
everyday English and contain commonly used mathematical notations.
Answer: True.
34. “Java virtual machine.” Wikipedia. Wikimedia Foundation. Accessed March 18, 2023. https://
en.wikipedia.org/wiki/Java_virtual_machine#Bytecode_interpreter_and_just-in-
time_compiler.
35. “The Bytecode Interpreter.” Accessed March 18, 2023. https://devguide.python.org/internals/
interpreter/.
36. “Common Language Runtime (CLR) overview.” Accessed March 18, 2023. https://learn.micro-
soft.com/en-us/dotnet/standard/clr.
1.5 Operating Systems 15
popular desktop/laptop operating systems—you can use any of these with this book. The
most popular mobile operating systems used in smartphones and tablets are Google’s
Android and Apple’s iOS.
37. Alison DeNisco Rayome and Shelby Brown. “Every Difference You Should Care About Between
Windows 10 and Windows 11.” November 5, 2022. Accessed March 18, 2023. https://
www.cnet.com/tech/computing/every-difference-you-should-care-about-between-win-
dows-10-and-windows-11/.
38. “Desktop Operating System Market Share Worldwide.” Accessed March 18, 2023. https://
gs.statcounter.com/os-market-share/desktop/worldwide.
39. “Welcome to the Apache Projects Directory.” Accessed March 18, 2023. https://proj-
ects.apache.org/.
40. “Eclipse Foundation.” Wikipedia. Wikimedia Foundation. Accessed March 18, 2023. https://
en.wikipedia.org/wiki/Eclipse_Foundation.
41. “Welcome to the Mozilla Laboratory.” Accessed March 18, 2023. https://labs.mozilla.org/
projects/.
16 Chapter 1 Intro to Computers and C++
Apple’s macOS and Apple’s iOS for iPhone® and iPad® Devices
Apple, founded in 1976 by Steve Jobs and Steve Wozniak, quickly became a leader in per-
sonal computing. In 1979, Jobs and several Apple employees visited Xerox PARC (Palo
Alto Research Center) to learn about Xerox’s desktop computer that featured a graphical
user interface (GUI). That GUI served as the inspiration for the Apple Macintosh,
launched in 1984.
The Objective-C programming language, created by Stepstone in the early 1980s,
added object-oriented programming (OOP) capabilities to the C programming language.
Steve Jobs left Apple in 1985 and founded NeXT Inc. In 1988, NeXT licensed Objective-
C from Stepstone. NeXT developed an Objective-C compiler and libraries, which were
used as the platform for the NeXTSTEP operating system’s user interface and Interface
Builder (for constructing graphical user interfaces).
Jobs returned to Apple in 1996 when they bought NeXT. Apple’s macOS operating
system is a descendant of NeXTSTEP. Apple has several other proprietary operating sys-
tems derived from macOS:
• iOS is used in iPhones.
• iPadOS is used in iPads.
• watchOS is used in Apple Watches.
• tvOS is used in Apple TV devices.
1.5 Operating Systems 17
In 2014, Apple introduced its Swift programming language, which it open-sourced in 2015.
The Apple app-development community has largely shifted from Objective-C to Swift.
Google’s Android
Android—the most widely used mobile and smartphone operating system—is based on
the Linux kernel, the Java programming language and now, the open-source Kotlin pro-
gramming language. Android is open-source and free. Though you can’t develop Android
apps purely in C++, you can incorporate C++ code.42
According to statista.com, in the fourth quarter of 2022, 71.8% of smartphones use
Android and 27.6% use Apple iOS.43 This represents an increasing market for Apple iOS.
The Android operating system is used in numerous smartphones, e-reader devices, tablets,
TVs, in-store touch-screen kiosks, cars, robots, multimedia players and more.
Checkpoint
1 (Fill-In) Windows is a(n) operating system—it’s controlled by Microsoft
exclusively.
Answer: proprietary.
42. “Add C and C++ code to your project.” Accessed March 18, 2023. https://devel-
oper.android.com/studio/projects/add-native-code.
43. “Mobile operating systems' market share worldwide from 1st quarter 2009 to 4th quarter 2022.”
Acccessed March 10, 2023. https://www.statista.com/statistics/272698/global-market-
share-held-by-mobile-operating-systems-since-2009.
18 Chapter 1 Intro to Computers and C++
44. Stroustrup, Bjarne. “A History of C++: 1979–1991.” Accessed March 18, 2023. https://
www.stroustrup.com/hopl2.pdf.
1.7 C++ Standard Library and Open-Source Libraries 19
Modern C++
Today’s C++ programmers build systems and system components using Modern C++,
which includes the C++20, C++17, C++14 and C++11 standards—the digits in each name
indicate the year in the 2000s when that version was approved by the ISO C++ standard
committee. Many of the language and library features introduced by these standards make
C++ easier to use, improve runtime performance and software quality, and enable appli-
cations to take advantage of today’s multi-core systems.
C++ is over four decades old, so there is much existing C++ code using older program-
ming idioms—this is typically referred to as legacy code. We emphasize Modern C++ idi-
oms in this book.
Checkpoint
1 (Fill-In) Most code for general-purpose operating systems is written in .
Answer: C or C++.
2 (Fill-In) The provide recommendations and sample code to help you use
Modern C++ correctly and effectively.
Answer: C++ Core Guidelines.
bilities that might eventually be incorporated into the C++ standard libraries. The follow-
ing StackOverflow post lists Modern C++ libraries and language features that evolved from
the Boost libraries:48
https://stackoverflow.com/a/8852421
We use the Boost Multiprecision library in our objects-natural case studies on super-sized
integers (Section 3.14) and precise monetary calculations (Section 4.14).
On GitHub, developers contribute to almost 56,000 C++ code repositories:
https://github.com/topics/cpp
provide curated lists of popular C++ libraries for many application areas—you’ll enjoy
exploring these sites.
Checkpoint
1 (Fill-In) Most C++ programmers take advantage of the rich collection of existing
functions called the .
Answer: C++ standard library.
2 (Fill-In) Avoid “reinventing the wheel” Instead, use existing pieces from code librar-
ies. This is an example of .
Answer: software reuse.
48. Kennytm, Answer to “Which Boost Features Overlap with C++11?” Accessed March 18, 2023.
https://stackoverflow.com/a/8852421.
1.8 Other Popular Programming Languages 21
49. “Python programming language.” Wikipedia. Wikimedia Foundation. Accessed March 18, 2023.
https://en.wikipedia.org/wiki/Python_(programming_language).
50. “Java programming language.” Wikipedia. Wikimedia Foundation. Accessed March 18, 2023.
https://en.wikipedia.org/wiki/Java_(programming_language).
51. “What is Java used for?” March 14, 2022. Accessed March 18, 2023. https://www.future-
learn.com/info/blog/what-is-java-used-for.
52. “Build Better Apps with Kotlin.” Accessed March 18, 2023. https://developer.android.com/
kotlin/build-better-apps.
53. “C Sharp (programming language).” Wikipedia. Wikimedia Foundation. Accessed March 18, 2023.
https://en.wikipedia.org/wiki/C_Sharp_(programming_language).
54. Mahesh Chand, “What is Microsoft Mesh?” January 5, 2022. Accessed March 18, 2023. https://
www.c-sharpcorner.com/article/what-is-microsoft-mesh/.
55. “Visual Basic (.NET).” Wikipedia. Wikimedia Foundation. Accessed March 18, 2023. https://
en.wikipedia.org/wiki/Visual_Basic_(.NET).
22 Chapter 1 Intro to Computers and C++
Checkpoint
1 (Fill-In) Today, most code for general-purpose operating systems and other perfor-
mance-critical systems is written in .
Answer: C or C++.
2 (Fill-In) A key goal of the programming language is “write once, run any-
where,” enabling developers to write programs that will run on a great variety of computer
systems and computer-controlled devices.
Answer: Java.
56. “JavaScript.” Wikipedia. Wikimedia Foundation. Accessed March 18, 2023. https://en.wikipe-
dia.org/wiki/JavaScript.
57. Eric Elliott, “Top JavaScript Frameworks and Technology 2023.” February 19, 2023. Accessed
March 18, 2023. https://medium.com/javascript-scene/top-javascript-frameworks-and-
technology-2023-4e4a06d6be93.
58. Simran Kaur Arora, “10 Best JavaScript Frameworks to Use in 2023.” December 29, 2022. Accessed
March 18, 2023. https://hackr.io/blog/best-javascript-frameworks.
59. “Swift (programming language).” Wikipedia. Wikimedia Foundation. Accessed March 18, 2023.
https://en.wikipedia.org/wiki/Swift_(programming_language).
60. “Go (programming language).” Wikipedia. Wikimedia Foundation. Accessed March 18, 2023.
https://en.wikipedia.org/wiki/Go_(programming_language).
61. “Go (programming language).” Wikipedia. Wikimedia Foundation. Accessed March 18, 2023.
https://en.wikipedia.org/wiki/Go_(programming_language).
1.9 Introduction to Object Orientation 23
Automobile as an Object
Let’s begin with a simple analogy. Suppose you want to drive a car and make it go faster
by pressing its accelerator pedal. What must happen before you can do this? Well, some-
one has to design the car before you can drive it. A car typically begins as engineering
drawings, similar to the blueprints that describe the design of a house. These drawings
include the design for an accelerator pedal. The pedal hides from the driver the complex
mechanisms that make the car go faster, just as the brake pedal hides the mechanisms that
slow the car, and the steering wheel hides the mechanisms that turn the car. This enables
people with little or no knowledge of how engines, braking and steering mechanisms work
to drive a car easily.
Before you can drive a car, it must be built from the engineering drawings that
describe it. A completed car has an actual accelerator pedal to make the car go faster, but
even that’s not enough—the car won’t accelerate on its own (hopefully!), so the driver
must press the pedal to accelerate the car.
Instantiation
Just as someone has to build a car from its engineering drawings before you can drive a
car, you must build an object from a class before a program can perform the tasks defined
by the class’s member functions. The process of doing this is called instantiation, and an
object is then referred to as an instance of its class.
24 Chapter 1 Intro to Computers and C++
Reuse
Just as a car’s engineering drawings can be reused many times to build many cars, you can
reuse a class many times to build many objects. Reusing existing classes when building new
classes and programs saves time and effort. Reuse also helps you build more reliable and
effective systems because existing classes and components often have been extensively
SE tested, debugged and performance-tuned. Just as the notion of interchangeable parts was
crucial to the Industrial Revolution, reusable classes are crucial to the software revolution
spurred by object technology.
Encapsulation
Classes encapsulate (i.e., wrap) attributes and member functions into objects created from
those classes—an object’s attributes and member functions are intimately related. Objects
may communicate with one another, but they’re normally not allowed to know how other
objects are implemented internally. Those details are hidden inside the objects. As we’ll
SE see, this information hiding is crucial to good software engineering.
Inheritance
A new class of objects can be created quickly and conveniently by inheritance. The new
class absorbs the characteristics of an existing class, possibly customizing them and adding
unique characteristics of its own. In our car analogy, an object of the class “convertible”
certainly is an object of the more general class “automobile,” but more specifically, the
roof can be raised or lowered.
approach may work for small programs (like the ones we present in the book’s early chap-
ters), but what if you were asked to create a software system to control thousands of auto-
mated teller machines for a major bank? Or suppose you were asked to work on a team of
thousands of software developers building the next generation of the U.S. air traffic con-
trol system? For projects so large and complex, you should not simply sit down and start
writing programs.
To create the best solutions, you should follow a detailed analysis process for deter-
mining your project’s requirements (i.e., defining what the system is supposed to do) and
developing a design that satisfies them (i.e., deciding how the system should do it). Ideally,
you’d go through this process and carefully review the design (and have your design
reviewed by other software professionals) before writing any code. If this process involves
analyzing and designing your system from an object-oriented point of view, it’s called an
object-oriented analysis and design (OOAD) process. C++ has object-oriented program- SE
ming (OOP) capabilities that enable you to implement object-oriented designs as working
systems.
Checkpoint
1 (Fill-In) The size, shape, color and weight of an object are of the object’s
class.
Answer: attributes.
2 (True/False) Objects, or more precisely, the classes objects come from, are essentially
reusable software components.
Answer: True.
You type a C++ program’s source code using the editor, make any necessary corrections
and save the program on your computer’s disk. C++ source code filenames often end with
the .cpp, .cxx, .cc or .C (uppercase) extensions, which indicate that a file contains C++
source code. See the documentation for your C++ compiler for more information on file-
name extensions. Two editors widely used on Linux systems are vim and emacs. You also
can use a simple text editor, such as TextEdit on macOS, Notepad on Windows or Mic-
rosoft’s Visual Studio Code (a cross-platform, code-oriented text editor with plug-ins sup-
porting many languages).
26 Chapter 1 Intro to Computers and C++
Integrated development environments (IDEs) are available from many major soft-
ware suppliers. IDEs provide tools that support the software development process, includ-
ing editors for writing and editing programs and debuggers for locating logic errors—
errors that cause programs to execute incorrectly. Some popular IDEs include Microsoft®
Visual Studio Community Edition (a complete IDE), Eclipse, JetBrains CLion®, Apple’s
Xcode® and CodeLite.
Phase 2: Preprocessing a C++ Program
In Phase 2, you give the command to compile the program:
Phase 2:
Preprocessor Preprocessor program
Disk
processes the code
Phase 3:
Compiler Compiler creates
Disk object code and stores
it on disk
The object code produced by the C++ compiler typically contains “holes” due to these
missing parts. A linker links the object code with the code for the missing functions to pro-
duce an executable program (with no missing pieces).
Phase 5: Loading an Executable Program
Phase 5 is called loading. Before a program can be executed, it must first be placed in
memory:
1.10 Simplified View of a C++ Development Environment 27
Primary
Memory
Loader
Phase 5:
Loader puts executable
program in memory
...
Disk
This is done by the loader, which takes the executable image from disk and transfers it to
memory. Additional components from shared libraries that support the program are also
loaded.
net. There is also a standard error stream referred to as cerr. The cerr stream (normally
connected to the screen) displays error messages.
Err Errors such as division by zero occur as a program runs, so they’re called runtime
errors or execution-time errors. Fatal runtime errors cause programs to terminate imme-
diately without having successfully performed their jobs. Nonfatal runtime errors allow
programs to run to completion, often producing incorrect results.
Checkpoint
1 (Fill-In) C++ programs typically go through six phases to be executed: ,
, , , and .
Answer: edit, preprocess, compile, link, load, execute.
2 (Fill-In) A(n) occurs when the compiler cannot recognize a statement
because it violates the rules of the language, and an error that occurs as a program runs is
called a(n) or execution-time error.
Answer: syntax error, runtime error.
62. We intentionally do not cover the code for this C++ program here. Its purpose is simply to demon-
strate compiling and running a program using each compiler we discuss in this section. We present
secure random-number generation in Chapter 5.
63. If you’re interested in using Microsoft’s Visual Studio Code cross-platform code editor to program in
C++, see the instructions at https://code.visualstudio.com/docs/languages/cpp.
1.11 Test-Driving a C++20 Application Various Ways 29
When you edit C++ code, Visual Studio displays each file as a separate tab within the
window. The Solution Explorer—docked to Visual Studio’s left or right side—is for view-
30 Chapter 1 Intro to Computers and C++
ing and managing your application’s files. In this book’s examples, you’ll typically place
each program’s code files in the Source Files folder. If the Solution Explorer is not dis-
played, you can display it by selecting View > Solution Explorer.
64. For the multiple source-code-file programs that you’ll see in later chapters, select all the files for a
given program.
65. To try new C++ features as Microsoft adds them to Visual C++, select Preview - Features from the
Latest C++ Working Draft (/std:c++latest) rather than ISO C++20 Standard (/std:c++20).
1.11 Test-Driving a C++20 Application Various Ways 31
Once you install and launch the Ubuntu app on your Windows System, you can use the
following command to change to the folder containing the test-drive code example on
your Windows system:
cd /mnt/c/Users/YourUseName/Documents/examples/ch01
~$ cd ~/Documents/examples/ch01
~/Documents/examples/ch01$
66. At the time of this writing, the current g++ version was 13.1. You can determine your system’s g++
version number with the command g++ --version. If you have an older version of g++, consider
searching online for the instructions to upgrade the GNU Compiler Collection (GCC) for your
Linux distribution or consider using the GCC Docker container discussed in Section 1.11.3.
1.11 Test-Driving a C++20 Application Various Ways 33
In this section’s figures, we use bold to highlight the user inputs. The prompt in our
Ubuntu Linux shell uses a tilde (~) to represent the home directory. Each prompt ends
with the dollar sign ($). The prompt may differ on your Linux system.
~/Documents/examples/ch01$ ./GuessNumber
I have a number between 1 and 1000.
Can you guess my number?
Please type your first guess.
?
The ./ before GuessNumber tells Linux to run GuessNumber from the current directory.
~/Documents/examples/ch01$ ./GuessNumber
I have a number between 1 and 1000.
Can you guess my number?
Please type your first guess.
? 500
Too high. Try again.
?
In our case, the application displayed "Too high. Try again." because the value entered
was greater than the number the application chose as the correct guess.
67. If you have multiple g++ versions installed, you might need to use g++-##, where ## is the g++ version
number. For example, the command g++-13 might be required to run g++ version 13.
34 Chapter 1 Intro to Computers and C++
~/Documents/examples/ch01$ ./GuessNumber
I have a number between 1 and 1000.
Can you guess my number?
Please type your first guess.
? 500
Too high. Try again.
? 250
Too high. Try again.
?
? 125
Too high. Try again.
? 62
Too low. Try again.
? 93
Too low. Try again.
? 109
Too high. Try again.
? 101
Too low. Try again.
? 105
Too high. Try again.
? 103
Too high. Try again.
? 102
1.11.3 Compiling and Running with g++ in the GCC Docker Container
You can use the latest GNU C++ compiler on your system, regardless of your operating
system. One of the most convenient cross-platform ways to do this is by using the GNU
Compiler Collection (GCC) Docker container. This section assumes that you’ve already
performed the following steps described in the Before You Begin section that follows the
Preface:
1.11 Test-Driving a C++20 Application Various Ways 35
3. macOS/Linux users: Launch the GCC Docker container with the command
docker run --rm -it -v "$(pwd)":/usr/src gcc:latest
The container uses a Linux operating system. Its prompt displays the current folder loca-
tion between the : and #.
root@01b4d47cadc6:/# cd /usr/src/ch01
root@01b4d47cadc6:/usr/src/ch01#
To compile, run and interact with the GuessNumber application in the Docker container,
follow Steps 2–7 of Section 1.11.2, Compiling and Running with GNU C++ on Linux.
68. A notification might appear asking you to allow Docker to access the files in the current folder. You
must allow this; otherwise, you will not be able to access our source-code files in Docker.
69. If you’d like to keep your GCC container up-to-date with the latest release, you can execute the com-
mand docker pull gcc:latest before running the container.
36 Chapter 1 Intro to Computers and C++
The container uses a Linux operating system. Its prompt displays the current folder loca-
tion between the : and #.
70. The Clang C++ (clang++) Docker container is a good alternative to Xcode for macOS users. The
version of Clang C++ used in Xcode is missing several key C++20 features used throughout this book.
71. A notification will appear asking you to allow Docker to access the files in the current folder. You
must allow this; otherwise, you will not be able to access our source-code files in Docker.
1.11 Test-Driving a C++20 Application Various Ways 37
root@9753bace2e87:/# cd /usr/src/ch01
root@9753bace2e87:/usr/src/ch01#
where:
• The -std=c++20 option indicates that we’re using C++20.
• The -o option names the executable file (GuessNumber) that you’ll use to run the
program. If you do not include this option, clang++ automatically names the exe-
cutable a.out.
for instructions on using Xcode to run the book’s examples in Chapters 4 and higher.
If this is your first time running Xcode, the Welcome to Xcode window appears. Close this
window—you can access it by selecting Window > Welcome to Xcode. We use the > char-
acter to indicate selecting a menu item from a menu. For example, File > Open… indicates
that you should select the Open… menu item from the File menu.
Step 3: Creating a Project
A project is a group of related files, such as the C++ source-code files that compose an
application. The Xcode projects we created for this book’s examples are Command Line
Tool projects that you’ll execute directly in the IDE. To create a project:
1. Select File > New > Project….
2. At the top of the Choose a template for your new project dialog, click macOS.
3. Under Application, click Command Line Tool and click Next.
4. For Product Name, enter a name for your project—we specified cpp20_test.
5. In the Language drop-down list, select C++, then click Next.
6. Specify where you want to save your project. We selected the examples folder
containing this book’s code examples.
7. Click Create.
Xcode creates your project and displays the workspace window initially showing three
areas—the Navigator area (left), Editor area (middle) and Utilities area (right).
The left-side Navigator area has icons at its top for the navigators that can be displayed
there. For this book, you’ll primarily work with two of these navigators:
• Project ( )—Shows all the files and folders in your project.
• Issue ( )—Shows you warnings and errors generated by the compiler.
Clicking a navigator button displays the corresponding navigator panel.
The middle Editor area is for managing project settings and editing source code. This
area is always displayed in your workspace window. When you select a file in the Project nav-
igator, the file’s contents display in the Editor area. The right-side Utilities area typically dis-
plays inspectors. For example, if you were building an iPhone app that contained a touchable
button, you’d be able to configure the button’s properties (its label, size, position, etc.) in this
area. You will not use the Utilities area in this book. There’s also a Debug area where you’ll
interact with the running guess-the-number program. This will appear below the Editor area.
The workspace window’s toolbar contains options for executing a program ( ), and
hiding or showing the left (Navigator, ) and right (Utilities, ) areas. It also contains
a display area that shows the progress of tasks executing in Xcode.
Step 4: Configuring the Project to Compile Using C++20
The Apple Clang compiler in Xcode supports several versions of the C++ standard. For
this book, we use C++20, which we must configure in our project’s settings:
1. In the Project navigator, select your project’s name (cpp20_test).
2. In the Editor area’s left side, select your project’s name under TARGETS.
3. At the top of the Editors area, click Build Settings, and just below it, click All.
4. Scroll to the Apple Clang - Language - C++ section.
5. Click the value to the right of C++ Language Dialect and select GNU++20
[-std=gnu++20].
1.11 Test-Driving a C++20 Application Various Ways 39
73. For the multiple source-code-file programs that you’ll see later in the book, drag all the files for a
given program to the project’s folder. When you begin creating your own programs, you can right-
click the project’s folder and select New File… to display a dialog for adding a new file.
40 Chapter 1 Intro to Computers and C++
74. Michael Irving. “World's fastest Internet network upgraded to staggering 46 Terabit/s.” October 11,
2022. Accessed March 18, 2023. https://newatlas.com/telecommunications/esnet6-worlds-
fastest-internet-46-terabit-second/.
42 Chapter 1 Intro to Computers and C++
75. Charles Griffiths, “The Latest Cloud Computing Statistics.” March 6, 2023. Accessed March 25,
2023. https://aag-it.com/the-latest-cloud-computing-statistics/.
76. Anina Ot, “Top 16 Cloud Service Providers & Companies in 2023.” February 22, 2023. Accessed
March 25, 2023. https://www.datamation.com/cloud/cloud-service-providers/.
1.12 Internet, World Wide Web, the Cloud and IoT 43
1.12.6 Mashups
The applications-development methodology of mashups enables you to rapidly develop
powerful software by combining (often free) complementary web services and various forms
of information feeds. One of the first mashups, www.housingmaps.com, combined the real-
estate listings from www.craigslist.org with Google Maps to show the locations of homes
for sale or rent in a given area. Check out www.housingmaps.com for some interesting facts,
history and articles on how it influenced real-estate industry listings.
A focus of this book’s object-natural approach is software reuse—you’ll work with
easy-to-use, powerful preexisting classes that do significant things. Similarly, before build-
ing apps that use web services, consider reusing the many powerful preexisting services
available across the Internet. Numerous online catalogs exist listing dozens to thousands
of existing web services, including:
• GitHub’s Public APIs page (https://github.com/public-apis/public-apis)
lists 51 categories containing hundreds of publicly available web services.
• The Google APIs Explorer (https://developers.google.com/apis-explorer)
enables you to learn about and experiment with 266 of Google’s web services
without writing any code.
77. Mohammad Hasan, “State of IoT 2022: Number of connected IoT devices growing 18% to 14.4
billion globally.” May 18, 2022. Accessed March 18, 2023. https://iot-analytics.com/number-
connected-iot-devices/.
78. “Edge computing.” Wikipedia. Wikimedia Foundation. Accessed March 25, 2023. https://
en.wikipedia.org/wiki/Edge_computing.
79. Robert Napoli, “Edge Computing: What Is It And Why Does It Matter?” April 25, 2022. Accessed
March 25, 2023. https://www.forbes.com/sites/forbestechcouncil/2022/04/25/edge-com-
puting-what-is-it-and-why-does-it-matter/.
44 Chapter 1 Intro to Computers and C++
Checkpoint
1 (Fill-In) The (simply called “the web”) is a collection of hardware and soft-
ware associated with the Internet that allows computer users to locate and view documents
(with various combinations of text, graphics, animations, audios and videos).
Answer: World Wide Web.
2 (Fill-In) In the Internet of Things (IoT), a thing is any object with a(n) and
the ability to send, and in some cases receive, data over the Internet.
Answer: IP address.
1.13 Metaverse
The term Metaverse was coined in Neal Stephenson’s 1992 novel Snow Crash, where the
character Hiro “exists in a computer-generated universe that his computer is drawing into
his goggles and pumping into his earphones. …this imaginary place is known as the
Metaverse.”80,81 Gartner says the Metaverse is the Internet’s next iteration and defines it as
a “collective virtual shared space, created by the convergence of virtually enhanced physical
and digital reality.”82 This section presents several key Metaverse technologies. Section 1.16
presents artificial intelligence, which improves the Metaverse’s immersive nature by helping
generate realistic digital avatars, environments, natural-language dialog in your preferred
spoken language and more.83
• fully immersive VR—in which you interact with the 3D environment via a head-
mounted display (like a headset) and other devices (like hand-held controllers),
making you feel like you’re part of the environment.
84. Alexander S. Gillis, "What is augmented reality (AR)?" Accessed March 18, 2023. https://
www.techtarget.com/whatis/definition/augmented-reality-AR.
85. “Augmented reality.” Wikipedia. Wikimedia Foundation. Accessed March 18, 2023. https://
en.wikipedia.org/wiki/Augmented_reality.
86. Nick Statt, “Niantic adds ‘reality blending’ to Pokémon Go to make your virtual pals even more real-
istic.” May 26, 2020. Accessed March 18, 2023. https://www.theverge.com/2020/5/26/
21269862/niantic-pokemon-go-reality-blending-ar-features-release-update.
87. Michael Sawh. “Best smartglasses and AR specs 2023: Tested picks from Snap, Meta and Amazon.”
November 15, 2022. Accessed March 18, 2023. https://www.wareable.com/ar/the-best-
smartglasses-google-glass-and-the-rest.
88. Mike Elgan, “What’s so great about Google’s ‘translation glasses’?” May 20, 2022. Accessed March
18, 2023. https://www.computerworld.com/article/3661209/what-s-so-great-about-goo-
gle-s-translation-glasses.html.
46 Chapter 1 Intro to Computers and C++
1.13.4 Blockchain
Accounting systems use ledgers to keep track of transactions. Blockchain92,93 is a software-
based ledger distributed over nodes on the Internet. It maintains transaction data in cryp-
tographically secured chunks—called blocks—that are linked together, and new blocks are
always added at the end. Once created, each block is immutable (not modifiable), so the
blockchain maintains a permanent transaction record. The blockchain is decentralized, so
no one person or group has control. This decentralization is the basis for the decentralized
apps (dApps) that enable digital ownership in the Metaverse.
Blockchain is behind various digital technologies that have exploded in popularity over
the last several years, such as cryptocurrencies (Section 1.13.5) and non-fungible tokens
(Section 1.13.7). It’s also used to implement many other kinds of applications,94 including
• decentralized finance (DeFi) applications (lending, money transfer),
• smart contracts,
• safer Internet of Things (IoT) apps,
• secure digital identities to help prevent fraud,
• securing and sharing healthcare information,
• business logistics, and
• protecting intellectual property (IP).
89. Bernard Marr, “The Important Difference Between Augmented Reality And Mixed Reality.”
Accessed March 18, 2023. https://bernardmarr.com/the-important-difference-between-
augmented-reality-and-mixed-reality/.
90. “Mixed reality.” Wikipedia. Wikimedia Foundation. Accessed March 18, 2023. https://en.wiki-
pedia.org/wiki/Mixed_reality.
91. “Extended reality.” Wikipedia. Wikimedia Foundation. Accessed March 25, 2023. https://
en.wikipedia.org/wiki/Extended_reality.
92. “Blockchain.” Wikipedia. Wikimedia Foundation. Accessed March 18, 2023. https://en.wikipe-
dia.org/wiki/Blockchain.
93. Xiaojie Liu, “What Is a Blockchain?” Accessed March 18, 2023. https://www.investopedia.com/
terms/b/blockchain.asp.
94. Sam Daley, “33 Blockchain Applications and Real-World Use Cases.” March 2, 2023. Accessed
March 18, 2023. https://builtin.com/blockchain/blockchain-applications.
95. Jake Frankenfield, “Cryptocurrency Explained With Pros and Cons for Investment.” February 4, 2023.
Accessed March 18, 2023. https://www.investopedia.com/terms/c/cryptocurrency.asp.
1.13 Metaverse 47
secure, decentralized transaction tracking and processing.96 The original, most well-
known and most valuable cryptocurrency is Bitcoin, which was created in 2009.97 It is a
decentralized cryptocurrency built using blockchain technology.98
1.13.6 Ethereum
Ethereum is a programmable platform that enables you to “build and deploy decentralized
applications (dApps) on its network … that use the blockchain to store data or control what
your app can do.” One of its key features is smart contracts, which are used to implement
lending apps, decentralized trading exchanges, insurance, crowdfunding apps and more.99
Its native cryptocurrency is Ether—the world’s second most valuable cryptocurrency.100
1.13.8 Web3
Like the Metaverse, some people refer to Web3 as the Internet’s next generation.104,105
Web3 and the Metaverse are sometimes confused with one another because they share
some of the same technologies. Forbes defines Web3 as “the decentralized Internet—built
on distributed technologies like blockchain … rather than centralized on servers owned by
96. “Cryptocurrency.” Wikipedia. Wikimedia Foundation. Accessed March 18, 2023. https://
en.wikipedia.org/wiki/Cryptocurrency.
97. Julie Pinkerton, “The History of Bitcoin, the First Cryptocurrency.” February 27, 2023. Accessed
March 18, 2023. https://money.usnews.com/investing/articles/the-history-of-bitcoin.
98. “Bitcoin.” Wikipedia. Wikimedia Foundation. Accessed March 18, 2023. https://en.wikipe-
dia.org/wiki/Bitcoin.
99. “What is Ethereum?” Accessed March 18, 2023. https://ethereum.org/en/what-is-ethereum/.
100.“Ethereum.” Wikipedia. Wikimedia Foundation. Accessed March 18, 2023. https://en.wikipe-
dia.org/wiki/Ethereum.
101.“Non-fungible token.” Wikipedia. Wikimedia Foundation. Accessed March 18, 2023. https://
en.wikipedia.org/wiki/Non-fungible_token.
102.Melanie Kramer, Stephen Graves and Daniel Phillips, “Beginner’s Guide to NFTs: What Are Non-
Fungible Tokens?” Jan 12, 2022. Accessed March 18, 2023. https://decrypt.co/resources/
non-fungible-tokens-nfts-explained-guide-learn-blockchain.
103.“The 26 most expensive sold NFTs in the world.” Accessed March 25, 2023. https://metav.rs/
blog/most-expensive-nfts/.
104.Thomas Stackpole, “What Is Web3?” Harvard Business Review, May 10, 2022. Accessed March 18.
2023. https://hbr.org/2022/05/what-is-web3.
105.“Web3.” Wikipedia. Wikimedia Foundation. Accessed March 18, 2023. https://en.wikipe-
dia.org/wiki/Web3.
48 Chapter 1 Intro to Computers and C++
individuals or corporations.”106 A key focus of Web3 is that blockchain and its related
technologies (like NFTs, cryptocurrencies and smart contracts) will give users greater con-
trol of their data and online interactions.
Checkpoint
1 (Fill-In) The , with its immersive user experiences, is considered by many to
be the next iteration of the Internet.
Answer: Metaverse.
2 (Fill-In) is the technology that serves as the basis for the decentralized apps
(dApps) that enable digital ownership in the Metaverse.
Answer: Blockchain.
106.Bernard Marr, “The Important Difference Between Web3 And The Metaverse.” February 22, 2022.
Accessed March 25. 2023. https://www.forbes.com/sites/bernardmarr/2022/02/22/the-
important-difference-between-web3-and-the-metaverse/.
107.“Code refactoring.” Wikipedia. Wikimedia Foundation. Accessed March 27, 2023. https://
en.wikipedia.org/wiki/Code_refactoring.
108.“Software design pattern.” Wikipedia. Wikimedia Foundation. Accessed March 27, 2023. https://
en.wikipedia.org/wiki/Software_design_pattern.
109.“Software development kit.” Wikipedia. Wikimedia Foundation. Accessed March 27, 2023. https://
en.wikipedia.org/wiki/Software_development_kit.
110.“2022 Developer Survey.” May 2022. Accessed March 25, 2023. https://survey.stackover-
flow.co/2022/#version-control-version-control-system.
1.15 How Big Is Big Data? 49
interaction between the development team and customers. The process is geared
toward enabling customers to begin using the software faster, even if it does not
yet meet all their requirements or those requirements change.111
• Test-Driven Development (TDD): An aspect of agile software development in
which developers create software test-cases before creating the software itself.
Then, as they develop the software, they continually ensure it passes all the test
cases, enabling them to confirm the software meets the system requirements.112
• Microservices: A software architecture consisting of small, independent software
services that can be combined to form larger applications. Microservices are often
implemented as web services.113
• Containerization: In Sections 1.11.3 and 1.11.4, we discussed running the g++ and
clang++ compilers in Docker containers. Containers are configured with every-
thing you need to use their software, giving you a convenient mechanism to run
that software across platforms. Containerization uses a technique called virtualiza-
tion to hide the underlying platform details, enabling containers to execute across
platforms.114 Docker is the most popular containerization platform in use today.115
Checkpoint
1 (Fill-In) is the process of reworking programs to make them clearer and eas-
ier to maintain while preserving their correctness and functionality.
Answer: refactoring.
111.“Agile software development.” Wikipedia. Wikimedia Foundation. Accessed March 18, 2023. https://
en.wikipedia.org/wiki/Agile_software_development.
112.“Test-driven development.” Wikipedia. Wikimedia Foundation. Accessed March 18, 2023. https://
en.wikipedia.org/wiki/Test-driven_development.
113.“Microservices.” Wikipedia. Wikimedia Foundation. Accessed March 18, 2023. https://en.wiki-
pedia.org/wiki/Microservices.
114.“Containerization (computing).” Wikipedia. Wikimedia Foundation. Accessed March 25, 2023.
https://en.wikipedia.org/wiki/Containerization_(computing).
115.“Containerization.” Accessed March 25, 2023. https://6sense.com/tech/containerization.
116.“Welcome to the world of A.I..” Accessed March 18, 2023. https://www.ibm.com/blogs/watson/
2016/06/welcome-to-the-world-of-a-i/.
117.“Accelerate Research and Discovery.” Accessed March 18, 2023. https://www.ibm.com/watson/
advantages/accelerate.
118.Andy Patrizio, “IDC: Expect 175 zettabytes of data worldwide by 2025.” December 3, 2018.
Accessed March 18, 2023. https://www.networkworld.com/article/3325397/storage/idc-
expect-175-zettabytes-of-data-worldwide-by-2025.html.
50 Chapter 1 Intro to Computers and C++
Megabytes
One megabyte (MB) is about one million (actually 220) bytes. High-quality MP3-format
audio files require from 1 to 2.4 MB per minute.119 JPEG-format photos taken on a dig-
ital camera can require 8 to 10 MB per photo. On one of our iPhones, the Camera settings
app reports that 1080p video at 30 frames-per-second (FPS) requires 65 MB/minute, and
4K video at 60 FPS requires 440 MB/minute.
Gigabytes
One gigabyte (GB) is 1024 megabytes. A DVD can store up to 8.5 GB120, which could hold
141 hours of MP3 audio, 1000 photos from a 16-megapixel camera, 7.7 minutes of 1080p
video at 30 frames-per-second (FPS), or 2.85 minutes of 4K video at 30 FPS. The current
highest-capacity Ultra HD Blu-ray discs can store up to 100 GB of video.121 Streaming a 4K
movie can use between 7 and 10 GB (highly compressed) per hour.
Terabytes
One terabyte (TB) is 1024 gigabytes. Recent disk drives for desktop computers come in sizes
up to 20 TB,122 which could hold 28 years of MP3 audio, 1.68 million photos from a 16-
megapixel camera, 226 hours of 1080p video at 30 frames-per-second (FPS), or 84 hours of
4K video at 30 FPS. Nimbus Data now has the largest solid-state drive (SSD) at 100 TB,
which can store five times the 20 TB examples of audio, photos and video listed above.123
127.Kit Smith, “57 Fascinating and Incredible YouTube Statistics.” February 21, 2020. Accessed March
18, 2023. https://www.brandwatch.com/blog/youtube-stats/.
128.“Worldometer.” Accessed March 18, 2023. https://www.worldometers.info/.
129.Matt McGee. “Facebook: 3.2 Billion Likes & Comments Every Day.” Accessed March 18, 2023.
https://marketingland.com/facebook-3-2-billion-likes-comments-every-day-19978.
130. Samantha Scelzo, “Facebook celebrates World Emoji Day by releasing some pretty impressive facts.”
Accessed March 18, 2023. https://mashable.com/2017/07/17/facebook-world-emoji-day/.
131.“Data Never Sleeps.” Accessed March 18, 2023. https://www.domo.com/data-never-sleeps.
132.“‘Tsunami of data’ could consume one fifth of global electricity by 2025.” Accessed March 18, 2023.
https://www.theguardian.com/environment/2017/dec/11/tsunami-of-data-could-con-
sume-fifth-global-electricity-by-2025.
133.“One Bitcoin Transaction Consumes As Much Energy As Your House Uses in a Week.” Accessed
March 18, 2023. https://motherboard.vice.com/en_us/article/ywbbpm/bitcoin-mining-
electricity-consumption-ethereum-energy-climate-change.
52 Chapter 1 Intro to Computers and C++
vehicle demand in 2025.”134 This situation is unsustainable, especially given the huge
interest in blockchain-based applications, even beyond the cryptocurrency explosion. The
blockchain community is working on fixes.135,136
Checkpoint
1 (Fill-In) The technology that could wreak havoc with blockchain-based cryptocur-
rencies, like Bitcoin, and other blockchain-based technologies is .
Answer: quantum computers.
2 (True/False) With cloud computing, you pay a fixed price for cloud services regardless
of how much you use those services.
Answer: False. A key cloud-computing benefit is that you pay for only what you use to
accomplish a given task.
134.“Power Play: What Impact Will Cryptocurrencies Have on Global Utilities?” Accessed March 18,
2023. https://www.morganstanley.com/ideas/cryptocurrencies-global-utilities.
135.Mike Orcutt, “Blockchains Use Massive Amounts of Energy—But There’s a Plan to Fix That.”
November 16, 2017. Accessed March 18, 2023. https://www.technologyreview.com/s/609480/
bitcoin-uses-massive-amounts-of-energybut-theres-a-plan-to-fix-it/.
136.Stan Schroeder, “How to fix Bitcoin's energy-consumption problem.” December 1, 2017. Accessed
March 18, 2023. http://mashable.com/2017/12/01/bitcoin-energy/.
137.“A Very Short History Of Data Science.” Accessed March 18, 2023. https://www.forbes.com/
sites/gilpress/2013/05/28/a-very-short-history-of-data-science/.
138.“A Brief History of Data Analysis.” Accessed March 18, 2023. https://www.flydata.com/blog/a-
brief-history-of-data-analysis/.
139.Diebold, Francis. (2012). On the Origin(s) and Development of the Term “Big Data”. SSRN Elec-
tronic Journal. 10.2139/ssrn.2152421. https://www.researchgate.net/publication/
255967292_On_the_Origins_and_Development_of_the_Term_.
140.“The Four V’s of Big Data – What is big data?" December 2021. Accessed March 18, 2023. https://
www.analyticsinsight.net/the-four-vs-of-big-data-what-is-big-data/.
141.There are lots of articles and papers that add many other “V-words” to this list.
142.David Gewitz. “Volume, velocity, and variety: Understanding the three V’s of Big Data.” March, 21,
2018. Accessed Match 18, 2023. https://www.zdnet.com/article/volume-velocity-and-
variety-understanding-the-three-vs-of-big-data/.
143.Ben Lutkevich, “3Vs (volume, variety and velocity).” Accessed March 18, 2023. https://wha-
tis.techtarget.com/definition/3Vs.
144.Brent Dykes, “Big Data: Forget Volume and Variety, Focus On Velocity.” June 28, 2017. Accessed
March 18, 2023. https://www.forbes.com/sites/brentdykes/2017/06/28/big-data-forget-
volume-and-variety-focus-on-velocity.
1.15 How Big Is Big Data? 53
1.15.2 Data Science and Big Data Are Making a Difference: Use Cases
The data-science field is growing rapidly because it produces results that make a difference
in our personal and business lives. The following table enumerates lots of data-science and
big-data use cases. Big-data analytics has resulted in improved profits, better customer rela-
tions, and even sports teams winning more games and championships.147,148,149
145.Michael Lesk, “How Much Information Is There In the World?” Accessed March 18, 2023. http://
www.lesk.com/mlesk/ksg97/ksg.html. [The following article pointed us to this Michael Lesk arti-
cle: https://www.forbes.com/sites/gilpress/2013/05/28/a-very-short-history-of-data-
science/.]
146.Matt Turck, “Red Hot: The 2021 Machine Learning, AI and Data (MAD) Landscape,” https://
mattturck.com/data2021/.
147.Sawchik, T., Big Data Baseball: Math, Miracles, and the End of a 20-Year Losing Streak (New York:
Flat Iron Books, 2015).
148.Ayres, I., Super Crunchers (Bantam Books, 2007), pp. 7–10.
149.Lewis, M., Moneyball: The Art of Winning an Unfair Game (W. W. Norton & Company, 2004).
54 Chapter 1 Intro to Computers and C++
155.“Artificial general intelligence.” Wikipedia. Wikimedia Foundation. Accessed March 18, 2023.
https://en.wikipedia.org/wiki/Artificial_general_intelligence.
156.Kerem Gülen, “How close are we to AI with human capabilities?.” October 6, 2022. Accessed March
18, 2023. https://dataconomy.com/2022/10/artificial-general-intelligence-definition/.
157.“Technological singularity.” Wikipedia. Wikimedia Foundation. Accessed March 18, 2023. https://
en.wikipedia.org/wiki/Technological_singularity.
158.Gary Marcus, “Artificial General Intelligence Is Not as Imminent as You Might Think.” July 1, 2022.
Accessed March 25, 2023. https://www.scientificamerican.com/article/artificial-gen-
eral-intelligence-is-not-as-imminent-as-you-might-think1/.
159.Max Roser, “AI timelines: What do experts in artificial intelligence expect for the future?” February
7, 2023. Accessed March 25, 2023. https://ourworldindata.org/ai-timelines.
160.“Deep Blue versus Garry Kasparov.” Wikipedia. Wikimedia Foundation. Accessed March 18, 2023.
https://en.wikipedia.org/wiki/Deep_Blue_versus_Garry_Kasparov.
161.“Deep Blue (chess computer).” Wikipedia. Wikimedia Foundation. Accessed March 18, 2023.
https://en.wikipedia.org/wiki/Deep_Blue_(chess_computer).
162.“IBM Deep Blue Team Gets $100,000 Prize.” Accessed March 18, 2023. https://arti-
cles.latimes.com/1997/jul/30/news/mn-17696.
163.Jo Best, “IBM Watson: The inside story of how the Jeopardy-winning supercomputer was born, and
what it wants to do next.” Accessed March 18, 2023. https://www.techrepublic.com/article/
ibm-watson-the-inside-story-of-how-the-jeopardy-winning-supercomputer-was-born-
and-what-it-wants-to-do-next/.
164.“Watson (computer).” Wikipedia. Wikimedia Foundation. Accessed March 18, 2023. https://
en.wikipedia.org/wiki/Watson_(computer).
165.Ferrucci, D., Brown, E., Chu-Carroll, J., Fan, J., Gondek, D., Kalyanpur, A. A., Lally, A., Murdock,
J. W., Nyberg, E., Prager, J., Schlaefer, N., & Welty, C. (2010). "Building Watson: An Overview of
the DeepQA Project." AI Magazine, 31(3), 59-79. https://doi.org/10.1609/aimag.v31i3.2303.
56 Chapter 1 Intro to Computers and C++
• Go—a board game created in China thousands of years ago166—is widely con-
sidered one of the most complex games ever invented, with 10170 possible board
configurations.167 To understand how large that number is, it’s believed there are
(only) between 1078 and 1082 atoms in the known universe!168 In 2015,
AlphaGo—created by Google’s DeepMind group—used the AI technique of
deep learning (Section 1.16.5) with two neural networks to beat the European
Go champion Fan Hui. Go is considered to be a far more complex game than
chess.
• More recently, Google generalized its AlphaGo AI to create AlphaZero—a game-
playing AI that teaches itself to play other games. In December 2017, AlphaZero
learned the rules and taught itself to play chess in less than four hours using the
AI technique of reinforcement learning. It then beat the world champion chess
program, Stockfish 8, in a 100-game match—winning or drawing every game.
After training itself in Go for just eight hours, AlphaZero was able to beat its
AlphaGo predecessor in 60 of 100 games.169
it proceeds through the network layers.173 The availability of big data, significant processor
power, faster Internet speeds and advancements in parallel computing hardware and software
are making it possible for more organizations and individuals to pursue resource-intensive
deep-learning solutions that are producing impressive results in computer vision, speech rec-
ognition, speech synthesis and newer generative AI applications (Section 1.16.7).174
ChatGPT
OpenAI’s ChatGPT is an AI-based chatbot you can converse with using natural lan-
guage.178 For example, you could prompt it with text like
• “tell me about the history of C++,”
• “who coined the term Metaverse?” or
• “summarize the article at” followed by a link to the article.
ChatGPT then responds with answers that look and feel as if they were generated by a
human. ChatGPT is based on a large language model named GPT (Generative Pre-
Trained Transformer),179 which was trained on massive amounts of text using several arti-
ficial intelligence techniques.180 At the time of this writing, GPT-4 had just been released
173.“Deep learning.” Wikipedia. Wikimedia Foundation. Accessed March 18, 2023. https://en.wiki-
pedia.org/wiki/Deep_learning.
174.Sharon Goldman, “10 years later, deep learning ‘revolution’ rages on, say AI pioneers Hinton, LeCun
and Li.” September 14, 2022. Accessed March 27, 2023. https://venturebeat.com/ai/10-
years-on-ai-pioneers-hinton-lecun-li-say-deep-learning-revolution-will-continue/.
175.M. Tim Jones, “Train a software agent to behave rationally with reinforcement learning.” October
11, 2017. Accessed March 27, 2023. https://developer.ibm.com/articles/cc-reinforce-
ment-learning-train-software-agent/.
176.“What is generative AI?” January 19, 2023. Accessed March 18, 2023. https://www.mck-
insey.com/featured-insights/mckinsey-explainers/what-is-generative-ai.
177.“Generative artificial intelligence.” Wikipedia. Wikimedia Foundation. Accessed March 18, 2023.
https://en.wikipedia.org/wiki/Generative_artificial_intelligence.
178.“Introducing ChatGPT.” Accessed March 18, 2023. https://openai.com/blog/chatgpt.
179.“Large language model.” Wikipedia. Wikimedia Foundation. Accessed March 18, 2023. https://
en.wikipedia.org/wiki/Large_language_model.
180.“ChatGPT.” Wikipedia. Wikimedia Foundation. Accessed March 18, 2023. https://en.wikipe-
dia.org/wiki/ChatGPT.
58 Chapter 1 Intro to Computers and C++
with the ability to process both text and image inputs.181 Powerful, large-language-model
apps like ChatGPT and Google’s Bard182 sometimes produce incorrect results or “halluci-
nations,”183 so you should verify the information tools like these provide.
When you converse with ChatGPT and similar tools, it may seem like you’re chatting
with another person. In 1950, Alan Turing proposed the imitation game—now known
as the Turing test—as a way to determine whether a computer exhibits intelligent behav-
ior.184 In it, three computer terminals would be hidden from one another, with two people
operating terminals via text-based inputs and the third being computer-operated. One
person would ask text-based questions that would be sent to the other two terminals. The
second person and the computer would send text responses. If the person asking the ques-
tions could not determine whether the answers came from the other person or the com-
puter, then the computer would be considered to have exhibited intelligent behavior.
Dall-E 2
OpenAI’s Dall-E 2 is a generative AI for creating images from natural-language text
prompts185,186 such as, “Generate an image of a golden retriever dog in the style of Claude
Monet.” Visit https://labs.openai.com/ to view sample images created by Dall-E 2—
hovering over an image reveals the text prompt on which the image is based. Some text
prompts that have produced cool-looking images include:
• “An armchair in the shape of an avocado.”
• “A futuristic neon lit cyborg face.”
• “A van Gogh style painting of an American football player.”
• “A Formula 1 car driving on a neon road.”
• “A Shiba Inu dog wearing a beret and black turtleneck.”
• “A comic book cover of a superhero wearing headphones.”
Checkpoint
1 (Fill-In) The ultimate goal of AI is to produce a(n) .
Answer: artificial general intelligence.
2 (Fill-In) IBM’s Watson beat the two best human Jeopardy! players. Watson was
trained using a combination of learning and learning techniques.
Answer: machine, reinforcement.
1.17 Wrap-Up
This chapter introduced basic computer hardware, software and Internet concepts. We
considered how computers are organized into logical units. We discussed Moore’s Law
and noted that the continued improvements it so accurately predicted for many years seem
to be ending. As a result, computer hardware designers have shifted to multi-core hardware
architectures, which are programmed with the concurrent programming techniques we
discuss in depth in Chapter 17, Parallel Algorithms and Concurrency: A High-Level View,
and Chapter 18, C++20 Coroutines.
We showed how data items can be viewed as an organized hierarchy of increasingly
complex types, from bits, to bytes, to fields, to records to databases. We discussed the evolu-
tion of computer languages, from machine languages to assembly languages to high-level lan-
guages like C++, and we mentioned other popular high-level programming languages.
We considered popular desktop and laptop operating systems, including the propri-
etary Microsoft Windows and the open-source Linux. And we considered mobile operat-
ing systems, including Apple’s proprietary iOS for its iPhones and Google’s open-source
Android that runs on a wide variety of smartphones from other vendors.
We encouraged you to avoid reinventing the wheel when developing new software
and instead use existing software components from the C++ standard library and open-
source C++ libraries, like Boost. We use Boost classes in two of our nine objects-natural
case studies.
We presented a friendly introduction to object orientation using an automobile anal-
ogy to discuss classes, objects, inheritance and polymorphism. This provides the ground-
work for our objects-natural case studies in Chapters 2 through 9 and our detailed
treatment of the principles of object-oriented programming in Chapters 9–11, which are
then used throughout the rest of the book.
We discussed a simplified view of a C++ development environment and the steps
involved in C++ program development, including editing, preprocessing, compiling, link-
ing, loading and executing. Between the software installation discussions in the Before You
Begin section and the Test-Drives in Section 1.11, you installed the compiler(s) you’ll use
to compile this book’s programs and the programs you write to solve the exercises.
We discussed the Internet, the World Wide Web, the Cloud and the Internet of
Things (IoT). We introduced the Metaverse and associated technologies, including block-
chain, cryptocurrencies, non-fungible tokens (NFTs), Web3, augmented reality (AR), vir-
tual reality (VR) and mixed reality.
We considered various key software development technologies, including refactoring,
design patterns, software development kits (SDKs), version control systems (VCS), agile
software development, test-driven development (TDD), microservices and containerization.
We considered big data and various data sizes from megabytes to exabytes. Finally, we
discussed artificial intelligence (AI)—an intersection between computer science and data
science—introducing various AI technologies, including artificial general intelligence
(AGI), machine learning and deep learning and reinforcement learning, and presenting
various AI milestones, including generative AIs like ChatGPT and Dall-E 2. In Chapter
2, we begin our presentation of C++ programming.
60 Chapter 1 Intro to Computers and C++
Exercises
1.1 Categorize each of the following items as either hardware or software:
a) CPU.
b) C++ compiler.
c) ALU.
d) C++ preprocessor.
e) input unit.
f) an editor program.
1.2 (Computer Organization) Fill in the blanks in each of the following statements:
a) The logical unit that receives information from outside the computer for use by
the computer is the .
b) is the logical unit that sends information the computer has already
processed to various devices for use outside the computer.
c) and are the computer’s logical units that retain information.
d) is the computer’s logical unit for performing calculations.
e) is the computer’s logical unit for making logical decisions.
f) is the computer’s logical unit for coordinating the other logical units’
activities.
1.3 Discuss the purpose of each of the following:
a) cin
b) cout
c) cerr
1.4 Fill in the blanks in each of the following statements:
a) Information in the computer’s memory unit is —it’s typically lost
when the computer’s power is turned off.
b) As a measure of computer memory size, TB stands for —which is
1024 gigabytes.
c) Most computers today have processors that economically implement
multiple processors on a single integrated circuit chip.
d) enable concurrent programming with a sequential like coding style.
e) The most popular database model is the database in which data is
stored in simple tables of rows and columns.
f) is the process of searching through extensive collections of data to find
valuable insights.
g) With software individuals contribute to developing, maintaining and
evolving the software. Anyone can then use that software for their own purpos-
es—normally at no charge, but subject to various (typically generous) licensing
requirements.
h) Today, most of the code for general-purpose operating systems is written in
.
i) The C++ programming models are , , , ,
.
j) Existing older C++ code using older coding idioms is called code.
k) When writing new software avoid . Instead use existing pieces from
code libraries.
Exercises 61
1.9 (Research: Intelligent Assistants) Many companies now offer computerized intelli-
gent assistants, such as Amazon Alexa, Apple Siri, Google Assistant and Microsoft Corta-
na. Research these and others, and list uses that can improve people’s lives. Research
privacy and ethics issues for intelligent assistants. Research intelligent-assistant anecdotes.
Would you do what an intelligent assistant told you to?
1.10 (Research: AI in Health Care) Research the rapidly growing field of AI big-data ap-
plications in health care. For example, suppose a diagnostic medical application had access
to every x-ray that’s ever been taken and the associated diagnoses—that’s surely big data.
“Deep Learning” computer-vision applications could work with this “labeled” data to
learn to diagnose medical problems. Research deep learning in diagnostic medicine and
list some of its most significant accomplishments. What are some ethical issues of having
machines instead of human doctors performing medical diagnoses? Would you trust a ma-
chine-generated diagnosis? Would you seek a second opinion from another diagnostic ma-
chine? Would you insist on a second opinion from a human doctor?
1.11 (Research: Privacy and Data Integrity Legislation) Some key privacy laws are HI-
PAA (the Health Insurance Portability and Accountability Act) and the California Con-
sumer Privacy Act (CCPA)—both in the United States, and GDPR (the General Data
Protection Regulation) in the European Union. Laws like these are becoming more com-
mon and stricter. Investigate these laws and the major protections they provide for your
privacy.
1.12 (Research: Personally Identifiable Information) Protecting users’ personally iden-
tifiable information (PII) is an important aspect of privacy. Research and comment on this
issue.
1.13 (Research: Big Data, AI and the Cloud—How Companies Use These Technologies)
For a major organization of your choice, research how they might be using each of the fol-
lowing technologies: AI, big data, the cloud, mobile, natural-language processing, speech
recognition, speech synthesis, database, machine learning, deep learning, reinforcement
learning, Internet of Things (IoT) and web services.
1.14 (Research: Raspberry Pi and the Internet of Things) It’s now possible to have a
computer at the heart of just about any device and to connect those devices to the Internet.
This has led to the Internet of Things (IoT), which is already connecting billions of devic-
es. The Raspberry Pi is an economical computer often at the heart of IoT devices, and it
can be programmed in C++. Research the Raspberry Pi and some of the many IoT appli-
cations in which it’s used.
1.15 (Research: The Ethics of Deep Fakes) Artificial intelligence deep-learning technol-
ogies make it possible to create deep fakes—realistic fake videos of people that capture
their appearance, voice, body motions and facial expressions. You can have them say and
do whatever you specify. Research the ethics of deep fakes. What would happen if you
turned on your TV and saw a deep-fake video of a prominent government official or news-
caster reporting that an attack was about to happen? A famous low-tech version of this was
Orson Welles’s “War of the Worlds” radio broadcast of 1938, in which he created a mass
panic by announcing that Martians were attacking New Jersey.
1.16 (Research: Blockchain—A World of Opportunity) Cryptocurrencies like Bitcoin
and Ethereum are based on blockchain technology that has seen explosive growth over the
64 Chapter 1 Intro to Computers and C++
last few years. Research blockchain’s origin, applications and how it came to be used as the
basis for cryptocurrencies. Research other major applications of blockchain. It is expected
that blockchain technology will be crucial to implementing the Metaverse. Over the next
many years, there will be extraordinary opportunities for software developers who thor-
oughly understand blockchain application development.
1.17 (Public-Key Cryptography) Cryptography is a crucial technology for privacy and
security. In this book, you’ll have the opportunity to study both secret-key and public-key
cryptography. Research how public-key cryptography is used to implement the Bitcoin
cryptocurrency.
1.18 (Programmer Responsibility and Liability) As a programmer working in the
health-care industry, suppose a software bug in one of your programs caused a cancer pa-
tient to receive an excessive dose of radiation therapy resulting in severe injury or death.
Discuss the issues.
1.19 (2010 “Flash Crash”) An example of the consequences of our dependency on com-
puters was the so-called “flash crash,” which occurred on May 6, 2010, when the U.S.
stock market fell precipitously in a matter of minutes, wiping out trillions of dollars of in-
vestments—then recovered within minutes. Use the Internet to investigate the causes of
this crash and discuss the issues it raises.
Intro to C++20 Programming 2
Objectives
In this chapter, you’ll:
■ Write simple C++
applications.
■ Use input and output
statements.
■ Use fundamental data types.
2.1 Introduction
This chapter presents several code examples that demonstrate how your programs can dis-
play messages and obtain data from the user for processing. The first three examples out-
put messages on the screen. The fourth example obtains two numbers from a user at the
keyboard, calculates their sum and displays the result—the accompanying discussion
introduces C++’s arithmetic operators. The fifth example demonstrates decision-making
by showing how to compare two numbers, then display messages based on the comparison
results.
1 // fig02_01.cpp
2 // Text-printing program.
3 #include <iostream> // enables program to output data to the screen
4
5 // function main begins program execution
6 int main() {
7 std::cout << "Welcome to C++!\n"; // display message
8
9 return 0; // indicate that program ended successfully
10 } // end function main
Welcome to C++!
Comments
Lines 1 and 2
// fig02_01.cpp
// Text-printing program.
both begin with //, indicating that the remainder of each line is a comment. You insert
comments to document your programs and help other people read and understand them.
Comments do not cause the computer to perform any action when the program is run—
they’re ignored by the C++ compiler. In our programs, the first-line comment contains the
program’s file name. The second-line comment "Text-printing program." describes the
program’s purpose. A comment beginning with // is called a single-line comment because
it terminates at the end of the current line. You can create single or multiline comments
by enclosing them in /* and */, as in
/* fig02_01.cpp: Text-printing program. */
or
/* fig02_01.cpp
Text-printing program. */
is a part of every C++ program. The parentheses after main indicate that it’s a function.
C++ programs typically consist of one or more functions and classes. One function in
every program must be named main. This is where C++ programs begin executing. The
keyword int indicates that after main finishes executing, it “returns” an integer (whole
number) value. Keywords, like return, are reserved for use by C++. We show the com-
plete list of C++ keywords in Chapter 3. We’ll explain what it means for a function to
“return a value” when we demonstrate how to create your own functions in Chapter 5. For
now, simply include the keyword int to the left of main in each of your programs.
A left brace, {, (end of line 6) must begin each function’s body, which contains the
instructions the function performs. A corresponding right brace, }, (line 10) must end
each function’s body.
An Output Statement
Line 7
std::cout << "Welcome to C++!\n"; // display message
displays the characters contained between the double quotation marks. The quotation
marks and the characters between them are called a string, a character string or a string
literal. We refer to characters between double quotation marks simply as strings.
Whitespace characters in strings are not ignored by the compiler. The entire line 7—
including std::cout, the << operator, the string "Welcome to C++!\n" and the semicolon
(;)—is called a statement. Most C++ statements end with a semicolon. Preprocessing direc-
tives (such as #include) are not C++ statements and do not end with a semicolon.
Typically, output and input in C++ are accomplished with streams of data. When the
preceding statement executes, it sends the stream of characters Welcome to C++!\n to the
standard output stream object (std::cout), which is usually “connected” to the screen.
Err Omitting the semicolon at the end of a C++ statement is a syntax error. The syntax
of a programming language specifies the rules for creating proper programs in that lan-
guage. A syntax error occurs when the compiler encounters code that violates C++’s lan-
guage rules (i.e., its syntax). The compiler issues an error message to help you locate and
fix the incorrect code. Syntax errors are also called compiler errors, compile-time errors
or compilation errors because the compiler detects them during the compilation phase.
You cannot execute your program until you correct all the syntax errors. As you’ll see,
some compilation errors are not syntax errors.
Indentation
Indent each function’s body one level within the braces that delimit the body. This makes
a program’s functional structure stand out, making the program easier to read. Set a con-
vention for the indent size you prefer, then apply it uniformly. The tab key may be used
to create indents, but tab stops may vary. We prefer three spaces per level of indent.
2.2 First Program in C++: Displaying a Line of Text 69
\n Newline. Positions the screen cursor to the beginning of the next line.
\t Horizontal tab. Moves the screen cursor right to the next tab stop.
\r Carriage return. Positions the screen cursor to the beginning of the
current line; does not advance to the next line.
\a Alert. Sounds the system bell.
\\ Backslash. Includes a backslash character in a string.
\' Single quote. Includes a single-quote character in a string.
\" Double quote. Includes a double-quote character in a string.
is one of several means we’ll use to exit a function. In this return statement at the end of
main, the value 0 indicates that the program terminated successfully. The main function
implicitly returns 0 if program execution reaches the closing brace without encountering
a return statement. For this reason, we omit main’s return statement in subsequent pro-
grams that terminate successfully.
Checkpoint
1 (Fill-in) Together, blank lines, spaces and tabs are known as and are usually
ignored by the compiler.
Answer: whitespace.
1. We pronounce “std::” as “standard,” rather as its individual letters s, t and d.
70 Chapter 2 Intro to C++20 Programming
2 (Code) Write a statement that outputs the string "Hello world" then moves the cur-
sor to the beginning of the next line.
Answer: std::cout << "Hello World\n"; // display message
3 (True/False) The following statement, when executed at the end of main, indicates
that the program did not execute correctly:
return 0;
Answer: False. This statement indicates that the program executed successfully.
1 // fig02_02.cpp
2 // Displaying a line of text with multiple statements.
3 #include <iostream> // enables program to output data to the screen
4
5 // function main begins program execution
6 int main() {
7 std::cout << "Welcome ";
8 std::cout << "to C++!\n";
9 } // end function main
Welcome to C++!
1 // fig02_03.cpp
2 // Displaying multiple lines of text with a single statement.
3 #include <iostream> // enables program to output data to the screen
4
5 // function main begins program execution
6 int main() {
7 std::cout << "Welcome\nto\n\nC++!\n";
8 } // end function main
Fig. 2.3 | Displaying multiple lines of text with a single statement. (Part 1 of 2.)
2.4 Another C++ Program: Adding Integers 71
Welcome
to
C++!
Fig. 2.3 | Displaying multiple lines of text with a single statement. (Part 2 of 2.)
Checkpoint
1 (True/False) The following statement displays the string "Hello" then positions the
output cursor on the next line.
std::cout << "Hello";
Answer: False. This statement displays the string "Hello" and leaves the output cursor po-
sitioned after the "o" in "Hello".
2 (True/False) A single statement can display multiple lines by using additional newline
characters.
Answer: True.
3 (Code) Write a statement that outputs a single string, displaying the following and
leaves the output cursor positioned on a new line:
Hello
World
1 // fig02_04.cpp
2 // Addition program that displays the sum of two integers.
3 #include <iostream> // enables program to perform input and output
4
5 // function main begins program execution
6 int main() {
7 // declaring and initializing variables
8 int number1{0}; // first integer to add (initialized to 0)
9 int number2{0}; // second integer to add (initialized to 0)
10 int sum{0}; // sum of number1 and number2 (initialized to 0)
11
12 std::cout << "Enter first integer: "; // prompt user for data
13 std::cin >> number1; // read first integer from user into number1
14
15 std::cout << "Enter second integer: "; // prompt user for more data
16 std::cin >> number2; // read second integer from user into number2
Fig. 2.4 | Addition program that displays the sum of two integers. (Part 1 of 2.)
72 Chapter 2 Intro to C++20 Programming
17
18 sum = number1 + number2; // add the numbers; store result in sum
19
20 std::cout << "Sum is " << sum << "\n"; // display sum
21 } // end function main
Fig. 2.4 | Addition program that displays the sum of two integers. (Part 2 of 2.)
are declarations, and number1, number2 and sum are the names of variables. A variable is a
location in the computer’s memory where a value can be stored for use by a program.
These declarations specify that the variables number1, number2 and sum are data of type
int, meaning they will hold integer (whole number) values, such as 7, –11, 0 and 31914.
All variables must be declared with a name and a data type.
Lines 8–10 initialize each variable to 0 by placing a value in braces ({ and }) immedi-
ately following the variable’s name. This is known as braced initialization, which was
introduced in C++11. Although it’s not always necessary to initialize every variable explic-
itly, doing so will help you avoid many kinds of problems.
Lines 8–10 also can be written as:
int number1 = 0; // first integer to add (initialized to 0)
int number2 = 0; // second integer to add (initialized to 0)
int sum = 0; // sum of number1 and number2 (initialized to 0)
In legacy C++ programs, you’re likely to encounter initialization statements using this
older coding style. Our code examples use braced initialization. In subsequent chapters,
we’ll discuss various benefits of braced initializers.
However, this makes the program less readable and makes it awkward to provide com-
ments that describe each variable’s purpose.
Fundamental Types
We’ll soon discuss the type double for specifying real numbers and char for character data.
Real numbers are numbers with decimal points, such as 3.4, 0.0 and –11.19. A char vari-
able may hold one lowercase letter, uppercase letter, digit or special character (e.g., $ or *).
Types such as int, double, char and long are called fundamental types and are built into
2.4 Another C++ Program: Adding Integers 73
C++. Fundamental-type names typically consist of one or more keywords and must appear
in all lowercase letters. For a complete list of C++ fundamental types and their ranges, see
https://en.cppreference.com/w/cpp/language/types
In fact, lines 10 and 18 could have been combined into the following declaration and
placed just before line 20:
int sum{number1 + number2}; // initialize sum with number1 + number2
displays Enter first integer: followed by a space. This message is called a prompt
because it directs the user to take a specific action. Line 13
std::cin >> number1; // read first integer from user into number1
uses the standard input stream object cin (of namespace std) and the stream extraction
operator, >>, to obtain a value from the keyboard.
When the preceding statement executes, the program waits for you to enter a value
for variable number1. You respond by typing an integer (as characters), then pressing the
Enter key (sometimes called the Return key) to send the characters to the program. The
cin object converts the character representation of the number to an integer value and
assigns this value to the variable number1. Pressing Enter also causes the cursor to move to
the beginning of the next line on the screen.
When your program expects the user to enter an integer, the user could enter alpha-
betic characters, special symbols (like # or @) or a number with a decimal point (like 73.5).
In these early programs, we assume that the user enters valid data. We’ll present various
techniques for dealing with data-entry problems later.
displays Enter second integer: on the screen, prompting the user to take action. Line 16
std::cin >> number2; // read second integer from user into number2
adds the values of number1 and number2 and assigns the result to sum using the assignment
operator =. Most calculations are performed in assignment statements. The = operator and
the + operator are binary operators—each has two operands. For the + operator, the two
operands are number1 and number2. For the preceding = operator, the two operands are sum
and the value of the expression number1 + number2. Placing a space on each side of a binary
operator makes the operator stand out and makes the program more readable.
displays the string "Sum is" followed by the numerical value of variable sum and a newline.
This statement outputs values of multiple types. The stream insertion operator “knows”
how to output each type of data. Using multiple stream insertion operators (<<) in a single
statement is called concatenating, chaining or cascading stream insertion operations.
Calculations can also be performed in output statements. We could have eliminated
the variable sum by combining the statements in lines 18 and 20 into the statement
std::cout << "Sum is " << number1 + number2 << "\n";
2.5 Memory Concepts 75
A signature feature of C++ is that you can create your own data types called classes,
which we discuss in depth in Chapter 9 and subsequent chapters. You can then “teach”
C++ how to input and output values of these new data types using the >> and << operators,
respectively. This is called operator overloading, which we explore in Chapter 11.
Checkpoint
1 (Code) Write a statement that initializes the int variable total to 0 using braced ini-
tialization.
Answer: int total{0};
2 (Code) Assume the int variables billAmount and tip exist and have been initialized.
Write an initialization statement that adds the values of billAmount and tip and stores
the result in the new int variable totalBill.
Answer: int totalBill{billAmount + tip};
3 (True/False) Variables must be defined with a type and a name before using them.
Answer: True.
the program places the integer typed by the user into a memory location to which the com-
piler assigned the name number1. If the user enters 45 for number1, the program places 45
into the location number1, as in:
number1 45
When a value is placed in a memory location, the new value overwrites the previous one
in that location—that previous value is lost.
Returning to our addition program, suppose the user enters 72 when the following
statement (line 16) executes:
std::cin >> number2; // read second integer from user into number2
The program places 72 into the location number2, and memory appears as in:
number1 45
number2 72
places the calculated sum of number1 and number2 into variable sum, after which memory
appears as follows:
number1 45
number2 72
sum 117
Performing the calculation uses, but does not modify, the values of number1 and number2.
Checkpoint
1 (Fill-in) Every variable has a name, a ,a and a .
Answer: type, size, value.
2 (True/False) Storing a value in a variable replaces the previous value in the corre-
sponding memory location.
Answer: True.
3 (True/False) An expression like number1 + number2 uses the values of the variables
number1 and number2, but does not modify them.
Answer: True.
2.6 Arithmetic
The following table summarizes the arithmetic operators:
Addition + f+7 f + 7
Subtraction - p–c p - c
Multiplication * bm or b ⋅ m b * m
Division / x / y or x-y- or x ÷ y x / y
Remainder % r mod s r % s
The asterisk (*) indicates multiplication, and the percent sign (%) is the remainder opera-
tor, which we’ll discuss shortly. These arithmetic operators are all binary operators.
Integer Division
Integer division in which the numerator and the denominator are integers yields an inte-
ger quotient. So, the expression 7 / 4 evaluates to 1, and the expression 17 / 5 evaluates to
3. Any fractional part resulting from integer division is truncated—no rounding occurs.
Remainder Operator
The remainder operator, % (also called the modulus operator), yields the remainder after
integer division and can be used only with integer operands. The expression x % y yields
the remainder after dividing x by y. Thus, 7 % 4 yields 3 and 17 % 5 yields 2.
2.6 Arithmetic 77
The parentheses are required because division has higher precedence than addition. The
entire quantity (a + b + c + d + e) is to be divided by 5. If the parentheses are erroneously
omitted, we obtain a + b + c + d + e / 5, which evaluates incorrectly as Err
e
a + b + c + d + ---
5
The following is an example of the equation of a straight line:
Algebra: y = mx + b
C++: y = m * x + b;
78 Chapter 2 Intro to C++20 Programming
No parentheses are required. Multiplication is applied first because it has higher prece-
dence than addition.
6 1 2 4 3 5
Redundant Parentheses
As in algebra, it’s acceptable to place unnecessary parentheses in an expression to make it
clearer. These are called redundant parentheses. For example, the second-degree polyno-
mial could be parenthesized as follows:
y = (a * x * x) + (b * x) + c;
2.7 Decision Making: Equality and Relational Operators 79
Checkpoint
1 (True/False) The expression 10 / 4, which contains two integer operands, produces
the quotient 2.5.
Answer: False. Integer division produces an integer quotient, so the quotient is 2.
2 (Fill-in) The result of the expression 10 % 3 is , and the result of the expres-
sion 10 % 7 is ,
Answer: 1, 3.
3 (Code) Write an expression that divides number1 by the difference between number2
and number3.
Answer: number1 / (number2 - number3)
Relational operators
> > x > y x is greater than y
< < x < y x is less than y
≥ >= x >= y x is greater than or equal to y
Equality operators
= == x == y x is equal to y
≠ != x != y x is not equal to y
The relational operators all have the same precedence and group from left-to-right. The
equality operators have the same precedence—lower than that of the relational opera-
tors—and group from left-to-right.
Reversing the order of the symbols in the operators !=, >= and <= (by writing them as
=!, => and =<, respectively) is usually a syntax error. In some cases, writing != as =! will not Err
be a syntax error but almost certainly will be a runtime logic error—an error that causes
the program to execute incorrectly. You’ll understand why when we cover logical operators
in Section 4.11.
Confusing == and =
Confusing the equality operator == with the assignment operator = results in logic errors. Err
We like to read the equality operator as “is equal to” or “double equals” and the assignment
operator as “gets” or “gets the value of” or “is assigned the value of.” Confusing these oper-
ators may not necessarily cause an easy-to-recognize syntax error, but it may cause subtle
logic errors. Compilers generally warn about this.
80 Chapter 2 Intro to C++20 Programming
1 // fig02_05.cpp
2 // Comparing integers using if statements, relational operators
3 // and equality operators.
4 #include <iostream> // enables program to perform input and output
5
6 using std::cout; // program uses cout
7 using std::cin; // program uses cin
8
9 // function main begins program execution
10 int main() {
11 int number1{0}; // first integer to compare (initialized to 0)
12 int number2{0}; // second integer to compare (initialized to 0)
13
14 cout << "Enter two integers to compare: "; // prompt user for data
15 cin >> number1 >> number2; // read two integers from user
16
17 if (number1 == number2) {
18 cout << number1 << " == " << number2 << "\n";
19 }
20
21 if (number1 != number2) {
22 cout << number1 << " != " << number2 << "\n";
23 }
24
25 if (number1 < number2) {
26 cout << number1 << " < " << number2 << "\n";
27 }
28
29 if (number1 > number2) {
30 cout << number1 << " > " << number2 << "\n";
31 }
32
33 if (number1 <= number2) {
34 cout << number1 << " <= " << number2 << "\n";
35 }
36
37 if (number1 >= number2) {
38 cout << number1 << " >= " << number2 << "\n";
39 }
40 } // end function main
Fig. 2.5 | Comparing integers using if statements, relational operators and equality operators.
(Part 1 of 2.)
2.7 Decision Making: Equality and Relational Operators 81
Fig. 2.5 | Comparing integers using if statements, relational operators and equality operators.
(Part 2 of 2.)
using Declarations
Lines 6–7
using std::cout; // program uses cout
using std::cin; // program uses cin
are using declarations that eliminate the need to repeat the std:: prefix as we did in ear-
lier programs. We can now simply write cout instead of std::cout and cin instead of
std::cin in the remainder of the program.
using Directive
In place of lines 6–7, many programmers prefer the using directive
using namespace std;
which enables your program to use names from the std namespace without the std::
qualification. In the early chapters, we’ll use this directive to simplify the code,2 but in
Chapter 6 we’ll return to using std::, which is considered good practice and can help you
avoid some subtle coding errors. Err
uses cascaded stream extraction operations to input two integers. Recall that we’re allowed
to write cin (instead of std::cin) because of line 7. This statement first reads a value into
number1, then reads another value into number2.
2. In Chapter 20, we’ll discuss some disadvantages of using directives in large-scale systems.
82 Chapter 2 Intro to C++20 Programming
Comparing Numbers
The if statement in lines 17–19
if (number1 == number2) {
cout << number1 << " == " << number2 << "\n";
}
determines whether the values of variables number1 and number2 are equal. If so, the out-
put statement (line 18) displays a line of text indicating that the numbers are equal. For
each condition that is true in the remaining if statements starting in lines 21, 25, 29, 33
and 37, the corresponding output statement displays an appropriate line of text.
Checkpoint
1 (Code) Write a using directive that enables you to use cin and cout without the std::
qualification.
Answer: using namespace std;
2 (Code) Assume number1 is 12 and number2 is 23. What does the following code print?
if (number1 > number2) {
cout << number1 << " > " << number2 << "\n";
}
Answer: The statement will not print anything because the condition is false, so the body
of the statement will be skipped.
3 (Code) Assume number1 is 23 and number2 is 23. What does the following code print?
[Write and execute a short program to see what this code actually does.]
if (number1 != number2); {
cout << number1 << " != " << number2 << "\n";
}
Answer: This code will incorrectly print 23 != 23 because a semicolon is incorrectly placed
immediately following the if statement’s condition.
3. You’ll learn additional string capabilities in subsequent chapters. Chapter 8 discusses class string
in detail, test-driving many more of its member functions.
84 Chapter 2 Intro to C++20 Programming
1 // fig02_06.cpp
2 // Standard library string class test program.
3 #include <iostream>
4 #include <string>
5 using namespace std;
6
7 int main() {
8 string s1{"happy"};
9 string s2{" birthday"};
10 string s3; // creates an empty string
11
12 // display the strings and show their lengths
13 cout << "s1: \"" << s1 << "\"; length: " << s1.length()
14 << "\ns2: \"" << s2 << "\"; length: " << s2.length()
15 << "\ns3: \"" << s3 << "\"; length: " << s3.length();
16
17 // compare strings with == and !=
18 cout << "\n\nThe results of comparing s2 and s1:" << boolalpha
19 << "\ns2 == s1: " << (s2 == s1)
20 << "\ns2 != s1: " << (s2 != s1);
21
22 // test string member function empty
23 cout << "\n\nTesting s3.empty():\n";
24
25 if (s3.empty()) {
26 cout << "s3 is empty; assigning to s3;\n";
27 s3 = s1 + s2; // assign s3 the result of concatenating s1 and s2
28 cout << "s3: \"" << s3 << "\"";
29 }
30
31 // testing new C++20 string member functions
32 cout << "\n\ns1 starts with \"ha\": " << s1.starts_with("ha") << "\n";
33 cout << "s2 starts with \"ha\": " << s2.starts_with("ha") << "\n";
34 cout << "s1 ends with \"ay\": " << s1.ends_with("ay") << "\n";
35 cout << "s2 ends with \"ay\": " << s2.ends_with("ay") << "\n";
36 }
Testing s3.empty():
s3 is empty; assigning to s3;
s3: "happy birthday"
Instantiating Objects
Typically, you cannot call a member function of a class until you create an object of that
class4—also called instantiating an object. Lines 8–10 create three string objects:
• s1 is initialized with a copy of the string literal "happy",
• s2 is initialized with a copy of the string literal " birthday", and
• s3 is initialized by default to the empty string (that is, "").
When we declare int variables, as we did earlier, the compiler knows what int is—it’s a
fundamental type built into C++. In lines 8–10, however, the compiler does not know in
advance what type string is—it’s a class type from the C++ standard library.
When packaged properly, classes can be reused by other programmers. This is one of
the most significant benefits of working with languages like C++ that support object-
oriented programming. Such languages have rich libraries of powerful prebuilt classes. For
example, you can reuse the C++ standard library’s classes in any program by including the
appropriate headers—in this case, the <string> header (line 4). The name string, like
the name cout, belongs to namespace std.
returns s1’s length by calling the object’s length member function. To call this member
function for a specific object, you specify the object’s name (s1), followed by the dot oper-
ator (.), then the member function name (length) and a set of parentheses. Empty paren-
theses indicate that length does not require additional information to perform its task.
Soon, you’ll see that some member functions require additional information called argu-
ments to perform their tasks.
From main’s view, when the length member function is called:
1. The program transfers execution from the call (line 13 in main) to member func-
tion length. Because length was called via the s1 object, length “knows” which
object’s data to manipulate.
2. Next, member function length performs its task—that is, it returns s1’s length
to line 13, where the function was called. The main function does not know how
length performs its task, just as the driver of a car doesn’t know how engines,
transmissions, steering mechanisms and brakes are implemented.
3. The cout object displays the number of characters returned by member function
length, then the program continues executing, displaying the strings s2 and s3
and their lengths.
4. You’ll see in Section 9.20 that you can call a class’s static member functions without creating an
object of that class.
86 Chapter 2 Intro to C++20 Programming
Checkpoint
1 (Code) Assume the string object name exists and is initialized. Write a string mem-
ber-function call that returns true if the name starts with "Je".
Answer: name.starts_with("Je")
2 (Code) Assume the string object name exists and is initialized. Write a string mem-
ber-function call that returns true if the name ends with "on".
Answer: name.ends_with("on")
2.9 Wrap-Up
We presented many important C++ features in this chapter, including displaying data on
the screen, inputting data from the keyboard and declaring variables of fundamental types.
You learned to use the output stream object cout and the input stream object cin to build
simple interactive programs. We declared and initialized variables and used arithmetic
operators to perform calculations. We discussed the order in which C++ applies operators
(i.e., the rules of operator precedence), as well as the grouping of the operators (also called
the associativity of the operators). You saw how C++’s if statement allows a program to
make decisions. We introduced the equality and relational operators, which we used to
form conditions in if statements.
5. In Chapter 8, you’ll see that strings perform “lexicographical” comparisons using the numerical val-
ues of the characters in each string.
Exercises 87
Exercises
2.1 Fill in the blanks in each of the following:
a) are used to document a program and improve its readability.
b) The object used to print information on the screen is .
c) A C++ statement that makes a decision is .
d) Most calculations are normally performed by statements.
e) The object inputs values from the keyboard.
f) What arithmetic operations are on the same level of precedence as multiplica-
tion? .
g) When parentheses are nested, which set of parentheses is evaluated first in an
arithmetic expression? .
h) A location in the computer’s memory that may contain different values
throughout the execution of a program is called a(n) .
2.2 Discuss the meaning of each of the following objects:
a) std::cin
b) std::cout
2.3 State whether each of the following is true or false. If false, explain why. Assume the
statement using std::cout; is used.
a) Comments cause the computer to print the text after the // on the screen when
the program is executed.
b) Displaying the escape sequence \n causes the cursor to position to the begin-
ning of the next line on the screen.
c) All variables must be declared before they’re used.
d) All variables must be given a type when they’re declared.
e) C++ considers the variables number and NuMbEr to be identical.
f) Declarations can appear almost anywhere in the body of a C++ function.
g) The remainder operator (%) can be used only with integer operands.
h) The arithmetic operators *, /, %, + and – all have the same level of precedence.
i) All operators are evaluated from left to right.
j) The following are all valid variable names: _under_bar_, m928134, t5, j7,
her_sales, his_account_total, a, b, c, z, z2.
k) The statement cout << "a = 5;"; is an assignment statement.
l) A valid arithmetic expression with no parentheses is evaluated from left to right.
m) The following are all invalid variable names: 3g, 87, 67h2, h22, 2h.
2.4 Write a single C++ statement to accomplish each of the following (assume that nei-
ther using declarations nor a using directive has been used):
88 Chapter 2 Intro to C++20 Programming
2.6 What, if anything, prints when each of the following statements executes? If noth-
ing prints, answer “nothing.” Assume x = 2 and y = 3.
a) cout << x;
b) cout << x + x;
c) cout << "x=";
d) cout << "x = " << x;
e) cout << x + y << " = " << y + x;
f) z = x + y;
g) cin >> x >> y;
h) // cout << "x + y = " << x + y;
i) cout << "\n";
2.7 Which of the following statements contain variables whose values are replaced?
a) cin >> b >> c >> d >> e >> f;
b) p = i + j + k + 7;
c) cout << "variables whose values are replaced";
d) cout << "a = 5";
2.8 Given the algebraic equation y = ax 3 + 7, which of the following, if any, are correct
C++ statements for this equation?
a) y = a * x * x * x + 7;
b) y = a * x * x * (x + 7);
c) y = (a * x) * x * (x + 7);
d) y = (a * x) * x * x + 7;
Exercises 89
e) y = a * (x * x * x) + 7;
f) y = a * x * (x * x + 7);
2.9 (Order of Evaluation) State the order of evaluation of the operators in each of the
following C++ statements and show the value of x after each statement is performed.
a) x = 7 + 3 * 6 / 2 - 1;
b) x = 2 % 2 + 2 * 2 - 2 / 2;
c) x = (3 * 9 * (3 + (9 * 3 / (3))));
2.10 Write a statement (or comment) to accomplish each of the following (assume that
using declarations have been used for cin, cout and endl):
a) Document that a program calculates the product of three integers.
b) Declare the variables x, y, z and result to be of type int (in separate state-
ments) and initialize each to 0.
c) Prompt the user to enter three integers.
d) Read three integers from the keyboard and store them in variables x, y and z.
e) Compute the product of the three integers in variables x, y and z, and assign
the result to the variable result.
f) Print "The product is " followed by the value of the variable result.
2.11 Using the statements you wrote in Exercise 2.10, write a complete program that
calculates and displays the product of three integers. Add comments to the code where ap-
propriate. [Note: You’ll need to write the necessary using declarations or directive.]
2.12 (Arithmetic) Write a program that asks the user to enter two integers, obtains the
numbers from the user and prints their sum, product, difference, and quotient.
2.13 (Printing) Write a program that prints the numbers 1 to 4 on the same line with
each pair of adjacent numbers separated by one space. Do this in several ways:
a) Using one statement with one stream insertion operator.
b) Using one statement with four stream insertion operators.
c) Using four statements.
2.14 (Comparing Integers) Write a program that asks the user to enter two integers, ob-
tains the numbers from the user, then prints the larger number followed by the words "is
larger." If the numbers are equal, print the message "These numbers are equal."
2.15 (Arithmetic, Smallest and Largest) Write a program that inputs three integers from
the keyboard and prints the sum, average, product, smallest and largest of these numbers.
The screen dialog should appear as follows:
Input three different integers: 13 27 14
Sum is 54
Average is 18
Product is 4914
Smallest is 13
Largest is 27
2.16 (Diameter, Circumference and Area of a Circle) Write a program that reads a cir-
cle’s radius as an integer and prints the circle’s diameter, circumference and area. Use the
constant value 3.14159 for π. Do all calculations in output statements. [Note: In this chap-
ter, we’ve discussed only integer constants and variables. In Chapter 4, we discuss floating-
point numbers, i.e., values that have decimal points.]
90 Chapter 2 Intro to C++20 Programming
2.18 (Largest and Smallest Integers) Write a program that reads in five integers and de-
termines and prints the largest and the smallest integers in the group. Use only the pro-
gramming techniques you learned in this chapter.
2.19 (Odd or Even) Write a program that reads an integer and determines and prints
whether it’s odd or even. [Hint: Use the remainder operator (%). An even number is a mul-
tiple of two. Any multiple of 2 leaves a remainder of zero when divided by 2.]
2.20 (Multiples) Write a program that reads in two integers and determines and prints
if the first is a multiple of the second. [Hint: Use the remainder operator (%).]
2.21 (Checkerboard Pattern) Display the following checkerboard pattern with eight
output statements, then display the same pattern using as few statements as possible.
* * * * * * * *
* * * * * * * *
* * * * * * * *
* * * * * * * *
* * * * * * * *
* * * * * * * *
* * * * * * * *
* * * * * * * *
2.22 (Integer Equivalent of a Character) Here is a peek ahead. In this chapter, you
learned about integers and the type int. C++ can also represent uppercase letters, lower-
case letters and various special symbols. C++ uses small integers internally to represent each
different character. The set of characters a computer uses and the corresponding integer
representations for those characters are called that computer’s character set. You can print
a character by enclosing that character in single quotes, as with
cout << 'A'; // print an uppercase A
You can print the integer equivalent of a character using static_cast as follows:
cout << static_cast<int>('A'); // print 'A' as an integer
4 2 3 3 9
2.24 (Table) Using only the techniques of this chapter, write a program that calculates
the squares and cubes of the integers from 0 to 10. Use tabs to print the following neatly
formatted table of values:
In later chapters, you’ll learn more elegant ways to solve this problem.
This page intentionally left blank
Algorithm Development and
Control Statements: Part 1 3
Objectives
In this chapter, you’ll:
■ Learn basic problem-solving
techniques.
■ Develop algorithms through
the process of top-down,
stepwise refinement.
■ Use the if and if…else
selection statements to
choose between alternative
actions.
■ Use the while iteration
statement to execute
statements in a program
repeatedly.
■ Use counter-controlled
iteration and sentinel-
controlled iteration.
■ Use nested control
statements.
■ Use the compound
assignment operators and the
increment and decrement
operators.
■ Learn why fundamental data
types are not portable.
■ Continue our Objects Natural
approach with a case study on
creating and manipulating
integers as large as you want
them to be.
94 Chapter 3 Algorithm Development and Control Statements: Part 1
Outline
3.1 Introduction 3.9.3 Implementing Sentinel-Controlled
Iteration
3.2 Algorithms
3.9.4 Mixed-Type Expressions and Implicit
3.3 Pseudocode Type Promotions
3.4 Control Structures 3.9.5 Formatting Floating-Point Numbers
3.4.1 Sequence Structure 3.10 Formulating Algorithms: Nested
3.4.2 Selection Statements Control Statements
3.4.3 Iteration Statements 3.10.1 Problem Statement
3.4.4 Summary of Control Statements 3.10.2 Top-Down, Stepwise Refinement:
3.5 if Single-Selection Statement Pseudocode Representation of the Top
3.10.3 Top-Down, Stepwise Refinement:
3.6 if…else Double-Selection First Refinement
Statement 3.10.4 Top-Down, Stepwise Refinement:
3.6.1 Nested if…else Statements Second Refinement
3.6.2 Blocks 3.10.5 Complete Second Refinement of the
3.6.3 Conditional Operator (?:) Pseudocode
3.7 while Iteration Statement 3.10.6 Implementing the Program
3.8 Formulating Algorithms: Counter- 3.10.7 Preventing Narrowing Conversions
with Braced Initialization
Controlled Iteration
3.8.1 Pseudocode Algorithm with Counter- 3.11 Compound Assignment Operators
Controlled Iteration 3.12 Increment and Decrement Operators
3.8.2 Implementing Counter-Controlled 3.13 Fundamental Types Are Not Portable
Iteration
3.8.3 Integer Division and Truncation 3.14 Objects Natural Case Study: Super-
3.8.4 Arithmetic Overflow Sized Integers
3.8.5 Input Validation 3.15 Wrap-Up
3.9 Formulating Algorithms: Sentinel- Exercises
Controlled Iteration
3.9.1 Top-Down, Stepwise Refinement:
The Top and First Refinement
3.9.2 Proceeding to the Second Refinement
3.1 Introduction
Before writing a program to solve a problem, you should have a thorough understanding
of it and a carefully planned approach to solving it. When writing a program, you also
should understand the available building blocks and employ proven program-construction
techniques. In this chapter and the next, we present the theory and principles of structured
programming. As we’ll see in later chapters, the concepts presented here will be crucial in
building classes and manipulating objects.
We discuss the if statement in additional detail and introduce the if…else and
while statements—all of these building blocks allow you to specify the logic required for
functions to perform their tasks. We also introduce the compound assignment operators
and the increment and decrement operators. We discuss why the fundamental types are
not portable. We continue our Objects Natural approach with a case study on creating and
manipulating super-sized integers that can represent values beyond the ranges of integers
supported by computer hardware.
3.2 Algorithms 95
3.2 Algorithms
Any computing problem can be solved by executing a series of actions in a specific order.
An algorithm is a procedure for solving a problem in terms of
1. the actions to execute and
2. the order in which these actions execute
The following example demonstrates that correctly specifying the order in which the
actions execute is essential.
Consider the “rise-and-shine algorithm” one executive follows for getting out of bed
and going to work: (1) Get out of bed; (2) take off pajamas; (3) take a shower; (4) get
dressed; (5) eat breakfast; (6) carpool to work. This routine gets the executive to work well
prepared to make critical decisions. Suppose that the same steps are performed in a slightly
different order: (1) Get out of bed; (2) take off pajamas; (3) get dressed; (4) take a shower;
(5) eat breakfast; (6) carpool to work. In this case, our executive shows up for work soaking
wet. Specifying the order in which statements (actions) execute in a program is called pro-
gram control. This chapter investigates program control using C++’s control statements.
Checkpoint
1 (Fill-in) Specifying the order in which statements (actions) execute in a program is
called .
Answer: program control.
2 (Fill-in) A procedure for solving a problem in terms of the to execute and
the in which these actions execute is called an algorithm.
Answer: actions, order.
3.3 Pseudocode
Pseudocode is an informal language that helps you develop algorithms without worrying
about the strict details of C++ language syntax. The pseudocode we present is particularly
useful for developing algorithms that will be converted to structured portions of C++ pro-
grams. Pseudocode is similar to everyday English (or your preferred language)—it’s con-
venient and user-friendly, but it’s not an actual computer programming language. You’ll
see an algorithm written in pseudocode momentarily.
Pseudocode does not execute on computers. Rather, it helps you “think out” a pro-
gram before attempting to write it in a programming language like C++. This chapter pro-
vides several examples of using pseudocode to develop C++ programs.
The style of pseudocode we present consists purely of characters, so you can type
pseudocode conveniently using any text-editor program. A carefully prepared pseudocode
program can easily be converted to a corresponding C++ program.
Pseudocode typically describes only statements representing the actions that occur
after you convert a program from pseudocode to C++ and run the program. Such actions
might include input, output, assignments or calculations. In our pseudocode, we typically
do not include variable declarations, but some programmers choose to list variables and
mention their purposes.
96 Chapter 3 Algorithm Development and Control Statements: Part 1
The pseudocode statements are simply English statements that convey what task is to
be performed in C++. Lines 1–2 correspond to the C++ statements in lines 12–13 of
Fig. 2.4. Lines 4–5 correspond to the statements in lines 15–16, and lines 7–8 correspond
to the statements in lines 18 and 20.
Checkpoint
1 (Fill-in) The actions described by pseudocode might include , ,
or .
Answer: input, output, assignments, calculations.
2 (Fill-in) is an informal language that helps you develop algorithms without
worrying about the strict details of C++ language syntax.
Answer: Pseudocode.
1. C. Böhm and G. Jacopini, “Flow Diagrams, Turing Machines, and Languages with Only Two For-
mation Rules,” Communications of the ACM, Vol. 9, No. 5, May 1966, pp. 336–371.
3.4 Control Structures 97
synonymous with “goto elimination.” The results were impressive. Software development
groups reported shorter development times, more frequent on-time delivery of systems
and more frequent within-budget completion of software projects. The key to these suc-
cesses was that structured programs were clearer, easier to debug and modify, and more
likely to be bug-free in the first place.
Böhm and Jacopini’s work demonstrated that all programs could be written in terms
of only three control structures—the sequence structure, the selection structure and the
iteration structure. We’ll discuss how C++ implements each of these.
C++ lets you have as many actions as you want in a sequence structure. As you’ll soon see,
anywhere you may place a single action, you may place several actions in sequence.
An activity diagram models the workflow (also called the activity) of a portion of a
software system. Such workflows may include a portion of an algorithm, like the sequence
structure in the preceding diagram. Activity diagrams are composed of symbols, such as
action-state symbols (rectangles with their left and right sides replaced with outward arcs),
diamonds and small circles. These symbols are connected by transition arrows, represent-
ing the activity’s flow—that is, the order in which the actions should occur.
Like pseudocode, activity diagrams help you develop and represent algorithms. Activ-
ity diagrams clearly show how control structures operate.
The preceding sequence-structure activity diagram contains two action states, each
containing an action expression—for example, “add grade to total” or “add 1 to
counter”—that specifies a particular action to perform. The arrows in the activity diagram
represent transitions, which indicate the order in which the actions represented by the
action states occur. The program that implements the activities illustrated in this activity
diagram first adds grade to total, then adds 1 to counter.
2. We use the UML (Unified Modeling Language) in this chapter and Chapter 4 to show the flow of
control in control statements, then use UML again in Chapters 9–10 when we present custom class
development.
98 Chapter 3 Algorithm Development and Control Statements: Part 1
The solid circle at the top of the activity diagram represents the initial state—the
beginning of the workflow before the program performs the modeled actions. The solid
circle surrounded by a hollow circle at the bottom of the diagram represents the final
state—that is, the end of the workflow after the program performs its actions.
The preceding sequence-structure activity diagram also includes rectangles with the
upper-right corners folded over. These are UML notes (like C++ comments)—explana-
tory remarks describing the purpose of symbols in the diagram. A dotted line connects
each note with the element it describes. This diagram’s UML notes show how the diagram
relates to the C++ code for each action state. Activity diagrams usually do not show the
C++ code.
Keywords
Each of the words if, else, switch, while, do and for is a C++ keyword. Keywords can-
not be used as identifiers, such as variable names, and contain only lowercase letters (and
sometimes underscores). The following table shows the complete list of C++ keywords:
C++ keywords
Checkpoint
1 (Fill-in) Böhm and Jacopini’s work demonstrated that all programs could be written
in terms of only three control structures— , and structure.
Answer: sequence, selection, iteration.
100 Chapter 3 Algorithm Development and Control Statements: Part 1
2 (True/False) The while, for and do…while statements perform their action (or
group of actions) zero or more times.
Answer: False. The while and for statements perform their action (or group of actions)
zero or more times. The do…while statement performs its action (or group of actions) one
or more times.
3 (Fill-in) control statements make it easy to build readable programs by con-
necting the exit point of one to the entry point of the next using control-statement stacking.
Answer: Single-entry/single-exit.
This figure contains the most important symbol in an activity diagram—the diamond, or
decision symbol, which indicates that a decision is to be made. The workflow continues
along a path determined by the symbol’s associated guard conditions, which can be true
or false. Each transition arrow emerging from a UML decision symbol has a guard condi-
tion (specified in square brackets next to the arrow). If a guard condition is true, the work-
flow enters the action state to which the transition arrow points. The diagram shows that
if the grade is greater than or equal to 60 (i.e., the condition is true), the program prints
“Passed” then transitions to the activity’s final state. If the grade is less than 60 (i.e., the
condition is false), the program immediately transitions to the final state without display-
ing a message. The if statement is a single-entry/single-exit control statement.
Checkpoint
1 (Pseudocode) Write a pseudocode if statement that determines whether a count is
greater than 10 and, if so, prints “Count is greater than 10.”
Answer:
if count grade is greater than 10
print “Count is greater than 10.”
2 (Code) Write an if statement that implements the preceding exercise’s pseudocode.
Assume the int variable count already exists.
Answer:
if (count > 10) {
cout << "Count is greater than 10.";
}
The if and else bodies are both indented equally. Whatever indentation convention you
choose should be applied consistently throughout your programs. If there are several
indentation levels, each should be indented the same additional amount of space. We pre-
fer three-space indents. IDEs often auto-indent the code for you.
If variable studentGrade is greater than or equal to 90, the first four conditions in the
nested if…else statement will be true, but only the statement in the if part of the first
if…else statement will execute. After that statement executes, the else part of the “out-
ermost” if…else statement is skipped. In a nested if…else statement, ensure that you
test for all possible cases.
The preceding nested if…else statement also can be written in the following form,
which is identical but uses fewer braces, less spacing and indentation:
if (studentGrade >= 90) {
cout << "A";
}
else if (studentGrade >= 80) {
cout << "B";
}
else if (studentGrade >= 70) {
cout << "C";
}
else if (studentGrade >= 60) {
cout << "D";
}
else {
cout << "F";
}
This form avoids deep indentation of the code to the right, which sometimes can force
lines to wrap. Throughout the text, we enclose control-statement bodies in braces ({ and
}), which avoids a logic error called the “dangling-else” problem. We investigate this Err
problem in Exercises 3.13–3.15.
104 Chapter 3 Algorithm Development and Control Statements: Part 1
3.6.2 Blocks
The if statement expects only one statement in its body. To include several statements in
an if’s or else’s body, enclose the statements in braces. It’s good practice always to use
braces. Statements in a pair of braces (such as a control statement’s or function’s body)
form a block. A block can be placed anywhere in a function where a single statement can
be placed.
The following example includes a block of multiple statements in an if…else state-
ment’s else part:
if (studentGrade >= 60) {
cout << "Passed";
}
else {
cout << "Failed\n";
cout << "You must retake this course.";
}
If studentGrade is less than 60, the program executes both statements in the body of the
else and prints
Failed
You must retake this course.
Without the braces surrounding the two statements in the else clause, the statement
cout << "You must retake this course.";
would be outside the body of the else part of the if…else statement and would execute
regardless of whether the studentGrade was less than 60—a logic error.
Empty Statement
Just as a block can be placed anywhere a single statement can be placed, it’s also possible
to have an empty statement, which is simply a semicolon (;) where a statement typically
would be. An empty statement has no effect.
Err Placing a semicolon after the parenthesized condition in an if or if…else statement
leads to a logic error in single-selection if statements and a syntax error in double-selection
if…else statements (when the if-part contains a body statement).
The operand to the left of the ? is a condition. The second operand (between the ? and :)
is the conditional expression’s value if the condition is true. The operand to the right of
the : is the conditional expression’s value if the condition is false. The conditional expres-
sion in this statement evaluates to the string "Passed" if the condition
studentGrade >= 60
is true and to the string "Failed" if it’s false. Thus, this statement with the conditional
operator performs essentially the same function as the first if…else statement in
Section 3.6. The precedence of the conditional operator is low, so the entire conditional
expression is normally placed in parentheses.
Checkpoint
1 (Pseudocode) Write a pseudocode if…else statement that determines whether a
counter is greater than 10. If so, the statement should print “counter is greater than 10.”
Otherwise, it should print “counter is less than or equal to 10.”
Answer:
if counter is greater than 10
print “counter is greater than 10.”
else
print “counter is less than or equal to 10.”
2 (Code) Write an if…else statement that implements the preceding exercise’s
pseudocode. Assume the int variable counter already exists.
Answer:
if (counter > 10) {
cout << "counter is greater than 10.";
}
else {
cout << "counter is less than or equal to 10.";
}
3 (Code) Write a nested if…else statement that displays whether the value of counter
is greater than 10, equal to 10 or less than 10.
Answer:
if (counter > 10) {
cout << "counter is greater than 10.";
}
else if (counter == 10) {
cout << "counter is equal to 10.";
}
else {
cout << "counter is less than 10.";
}
After this while statement executes, the variable product contains the result. Each itera-
tion of the while statement multiplies product by 3, so product takes on the values 9, 27,
81 and 243 successively. When product becomes 243, product <= 100 becomes false.
This terminates the iteration, so the final value of product is 243. At this point, program
Err execution continues with the next statement after the while statement. Not providing in
a while statement’s body an action that eventually causes the condition to become false
results in a logic error called an infinite loop (the loop never terminates).
merge
decision
[product <= 100]
product = 3 * product
[product > 100]
The UML represents both the merge symbol and the decision symbol as diamonds. The
merge symbol joins two flows of activity into one. In this diagram, the merge symbol joins
the transitions from the initial state and the action state, so they both flow into the decision
that determines whether the loop should begin (or continue) executing.
You can distinguish the decision and merge symbols by the number of incoming and
outgoing transition arrows. A decision symbol has one transition arrow pointing to the
diamond and two or more pointing out from it to indicate possible transitions from that
decision. Also, each arrow pointing out of a decision symbol has a guard condition. A
merge symbol has two or more transition arrows pointing to it, and only one pointing
from it to indicate multiple activity flows merging to continue the activity. None of the
transition arrows associated with a merge symbol has a guard condition.
3.8 Formulating Algorithms: Counter-Controlled Iteration 107
Checkpoint
1 (True/False) A UML merge symbol has one transition arrow pointing to the diamond
and two or more pointing out from it.
Answer: False. A decision symbol has one transition arrow pointing to the diamond and
two or more pointing out from it (each with a guard condition) to indicate possible tran-
sitions. A merge symbol has two or more transition arrows pointing to it, and only one
pointing from it to indicate multiple activity flows merging to continue the activity.
2 (Code) Using this section’s while statement as a guide, write code that determines the
first power of 2 greater than one million. Add a counter that determines what the first n is
for 2n > 1,000,000.
Answer:
int product{2};
int n{1};
cout << "First power of 2 greater than 1000000 is " << product
<< "\nwhich is 2 to the power of " << n << "\n";
Note the references in the preceding algorithm to a total and a counter. A total is a
variable used to accumulate the sum of several values. A counter is a variable used to
count—the grade counter indicates which of the 10 grades is about to be entered by the
user. Variables used to store totals normally are initialized to zero before being used in a
program. In pseudocode, we do not use braces around the statements that form the
pseudocode while’s body, but you could.
SE Experience has shown that the most challenging part of solving a problem on a com-
puter is developing the algorithm for the solution. Once a correct algorithm has been spec-
ified, producing a working C++ program from it is usually straightforward.
1 fig03_01.cpp
2 // Solving the class-average problem using counter-controlled iteration.
3 #include <iostream>
4 using namespace std;
5
6 int main() {
7 // initialization phase
8 int total{0}; // initialize sum of grades entered by the user
9 int gradeCounter{1}; // initialize grade # to be entered next
10
11 // processing phase uses counter-controlled iteration
12 while (gradeCounter <= 10) { // loop 10 times
13 cout << "Enter grade: "; // prompt
14 int grade;
15 cin >> grade; // input next grade
16 total = total + grade; // add grade to total
17 gradeCounter = gradeCounter + 1; // increment counter by 1
18 }
19
Fig. 3.1 | Solving the class-average problem using counter-controlled iteration. (Part 1 of 2.)
3.8 Formulating Algorithms: Counter-Controlled Iteration 109
20 // termination phase
21 int average{total / 10}; // int division yields int result
22
23 // display total and average of grades
24 cout << "\nTotal of all 10 grades is " << total;
25 cout << "\nClass average is " << average << "\n";
26 }
Enter grade: 67
Enter grade: 78
Enter grade: 89
Enter grade: 67
Enter grade: 87
Enter grade: 98
Enter grade: 93
Enter grade: 85
Enter grade: 82
Enter grade: 100
Fig. 3.1 | Solving the class-average problem using counter-controlled iteration. (Part 2 of 2.)
able total’s value. Then, line 25 displays the text "Class average is " followed by
average’s value. When execution reaches line 26, the program terminates.
adds each grade entered by the user to the total. Even this simple statement has a poten-
tial problem—adding the integers could result in a value too large to store in an int vari-
Err able. This is known as arithmetic overflow and causes undefined behavior, which can lead
Sec to unintended results and security problems. See, for example,
https://en.wikipedia.org/wiki/
Integer_overflow#Security_ramifications
The following expressions return your system’s maximum and minimum int values:
std::numeric_limits<int>::max()
std::numeric_limits<int>::min()
Each uses class numeric_limits from the C++ standard library header <limits>. You may
use similar expressions for any integral or floating-point type by replacing int in these
expressions.
Err assumes that the user will enter an integer grade from 0 to 100 but the user could enter:
• an integer less than 0,
• an integer greater than 100,
• an integer outside the range of values that can be stored in an int variable,
• a number containing a decimal point or
• a value containing letters or special symbols that do not even represent a number.
3.9 Formulating Algorithms: Sentinel-Controlled Iteration 111
Industrial-strength programs must test for all possible erroneous cases to ensure valid SE
inputs. A program that inputs grades should validate them using range checking to ensure
they are values from 0 to 100. You can then ask the user to re-enter any out-of-range value.
If a program requires inputs from a specific set of values (such as, non-sequential product
codes), you should ensure that each input matches a value in the set.
Checkpoint
1 (True/False) Dividing two integers results in integer division—any fractional part of
the calculation is rounded to the nearest integer.
Answer: False. Actually, any fractional part of the calculation is truncated.
2 (Fill-in) A variable declared in a(n) (such as a function’s body) is a local vari-
able that can be used only from the line of its declaration to the corresponding closing right
brace.
Answer: block.
3 (Code) Rewrite the initialization in the following code so the loop iterates 5 times.
int count{1};
Answer:
int count{0};
count is: 1
count is: 2
count is: 3
count is: 4
count is: 5
One way to solve this problem is to use a sentinel value (also called a signal value or
a flag value) to indicate the end of data entry. The user enters grades until all legitimate
grades have been entered. The user then enters the sentinel value to indicate that no more
grades will be entered.
You must choose a sentinel value that cannot be confused with an acceptable input
value. Grades on a quiz are non-negative integers, so –1 is an acceptable sentinel value for
this problem. Thus, a run of the class-averaging program might process a stream of inputs
such as 95, 96, 75, 74, 89 and –1. The program would then compute and print the class
average for the grades, excluding –1, because it’s the sentinel value and should not enter
into the averaging calculation.
The user could enter –1 before entering grades, which means the number of grades
will be zero. We must test for this case before calculating the class average. According to
the C++ standard, the result of division by zero in floating-point arithmetic is undefined.
When performing division (/) or remainder (%) calculations in which the right operand
could be zero, test for this and handle it (e.g., display an error message) rather than allow-
ing the calculation to proceed.
We use blank lines to make the pseudocode more readable and indentation to empha-
size the actions that should be placed in the control statements’ bodies. The blank lines
separate the algorithms into their phases and set off control statements; the indentation
emphasizes the bodies of the control statements.
Our pseudocode algorithm solves the more general class-average problem. This algo-
SE rithm required only two refinements—sometimes, more are needed. You terminate the
top-down, stepwise refinement process when you feel your pseudocode algorithm has suf-
ficient detail for you to convert the algorithm to C++.
Some programmers do not use program development tools like pseudocode. They feel
that their ultimate goal is to solve the problem on a computer and that writing pseudocode
merely delays the final product. This may work for simple and familiar problems but can
lead to significant errors and delays in large, complex projects.
1 // fig03_02.cpp
2 // Solving the class-average problem using sentinel-controlled iteration.
3 #include <iostream>
4 #include <iomanip> // parameterized stream manipulators
5 using namespace std;
6
7 int main() {
8 // initialization phase
9 double total{0.0}; // initialize sum of grades
10 int gradeCounter{0}; // initialize # of grades entered so far
11
12 // processing phase
13 // prompt for input and read grade from user
14 cout << "Enter grade or -1 to quit: ";
15 int grade;
16 cin >> grade;
17
18 // loop until sentinel value is read from user
19 while (grade != -1) {
20 total = total + grade; // add grade to total
21 gradeCounter = gradeCounter + 1; // increment counter
22
23 // prompt for input and read next grade from user
24 cout << "Enter grade or -1 to quit: ";
25 cin >> grade;
26 }
27
28 // termination phase
29 // if user entered at least one grade...
30 if (gradeCounter != 0) { // avoid division by zero
31 // calculate average of grades
32 double average{total / gradeCounter};
33
34 // display total and average (with two digits of precision)
35 cout << "\nTotal of the " << gradeCounter
36 << " grades entered is " << total;
37 cout << setprecision(2) << fixed;
38 cout << "\nClass average is " << average << "\n";
39 }
40 else { // no grades were entered, so output appropriate message
41 cout << "No grades were entered\n";
42 }
43 }
Fig. 3.2 | Solving the class-average problem using sentinel-controlled iteration. (Part 1 of 2.)
116 Chapter 3 Algorithm Development and Control Statements: Part 1
Fig. 3.2 | Solving the class-average problem using sentinel-controlled iteration. (Part 2 of 2.)
Recall that integer division produces an integer result. This program declares the vari-
able total as a double (line 9). As you’ll see, this will cause the average calculation to pro-
duce a floating-point result. This program also stacks control statements in sequence—the
while statement is followed in sequence by an if…else statement. Much of this pro-
gram’s code is identical to Fig. 3.1, so we concentrate on only the new concepts.
Program Logic for Sentinel-Controlled Iteration vs. Counter-Controlled Iteration
Line 10 initializes gradeCounter to 0 because no grades have been entered yet. Remember
that this program uses sentinel-controlled iteration to input the grades. The program
increments gradeCounter only when the user enters a valid grade. Line 32 declares the
double variable average, which stores the class average as a floating-point number.
Compare this program’s logic for sentinel-controlled iteration with Fig. 3.1’s counter-
controlled iteration:
• In counter-controlled iteration, each loop iteration (lines 12–18 of Fig. 3.1) reads
a value from the user for the specified number of iterations.
• In sentinel-controlled iteration, the program prompts for and reads the first value
(lines 14 and 16 of Fig. 3.2) before reaching the while. This value determines
whether the flow of control should enter the while’s body. If the condition is
false, the user entered the sentinel value, so no grades were entered, and the body
does not execute. If the condition is true, the body executes, adding the grade
value to the total and incrementing the gradeCounter. Then lines 24–25
prompt for and input the next grade. At this point, program control reaches the
loop’s closing right brace (line 26). Execution continues by testing the while’s
condition (line 19), using the most recently entered grade to determine whether
the loop body should execute again.
The next grade is always input from the user immediately before the while condition
is tested. This allows the program to determine whether the value just input is the sentinel
value before processing it (i.e., adding it to the total). If grade contains the sentinel value,
the loop terminates without adding –1 to the total. In a sentinel-controlled loop,
prompts should remind the user of the sentinel.
After the loop terminates, the if…else statement at lines 30–42 executes. The con-
dition at line 30 determines whether any grades were input. If none were input, the
if…else statement’s else part executes and displays the message "No grades were
entered". After the if…else executes, the program terminates.
divides total by gradeCounter to calculate the average. Recall that total is a double and
gradeCounter is an int. For arithmetic, the compiler knows how to evaluate only expres-