C++ How To Program An Objects

Download as pdf or txt
Download as pdf or txt
You are on page 1of 176

This page intentionally left blank

Recent Deitel Textbooks

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)

Please contact https://support.pearson.com/getsupport/s/ with any queries on this content.

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.

Library of Congress Cataloging-in-Publication Data


On file
uPDF
ISBN-10: 0-13-809242-7
ISBN-13: 978-0-13809242-9

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:

For a career devoted to improving people’s


lives through technology, innovation, industry,
entrepreneurship and philanthropy.

Paul and Harvey Deitel


Pearson’s Commitment to Diversity, Equity, and Inclusion
Pearson is dedicated to creating bias-free content that reflects the diversity, depth, and breadth of all
learners’ lived experiences. We embrace the many dimensions of diversity, including but not limited to
race, ethnicity, gender, sex, sexual orientation, socioeconomic status, ability, age, and religious or political
beliefs.
Education is a powerful force for equity and change in our world. It has the potential to deliver opportu-
nities that improve lives and enable economic mobility. As we work with authors to create content for
every product and service, we acknowledge our responsibility to demonstrate inclusivity and incorporate
diverse scholarship so that everyone can achieve their potential through learning. As the world’s leading
learning company, we have a duty to help drive change and live up to our purpose to help more people
create a better life for themselves and to create a better world.
Our ambition is to purposefully contribute to a world where:
• Everyone has an equitable and lifelong opportunity to succeed through learning.
• Our educational products and services are inclusive and represent the rich diversity of learners.
• Our educational content accurately reflects the histories and lived experiences of the learners
we serve.
• Our educational content prompts deeper discussions with students and motivates them to ex-
pand their own learning (and worldview).
We are also committed to providing products that are fully accessible to all learners. As per Pearson’s
guidelines for accessible educational Web media, we test and retest the capabilities of our products against
the highest standards for every release, following the WCAG guidelines in developing new products for
copyright year 2022 and beyond. You can learn more about Pearson’s commitment to accessibility at
https://www.pearson.com/us/accessibility.html.

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

Before You Begin liii


1 Intro to Computers and C++ 1
1.1 Introduction 2
1.2 Hardware 4
1.2.1 Computer Organization 4
1.2.2 Moore’s Law, Multi-Core Processors and Concurrent Programming 7
1.3 Data Hierarchies 10
1.4 Machine Languages, Assembly Languages and High-Level Languages 13
1.5 Operating Systems 14
1.6 C and C++ 18
1.7 C++ Standard Library and Open-Source Libraries 19
1.8 Other Popular Programming Languages 21
1.9 Introduction to Object Orientation 23
1.10 Simplified View of a C++ Development Environment 25
1.11 Test-Driving a C++20 Application Various Ways 28
1.11.1 Compiling and Running on Windows with Visual Studio
Community Edition 29
1.11.2 Compiling and Running with GNU C++ on Linux 32
1.11.3 Compiling and Running with g++ in the GCC Docker Container 34
1.11.4 Compiling and Running with clang++ in a Docker Container 36
1.11.5 Compiling and Running with Xcode on macOS 37
1.12 Internet, World Wide Web, the Cloud and IoT 41
1.12.1 The Internet: A Network of Networks 41
1.12.2 The World Wide Web: Making the Internet User-Friendly 42
1.12.3 The Cloud 42
1.12.4 The Internet of Things (IoT) 42
1.12.5 Edge Computing 43
1.12.6 Mashups 43
1.13 Metaverse 44
1.13.1 Virtual Reality (VR) 44
1.13.2 Augmented Reality (AR) 45
1.13.3 Mixed Reality 46
1.13.4 Blockchain 46
1.13.5 Bitcoin and Cryptocurrency 46
viii Contents

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

2 Intro to C++20 Programming 65


2.1 Introduction 66
2.2 First Program in C++: Displaying a Line of Text 66
2.3 Modifying Our First C++ Program 70
2.4 Another C++ Program: Adding Integers 71
2.5 Memory Concepts 75
2.6 Arithmetic 76
2.7 Decision Making: Equality and Relational Operators 79
2.8 Objects Natural Case Study:Creating and Using Objects of
Standard-Library Class string 83
2.9 Wrap-Up 86

3 Algorithm Development and Control


Statements: Part 1 93
3.1 Introduction 94
3.2 Algorithms 95
3.3 Pseudocode 95
3.4 Control Structures 96
3.4.1 Sequence Structure 97
3.4.2 Selection Statements 98
3.4.3 Iteration Statements 98
3.4.4 Summary of Control Statements 99
3.5 if Single-Selection Statement 100
3.6 if…else Double-Selection Statement 101
3.6.1 Nested if…else Statements 102
3.6.2 Blocks 104
3.6.3 Conditional Operator (?:) 104
3.7 while Iteration Statement 105
Contents ix

3.8 Formulating Algorithms: Counter-Controlled Iteration 107


3.8.1 Pseudocode Algorithm with Counter-Controlled Iteration 107
3.8.2 Implementing Counter-Controlled Iteration 108
3.8.3 Integer Division and Truncation 110
3.8.4 Arithmetic Overflow 110
3.8.5 Input Validation 110
3.9 Formulating Algorithms: Sentinel-Controlled Iteration 111
3.9.1 Top-Down, Stepwise Refinement: The Top and First Refinement 112
3.9.2 Proceeding to the Second Refinement 112
3.9.3 Implementing Sentinel-Controlled Iteration 114
3.9.4 Mixed-Type Expressions and Implicit Type Promotions 116
3.9.5 Formatting Floating-Point Numbers 117
3.10 Formulating Algorithms: Nested Control Statements 118
3.10.1 Problem Statement 118
3.10.2 Top-Down, Stepwise Refinement: Pseudocode Representation
of the Top 119
3.10.3 Top-Down, Stepwise Refinement: First Refinement 119
3.10.4 Top-Down, Stepwise Refinement: Second Refinement 120
3.10.5 Complete Second Refinement of the Pseudocode 120
3.10.6 Implementing the Program 121
3.10.7 Preventing Narrowing Conversions with Braced Initialization 123
3.11 Compound Assignment Operators 125
3.12 Increment and Decrement Operators 125
3.13 Fundamental Types Are Not Portable 128
3.14 Objects Natural Case Study: Super-Sized Integers 129
3.15 Wrap-Up 134

4 Control Statements, Part 2 145


4.1 Introduction 146
4.2 Essentials of Counter-Controlled Iteration 146
4.3 for Iteration Statement 148
4.4 Examples Using the for Statement 151
4.5 Application: Summing Even Integers; Introducing
C++20 Text Formatting 152
4.6 Application: Compound-Interest Calculations;
Introducing Format Specifiers 153
4.7 do…while Iteration Statement 158
4.8 switch Multiple-Selection Statement 159
4.9 Selection Statements with Initializers 165
4.10 break and continue Statements 167
4.11 Logical Operators 169
4.11.1 Logical AND (&&) Operator 169
4.11.2 Logical OR (||) Operator 170
4.11.3 Short-Circuit Evaluation 170
4.11.4 Logical Negation (!) Operator 171
4.11.5 Example: Producing Logical-Operator Truth Tables 171
x Contents

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

5 Functions and an Intro to Function Templates 189


5.1 Introduction 190
5.2 C++ Program Components 191
5.3 Math Library Functions 192
5.4 Function Definitions and Function Prototypes 194
5.5 Order of Evaluation of a Function’s Arguments 197
5.6 Function-Prototype and Argument-Coercion Notes 197
5.6.1 Function Signatures and Function Prototypes 198
5.6.2 Argument Coercion 198
5.6.3 Argument-Promotion Rules and Implicit Conversions 198
5.7 C++ Standard Library Headers 200
5.8 Case Study: Random-Number Generation 203
5.8.1 Rolling a Six-Sided Die 204
5.8.2 Rolling a Six-Sided Die 60,000,000 Times 205
5.8.3 Seeding the Random-Number Generator 207
5.8.4 Seeding the Random-Number Generator with random_device 208
5.9 Case Study: Game of Chance; Introducing Scoped enums 209
5.10 Function-Call Stack and Activation Records 214
5.11 Inline Functions 217
5.12 References and Reference Parameters 219
5.13 Default Arguments 222
5.14 Function Overloading 224
5.15 Function Templates 227
5.16 Recursion 229
5.16.1 Factorials 230
5.16.2 Recursive Factorial Example 230
5.16.3 Recursive Fibonacci Series Example 234
5.16.4 Recursion vs. Iteration 237
5.17 Scope Rules 239
5.18 Unary Scope Resolution Operator 244
5.19 Lnfylun Lhqtomh Wjtz Qarcv: Qjwazkrplm xzz Xndmwwqhlz 245
5.20 Wrap-Up 248

6 arrays, vectors, Ranges and


Functional-Style Programming 259
6.1 Introduction 260
6.2 arrays 261
6.3 Declaring arrays 262
6.4 Initializing array Elements in a Loop 262
Contents xi

6.5 Initializing an array with an Initializer List 265


6.6 Range-Based for Statement 267
6.7 Calculating array Element Values and an Intro to constexpr 269
6.8 Totaling array Elements 271
6.9 Using a Primitive Bar Chart to Display array Data Graphically 272
6.10 Using array Elements as Counters 274
6.11 Using arrays to Summarize Survey Results 275
6.12 Sorting and Searching arrays 277
6.13 Multidimensional arrays 279
6.14 Intro to Functional-Style Programming 283
6.14.1 What vs. How 283
6.14.2 Passing Functions as Arguments to Other Functions:
Introducing Lambda Expressions 284
6.14.3 Filter, Map and Reduce: Intro to C++20’s Ranges Library 286
6.15 Objects-Natural Case Study: C++ Standard Library
Class Template vector 290
6.16 Wrap-Up 297

7 (Downplaying) Pointers in Modern C++ 309


7.1 Introduction 310
7.2 Pointer Variable Declarations and Initialization 312
7.2.1 Declaring Pointers 312
7.2.2 Initializing Pointers 312
7.2.3 Null Pointers 312
7.3 Pointer Operators 313
7.3.1 Address (&) Operator 313
7.3.2 Indirection (*) Operator 314
7.3.3 Using the Address (&) and Indirection (*) Operators 315
7.4 Pass-by-Reference with Pointers 316
7.5 Built-In Arrays 320
7.5.1 Declaring and Accessing a Built-In Array 320
7.5.2 Initializing Built-In Arrays 321
7.5.3 Passing Built-In Arrays to Functions 322
7.5.4 Declaring Built-In Array Parameters 322
7.5.5 Standard Library Functions begin and end 323
7.5.6 Built-In Array Limitations 323
7.6 Using C++20 to_array to Convert a Built-in Array to a std::array 324
7.7 Using const with Pointers and the Data Pointed To 325
7.7.1 Using a Nonconstant Pointer to Nonconstant Data 326
7.7.2 Using a Nonconstant Pointer to Constant Data 326
7.7.3 Using a Constant Pointer to Nonconstant Data 327
7.7.4 Using a Constant Pointer to Constant Data 327
7.8 sizeof Operator 329
7.9 Pointer Expressions and Pointer Arithmetic 331
7.9.1 Adding Integers to and Subtracting Integers from Pointers 332
xii Contents

7.9.2 Subtracting One Pointer from Another 333


7.9.3 Pointer Assignment 333
7.9.4 Cannot Dereference a void* Pointer 333
7.9.5 Comparing Pointers 334
7.10 Objects-Natural Case Study: C++20 spans—Views of Contiguous
Container Elements 334
7.11 A Brief Intro to Pointer-Based Strings 340
7.11.1 Command-Line Arguments 341
7.11.2 Revisiting C++20’s to_array Function 342
7.12 Looking Ahead to Other Pointer Topics 344
7.13 Wrap-Up 344

8 strings, string_views, Text Files,


CSV Files and Regex 357
8.1 Introduction 358
8.2 string Assignment and Concatenation 359
8.3 Comparing strings 361
8.4 Substrings 363
8.5 Swapping strings 364
8.6 string Characteristics 365
8.7 Finding Substrings and Characters in a string 367
8.8 Replacing and Erasing Characters in a string 370
8.9 Inserting Characters into a string 372
8.10 Numeric Conversions 373
8.11 string_view 374
8.12 Files and Streams 377
8.13 Creating a Sequential File 378
8.14 Reading Data from a Sequential File 381
8.15 Reading and Writing Quoted Text 384
8.16 Updating Sequential Files 385
8.17 String Stream Processing 386
8.18 Raw String Literals 389
8.19 Objects-Natural Data Science Case Study: Reading and Analyzing a
CSV File Containing Titanic Disaster Data 390
8.19.1 Using rapidcsv to Read the Contents of a CSV File 390
8.19.2 Reading and Analyzing the Titanic Disaster Dataset 392
8.20 Objects-Natural Data Science Case Study: Intro to Regular Expressions 399
8.20.1 Matching Complete Strings to Patterns 400
8.20.2 Replacing Substrings 405
8.20.3 Searching for Matches 405
8.21 Wrap-Up 408

9 Custom Classes 431


9.1 Introduction 432
Contents xiii

9.2 Test-Driving an Account Object 433


9.3 Account Class with a Data Member and Set and Get Member Functions 435
9.3.1 Class Definition 435
9.3.2 Access Specifiers private and public 437
9.4 Account Class: Custom Constructors 438
9.5 Software Engineering with Set and Get Member Functions 442
9.6 Account Class with a Balance 444
9.7 Time Class Case Study: Separating Interface from Implementation 447
9.7.1 Interface of a Class 448
9.7.2 Separating the Interface from the Implementation 448
9.7.3 Class Definition 449
9.7.4 Member Functions 450
9.7.5 Including the Class Header in the Source-Code File 450
9.7.6 Scope Resolution Operator (::) 451
9.7.7 Member Function setTime and Throwing Exceptions 451
9.7.8 Member Functions to24HourString and to12HourString 451
9.7.9 Implicitly Inlining Member Functions 452
9.7.10 Member Functions vs. Global Functions 452
9.7.11 Using Class Time 452
9.7.12 Object Size 454
9.8 Compilation and Linking Process 454
9.9 Class Scope and Accessing Class Members 455
9.10 Access Functions and Utility Functions 456
9.11 Time Class Case Study: Constructors with Default Arguments 457
9.11.1 Class Time 457
9.11.2 Overloaded Constructors and Delegating Constructors 462
9.12 Destructors 463
9.13 When Constructors and Destructors Are Called 464
9.14 Time Class Case Study: A Subtle Trap — Returning a Reference or a
Pointer to a private Data Member 468
9.15 Default Assignment Operator 470
9.16 const Objects and const Member Functions 472
9.17 Composition: Objects as Members of Classes 474
9.18 friend Functions and friend Classes 480
9.19 The this Pointer 482
9.19.1 Implicitly and Explicitly Using the this Pointer to Access
an Object’s Data Members 482
9.19.2 Using the this Pointer to Enable Cascaded Function Calls 484
9.20 static Class Members: Classwide Data and Member Functions 487
9.21 Aggregates in C++20 492
9.21.1 Initializing an Aggregate 493
9.21.2 C++20 Designated Initializers 493
9.22 Concluding Our Objects Natural Case Study Track: Studying the
Vigenère Secret-Key Cipher Implementation 494
9.23 Wrap-Up 507
xiv Contents

10 OOP: Inheritance and Runtime Polymorphism 529


10.1 Introduction 530
10.2 Base Classes and Derived Classes 532
10.2.1 CommunityMember Class Hierarchy 533
10.2.2 Shape Class Hierarchy and public Inheritance 534
10.3 Relationship Between Base and Derived Classes 535
10.3.1 Creating and Using a SalariedEmployee Class 535
10.3.2 Creating a SalariedEmployee–SalariedCommissionEmployee
Inheritance Hierarchy 538
10.4 Constructors and Destructors in Derived Classes 544
10.5 Intro to Runtime Polymorphism: Polymorphic Video Game 545
10.6 Relationships Among Objects in an Inheritance Hierarchy 546
10.6.1 Invoking Base-Class Functions from Derived-Class Objects 547
10.6.2 Aiming Derived-Class Pointers at Base-Class Objects 549
10.6.3 Derived-Class Member-Function Calls via Base-Class Pointers 550
10.7 Virtual Functions and Virtual Destructors 551
10.7.1 Why virtual Functions Are Useful 551
10.7.2 Declaring virtual Functions 552
10.7.3 Invoking a virtual Function 553
10.7.4 virtual Functions in the SalariedEmployee Hierarchy 553
10.7.5 virtual Destructors 557
10.7.6 final Member Functions and Classes 557
10.8 Abstract Classes and Pure virtual Functions 558
10.8.1 Pure virtual Functions 559
10.8.2 Device Drivers: Polymorphism in Operating Systems 559
10.9 Case Study: Payroll System Using Runtime Polymorphism 560
10.9.1 Creating Abstract Base Class Employee 561
10.9.2 Creating Concrete Derived Class SalariedEmployee 563
10.9.3 Creating Concrete Derived Class CommissionEmployee 565
10.9.4 Demonstrating Runtime Polymorphic Processing 567
10.10 Runtime Polymorphism, Virtual Functions and Dynamic Binding
“Under the Hood” 570
10.11 Program to an Interface, Not an Implementation 573
10.11.1 Rethinking the Employee Hierarchy—
CompensationModel Interface 575
10.11.2 Class Employee 575
10.11.3 CompensationModel Implementations 577
10.11.4 Testing the New Hierarchy 579
10.11.5 Dependency Injection Design Benefits 580
10.12 Wrap-Up 581

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

11.3 Operator Overloading Fundamentals 596


11.3.1 Operator Overloading Is Not Automatic 596
11.3.2 Operators That Cannot Be Overloaded 596
11.3.3 Operators That You Do Not Have to Overload 596
11.3.4 Rules and Restrictions on Operator Overloading 597
11.4 (Downplaying) Dynamic Memory Management with new and delete 598
11.5 Modern C++ Dynamic Memory Management: RAII and Smart Pointers 600
11.5.1 Smart Pointers 601
11.5.2 Demonstrating unique_ptr 601
11.5.3 unique_ptr Ownership 603
11.5.4 unique_ptr to a Built-In Array 603
11.6 MyArray Case Study: Crafting a Valuable Class with Operator Overloading 604
11.6.1 Special Member Functions 605
11.6.2 Using Class MyArray 606
11.6.3 MyArray Class Definition 615
11.6.4 Constructor That Specifies a MyArray’s Size 617
11.6.5 Passing a Braced Initializer to a Constructor 618
11.6.6 Copy Constructor and Copy Assignment Operator 619
11.6.7 Move Constructor and Move Assignment Operator 622
11.6.8 Destructor 626
11.6.9 toString and size Functions 626
11.6.10 Overloading the Equality (==) and Inequality (!=) Operators 627
11.6.11 Overloading the Subscript ([]) Operator 629
11.6.12 Overloading the Unary bool Conversion Operator 630
11.6.13 Overloading the Preincrement Operator 631
11.6.14 Overloading the Postincrement Operator 632
11.6.15 Overloading the Addition Assignment Operator (+=) 633
11.6.16 Overloading the Binary Stream Extraction (>>) and
Stream Insertion (<<) Operators 633
11.6.17 friend Function swap 636
11.7 C++20 Three-Way Comparison Operator (<=>) 636
11.8 Converting Between Types 640
11.9 explicit Constructors and Conversion Operators 641
11.10 Overloading the Function Call Operator () 644
11.11 Wrap-Up 644

12 Exceptions and a Look Forward to Contracts 653


12.1 Introduction 654
12.2 Exception-Handling Flow of Control 658
12.2.1 Defining a Custom Exception Class 658
12.2.2 Demonstrating Exception Handling 659
12.2.3 Enclosing Code in a try Block 660
12.2.4 Defining a catch Handler for DivideByZeroExceptions 661
12.2.5 Termination Model of Exception Handling 662
12.2.6 Flow of Control When the User Enters a Nonzero Denominator 663
12.2.7 Flow of Control When the User Enters a Zero Denominator 663
xvi Contents

12.3 Exception Safety Guarantees and noexcept 664


12.4 Rethrowing an Exception 665
12.5 Stack Unwinding and Uncaught Exceptions 667
12.6 When to Use Exception Handling 669
12.6.1 assert Macro 671
12.6.2 Failing Fast 671
12.7 Constructors, Destructors and Exception Handling 672
12.7.1 Throwing Exceptions from Constructors 672
12.7.2 Catching Exceptions in Constructors via Function try Blocks 673
12.7.3 Exceptions and Destructors: Revisiting noexcept(false) 675
12.8 Processing new Failures 676
12.8.1 new Throwing bad_alloc on Failure 677
12.8.2 new Returning nullptr on Failure 678
12.8.3 Handling new Failures Using Function set_new_handler 679
12.9 Standard Library Exception Hierarchy 680
12.10 C++’s Alternative to the finally Block: Resource Acquisition Is
Initialization (RAII) 683
12.11 Some Libraries Support Both Exceptions and Error Codes 683
12.12 Logging 685
12.13 Looking Ahead to Contracts 685
12.14 Wrap-Up 694

13 Data Structures: Standard Library Containers


and Iterators 697
13.1 Introduction 698
13.2 A Brief Intro to Big O 700
13.3 A Brief Intro to Hash Tables 703
13.4 Introduction to Containers 704
13.4.1 Common Nested Types in Sequence and Associative Containers 706
13.4.2 Common Container Member and Non-Member Functions 707
13.4.3 Requirements for Container Elements 710
13.5 Working with Iterators 710
13.5.1 Using istream_iterator for Input and ostream_iterator
for Output 710
13.5.2 Iterator Categories 712
13.5.3 Container Support for Iterators 712
13.5.4 Predefined Iterator Type Names 713
13.5.5 Iterator Operators 713
13.6 A Brief Introduction to Algorithms 714
13.7 Sequence Containers 715
13.8 vector Sequence Container 715
13.8.1 Using vectors and Iterators 716
13.8.2 vector Element-Manipulation Functions 719
13.9 list Sequence Container 723
13.10 deque Sequence Container 728
Contents xvii

13.11 Associative Containers 730


13.11.1 multiset Associative Container 730
13.11.2 set Associative Container 734
13.11.3 multimap Associative Container 736
13.11.4 map Associative Container 738
13.12 Container Adaptors 739
13.12.1 stack Adaptor 740
13.12.2 queue Adaptor 742
13.12.3 priority_queue Adaptor 743
13.13 bitset Near Container 744
13.14 Wrap-Up 746

14 Standard Library Algorithms and


C++20 Ranges & Views 773
14.1 Introduction 774
14.2 Algorithm Requirements: C++20 Concepts 776
14.3 Lambdas and Algorithms 778
14.4 Algorithms 781
14.4.1 fill, fill_n, generate and generate_n 781
14.4.2 equal, mismatch and lexicographical_compare 783
14.4.3 remove, remove_if, remove_copy and remove_copy_if 786
14.4.4 replace, replace_if, replace_copy and replace_copy_if 790
14.4.5 Shuffling, Counting, and Minimum and Maximum
Element Algorithms 792
14.4.6 Searching and Sorting Algorithms 796
14.4.7 swap, iter_swap and swap_ranges 800
14.4.8 copy_backward, merge, unique, reverse, copy_if and copy_n 802
14.4.9 inplace_merge, unique_copy and reverse_copy 805
14.4.10 Set Operations 807
14.4.11 lower_bound, upper_bound and equal_range 810
14.4.12 min, max and minmax 812
14.4.13 Algorithms gcd, lcm, iota, reduce and partial_sum from
Header <numeric> 813
14.4.14 Heapsort and Priority Queues 816
14.5 Function Objects (Functors) 821
14.6 Projections 825
14.7 C++20 Views and Functional-Style Programming 828
14.7.1 Range Adaptors 828
14.7.2 Working with Range Adaptors and Views 830
14.8 Intro to Parallel Algorithms 834
14.9 Standard Library Algorithm Summary 836
14.10 Future Ranges Enhancements 839
14.11 Wrap-Up 840
xviii Contents

15 Templates, C++20 Concepts and


Metaprogramming 845
15.1 Introduction 846
15.2 Custom Class Templates and Compile-Time Polymorphism 849
15.3 C++20 Function Template Enhancements 854
15.3.1 C++20 Abbreviated Function Templates 854
15.3.2 C++20 Templated Lambdas 856
15.4 C++20 Concepts: A First Look 856
15.4.1 Unconstrained Function Template multiply 857
15.4.2 Constrained Function Template with a C++20 Concepts
requires Clause 860
15.4.3 C++20 Predefined Concepts 862
15.5 Type Traits 864
15.6 C++20 Concepts: A Deeper Look 868
15.6.1 Creating a Custom Concept 868
15.6.2 Using a Concept 869
15.6.3 Using Concepts in Abbreviated Function Templates 870
15.6.4 Concept-Based Overloading 871
15.6.5 requires Expressions 874
15.6.6 C++20 Exposition-Only Concepts 877
15.6.7 Techniques Before C++20 Concepts: SFINAE and Tag Dispatch 878
15.7 Testing C++20 Concepts with static_assert 879
15.8 Creating a Custom Algorithm 881
15.9 Creating a Custom Container and Iterators 883
15.9.1 Class Template ConstIterator 885
15.9.2 Class Template Iterator 888
15.9.3 Class Template MyArray 890
15.9.4 MyArray Deduction Guide for Braced Initialization 893
15.9.5 Using MyArray with std::ranges Algorithms 894
15.10 Default Arguments for Template Type Parameters 898
15.11 Variable Templates 898
15.12 Variadic Templates and Fold Expressions 899
15.12.1 tuple Variadic Class Template 899
15.12.2 Variadic Function Templates and an Intro to Fold Expressions 902
15.12.3 Types of Fold Expressions 906
15.12.4 How Unary Fold Expressions Apply Their Operators 906
15.12.5 How Binary-Fold Expressions Apply Their Operators 909
15.12.6 Using the Comma Operator to Repeatedly Perform an Operation 910
15.12.7 Constraining Parameter Pack Elements to the Same Type 911
15.13 Template Metaprogramming 913
15.13.1 C++ Templates Are Turing Complete 914
15.13.2 Computing Values at Compile-Time 914
15.13.3 Conditional Compilation with Template Metaprogramming
and constexpr if 919
15.13.4 Type Metafunctions 921
15.14 Wrap-Up 925
Contents xix

16 C++20 Modules: Large-Scale Development 933


16.1 Introduction 934
16.2 Compilation and Linking Before C++20 936
16.3 Advantages and Goals of Modules 937
16.4 Example: Transitioning to Modules—Header Units 938
16.5 Modules Can Reduce Translation Unit Sizes and Compilation Times 941
16.6 Example: Creating and Using a Module 942
16.6.1 module Declaration for a Module Interface Unit 943
16.6.2 Exporting a Declaration 945
16.6.3 Exporting a Group of Declarations 945
16.6.4 Exporting a namespace 945
16.6.5 Exporting a namespace Member 946
16.6.6 Importing a Module to Use Its Exported Declarations 946
16.6.7 Example: Attempting to Access Non-Exported Module Contents 948
16.7 Global Module Fragment 951
16.8 Separating Interface from Implementation 951
16.8.1 Example: Module Implementation Units 951
16.8.2 Example: Modularizing a Class 954
16.8.3 :private Module Fragment 958
16.9 Partitions 958
16.9.1 Example: Module Interface Partition Units 959
16.9.2 Module Implementation Partition Units 962
16.9.3 Example: “Submodules” vs. Partitions 962
16.10 Additional Modules Examples 967
16.10.1 Example: Importing the C++ Standard Library as Modules 967
16.10.2 Example: Cyclic Dependencies Are Not Allowed 969
16.10.3 Example: imports Are Not Transitive 970
16.10.4 Example: Visibility vs. Reachability 971
16.11 Migrating Code to Modules 972
16.12 Future of Modules and Modules Tooling 973
16.13 Wrap-Up 975

17 Parallel Algorithms and Concurrency:


A High-Level View 987
17.1 Introduction 988
17.2 Standard Library Parallel Algorithms 991
17.2.1 Example: Profiling Sequential and Parallel Sorting Algorithms 991
17.2.2 When to Use Parallel Algorithms 994
17.2.3 Execution Policies 995
17.2.4 Example: Profiling Parallel and Vectorized Operations 996
17.2.5 Additional Parallel Algorithm Notes 998
17.3 Multithreaded Programming 999
17.3.1 Thread States and the Thread Life Cycle 999
17.3.2 Deadlock and Indefinite Postponement 1001
xx Contents

17.4 Launching Tasks with std::jthread 1003


17.4.1 Defining a Task to Perform in a Thread 1003
17.4.2 Executing a Task in a jthread 1005
17.4.3 How jthread Fixes thread 1007
17.5 Producer–Consumer Relationship: A First Attempt 1008
17.6 Producer–Consumer: Synchronizing Access to Shared Mutable Data 1015
17.6.1 Class SynchronizedBuffer: Mutexes, Locks and
Condition Variables 1017
17.6.2 Testing SynchronizedBuffer 1023
17.7 Producer–Consumer: Minimizing Waits with a Circular Buffer 1027
17.8 Readers and Writers 1036
17.9 Cooperatively Canceling jthreads 1037
17.10 Launching Tasks with std::async 1040
17.11 Thread-Safe, One-Time Initialization 1047
17.12 A Brief Introduction to Atomics 1048
17.13 Coordinating Threads with C++20 Latches and Barriers 1052
17.13.1 C++20 std::latch 1052
17.13.2 C++20 std::barrier 1055
17.14 C++20 Semaphores 1058
17.15 C++23: A Look to the Future of C++ Concurrency 1062
17.15.1 Parallel Ranges Algorithms 1062
17.15.2 Concurrent Containers 1062
17.15.3 Other Concurrency-Related Proposals 1063
17.16 Wrap-Up 1063

18 C++20 Coroutines 1073


18.1 Introduction 1074
18.2 Coroutine Support Libraries 1075
18.3 Installing the concurrencpp and generator Libraries 1077
18.4 Creating a Generator Coroutine with co_yield and
the generator Library 1077
18.5 Launching Tasks with concurrencpp 1081
18.6 Creating a Coroutine with co_await and co_return 1085
18.7 Low-Level Coroutines Concepts 1093
18.8 Future Coroutines Enhancements 1096
18.9 Wrap-Up 1096

19 Stream I/O & C++20 Text Formatting 1101


19.1 Introduction 1102
19.2 Streams 1102
19.2.1 Classic Streams vs. Standard Streams 1103
19.2.2 iostream Library Headers 1103
19.2.3 Stream Input/Output Classes and Objects 1103
Contents xxi

19.3 Stream Output 1104


19.3.1 Output of char* Variables 1105
19.3.2 Character Output Using Member Function put 1106
19.4 Stream Input 1106
19.4.1 get and getline Member Functions 1106
19.4.2 istream Member Functions peek, putback and ignore 1109
19.5 Unformatted I/O Using read, write and gcount 1110
19.6 Stream Manipulators 1111
19.6.1 Integral Stream Base: dec, oct, hex and setbase 1112
19.6.2 Floating-Point Precision (setprecision, precision) 1112
19.6.3 Field Width (width, setw) 1114
19.6.4 User-Defined Output Stream Manipulators 1115
19.6.5 Trailing Zeros and Decimal Points (showpoint) 1116
19.6.6 Alignment (left, right and internal) 1117
19.6.7 Padding (fill, setfill) 1118
19.6.8 Integral Stream Base (dec, oct, hex, showbase) 1119
19.6.9 Floating-Point Numbers; Scientific and Fixed Notation
(scientific, fixed) 1120
19.6.10 Uppercase/Lowercase Control (uppercase) 1121
19.6.11 Specifying Boolean Format (boolalpha) 1122
19.6.12 Setting and Resetting the Format State via Member
Function flags 1123
19.7 Stream Error States 1124
19.8 Tying an Output Stream to an Input Stream 1127
19.9 C++20 Text Formatting 1127
19.9.1 C++20 std::format Presentation Types 1128
19.9.2 C++20 std::format Field Widths and Alignment 1130
19.9.3 C++20 std::format Numeric Formatting 1131
19.9.4 C++20 std::format Field Width and Precision Placeholders 1132
19.10 Wrap-Up 1133

20 Other Topics and a Look Toward the


Future of C++ 1141
20.1 Introduction 1142
20.2 shared_ptr and weak_ptr Smart Pointers 1143
20.2.1 Reference Counted shared_ptr 1143
20.2.2 weak_ptr: shared_ptr Observer 1147
20.3 Runtime Polymorphism with std::variant and std::visit 1154
20.4 protected Class Members: A Deeper Look 1160
20.5 Non-Virtual Interface (NVI) Idiom 1161
20.6 Inheriting Base-Class Constructors 1168
20.7 Multiple Inheritance 1169
20.7.1 Diamond Inheritance 1174
20.7.2 Eliminating Duplicate Subobjects with virtual
Base-Class Inheritance 1176
xxii Contents

20.8 public, protected and private Inheritance 1177


20.9 namespaces: A Deeper Look 1179
20.9.1 Defining namespaces 1180
20.9.2 Accessing namespace Members with Qualified Names 1181
20.9.3 using Directives Should Not Be Placed in Headers 1181
20.9.4 Nested Namespaces 1181
20.9.5 Aliases for namespace Names 1181
20.10 Storage Classes and Storage Duration 1182
20.10.1 Storage Duration 1182
20.10.2 Local Variables and Automatic Storage Duration 1182
20.10.3 Static Storage Duration 1183
20.10.4 mutable Class Members 1184
20.11 Operator Keywords 1185
20.12 decltype Operator 1186
20.13 Trailing Return Types for Functions 1187
20.14 [[nodiscard]] Attribute 1187
20.15 Some Key C++23 Features 1189
20.16 Wrap-Up 1194

21 Computer Science Thinking:


Searching, Sorting and Big O 1197
21.1 Introduction 1198
21.2 Efficiency of Algorithms: Big O 1199
21.2.1 O(1) Algorithms 1199
21.2.2 O(n) Algorithms 1199
21.2.3 O(n2) Algorithms 1200
21.3 Linear Search 1201
21.3.1 Implementation 1201
21.3.2 Efficiency of Linear Search 1202
21.4 Binary Search 1203
21.4.1 Implementation 1203
21.4.2 Efficiency of Binary Search 1207
21.5 Insertion Sort 1208
21.5.1 Implementation 1209
21.5.2 Efficiency of Insertion Sort 1210
21.6 Selection Sort 1210
21.6.1 Implementation 1211
21.6.2 Efficiency of Selection Sort 1213
21.7 Merge Sort (A Recursive Implementation) 1213
21.7.1 Implementation 1214
21.7.2 Efficiency of Merge Sort 1219
21.7.3 Summarizing Various Algorithms’ Big O Notations 1219
21.8 Wrap-Up 1221

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.”

Live-Code Approach and Getting the Code


At the heart of the book is the Deitel signature live-code approach. Rather than code snip-
pets, we show C++ as it’s intended to be used in the context of 255 complete, working,
real-world C++ programs with live outputs.
Read the Before You Begin section that follows this Preface to learn how to set up your
Windows, macOS or Linux computer to run the code examples. For your convenience,
we provide the book’s examples in C++ source-code (.cpp and .h) files for use with inte-
grated development environments and command-line compilers. All the source code is
available for download at
• https://github.com/pdeitel/CPlusPlusHowToProgram11e
• https://www.deitel.com/cpphtp11
Chapter 1’s Test-Drives (Section 1.11) shows how to compile and run the code exam-
ples with each of our preferred compilers. Executing each program in parallel with reading
the text will make your learning experience “come alive.” If you encounter a problem, you
can reach us at [email protected], and we’ll respond promptly.

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

Key Computing Trends


For many decades:
• computer hardware has rapidly been getting faster, cheaper and smaller,
• Internet bandwidth (that is, its information-carrying capacity) has rapidly been
getting larger and cheaper, and
• quality computer software has become ever more abundant and often free or
nearly free through the open-source movement.
The Internet of Things (IoT) already connects tens of billions of computerized devices of
every imaginable type, and that number is likely to grow quickly. These generate enor-
mous volumes of data (one form of “big data”) at rapidly increasing speeds and quantities.
And most computing will eventually be performed in “the Cloud”—that is, by using com-
puting services accessible over the Internet.
For the novice, the book’s early chapters establish a solid foundation in programming
fundamentals. The mid-range to high-end chapters and the 50 more significant case study
examples and case study exercises will ease you into professional software-development
challenges and practices.
Given the extraordinary performance demands that today’s applications place on
computer hardware, software and the Internet, professionals often choose C++ to build the
most performance-intensive portions of these applications. Throughout the book, we
emphasize performance issues to help you prepare for industry.

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

4 “Objects-Natural” Learning Approach


Traditionally object-oriented programming textbooks have been designated as “late
objects” or “early objects.” What’s really “late” or “early” in these textbooks is not
“objects.” Rather, it’s teaching how to develop custom classes—the blueprints from which
objects are built. We’ve written textbooks using both of these approaches.

What Is “Objects Natural?”


As we wrote our Python textbook,3 we noticed that although our presentation fit the “late
objects” model, it was actually something more—and that something is special. We call it
the “objects-natural approach,” and we’re now applying it to C++ and the other object-
oriented programming languages we write about.
Similar to “late objects,” our objects-natural approach begins with programming fun-
damentals, but you’ll work extensively in the early chapters with easy-to-use powerful pre-
existing classes that do significant things. You’ll quickly create objects of those classes
(typically with one line of code) and tell them to “strut their stuff” with a minimal number
of simple C++ statements.
Even if you’re a programming novice, you can perform significant tasks long before
you learn how to create custom C++ classes in Chapter 9. This is one of the most compel-
ling aspects of working with a mature object-oriented language like C++. After covering
programming fundamentals with the objects-natural approach, we provide a deep treat-
ment of object-oriented programming beginning with a rich treatment of custom class cre-
ation.

An Abundance of Free Classes


We emphasize using the massive number of valuable free classes in the C++ ecosystem.
These typically come from:
• the C++ standard library,
• platform-specific libraries, such as those provided with Microsoft Windows,
Apple macOS or various Linux versions, and
• free third-party C++ libraries, often created by the open-source community.
We encourage you to view lots of free, open-source C++ code available on sites like
GitHub. Reading other programmers’ code is a great way to learn.

The Boost Project


Boost provides 168 powerful open-source C++ libraries4 and serves as a “breeding ground”
for new capabilities that might eventually be incorporated into the C++ standard libraries.
The following StackOverflow post lists Modern C++ libraries and language features that
evolved from the Boost libraries:5
https://stackoverflow.com/a/8852421

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).

Objects-Natural Case Studies


Chapter 1 presents a friendly introduction to the basic concepts and terminology of object
technology. In the early chapters, you’ll create and use objects of preexisting classes long
before Chapter 9 discusses how to create custom classes. See Section 6’s Tour of the Book
for descriptions of our objects-natural case studies in Chapters 2–9. A perfect example of
the objects-natural approach is using objects of standard library classes, like array and
vector (Chapter 6), without knowing how to write classes in general or how those classes
are implemented in particular. Throughout the rest of the book, we use C++ standard
library capabilities extensively.

5 Programming Wisdom and Key C++20 Features


We integrate smoothly into the flow of the text software-development wisdom, data sci-
ence topics, C++20 modules and C++20 concepts features:
• Software engineering observations highlight architectural and design issues for SE
proper software construction, especially for larger systems.
• Security best practices help you strengthen your programs against attacks. Sec
• Performance tips highlight opportunities to make your programs run faster or Perf
minimize the amount of memory they occupy.
• Common programming errors help reduce the likelihood that you’ll make the Err
same mistakes.
• C++ Core Guidelines recommendations (introduced in Section 12). CG
• C++20’s new modules features. Mod
• C++20’s new concepts features.
C Concepts
• We present and use data science topics in several examples and exercises. DS

6 Tour of the Book


The one-page Table of Contents diagram earlier in this Preface provides a high-level over-
view of the book’s modular architecture from “40,000 feet.” We recommend that you
refer to that diagram as you read this section.
The early chapters establish a solid foundation in C++20 fundamentals. The mid-
range to high-end chapters introduce Modern C++ software development. We discuss
C++’s programming models:
• procedural programming,
• functional-style programming,
• object-oriented programming,
• generic programming and
• template metaprogramming.
xxviii Preface

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.

Part 1: Programming Fundamentals Quickstart


Chapter 1, Intro and Test-Driving Popular, Free C++ Compilers, engages programming
novices with intriguing facts and figures to excite them about studying computers and
computer programming. The chapter includes current technology trends, hardware, soft-
ware and Internet concepts, and a sample data hierarchy from bits to bytes, fields, records
and databases. It lays the groundwork for the C++ programming discussions in Chapters
2–21 and the substantial integrated case study examples, exercises and projects.
We discuss the programming-language types and technologies you’ll likely use as you
develop software. We introduce the C++ standard library—existing, reusable, top-quality,
high-performance capabilities that help you avoid “reinventing the wheel.” You’ll enhance
your productivity by using libraries to perform significant tasks while writing only modest
numbers of instructions. We also introduce the Internet, the World Wide Web, the
“Cloud” and the Internet of Things (IoT), laying the groundwork for modern applications
development.
This chapter’s test-drives demonstrate how to compile and execute C++ code with
three of the most popular C++ development environments:
• Microsoft’s Visual C++ in Visual Studio on Windows,
• GNU’s g++ on macOS/Linux and
• The LLVM Compiler Infrastructure’s clang++ on macOS/Linux.
We tested the book’s 255 code examples using each compiler.6 Choose whichever you pre-
fer—the book also works well with many others. See the Before You Begin section that
follows this Preface for compiler installation instructions.
We also demonstrate running g++ and clang++ using Docker containers. Docker is
an important tool that enables you to run the latest versions of these compilers on Win-
dows, macOS or Linux. See Section 7 of this Preface for more details on Docker and
Docker containers.
You’ll learn just how big “big data” is and how quickly it’s getting even bigger. The
chapter closes with an introduction to artificial intelligence (AI)—a key overlap between
computer-science and data-science. AI and data science will likely play significant roles in
your computing career.
Chapter 2, Intro to C++ Programming, presents C++ fundamentals and illustrates key
language features, including input, output, fundamental data types, arithmetic operators
and their precedence, and decision-making. As part of our objects-natural approach,
Section 2.8’s objects-natural case study demonstrates creating and using objects of the
C++ standard library class string—without you having to know how to develop custom
classes in general or how the large complex class string is implemented in particular).

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.

7. “Vigenère Cipher.” Accessed April 29, 2023. https://en.wikipedia.org/wiki/Vigenère_cipher.


xxx Preface

Part 2: Arrays, Pointers and Strings


Chapter 6, arrays, vectors, Ranges and Functional-Style Programming, begins our
early coverage of the C++ standard library’s containers, iterators and algorithms. We pres-
ent the C++ standard library’s array container for representing lists and tables of values.
You’ll define and initialize arrays and access their elements. We discuss passing arrays to
functions, sorting and searching arrays and manipulating multidimensional arrays.
Like many modern languages, C++ offers “functional-style” programming features.
These can help you write more concise code that’s less likely to contain errors and is easier
to read, debug and modify. Chapter 6 begins our introduction to functional-style pro-
gramming using arrays, lambda expressions (anonymous functions), and C++20
ranges—a C++20 “big four” feature that simplifies how you call many of the C++ standard
library’s predefined algorithms. We continue that discussion in Chapters 13 and 14.
Section 6.15’s objects-natural case study demonstrates the C++ standard library class
template vector. Chapter 6 is essentially a large objects-natural case study of both arrays
and vectors. The code in this chapter is a good example of Modern C++ coding idioms.
This chapter’s exercises include a case study on the famous Knight’s Tour problem, which
we approach in various ways, including an AI strategy called heuristic programming.
Chapter 7, (Downplaying) Pointers in Modern C++, explains pointer concepts, such as
declaring pointers, initializing pointers, getting the memory address of a variable, dereferenc-
ing pointers, pointer arithmetic and the close relationship among built-in pointers, pointer-
based arrays and pointer-based strings, each of which C++ inherited from the C program-
ming language. Pointers are powerful but challenging to work with. So, we focus on Modern
C++ features that eliminate the need for most pointers and make your code more robust and
Sec secure, including references, “smart pointer” objects, arrays and vectors, strings, C++20
spans and C++17 string_views. We still cover built-in arrays because they remain useful in
C++, and so you’ll be able to read legacy C++ code that you’ll encounter in industry. In new
development, you should favor Modern C++ capabilities. Section 7.10’s objects-natural case
study demonstrates one such capability—C++20 spans. These enable you to view and
manipulate elements of contiguous containers, such as pointer-based arrays and standard
library arrays and vectors, without using pointers directly.
In a Random-Number Simulation case study exercise, you’ll implement the famous
race between the tortoise and the hare. This chapter also contains the first of our two sys-
tems programming case study exercises—Building Your Own Computer (as a virtual
machine). In the context of several case study exercises, you’ll “peel open” a hypothetical
computer and look at its internal structure. We introduce simple machine-language pro-
gramming and write several small machine-language programs for this computer, which
we call the Simpletron. As its name implies, it’s a simple machine, but as you’ll see, a pow-
erful one as well. The Simpletron runs programs written in the only language it directly
understands—that is, Simpletron Machine Language, or SML for short. To make this an
especially valuable experience, you’ll then build a computer (through the technique of
software-based simulation) on which you can actually run your machine-language pro-
grams! The Simpletron experience will give you a basic introduction to virtual
machines—one of the most important systems-architecture concepts in modern com-
puting. Chapter 13 contains the intimately related systems programming case study exer-
cise—Building Your Own Compiler.
6 Tour of the Book xxxi

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

8. “Anscombe’s quartet.” Accessed March 8, 2023. https://en.wikipedia.org/wiki/


Anscombe%27s_quartet.
xxxii Preface

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.

Part 3: Object-Oriented Programming


SE Chapter 9, Custom Classes, begins our substantially upgraded, multi-chapter, Modern
C++, object-oriented programming treatment. C++ is extensible—each class you create
becomes a new type you can use to create objects. In Chapters 9–11, you’ll learn C++’s
features for crafting valuable classes and manipulating objects of these classes.
In Section 9.22, we conclude our objects natural case study track by studying the
Vigenère Secret-Key Cipher class implementation that we demonstrated in Chapter 5’s
objects-natural case study. Objects-natural case study Exercises 9.32–9.33 demonstrate
how to serialize objects with JSON (JavaScript Object Notation)—a popular human-
and-machine-readable data format commonly used to transmit data over the Internet.
In the context of several Random-Number Simulation case study exercises, you’ll use
arrays of strings, random-number generation and simulation techniques to implement
Sec a text-based, card-shuffling-and-dealing program. In a Security and Cryptography case
study exercise, you’ll also explore public-key cryptography with the RSA algorithm. This
technique performs encryption with a public key known to every sender who might want
to send a secret message to a particular receiver. The public key can be used to encrypt mes-
sages but not decrypt them. Messages can be decrypted only with a paired private key
known only to the receiver, so it’s much more secure than secret keys in secret-key cryp-
tography. RSA is among the world’s most widely used public-key cryptography technolo-
gies. You’ll build a working, small-scale, classroom version of the RSA cryptosystem.
Chapter 10, OOP: Inheritance and Runtime Polymorphism, focuses on the relationships
among classes in an inheritance hierarchy and the powerful runtime polymorphic process-
ing capabilities (for “programming in the general”) that these relationships enable. In this
chapter’s runtime-polymorphism case study, you’ll implement an Employee class hierar-
chy in an application that performs polymorphic payroll calculations.
An important aspect of this chapter is understanding how polymorphism works. A
key feature of the chapter is its detailed diagram and explanation of how C++ typically
implements polymorphism, virtual functions and dynamic binding “under the hood.”
You’ll see that it can use an elegant pointer-based data structure. We also discuss program-
ming to an interface, not an implementation. In Chapter 20, we discuss other more
advanced mechanisms for achieving runtime polymorphism, including the non-virtual
interface idiom (NVI) and std::variant/std::visit.

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.

Part 4: Standard Library Containers, Iterators and Algorithms


Chapter 13, Standard Library Containers and Iterators, begins our broader and deeper
treatment of three key C++ standard library components:
• containers (templatized data structures),
• iterators (for traversing containers and accessing their elements) and
• algorithms (which use iterators to manipulate containers).

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.

Part 5: Advanced Topics


Chapter 15, Templates, C++20 Concepts and Metaprogramming, presents our substan-
tially enhanced treatment of compile-time (static) polymorphism, generic programming
with templates, C++20 concepts and template metaprogramming. The importance of
templates has increased with each new C++ release. A major Modern C++ theme is to do
Perf more at compile-time for better type checking and better runtime performance—any-
thing resolved at compile-time avoids runtime overhead and makes systems faster. As
you’ll see, templates and especially template metaprogramming are the keys to powerful
compile-time operations.
We demonstrate C++20’s new template capabilities, including abbreviated function
Concepts C templates, templated lambdas and concepts. We introduce type traits for testing type attri-
butes at compile-time. We show variadic function templates that receive a variable number
of parameters and use fold expressions to conveniently apply an operation to all the argu-
ments passed to a variadic template.
6 Tour of the Book xxxv

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

enabling you to do concurrent programming with a simple sequential-like coding style.


The mechanisms supporting this are handled entirely by code that’s written for you by the
compiler. A function containing any of the keywords co_await, co_yield or co_return
is a coroutine.
Coroutines require sophisticated infrastructure, which you can write yourself, but
doing so is complex, tedious and error-prone. Instead, most experts agree that you should
SE use high-level coroutine support libraries, which is the approach we show. The open-
source community has created several experimental libraries for developing coroutines
quickly and conveniently—we use two in our presentation. C++23 has standard library
support for generator coroutines, and more coroutine support is expected in C++26.
Perf We present three multithreading and multicore systems performance case studies:
• Creating a Generator Coroutine with co_yield and the generator Library
• Launching Tasks with concurrencpp
• Creating a Coroutine with co_await and co_return
To help readers understand how coroutines work, the first and third case studies include
diagrams illustrating each application’s flow of control.
Chapter 19, Stream I/O & C++20 Text Formatting, discusses C++ stream input/output
capabilities and formatting features. We include stream formatting primarily for people who
might encounter it in legacy code. Section 19.9 presents an in-depth case study on C++20’s
new text-formatting features. In introductory computer science courses, instructors may
wish to present Section 19.9 after we introduce C++20 text formatting in Chapter 4.
Chapter 20, Other Topics and a Look Toward the Future of C++, continues our discus-
sion of runtime polymorphism from Chapter 10 with case studies on runtime type infor-
mation (RTTI), inheriting base-class constructors, the non-virtual interface idiom, duck
typing with std::variant and std::visit (for runtime polymorphism with objects of
classes that are not related by inheritance), and multiple inheritance. The chapter also pres-
ents miscellaneous C++ topics, including storage classes, storage duration, mutable class
members, namespaces, operator keywords, pointers to class members, the [[nodiscard]]
attribute, the std::shared_ptr and std::weak_ptr smart pointers, determining types at
compile-time with decltype, and the [[likely]] and [[unlikely]] attributes. The chap-
ter ends with a look forward to features coming in the C++23 and C++26 standards.
Chapter 21, Computer Science Thinking: Searching, Sorting and Big O, introduces
some classic computer-science topics. We consider several algorithms and compare their
processor demands and memory consumption. We present a friendly introduction to
computer science’s Big O notation, which indicates how hard an algorithm may have to
work to solve a problem based on the number of items it must process.
Perf The chapter includes two case studies that visualize the high-speed binary search and
merge sort algorithms to illustrate how these algorithms work. In introductory computer
science courses, instructors can present this chapter after Chapter 6.

Modern C++ Data Structures Courses


Our recursion (Chapter 5), arrays (Chapter 6), searching (Chapters 6 and 21), sorting
(Chapters 6 and 21), Big O (Chapter 21), containers (Chapter 13), iterators (Chapter 13)
7 Compilers, Docker and Static Code Analysis Tools xxxvii

and algorithms (Chapter 14) coverage provides nice content for a course emphasizing
Modern C++ data structures.

7 Compilers, Docker and Static Code Analysis Tools


Industrial-Strength Compilers
We tested all the code for correctness on the Windows, macOS and Linux operating sys-
tems using the latest versions of
• Visual C++® in Microsoft® Visual Studio® Community edition on Windows®,
• GNU® C++ (g++) and
• Clang C++ (clang++).
See the Before You Begin section that follows this Preface for software installation instruc-
tions.
Most C++20 features are now fully implemented in these compilers. We point out
exceptions as appropriate. As coverage improves, we’ll post code updates to the book’s
GitHub repository:
https://github.com/pdeitel/CPlusPlusHowToProgram11e

and both code and text updates on the book’s website:


https://www.deitel.com/books/cpphtp11

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.

Static Code Analysis Tools


Static code analysis tools let you quickly check your code for common errors and security Err
problems and provide insights for code improvement. Using these tools is like having Sec
world-class experts checking your code. To help us adhere to the C++ Core Guidelines and
improve our code in general, we used the following static-code analyzers:
• clang-tidy—https://clang.llvm.org/extra/clang-tidy/
• cppcheck—https://cppcheck.sourceforge.io/
xxxviii Preface

• 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++.

8 Thinking Like a Developer—GitHub, StackOverflow


and More
The best way to prepare [to be a programmer] is to write programs, and to study great programs
that other people have written. In my case, I went to the garbage cans at the Computer Science
Center and fished out listings of their operating systems.14—William Gates

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

GitHub is a crucial element of the professional software developer’s arsenal,


with version-control tools that help developer teams manage public open-source
projects and private projects. There is a massive C++ open-source community on
GitHub where developers contribute to almost 58,00018 C++ code repositories.
We encourage you to study and execute lots of developers’ open-source C++
code. This is a great way to learn and is a natural extension of our live-code teach-
ing approach.19

9 Computing and Data Science Curricula DS


This book is designed for courses that adhere to one or more of the following ACM/IEEE
CS-and-related curricula, which call for covering security, data science, ethics, privacy and
performance concepts and using real-world data:
• Computer Science Curricula 2013,20
• CC2020: A Vision on Computing Curricula,21
• Computing Curricula 2020 recommendations,22
• Information Technology Curricula 2017,23
• Cybersecurity Curricula 2017,24
• the 2016 data science initiative “Curriculum Guidelines for Undergraduate Pro-
grams in Data Science”25 from the faculty group sponsored by the NSF and the
Institute for Advanced Study, and
• ACM Data Science Task Force’s Computing Competencies for Undergraduate
Data Science Curricula Final Report.26

18. “C++.” Accessed March 8, 2023. https://github.com/topics/cpp.


19. You’ll need to become familiar with the variety of open-source licenses for software on GitHub.
20. ACM/IEEE (Assoc. Comput. Mach./Inst. Electr. Electron. Eng.). 2013. Computer Science Curricula
2013: Curriculum Guidelines for Undergraduate Degree Programs in Computer Science (New York:
ACM). Accessed March 8, 2023. http://ai.stanford.edu/users/sahami/CS2013/final-
draft/CS2013-final-report.pdf.
21. A. Clear, A. Parrish, G. van der Veer and M. Zhang “CC2020: A Vision on Computing Curricula.”
Accessed March 8, 2023. https://dl.acm.org/citation.cfm?id=3017690.
22. CC2020 Task Force, Computing Curricula 2020. Accessed March 8, 2023. https://www.acm.org/
binaries/content/assets/education/curricula-recommendations/cc2020.pdf.
23. Information Technology Curricula 2017. Accessed March 8, 2023. http://www.acm.org/binaries/
content/assets/education/it2017.pdf.
24. Cybersecurity Curricula 2017. Accessed March 8, 2023. https://cybered.hosting.acm.org/wp-
content/uploads/2018/02/newcover_csec2017.pdf.
25. “Curriculum Guidelines for Undergraduate Programs in Data Science” Accessed March 8, 2023.
http://www.annualreviews.org/doi/full/10.1146/annurev-statistics-060116-053930.
26. ACM Data Science Task Force, Computing Competencies for Undergraduate Data Science Curricula.
Accessed March 8, 2023. https://dstf.acm.org/DSTF_Final_Report.pdf.
xl Preface

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

DS 10 Data Science Overlaps with Computer Science29


The undergraduate data science curriculum proposal30 includes algorithm development,
programming, computational thinking, data structures, database, mathematics, statistical
thinking, machine learning, data science and more—a significant overlap with computer
science, especially given that the data science courses include some key AI topics. We work
some basic data science topics into various examples, exercises, projects and case studies.

Key Points from the Data Science Curriculum Proposal


This section calls out some key points from the data science undergraduate curriculum
proposal and its detailed course descriptions appendix.31 We cover each of the following:
• Learn programming fundamentals commonly presented in computer science
courses, including working with data structures.
• Be able to solve problems by creating algorithms.
• Work with procedural, functional and object-oriented programming.
• Explore concepts via simulations.
• Use development environments (we tested all our code on Microsft Visual C++,
GNU g++ and LLVM clang++).
• Work with real-world data in practical case studies and projects.
• Create data visualizations.
• Work with existing software.
• Work with high-performance tools, such as C++’s multithreading libraries.
• Focus on data’s ethics, security and privacy issues.

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.

12 C++ Core Guidelines


The C++ Core Guidelines CG
https://isocpp.github.io/CppCoreGuidelines/CppCoreGuidelines

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.

32. C++ Core Guidelines, “Abstract.” Accessed March 8, 2023. https://isocpp.github.io/CppCore-


Guidelines/CppCoreGuidelines#S-abstract.
33. C++ Core Guidelines, “Abstract.”
xlii Preface

Guidelines Support Library


The C++ Core Guidelines often refer to capabilities of the Guidelines Support Library
(GSL), which provides reusable C++ components that support various recommenda-
tions.34 Microsoft provides an open-source GSL implementation on GitHub at
https://github.com/Microsoft/GSL

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.

13 Pedagogic Features and Conventions


C++ How to Program: An Objects-Natural Approach, 11/e contains hundreds of live-code
SE examples. We stress program clarity and concentrate on building well-engineered software.

Using Fonts for Emphasis


Our C++ code uses a fixed-width font (e.g., x = 5). We place on-screen components in
the bold Helvetica font (e.g., the File menu).

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

Objectives and Outline


Each chapter begins with objectives that tell you what to expect.

Tables and Illustrations


Abundant tables and line drawings are included.

Programming Tips and Key Features


We call out programming tips and key features with icons in the margins (see Section 5).

Index
For convenient reference, we’ve included an extensive index, with defining occurrences of
key terms highlighted with a bold page number.

C++ Programming Fundamentals


In our rich coverage of C++ fundamentals:
• We emphasize problem-solving and algorithm development.
• To help students prepare to work in industry, we use the terminology from the
latest C++ standard document in preference to general programming terms.

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

• We avoid heavy math, leaving it to upper-level courses. Optional mathematical


exercises and projects are included for science and engineering courses.

Innovation: “Intro-to” Pedagogy with 452 Integrated Checkpoint Exercises


This book uses our new “Intro to” pedagogy with integrated Checkpoint exercises and
answers. We introduced this pedagogy in our textbook, Intro to Python for Computer Sci-
ence and Data Science: Learning to Program with AI, Big Data and the Cloud (https:// DS
deitel.com/pycds). Chapter sections are intentionally small. We use a “read-a-little,
code-a-little, test-a-little” approach. In the core computer science chapters (1–12 and 21),
you read about a new concept, study and execute the corresponding code examples, then
test your understanding via the integrated fill-in-the-blank, true/false, discussion and
code-based Checkpoint exercises immediately followed by their answers. This will help
you keep a brisk learning pace.

KIS (Keep It Simple), KIS (Keep it Small), KIT (Keep it Topical)


• Keep it simple—We strive for simplicity and clarity.
• Keep it small—Many of the book’s examples are small. We use more substantial
code examples, exercises and projects when appropriate, particularly in the case
studies that are a core feature of this textbook.
• Keep it topical—To “take the pulse” of Modern C++, which changes the way
developers write C++ programs, we read, browsed or watched approximately
6,000 current articles, research papers, white papers, books, documentation
pieces, blog posts, forum posts, webinars and videos.
• We show C++ as it’s intended to be used with a rich collection of applications
programming and systems programming case studies, focusing on computer sci-
ence, artificial intelligence, data science and other fields. DS

Over 700 Contemporary Examples, Exercises and Projects (EEPs)


Consistent with our live-code and object-natural approaches, you’ll learn hands-on from
a broad selection of 255 real-world examples and case studies, and 476 exercises and proj-
ects drawn from computer science, data science and other fields: DS
• Our code examples, exercises and projects familiarize students with current topics
of interest to developers. We begin in Chapter 1 by briefly touring topics of cur-
rent interest including open-source software, virtualization, simulation, web ser-
vices, multithreading, multicore hardware architecture, systems programming,
artificial intelligence, natural language processing, data science, robust secure DS
programming, cryptography, Docker, GitHub, StackOverflow, forums, the
metaverse, blockchain, NFTs (nonfungible tokens), cryptocurrencies (like Bit-
coin and Ethereum), generative AI (ChatGPT, Dall-E), general artificial intelli-
gence and more.
• We added a variety of systems programming and application programming case
studies. Some are book sections that walk through the complete source code, some
are exercises with detailed specifications from which you should be able to develop
the code solution on your own, and some are exercises requiring additional
research. We enumerate the 50 case studies and case-study exercises in this preface.
xliv Preface

• 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.

Sec Security Emphasis and Cryptography Case Studies


Consistent with our richer treatment of security, we’ve added case studies on secret-key
and public-key cryptography. The latter is a project exercise that includes a detailed walk-
through of the enormously popular RSA algorithm’s steps, providing hints to help you
build a working, simple, small-scale classroom implementation.

Working with Open-Source Software


Open source is software with source code that anyone can inspect, modify, and
enhance.”35 We encourage you to try lots of demos and view free, open-source code exam-
ples (available on sites such as GitHub) for inspiration.
35. “What is open source?” Accessed March 8, 2023. https://opensource.com/resources/what-
open-source.
14 Instructor Supplements xlv

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.

36. “Curricula Recommendations.” Accessed March 8, 2023. https://www.acm.org/education/


curricula-recommendations.
37. “Curricula Recommendations.” Accessed March 8, 2023. https://www.acm.org/education/
curricula-recommendations.
38. “Introducing ChatGPT.” Accessed March 8, 2023. https://openai.com/blog/chatgpt.
39. “Dall-E 2.” Accessed March 8, 2023. https://openai.com/product/dall-e-2.
xlvi Preface

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

15 Some Key C++ Documentation and Resources


The book includes almost 800 citations to videos, blog posts, articles, whitepapers and
online documentation we studied while writing the manuscript. You may want to access
some of these resources to investigate more advanced features and idioms. The website
cppreference.com has become the defacto C++ documentation site. We reference it fre-
quently so you can get more details about the standard C++ classes and functions we use
throughout the book. We also frequently cite the final draft of the C++20 standard docu-
ment, which is available free on GitHub at
https://timsong-cpp.github.io/cppwp/n4861/

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/

• The GNU C++ Standard Library Reference Manual: https://gcc.gnu.org/


onlinedocs/libstdc++/manual/index.html

16 Getting Your Questions Answered


Popular C++ and general programming online forums include
• https://stackoverflow.com

• 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

For a list of other valuable sites, see


https://www.geeksforgeeks.org/stuck-in-programming-get-the-solution-
from-these-10-best-websites/

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.

Communicating with the Authors


As you read the book, if you have questions, we’re easy to reach at
[email protected]

We’ll respond promptly.

17 Join the Deitel & Associates, Inc. Social Media


Communities
You can keep up-to-date with Deitel on the following social media platforms:
• LinkedIn®—https://www.linkedin.com/company/deitel-&-associates/
• YouTube®—https://youtube.com/DeitelTV
• Twitter®—https://twitter.com/deitel
• Facebook®—https://facebook.com/DeitelFan
• Instagram®—https://instagram.com/DeitelFan

18 Live Instructor-Led Training with Paul Deitel


Paul Deitel has been teaching programming languages to academic and professional audi-
ences for three decades. He presents a variety of one- to five-day C++, C, Python and Java
courses, and teaches Python with an Introduction to Data Science for the UCLA Ander-
son School of Management’s Master of Science in Business Analytics (MSBA) program.
The longer classes include intense, hands-on labs. His courses are delivered worldwide on-
site or virtually. Please contact [email protected] for a proposal customized to meet
your programming-language training needs.

19 College Textbook Digital Formats


Our college textbook, C++ How to Program: An Objects-Natural Approach, 11/e, is avail-
able in three digital formats:
• Online e-books offered through popular e-book providers.
• Interactive Pearson eText (see below).
• Interactive Pearson Revel with assessment (see below).
All of these textbook versions include standard “How to Program” features such as:
• A chapter introducing hardware, software and Internet concepts.
• An introduction to programming for novices.
xlviii Preface

• End-of-section programming and non-programming Checkpoint self-review


exercises with answers.
• End-of-chapter exercises.
Deitel Pearson eTexts and Revels include:
• Videos in which Paul Deitel discusses the material in the book’s core CS1 chap-
ters (1–10).
• Interactive programming and non-programming Checkpoint self-review exer-
cises with answers.
• Glossaries, flashcards, matching exercises and other learning tools.
In addition, Pearson Revels include interactive programming and non-programming
automatically graded exercises, as well as instructor course-management tools, such as a
grade book.
Supplements available to qualified college instructors teaching from the textbook
include:
• Instructor solutions manual with solutions to most of the end-of-chapter exer-
cises.
• Test-item file with four-part, code-based and non-code-based multiple-choice
questions with answers.
• Customizable PowerPoint lecture slides.
Please write to [email protected] for more information.

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]

We’ll respond promptly.


Welcome to the exciting world of C++ programming. We’ve enjoyed writing 11 edi-
tions of our academic and professional C++ content over the last 30 years. We hope you
have an informative, challenging and entertaining learning experience with C++ How to
Program: An Objects-Natural Approach, 11/e and enjoy this look at Modern C++ soft-
ware development.
Paul Deitel
Harvey Deitel

41. “Grammarly.” Accessed March 8, 2023. https://www.grammarly.com.


l Preface

21 About the Authors


Paul J. Deitel, CEO and Chief Technical Officer of Deitel & Associates, Inc., is an MIT
graduate with 43 years in computing. He is one of the world’s most experienced
programming-languages trainers, having taught professional courses to software develop-
ers since 1992. He has delivered hundreds of programming courses to academic, industry,
government and military clients of Deitel & Associates, Inc. internationally, including
UCLA, SLB (formerly Schlumberger), Cisco, IBM, Siemens, Sun Microsystems (now
Oracle), Dell, Fidelity, NASA at the Kennedy Space Center, the National Severe Storm
Laboratory, White Sands Missile Range, Rogue Wave Software, Boeing, Puma, iRobot
and many more.
Dr. Harvey M. Deitel, Chairman and Chief Strategy Officer of Deitel & Associates,
Inc., has 62 years of experience in computing. Dr. Deitel earned B.S. and M.S. degrees in
Electrical Engineering from MIT and a Ph.D. in Mathematics from Boston University—
he studied computing in each of these programs before they spun off Computer Science
departments. He has extensive college and professional teaching experience, including
earning tenure and serving as the Chairman of the Computer Science Department at Bos-
ton College before founding Deitel & Associates in 1991 with his son, Paul. The Deitels’
publications have earned international recognition, with more than 100 translations pub-
lished in Japanese, German, Russian, Spanish, French, Polish, Italian, Simplified Chinese,
Traditional Chinese, Korean, Portuguese, Greek, Urdu and Turkish. Dr. Deitel has deliv-
ered hundreds of programming courses to academic, corporate, government and military
clients.

22 About Deitel® & Associates, Inc.


Deitel & Associates, Inc., founded by Paul Deitel and Harvey Deitel, is an internationally
recognized authoring and corporate-training organization specializing in computer pro-
gramming languages, object technology, mobile app development and Internet and web
software technology. The company’s training clients include some of the world’s largest
companies, government agencies, branches of the military, and academic institutions. The
company offers instructor-led training courses delivered virtually and live at client sites
worldwide, and virtually worldwide for Pearson Education on O’Reilly Online Learning
(https://learning.oreilly.com), formerly called Safari Books Online.
Through its 48-year publishing partnership with Pearson, Deitel & Associates, Inc.
publishes leading-edge computer programming college textbooks and professional books
in print and digital formats, LiveLessons video courses, O’Reilly Online Learning live
training courses and Revel™ and eText interactive multimedia college courses.
To contact Deitel & Associates, Inc. and the authors, or to request a proposal for vir-
tual or on-site, instructor-led training worldwide, write to
[email protected]

To learn more about Deitel virtual and on-site corporate training, visit
https://deitel.com/training

Individuals wishing to purchase Deitel books can do so at


https://amazon.com
https://www.barnesandnoble.com/
22 About Deitel® & Associates, Inc. li

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]

Deitel e-books are available in various formats from


https://www.amazon.com/ https://www.vitalsource.com/
https://www.barnesandnoble.com/ https://www.redshelf.com/
https://www.informit.com/ https://www.chegg.com/

To register for a free 10-day trial to O’Reilly Online Learning, visit


https://learning.oreilly.com/register/
This page intentionally left blank
Before
You Begin
Before using this book, please read this section to understand our conventions and set up
your computer to compile and run our example programs. If there are changes to the
instructions presented here, we’ll post updates on the book’s webpage:
https://deitel.com/cpphtp11

Font and Naming Conventions


We use fonts to distinguish application elements and C++ code elements from regular text:
• We use a bold sans-serif font for on-screen application elements, such as “the File
menu.”
• We use a sans-serif font for commands and C++ code elements, as in sqrt(9).

Obtaining the Code Examples


Download the C++ How to Program: An Objects-Natural Approach, 11/e code examples
from our GitHub repository at
https://github.com/pdeitel/CPlusPlusHowToProgram11e

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.

Installing Visual Studio Community Edition on Windows


If you are a Windows user, first ensure that your system meets the requirements for Mic-
rosoft Visual Studio Community edition at
https://docs.microsoft.com/en-us/visualstudio/releases/2022/system-
requirements

Next, go to
https://visualstudio.microsoft.com/downloads/

Then perform the following installation steps:


1. Click Free Download under Community.
2. Depending on your web browser, you may see a pop-up at the bottom of your
screen where you can click Run to start the installation process. If not, double-
click the installer file in your Downloads folder when the download completes.
3. In the User Account Control dialog, click Yes to allow the installer to make chang-
es to your system.
4. In the Visual Studio Installer dialog, click Continue to allow the installer to down-
load the components it needs for you to configure your installation.

1. GNU C++ (g++) 13.1 at the time of this writing.


2. Xcode 14.3.1 at the time of this writing.
3. Clang C++ (clang++) 16 at the time of this writing.
Installing Xcode on macOS lv

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 Xcode on macOS


On macOS, perform the following steps to install Xcode:
1. Click the Apple menu and select App Store…, or click the App Store icon in the
dock at the bottom of your Mac screen.
2. In the App Store’s Search field, type Xcode.
3. Click the Get button to install Xcode.

Installing GNU C++ (g++) 13 on macOS


On macOS, perform the following steps to install GNU C++:
1. In the Finder’s Go menu, select Utilities, then double-click Terminal to open a Ter-
minal (command line) window.
2. Check if the brew command is installed by typing brew and pressing Enter (or re-
turn). If macOS does not recognize the command, go to https://brew.sh and
copy the installation command below Install Homebrew. Paste this command into
the Terminal window, then press Enter (or return).
3. Type the following command, then press Enter (or return) to install the GNU
Compiler Collection (GCC), which includes g++:
brew install gcc@13

Installing the GNU C++ (g++) 13 on Linux


There are many Linux distributions, and they often use different software upgrade tech-
niques. Check your distribution’s online documentation for instructions on how to upgrade
GNU C++ to the latest version. You also can download GNU C++ for various platforms at
https://gcc.gnu.org/install/binaries.html

Docker and Docker Containers


Docker is a tool for packaging software into containers (also called images) that bundle
everything required to execute that software across platforms, which is particularly useful
for software packages with complicated setups and configurations. For many such pack-
ages, there are free preexisting Docker containers (often at https://hub.docker.com) that
you can download and execute locally on your system. Docker is a great way to get started
with new technologies quickly and to experiment with new compiler versions.

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/

Getting the GNU Compiler Collection Docker Container


The GNU team maintains official Docker containers at
https://hub.docker.com/_/gcc

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.

Getting an LLVM Clang C++ Docker Container


Currently, the LLVM Clang team does not provide an official Docker container, but
many working containers are available on https://hub.docker.com. For this book, we
used a popular one from
https://hub.docker.com/r/teeks99/clang-ubuntu

Open a Command Prompt (Windows), Terminal (macOS/Linux) or shell (Linux), then


execute the command
docker pull teeks99/clang-ubuntu:16

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.

Getting Your C++ Questions Answered


As you read the book, if you have questions, we’re easy to reach at
[email protected]
and
https://deitel.com/contact-us
We’ll respond promptly.
The web is loaded with programming information. An invaluable resource for nonpro-
grammers and programmers alike is the website
https://stackoverflow.com

on which you can


• search for answers to common programming questions,
• search for error messages to see what causes them,

4. Windows users should choose Run as administrator when opening the Command Prompt.
Online C++ Documentation lvii

• ask programming questions to get answers from programmers worldwide and


• gain valuable insights about programming in general.
For live C++ discussions, check out the Slack channel cpplang:
https://cpplang-inviter.cppalliance.org

and the Discord server #include<C++>:


https://www.includecpp.org/discord/

Online C++ Documentation


For C++ standard library documentation, visit
https://cppreference.com

Also, be sure to check out the C++ FAQ at


https://isocpp.org/faq

Static Code Analysis Tools


We used the following static code analyzers to check our code examples for adherence to
the C++ Core Guidelines, adherence to coding standards, adherence to Modern C++ idi-
oms, possible security problems, common bugs, possible performance issues, code read-
ability and more:
• clang-tidy—https://clang.llvm.org/extra/clang-tidy/

• 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).

1. “TIOBE Index.” Accessed March 18, 2023. https://www.tiobe.com/tiobe-index/.


2. “Top Programming Languages 2022.” Accessed March 18, 2023. https://spectrum.ieee.org/
top-programming-languages-2022.
3. “PYPL PopularitY of Programming Language.” Accessed March 18, 2023. https://
pypl.github.io/PYPL.html.
1.1 Introduction 3

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.

This Book’s Architecture


Before you “dig in,” we recommend getting a “40,000-foot” view of the book’s architec-
ture to understand where you’re headed as you prepare to learn the powerful language that
is C++20. To do so, we recommend reviewing the following items:
• In the Preface, the one-page, full-color Table of Contents diagram presents a
high-level overview of the book’s architecture. You can view a scalable PDF ver-
sion of this diagram at
https://deitel.com/cpphtp11

• 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.

1.2.1 Computer Organization


Regardless of physical differences, computers have various logical units or sections.
1.2 Hardware 5

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.

Arithmetic and Logic Unit (ALU)


This “manufacturing” section performs calculations (e.g., addition, subtraction, multipli-
cation and division) and makes decisions (e.g., comparing two items from the memory
unit to determine whether they’re equal). In today’s systems, the ALU is part of the next
logical unit, the CPU.

Central Processing Unit (CPU)


This “administrative” section coordinates and supervises the operation of the other sec-
tions. The CPU tells
• the input unit when to read information into the memory unit,
• the ALU when to use information from the memory unit in calculations, and
• the output unit when to send information from the memory unit to specific out-
put devices.
Most computers today have multi-core processors that economically implement multiple
processors on a single integrated circuit chip. Such processors can perform many opera-
tions simultaneously. We say more about these in Section 1.2.2.

Secondary Storage Unit


This is the long-term, high-capacity “warehousing” section. Programs and data not actively
being used by the other units are placed on secondary storage devices until they’re again
needed, possibly hours, days, months or even years later. Information on secondary storage
devices is persistent—it’s preserved even when the computer’s power is turned off. Second-
ary storage information takes much longer to access than information in primary memory,
but its cost is much less than RAM. Examples of secondary storage devices include solid-
state drives (SSDs), USB flash drives and read/write Blu-ray drives. Many current drives
hold terabytes (TB) of data—each terabyte is approximately one trillion bytes. Typical
desktop and notebook-computer secondary storage devices hold up to 8 TB, and some
recent desktop-computer hard drives hold up to 26 TB.13 The largest commercial SSD
holds up to 100 TB (and costs about $40,000).14

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.

1.2.2 Moore’s Law, Multi-Core Processors and Concurrent Programming


Many of today’s personal computers can perform billions of calculations in one second—
more than a human can perform in a lifetime. Supercomputers already perform over one
million trillion (a quintillion) instructions per second! As of November 2022, the USA’s
Frontier (from Hewlett Packard Enterprise) is the world’s fastest supercomputer15—it can
perform 1.102 quintillion calculations per second (1.102 exaflops)!16 For perspective, this
supercomputer can perform in one second almost 140 million calculations for every per-
son on the planet!17 And supercomputing “upper limits” are growing quickly.

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).

Multi-Core Processors and Performance


Most computers today have multi-core processors that economically implement multiple
processors on a single integrated circuit chip. A dual-core processor has two CPUs, a
quad-core processor has four, and an octa-core processor has eight. Intel has some pro-
cessors with up to 72 cores. Our primary testing computer uses an eight-core Intel proces-
sor. Apple’s recent M2 Pro and M2 Max processors have 12-core CPUs. In addition, the
top-of-the-line M2 Pro has a 19-core graphics processing unit (GPU), while the top-of-
the-line M2 Max processor has a 28-core GPU. Both have a 16-core “neural engine” for
machine learning.20 Intel is working on processors with up to 80.21 AMD is working on
processors with 192 and 256 cores.22 The number of cores will continue to grow. Today’s
most powerful GPUs used in high-end gaming computers and artificial-intelligence appli-
cations often have thousands of cores in their GPUs. For example, at the time of this writ-
ing, the forthcoming NVIDIA RTX 4090 Ti is expected to have 18,176 cores!23
Perf In multi-core systems, the hardware can put multiple processors to work truly simul-
taneously on different parts of your task, enabling your program to complete faster. Tak-
ing full advantage of multi-core architecture requires writing multithreaded
applications (Chapter 17). When a program splits tasks into separate threads, a multi-core
system can run those threads in parallel when a sufficient number of cores is available.
Interest in multithreading is rising quickly because of the proliferation of multi-core
systems. Standard C++ multithreading was one of the most significant updates introduced
in C++11. Each subsequent C++ standard has added higher-level capabilities to simplify
multithreaded application development. Chapter 17, Parallel Algorithms and Concur-
rency: A High-Level View, discusses creating and managing multithreaded C++ applica-
tions. Chapter 18 introduces C++20 coroutines, which enable concurrent programming
SE with a simple sequential-like coding style.

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

Computing Power Over the Years


Data is getting more massive, and so is the computing power needed for processing it.
Today’s processor performance is often measured in terms of FLOPS (floating-point oper-
ations per second). In the early to mid-1990s, the fastest supercomputer speeds were mea-
sured in gigaflops (109 FLOPS). By the late 1990s, Intel produced the first teraflop (1012
FLOPS) supercomputers. In the early-to-mid 2000s, speeds reached hundreds of teraflops,
then in 2008, IBM released the first petaflop (1015 FLOPS) supercomputer. As of Novem-
ber 2022, Hewlett Packard Enterprise’s Frontier is the world’s fastest supercomputer24,25—
it can perform 1.102 quintillion calculations per second (1.102 exaflops—1018 FLOPS)!26
Companies like IBM also are working toward exaflop supercomputers.27
The quantum computers now under development theoretically could operate at
18,000,000,000,000,000,000 times the speed of today’s “conventional computers”!28
This number is so extraordinary that in one second, theoretically, a quantum computer
could do staggeringly more calculations than the total that have been done by all comput-
ing devices since the beginning of time. This almost unimaginable computing power could
wreak havoc with blockchain-based cryptocurrencies like Bitcoin. Engineers are already
rethinking blockchain29 to prepare for such massive increases in computing power.30
Computing power costs continue to decline, especially with advancements in proces-
sor architecture and cloud computing. People used to ask the question, “How much com-
puting power do I need on my local system to deal with my peak processing needs?”
Today, that thinking has shifted to “Can I quickly carve out in the cloud what I need tem-
porarily for my most demanding computing workloads?” You pay for only what you use
to accomplish a given task.

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++

1.3 Data Hierarchies


Data items processed by computers can form data hierarchies that become larger and more
complex in structure as we progress from the simplest items (called “bits”) to richer ones, such
as characters and fields. The following diagram illustrates a portion of a data hierarchy:

Matis Laurent

Edward Uwimana

Jazmin Ivanov File

Adriana Santos

Jacob Brown

Jazmin Ivanov Record

J a z m i n Field

01001010 Byte (ASCII character J)

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:

Unit Bytes Which is approximately

1 kilobyte (KB) 1024 bytes 103 bytes (1024 bytes exactly)


1 megabyte (MB) 1024 kilobytes 106 (1,000,000) bytes
1 gigabyte (GB) 1024 megabytes 109 (1,000,000,000) bytes
1 terabyte (TB) 1024 gigabytes 1012 (1,000,000,000,000) bytes
1 petabyte (PB) 1024 terabytes 1015 (1,000,000,000,000,000) bytes
1 exabyte (EB) 1024 petabytes 1018 (1,000,000,000,000,000,000) bytes
1 zettabyte (ZB) 1024 exabytes 1021 (1,000,000,000,000,000,000,000) bytes

The amount of data produced worldwide is enormous, and its growth is accelerating. Big
data applications deal with massive amounts of data.

Twitter®—A Favorite Big-Data Source


One big-data source favored by developers is Twitter. As of March 2023, there are approx-
imately 900,000,000 tweets per day.32 Though tweets are limited to 280 characters, pro-
grammers analyzing tweets can request additional metadata—such as who sent the tweet,
images, videos, links, mentions of other users and more—that can total approximately
10,000 bytes per tweet. So 900,000,000 times 10,000 is about 9,000,000,000,000 bytes
or 9 terabytes (TB) of data per day. That’s a nice example of big data.33
Prediction is a challenging and often costly process, but the potential rewards for
accurate predictions are remarkable. Data mining is the process of searching through
extensive collections of data, often big data, to find insights that can be valuable to indi-
viduals and organizations. The sentiment you data-mine from tweets could help predict
election results, the revenues a new movie will likely generate and the success of a com-
pany’s marketing campaign. It could also help companies spot weaknesses in competitors’
product offerings.

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.

32. “Worldometer.” Accessed March 18, 2023. https://www.worldometers.info/.


33. At the time of this writing, Twitter has announced changes to their APIs and limits, so the amount
of data you can access through their APIs may change.
1.4 Machine Languages, Assembly Languages and High-Level Languages 13

1.4 Machine Languages, Assembly Languages and High-


Level Languages
Programmers write instructions in various programming languages, some directly under-
standable by computers and others requiring intermediate translation steps. Hundreds of
such languages are in use today. These may be divided into three general types:
• Machine languages.
• Assembly languages.
• High-level languages.
Machine Languages
Any computer can directly understand only its own machine language, defined by its
hardware design. Machine languages generally consist of strings of numbers (ultimately
reduced to 1s and 0s) that instruct computers to perform their most elementary operations
one at a time. Machine languages are machine-dependent—a particular machine language
can be used on only one type of computer. Such languages are cumbersome for humans.
For example, here’s a section of an early machine-language payroll program that adds over-
time pay to base pay and stores the result in gross pay:
+1300042774
+1400593419
+1200274027

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.”

Assembly Languages and Assemblers


Programming in machine language was too slow and tedious for most programmers.
Instead of using the strings of numbers that computers could directly understand, pro-
grammers began using English-like abbreviations to represent elementary operations.
These abbreviations formed the basis of assembly languages. Translator programs called
assemblers were developed to convert assembly-language programs to machine language
at computer speeds. The following section of an assembly-language payroll program also
adds overtime pay to base pay and stores the result in gross pay:
load basepay
add overpay
store grosspay

Although such code is clearer to humans, it’s incomprehensible to computers until it’s
translated into machine language.

High-Level Languages and Compilers


With the advent of assembly languages, computer usage increased rapidly. However, pro-
grammers still had to use numerous instructions to accomplish even simple tasks. To speed
the programming process, high-level languages were developed in which single statements
14 Chapter 1 Intro to Computers and C++

could accomplish substantial tasks. A typical high-level-language program contains many


statements, known as the program’s source code.
Translator programs called compilers convert high-level-language source code into
machine language. High-level languages allow you to write instructions that look almost
like everyday English and contain common mathematical notations. A payroll program
written in a high-level language might contain a statement such as
grossPay = basePay + overTimePay

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.

1.5 Operating Systems


Operating systems are software that make using computers more convenient for users, soft-
ware developers and system administrators. They provide services that allow applications to
execute safely, efficiently and concurrently with one another. The software that contains the
core operating-system components is called the kernel. Linux, Windows and macOS are

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.

Windows—A Proprietary Operating System


In the mid-1980s, Microsoft developed the Windows operating system, consisting of a
graphical user interface built on top of DOS (Disk Operating System)—an enormously
popular desktop/laptop operating system that users interacted with by typing commands.
Windows 11 is Microsoft’s latest operating system.37 Windows is a proprietary operating
system controlled exclusively by Microsoft. It is the world’s most widely used desktop and
notebook operating system, with almost 72% market share (February 2023).38

Linux—An Open-Source Operating System


The Linux operating system is among the greatest successes of the open-source move-
ment. Proprietary software for sale or lease dominated software’s early years. With open
source, individuals and companies contribute to developing, maintaining and evolving the
software. Anyone can then use that software for their own purposes—normally at no
charge, but subject to various (typically generous) licensing requirements. Open-source
code is often scrutinized by a much larger audience than proprietary software, so errors can
get removed faster, making the software more robust. Open-source increases productivity
and has contributed to an explosion of innovation. You’ll use various popular open-source
libraries and tools throughout this book.
Some key organizations in the open-source community are:
• GitHub provides tools for managing open-source software-development proj-
ects. It has millions of them underway.
• The Apache Software Foundation created the Apache web server and now oversees
350+ open-source projects,39 including many big-data infrastructure technologies.
• The Eclipse Foundation oversees over 400 open-source projects, including the
Eclipse Integrated Development Environment.40
• The Mozilla Foundation is the creator of the Firefox web browser and several
other projects, including Firefox Reality (a virtual reality web browser), Hubs (a
virtual reality meeting space), Project Things (for building Internet of Things
apps), WebXR Viewer (an augmented reality viewer) and Spoke (for building 3D
social environments that can be visited using virtual reality devices).41

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++

• OpenML focuses on open-source tools and data for machine learning.


• OpenAI researches artificial intelligence and publishes open-source tools used in
AI research. They’re also the creators of ChatGPT and Dall-E 2, which have each
generated enormous interest in artificial intelligence. See Section 1.16 for more
about these technologies.
• OpenCV focuses on open-source computer-vision tools that can be used across
various operating systems and programming languages.
• The Python Software Foundation is responsible for the Python programming
language.
• The Boost organization manages the development of the open-source Boost C++
libraries (see Section 1.7).
Rapid improvements to computing and communications, decreasing costs and open-
source software have made it much easier and more economical to create software-based
businesses now than just a decade ago. A great example is Facebook, which was launched
from a college dorm room and built with open-source software.
The Linux kernel is the core of the most popular open-source, freely distributed, full-
featured operating system. It’s developed by a loosely organized team of volunteers and is
popular in servers, personal computers and embedded systems (such as the computer sys-
tems at the heart of smartphones, smart TVs and automobile systems). Unlike Microsoft’s
Windows and Apple’s macOS source code, the Linux source code is available to the public
for examination and modification, and is free to download and install. As a result, Linux
users benefit from a massive community of developers actively debugging and improving
the kernel, and the ability to customize the operating system to meet specific needs.

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.

Billions of Computerized Devices


Billions of personal computers and an even larger number of mobile devices are now in use.
The explosive growth of smartphones, tablets and other devices has created significant
opportunities for mobile app developers. The following table lists many computerized
devices, each of which can be part of the Internet of Things (see Section 1.12).

Some computerized devices

Activity trackers— Personal assistants— Smart home and building


Apple Watch®, FitBit®, … Amazon Echo® (Alexa®), controls—lights, video
ATMs Apple HomePod® (Siri®), cameras, doorbells, irriga-
e-Readers Google Home™ (Google tion controllers, security
Gaming consoles Assistant™) devices, smart locks, smart
GPS navigation systems Personal computers plugs, smoke detectors,
Home appliances Point-of-sale terminals thermostats, air vents
Medical devices— Printers Smart meters
blood glucose monitors, Robots Smartcards (credit cards)
blood pressure monitors, Self-driving cars Smartphones
CT scanners, electrocardio- Sensors— Thermostats
grams (EKG/ECG), electro- chemical, earthquake, gas, Tracking devices
encephalograms (EEG), GPS, humidity, light, opti- Transportation passes
heart monitors, MRIs, pace- cal, motion, pressure, tem- TVs and TV set-top boxes
makers, … perature, tsunami, … Vehicles
Parking meters Server computers Wireless network devices

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++

2 (True/False) Proprietary code is often scrutinized by a much larger audience than


open-source software, so errors often get removed faster.
Answer: False. Open-source code is often scrutinized by a much larger audience than pro-
prietary software, so errors often get removed faster.

1.6 C and C++


C Programming Language
C was implemented in 1972 by Dennis Ritchie at Bell Laboratories. It initially became
widely known as the UNIX operating system’s development language. Today, most of the
code for general-purpose operating systems is written in C or C++. C is available for most
computers and is hardware independent. With careful design, it’s possible to write C pro-
grams that are portable to most computers.
The widespread use of C with various kinds of computers (sometimes called hardware
platforms) led to many variations. The American National Standards Institute (ANSI)
cooperated with the International Organization for Standardization (ISO) to standardize
C worldwide—the joint standard document was published in 1990. An updated standard
is currently under development.

C++ Programming Language


C++44 was developed by Bjarne Stroustrup in 1979 at Bell Laboratories as an extension of
C. Originally called “C with Classes,” it was renamed C++ in the early 1980s—the name
derives from C’s increment operator, ++, which adds 1 to a number. It provides many fea-
tures that “spruce up” C, but more importantly, it includes capabilities for object-oriented
programming inspired by the Simula simulation programming language. As you’ll see,
C++ has evolved over the last 40 years to enable programmers to use five different pro-
gramming models, each of which you’ll learn in this book:
• procedural programming,
• object-oriented programming,
• functional-style programming,
• generic programming and
• template metaprogramming.
C++ is the premiere language for building high-performance, business-critical and
mission-critical computing systems, including operating systems, real-time systems,
embedded systems, game systems, banking systems, air-traffic-control systems, communi-
cations systems and more. Even for systems programmed primarily in other languages,
C++ is often used to build the performance-intensive portions of those systems. Stroustrup
maintains a lengthy list of C++ applications on his website at
https://www.stroustrup.com/applications.html

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.

C++ Core Guidelines


Bjarne Stroustrup, Herb Sutter (the ISO C++ committee chair) and several other contrib-
utors45 have created the evolving C++ Core Guidelines,46 containing extensive recom-
mendations and sample code to help you use Modern C++ correctly and effectively.
Various code-analysis tools (discussed in Preface Section 7) enable you to check your code
to ensure it follows these recommendations. We cite the C++ Core Guidelines frequently
throughout 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.

1.7 C++ Standard Library and Open-Source Libraries


C++ programs consist of pieces called functions and classes. You can program all the pieces
you’ll need yourself. Instead, most C++ programmers reuse the rich collections of classes
and functions in the C++ standard library. Thus, there are really two parts to learning C++
programming:
• learning the C++ language itself (often referred to as the “core language”), and
• learning how to use the C++ standard library’s classes and functions.

The Boost Project and Other Open Source Libraries


There are enormous numbers of open-source C++ libraries that can help you perform sig-
nificant tasks by writing only modest amounts of code. The Boost C++ libraries provide
168 powerful open-source libraries.47 Boost serves as a “breeding ground” for new capa-

45. “C++ Core Guidelines—Acknowledgments.” Accessed March 18, 2023. https://iso-


cpp.github.io/CppCoreGuidelines/CppCoreGuidelines#SS-ack.
46. “C++ Core Guidelines.” Accessed March 18, 2023. https://isocpp.github.io/CppCoreGuide-
lines/CppCoreGuidelines.
47. “Boost 1.81.0 Library Documentation.” Accessed March 18, 2023. https://www.boost.org/doc/
libs/1_81_0/.
20 Chapter 1 Intro to Computers and C++

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

In addition, pages such as


https://github.com/fffaraz/awesome-cpp
https://github.com/rigtorp/awesome-modern-cpp

provide curated lists of popular C++ libraries for many application areas—you’ll enjoy
exploring these sites.

Building-Block Approach to C++ Development


Throughout this book, we encourage a building-block approach to creating programs.
When programming in C++, you’ll typically use the following building blocks:
• C++ standard library classes and functions,
• open-source C++ library classes and functions,
• functions and classes you create (after studying Chapters 5 and 9, respectively), and
• classes and functions other people have created and made available to you.
The advantage of creating your own classes and functions is knowing exactly how they
work. The disadvantage is the time-consuming effort that goes into designing, developing,
SE debugging and performance-tuning them. Throughout the book, we focus on using the
existing C++ standard library and various open-source libraries to leverage your program-
development efforts and avoid “reinventing the wheel.” This is called software reuse and
is a key part of our objects-natural teaching methodology.
Perf Using C++ Standard Library classes and functions instead of writing your own ver-
sions can improve program performance because they’re written carefully to perform effi-
SE ciently. This technique also shortens program development time. Using C++ Standard
Library classes and functions instead of writing your own also improves program portabil-
ity because they’re included in every C++ implementation.

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

1.8 Other Popular Programming Languages


The following is a brief intro to several other popular programming languages:
• Python is an open-source, object-oriented language that was released publicly in
1991. It was developed by Guido van Rossum of the National Research Institute
for Mathematics and Computer Science in Amsterdam. Python has rapidly
become one of the world’s most popular programming languages, especially for
scientific computing, data science and artificial intelligence. It has extensive stan-
dard libraries and thousands of third-party open-source libraries.49
• Java50—a C++-based object-oriented programming language—was created in
1991 when Sun Microsystems funded an internal corporate research project led
by James Gosling. A key Java goal is “write once, run anywhere,” enabling devel-
opers to write programs that run on a wide variety of computer systems. Java is
used in many kinds of applications, including big data (Section 1.15), the Inter-
net of Things (Section 1.12; devices connected to the Internet, such as sensors,
smartphones, tablets, television set-top boxes, appliances and automobiles),
enterprise applications, web servers (the computers that provide the content to
our web browsers), video games and more.51 Originally, Java was the official
Android app-development language, though over 60% of Android app develop-
ers now use Kotlin.52
• C# 53 (based on C++ and Java) is one of Microsoft’s three primary object-oriented
programming languages—the other two are Visual C++ and Visual Basic. C# was
developed to integrate the web into computer applications and is now widely
used to develop many kinds of applications. It is Microsoft’s primary language for
Metaverse (Section 1.13) development.54 Microsoft now offers open-source ver-
sions of C# and Visual Basic.
• Visual Basic55 was originally based on the BASIC programming language, devel-
oped in the 1960s at Dartmouth College to familiarize novices with program-
ming. Both C# and Visual Basic use the vast code libraries of Microsoft’s .NET
platform. Components written in both languages typically can be used inter-
changeably, enabling developers to work with their preferred programming lan-
guage to build powerful .NET-based applications.

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++

• JavaScript56 is widely used to add programmability to web pages (e.g., anima-


tions, user interactivity and more). All major web browsers support it. Many visu-
alization libraries in other programming languages output JavaScript to create
interactive visualizations you can view in your web browser. Tools such as
NodeJS also enable JavaScript to run outside of web browsers. A key aspect of
Modern JavaScript development is creating powerful web applications using
JavaScript frameworks such as React, Angular, Vue and others.57,58
• Swift59 was introduced by Apple in 2014 and is their programming language for
developing iOS and macOS apps. Swift is a contemporary language with popular
features from Objective-C, Java, C#, Ruby, Python and other languages. Swift is
open-source, so it also can be used on non-Apple platforms.
• Go60 is a high-performance, open-source systems programming language intro-
duced by Google in 2009. It was designed specifically for developing systems to
take advantage of today’s multi-core, networked systems. The language is used
widely at Google and in many popular open-source applications.
• Rust61 is a high-performance, open-source, general-purpose programming lan-
guage that began as a personal project of Mozilla research developer Graydon
Hoare in 2006, then became an official Mozilla project released in 2015. A key
language feature is its support for concurrency. Some companies using Rust
include Amazon, Google, Microsoft, Facebook and Dropbox.

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

1.9 Introduction to Object Orientation


Building software quickly, correctly and economically remains an elusive goal at a time
when demands for new and more powerful software are soaring. Objects, or more pre-
cisely—as we’ll see in Chapter 9—the classes objects come from, are essentially reusable
software components. There are date objects, time objects, audio objects, video objects,
automobile objects, people objects, etc. Almost any noun can be reasonably represented as
a software object in terms of attributes (e.g., name, color and size) and behaviors (e.g., cal-
culating, moving and communicating). Software developers have discovered that using a
modular, object-oriented design-and-implementation approach can make software devel-
opment groups much more productive than was possible with earlier techniques—object-
oriented programs are often easier to understand, correct and modify.

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.

Functions, Member Functions and Classes


Let’s use our car example to introduce some key object-oriented programming concepts.
Performing a task in a program requires a function. The function houses the program
statements that perform its task. It hides these statements from its user, just as the accel-
erator pedal of a car hides from the driver the mechanisms of making the car go faster. In
C++, we often create a program unit called a class to house the set of functions that per-
form the class’s tasks—these are known as the class’s member functions. For example, a
class representing a bank account might contain a member function to deposit money to
an account, another to withdraw money from an account and a third to query the
account’s current balance. A class is similar to a car’s engineering drawings, which house
the design of an accelerator pedal, brake pedal, steering wheel, and so on.

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.

Messages and Member-Function Calls


When you drive a car, pressing its gas pedal sends a message to the car to perform a task—
that is, to “go faster.” Similarly, you send messages to an object. Each message is imple-
mented as a member-function call that tells a member function of the object to perform
its task. For example, a program might call a particular bank account object’s deposit
member function to increase the account’s balance by the deposit amount.

Attributes and Data Members


Besides having capabilities to accomplish tasks, a car also has attributes, such as its color,
number of doors, amount of gas in its tank, current speed and record of total miles driven
(i.e., its odometer reading). Like its capabilities, the car’s attributes are represented as part
of its design in its engineering diagrams (which, for example, include an odometer and a
fuel gauge). As you drive a car, these attributes are “carried along” with the car. Every car
maintains its own attributes. For example, each car knows how much gas is in its own gas
tank but not how much is in the tanks of other cars.
An object, similarly, has attributes that it carries along as it’s used in a program. These
attributes are specified as part of the object’s class. For example, a bank-account object has
a balance attribute representing the amount of money in the account. Each bank-account
object knows the balance in the account it represents but not the balances of the other
accounts in the bank. Attributes are specified by the class’s data members.

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.

Object-Oriented Analysis and Design


Soon you’ll be writing programs in C++. How will you create the code for your programs?
Perhaps, like many programmers, you’ll turn on your computer and start typing. This
1.10 Simplified View of a C++ Development Environment 25

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.

1.10 Simplified View of a C++ Development Environment


C++ systems generally consist of three parts: a program development environment, the
language and the C++ Standard Library. C++ programs typically go through six phases:
edit, preprocess, compile, link, load and execute. The following discussion explains a typ-
ical C++ program development environment.

Phase 1: Editing a C++ Program


Phase 1 consists of editing a file with an editor program, normally known simply as an editor:
Phase 1:
Editor Programmer creates program
Disk in the editor and stores it on
disk

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

In a C++ system, a preprocessor program executes automatically before the compiler’s


translation phase begins (so we call preprocessing Phase 2 and compiling Phase 3). The
C++ preprocessor obeys commands called preprocessing directives, which indicate that
certain manipulations are to be performed on the program before compilation. These
manipulations usually include (i.e., copy into the program file) other text files to be com-
piled and perform various text replacements. The most common preprocessing directives
are discussed in the early chapters; a detailed discussion of preprocessor features appears in
the “Preprocessor” appendix at https://deitel.com/cpphtp11.
Phase 3: Compiling a C++ Program
In Phase 3, the compiler translates the C++ program into machine-language code—also
referred to as object code:

Phase 3:
Compiler Compiler creates
Disk object code and stores
it on disk

Phase 4: Linking to Create an Executable Program


Phase 4 is called linking. C++ programs typically contain references to functions and data
defined elsewhere, such as in the standard libraries or in the private libraries of groups of
programmers working on a particular project:
Phase 4:
Linker links the object
Linker code with the libraries,
Disk
creates an executable file 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.

Phase 6: Executing the Program


Finally, the computer, under the control of its CPU, executes the program one instruction
at a time:
Primary
Memory
CPU
Phase 6:
CPU takes each
instruction and
executes it, possibly
storing new data
values as the program
executes
...

Modern multi-core computer architectures can execute several instructions in parallel.

Problems That May Occur at Execution Time


Programs might not work on the first try. Each of the preceding phases can fail because of
various errors that we’ll discuss throughout this book. For example, an executing program
might try to divide by zero (an illegal operation for integer arithmetic in C++). This would
cause the C++ program to display an error message. If this occurred, you’d have to return
to the editing phase, make the necessary corrections and proceed through the remaining
phases again to determine that the corrections fixed the problem(s). Certain C++ functions
take their input from cin (the standard input stream; pronounced “see-in”), which is nor-
mally the keyboard, but cin can be redirected to another device. Data is often output to
cout (the standard output stream; pronounced “see-out”), which is normally the com-
puter screen, but cout can be redirected to another device. When we say that a program
prints a result, we normally mean that the result is displayed on a screen. Data may be out-
put to other devices, such as disks, hardcopy printers, or even transmitted over the Inter-
28 Chapter 1 Intro to Computers and C++

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.

1.11 Test-Driving a C++20 Application Various Ways


Please read the Before You Begin section before reading this section and attempting any
of the test-drives. In this section, you’ll compile, run and interact with your first C++
application62—a guess-the-number game, which picks a random number from 1 to 1,000
and prompts you to guess it. If you guess the randomly selected number, the game ends.
If you guess incorrectly, the application indicates whether your guess is higher or lower
than the correct number. There’s no limit on the number of guesses you can make. There’s
some nice computer science behind this game—in a later chapter, you’ll explore the binary
search technique. You’ll program the guess-the-number game in Exercise 5.22.

Summary of the Compiler and IDE Test-Drives


We’ll show how to compile and execute C++ code using:
• Microsoft Visual Studio Community edition for Windows (Section 1.11.1),63
• GNU g++ in a shell on Linux (Section 1.11.2),
• g++ in a shell running inside the GNU Compiler Collection (GCC) Docker con-
tainer (Section 1.11.3), and
• LLVM clang++ (the command-line version of the Clang C++ compiler) in a shell
running inside a Docker container (Section 1.11.4).
• Apple Xcode on macOS (Section 1.11.5),
You can read only the section that corresponds to your platform. To use the Docker con-
tainers for g++ and clang++, you must have Docker installed and running, as discussed in
the Before You Begin section that follows the Preface.

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

1.11.1 Compiling and Running on Windows with Visual Studio


Community Edition
In this section, you’ll run a C++ program on Windows using Microsoft Visual Studio
Community edition. There are several versions of Visual Studio available—on some ver-
sions, the options, menus and instructions we present might differ slightly.

Step 1: Checking Your Setup


If you have not already done so, read the Before You Begin section to install the IDE and
download the book’s code examples.

Step 2: Launching Visual Studio


Open Visual Studio from the Start menu. Dismiss this initial Visual Studio window by
pressing the Esc key. Do not click the X in the upper-right corner—that will terminate
Visual Studio. You can access this window at any time by selecting File > Start Window.
We use > to indicate selecting a menu item from a menu, so File > Open means “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. Visual Studio organizes applications into projects and solutions. A solution
contains one or more projects. Each application in this book requires only a single-project SE
solution. Multi-project solutions are used to create large-scale applications. For our code
examples, you’ll begin with an Empty Project and add files to it.
When you first open Visual Studio, a dialog will appear containing links to your
recently opened solutions in the Open Recent column and several shortcuts in the Get
Started column. For this test drive, we’ll create a new project directly in Visual Studio, so
press the Esc key to dismiss this initial dialog. To create a project:
1. Select File > New > Project… to display the Create a New Project dialog.
2. Depending on your Visual Studio version and its installed features, many project
types may be displayed. You can filter your choices using the Search for templates
textbox and the drop-down lists below it. In the drop-down list that initially says
All languages, select C++.
3. Select the Empty Project template with the tags C++, Windows and Console. This
project template is for programs that execute in a Command Prompt window—
this is a text-based window in which programs can display text and receive text
typed by the user at the keyboard. Click Next to display the Configure your new
project dialog.
4. Provide a Project name and Location. For the Project name, we specified
cpp20_test. For the Location, we selected this book’s examples folder. Click
Create to place your project into the following folder (or the folder you specified)
and open your new project in Visual Studio:
C:\Users\YourUserAccount\Documents\examples

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.

Step 4: Adding the GuessNumber.cpp File to the Project


Next, you’ll add to the project you created in Step 3 the file GuessNumber.cpp, containing
the C++ code that implements the guess-the-number game. In the Solution Explorer:
1. Right-click the Source Files folder and select Add > Existing Item….
2. In the dialog that appears, navigate to the ch01 subfolder of the book’s examples
folder, select GuessNumber.cpp and click Add.64

Step 5: Configuring Your Project to Use C++20


The Visual C++ compiler in Visual Studio supports several C++ versions. For this book,
we use C++20, which you must configure in your project’s settings:
1. Right-click the project’s node— —in the Solution Explorer and select
Properties to display the project’s cpp20_test Property Pages dialog.
2. In the Configuration drop-down list, select All Configurations. In the Platform
drop-down list, select All Platforms.
3. In the left column below Configuration Properties, expand the C/C++ node, then
select Language.
4. In the right column, click in the field to the right of C++ Language Standard, click
the down arrow, then select ISO C++20 Standard (/std:c++20)65 and click OK.

Step 6: Compiling and Running the Project


To compile and run the project so you can test-drive the guess-the-number game, select
Debug > Start without debugging or type Ctrl + F5. If the program compiles correctly,
Visual Studio opens a Command Prompt window and executes the program. We changed
the Command Prompt’s color scheme and font size for readability:
The title bar shows the
location and name of the
currently executing project

Step 7: Entering Your First Guess


At the ? prompt, type 500, and press Enter—the program selects a number randomly each
time you run it, so your interactions with the program will vary during each execution. In
our case, the application displayed "Too low. Try again." to indicate the value was less
than the number the application chose as the correct guess:

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

Step 8: Entering Another Guess


At the next prompt, if your system said the first guess was too low, type 750 and press
Enter; otherwise, type 250 and press Enter. In our case, we entered 750, and the application
displayed "Too high. Try again." because the value was greater than the correct guess:

Step 9: Entering Additional Guesses


Continue to play the game by entering values until you guess the correct number. When
you guess correctly, the application displays "Excellent! You guessed the number!":
32 Chapter 1 Intro to Computers and C++

Step 10: Playing the Game Again or Exiting the Application


After guessing the correct number (which you should always be able to do in 10 or fewer
guesses), the application asks if you’d like to play another game. At the "Would you like
to play again (y or n)?" prompt, entering y causes the application to choose a new num-
ber and start a new game. Entering n terminates the application.

Reusing This Project for Subsequent Examples


You can follow the steps in this section to create a separate project for every application in
the book. However, for our examples, you may find it more convenient to remove the cur-
rent program from the project, then add a new program. To remove a file from your proj-
ect (but not your system), select it in the Solution Explorer, then press Del (or Delete). You
can then repeat Step 4 to add a different program to the project. When you begin creating
programs yourself, you can right-click the Source Files folder and select Add > New Item…
to display a dialog for adding a new file.

Using Ubuntu Linux in the Windows Subsystem for Linux


Some Windows users may want to use the GNU g++ compiler on Windows. You can do
this using the GNU Compiler Collection Docker container (Section 1.11.3), or you can
use g++ in Ubuntu Linux running in the Windows Subsystem for Linux. To install the
Windows Subsystem for Linux, follow the instructions at
https://docs.microsoft.com/en-us/windows/wsl/install

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

Then you can continue with Step 2 in Section 1.11.2.

1.11.2 Compiling and Running with GNU C++ on Linux


In this section, you’ll run a C++ program in a Linux shell using the GNU C++ compiler
(g++).66 For this test-drive, we assume that you’ve read the Before You Begin section and
that you’ve placed the book’s examples in your user account’s Documents/examples folder.

Step 1: Changing to the ch01 Folder


From a Linux shell or Terminal window, use the cd command to change to the ch01 sub-
folder of the book’s examples folder:

~$ 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.

Step 2: Compiling the Application


Before running the application, you must first compile it with the g++ command:67
• 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, g++ automatically names the execut-
able a.out.

~/Documents/examples/ch01$ g++ -std=c++20 GuessNumber.cpp -o GuessNumber


~/Documents/examples/ch01$

Step 3: Running the Application


Type ./GuessNumber at the prompt and press Enter to run the program:

~/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.

Step 4: Entering Your First Guess


The application displays "Please type your first guess.", then displays a question mark
(?) as a prompt on the next line. At the prompt, enter 500——the program selects a num-
ber randomly each time you run it, so your interactions with the program will vary during
each execution:

~/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++

Step 5: Entering Another Guess


At the next prompt, if your system said the first guess was too low, type 750 and press
Enter; otherwise, type 250 and press Enter. In our case, we entered 250, and the application
displayed "Too high. Try again." because the value was greater than the correct guess:

~/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.
?

Step 6: Entering Additional Guesses


Continue to play the game by entering values until you guess the correct number. When
you guess correctly, the application displays "Excellent! You guessed the number.":

? 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

Excellent! You guessed the number!


Would you like to play again (y or n)?

Step 7: Playing the Game Again or Exiting the Application


After guessing the correct number (which you should always be able to do in 10 or fewer
guesses), the application asks if you’d like to play another game. At the "Would you like to
play again (y or n)?" prompt, entering y causes the application to choose a new number
and start a new game. Entering n terminates the application and returns you to the shell.

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

1. Installed either Docker Desktop (Windows or macOS) or Docker Engine (Linux).


2. Installed the GCC Docker container.
3. Placed the book’s examples in your user account’s Documents/examples folder.

Executing the GNU Compiler Collection (GCC) Docker Container


Open a Command Prompt (Windows), Terminal (macOS/Linux) or shell (Linux), then
perform the following steps to launch the GCC Docker container:
1. Use cd to navigate to the examples folder containing this book’s examples.
2. Windows users: Launch the GCC Docker container with the command68
docker run --rm -it -v "%CD%":/usr/src gcc:latest

3. macOS/Linux users: Launch the GCC Docker container with the command
docker run --rm -it -v "$(pwd)":/usr/src gcc:latest

In the preceding commands:


• --rm cleans up the container’s resources when you eventually shut it down.
• -it runs the container in interactive mode, so you can enter commands to change
folders, and compile and run programs using the GNU C++ compiler.
• -v "%CD%":/usr/src (Windows) or -v "$(pwd)":/usr/src (macOS/Linux)
maps the Docker container’s /usr/src folder to the folder from which you exe-
cuted the docker run command on your local computer, enabling the Docker
container to access files in your local folder. You’ll navigate with the cd command
to subfolders of /usr/src to compile and run the book’s examples.
• gcc:latest is the container name. The :latest specifies that you want to use
the most up-to-date version of the gcc container.69
Once the container is running, you’ll see a prompt similar to:
root@67773f59d9ea:/#

The container uses a Linux operating system. Its prompt displays the current folder loca-
tion between the : and #.

Changing to the ch01 Folder in the Docker Container


The docker run command specified above attaches your examples folder to the con-
tainer’s /usr/src folder. In the Docker container, use the cd command to change to the
ch01 subfolder of /usr/src:

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++

Terminating the Docker Container


You can terminate the Docker container by typing Ctrl + d at the container’s prompt.

1.11.4 Compiling and Running with clang++ in a Docker Container


As with g++, you can use the latest LLVM/Clang C++70 (clang++) command-line com-
piler on your system, regardless of your operating system. Currently, the LLVM/Clang
team does not have an official Docker container, but many working containers are avail-
able on https://hub.docker.com. This section assumes that you’ve already performed
the following steps described in the Before You Begin section that follows the Preface:
1. Installed either Docker Desktop (Windows or macOS) or Docker Engine (Linux).
2. Installed the GCC Docker container.
3. Placed the book’s examples in your user account’s Documents/examples folder.

Executing the teeks99/clang-ubuntu Docker Container


Open a Command Prompt (Windows), Terminal (macOS/Linux) or shell (Linux), then
perform the following steps to launch the teeks99/clang-ubuntu Docker container:
1. Use cd to navigate into the examples folder containing this book’s examples.
2. Windows users: Launch the Docker container with the command71
docker run --rm -it -v "%CD%":/usr/src teeks99/clang-ubuntu:16

3. macOS/Linux users: Launch the Docker container with the command


docker run --rm -it -v "$(pwd)":/usr/src teeks99/clang-ubuntu:16

In the preceding commands:


• --rm cleans up the container’s resources when you eventually shut it down.
• -it runs the container in interactive mode, so you can enter commands to change
folders and to compile and run programs using the clang++ compiler.
• -v "%CD%":/usr/src (Windows) or -v "$(pwd)":/usr/src (macOS/Linux)
maps the Docker container’s /usr/src folder to the folder from which you exe-
cuted the docker run command on your local computer, enabling the Docker
container to access files in your local folder. You’ll navigate with the cd command
to subfolders of /usr/src to compile and run the book’s examples.
• teeks99/clang-ubuntu:16 is the container name.
Once the container is running, you’ll see a prompt similar to:
root@9753bace2e87:/#

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

Changing to the ch01 Folder in the Docker Container


The docker run command specified above attaches your examples folder to the con-
tainer’s /usr/src folder. In the Docker container, use the cd command to change to the
ch01 subfolder of /usr/src:

root@9753bace2e87:/# cd /usr/src/ch01
root@9753bace2e87:/usr/src/ch01#

Compiling the Application


Before running the application, you must first compile it. This container uses the com-
mand clang++, as in
clang++ -std=c++20 GuessNumber.cpp -o GuessNumber

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.

Running the Application


To run and interact with the GuessNumber application in the Docker container, follow
Steps 3–7 of Section 1.11.2, Compiling and Running with GNU C++ on Linux.

Terminating the Docker Container


You can terminate the Docker container by typing Ctrl + d at the container’s prompt.

1.11.5 Compiling and Running with Xcode on macOS


In this section, you’ll run a C++ program on macOS using Apple’s Xcode IDE.72 Xcode
uses a version of the LLVM/Clang C++ compiler, which at the time of this writing, is miss-
ing several important C++20 features that we use throughout the book. Visit
https://deitel.com/cpphtp11

for instructions on using Xcode to run the book’s examples in Chapters 4 and higher.

Step 1: Checking Your Setup


If you have not already done so, read the Before You Begin section to install Xcode and
download the book’s code examples.

Step 2: Launching Xcode


In the Finder’s Go menu, select Applications then double-click the Xcode icon:

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-

72. Xcode version was 14.2 at the time of this writing.


38 Chapter 1 Intro to Computers and C++

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

Step 5: Deleting the main.cpp File from the Project


By default, Xcode creates a main.cpp source-code file containing a simple program that
displays "Hello, World!". You won’t use main.cpp in this test-drive, so you should delete
the file. In the Project navigator, right-click the main.cpp file and select Delete. In the dia-
log that appears, select Move to Trash. The file will not be removed from your system until
you empty your trash.

Step 6: Adding the GuessNumber.cpp File into the Project


In a Finder window, open the ch01 folder in the book’s examples folder, then drag
GuessNumber.cpp onto the cpp20_test folder in the Project navigator. In the dialog that
appears, ensure that Copy items if needed is checked, then click Finish.73

Step 7: Compiling and Running the Project


To compile and run the project so you can test-drive the application, simply click the run
( ) button on Xcode’s toolbar. If the program compiles correctly, Xcode opens the Debug
area and executes the program in the right half of the Debug area, and the application dis-
plays "Please type your first guess." and a question mark (?) as a prompt for input:

Step 8: Entering Your First Guess


Click the Debug area, then type 500 and press Return——the program selects a number
randomly each time you run it, so your interactions with the program will vary during each
execution. In our case, the application displayed "Too high. Try again." because the
value was more than the number the application chose as the correct guess.

Step 9: Entering Another Guess


At the next prompt, if your system said the first guess was too low, type 750 and press
Enter; otherwise, type 250 and press Enter. In our case, we entered 250, and the application
displayed "Too high. Try again." because the value was greater than the correct guess:

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++

Step 10: Entering Additional Guesses


Continue to play the game by entering values until you guess the correct number. When
you guess correctly, the application displays "Excellent! You guessed the number.":

Playing the Game Again or Exiting the Application


After guessing the correct number (which you should always be able to do in 10 or fewer
guesses), the application asks if you’d like to play another game. At the "Would you like
to play again (y or n)?" prompt, entering y causes the application to choose a new num-
ber and start a new game. Entering n terminates the application.
Reusing This Project for Subsequent Examples
You can follow the steps in this section to create a separate project for every application in
the book. However, for our examples, you may find it more convenient to remove the cur-
rent program from the project, then add a new one. To remove a file from your project
(but not your system), right-click the file in the Project navigator and select Delete. In the
dialog that appears, select Remove Reference. You can then repeat Step 6 to add a different
program to the project. When you begin creating programs yourself, you can add a new
empty file to the project as follows:
1. Right-click the folder in your project and select New File….
2. Select the Empty file template from the Other category and click Next.
3. Specify a name for your file and be sure to include the .cpp extension, then click
Create.
1.12 Internet, World Wide Web, the Cloud and IoT 41

1.12 Internet, World Wide Web, the Cloud and IoT


In the late 1960s, ARPA—the Advanced Research Projects Agency of the United States
Department of Defense—rolled out plans for networking the main computer systems of
approximately a dozen ARPA-funded universities and research institutions. The computers
were to be connected with communications lines operating at speeds on the order of 50,000
bits per second, a stunning rate at a time when most people (of the few who even had net-
working access) were connecting over telephone lines to computers at a rate of 110 bits per
second. Academic research was about to take a giant leap forward. ARPA implemented
what quickly became known as the ARPANET, the precursor to today’s Internet. Today’s
fastest Internet speeds are on the order of billions of bits per second. Trillion-bits-per-sec-
ond (terabit) speeds are already in service—the Energy Sciences Network in the United
States is now capable of transmitting data at 46 Terabits per second!74
Things worked out differently from the original plan. Although the ARPANET
enabled researchers to network their computers, its main benefit proved to be the capabil-
ity for quick and easy communication via what came to be known as electronic mail (e-
mail). This is true even on today’s Internet, with e-mail, instant messaging, file transfer
and social media, such as Snapchat, TikTok, Instagram, Facebook and Twitter, enabling
billions of people worldwide to communicate quickly and easily.
The protocol (set of rules) for communicating over the ARPANET became known as
the Transmission Control Protocol (TCP). TCP ensured that messages, consisting of
sequentially numbered pieces called packets, were properly delivered from sender to
receiver, arrived intact and were reassembled in the correct order.

1.12.1 The Internet: A Network of Networks


In parallel with the evolution of the ARPANET, organizations worldwide were imple-
menting their own networks for intra-organization (that is, within an organization) and
inter-organization (that is, between organizations) communication. A huge variety of net-
working hardware and software appeared. One challenge was to enable these different net-
works to communicate with each other. ARPA accomplished this by developing the
Internet Protocol (IP), which created a true “network of networks,” the Internet’s current
architecture. The combined set of protocols is now called TCP/IP. Each Internet-con-
nected device has an IP address—a unique numerical identifier used by devices commu-
nicating via TCP/IP to locate one another on the Internet.
Businesses rapidly realized that, by using the Internet, they could improve their oper-
ations and offer new and better services to their clients. Companies started spending large
amounts of money on developing and enhancing their Internet presence. This generated
fierce competition among communications carriers and hardware and software suppliers
to meet the increased infrastructure demand. As a result, Internet bandwidth—the infor-
mation-carrying capacity of communications lines—has increased tremendously while
hardware costs have plummeted.

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++

1.12.2 The World Wide Web: Making the Internet User-Friendly


The World Wide Web (simply called “the web”) is a collection of hardware and software
associated with the Internet that allows computer users to locate and view documents
(with various combinations of text, graphics, animations, audios and videos) on almost
any subject. In 1989, Tim Berners-Lee of CERN (the European Organization for Nuclear
Research) began developing HyperText Markup Language (HTML)—the technology for
sharing information via “hyperlinked” text documents. He also wrote communication
protocols such as HyperText Transfer Protocol (HTTP) to form the backbone of his new
hypertext information system, which he referred to as the World Wide Web.
In 1994, Berners-Lee founded the World Wide Web Consortium (W3C, https://
www.w3.org), which was devoted to developing web technologies. A key W3C goal is to
make the web universally accessible to everyone regardless of disabilities, language or culture.

1.12.3 The Cloud


More and more computing today is done “in the cloud”—that is, using software and data
distributed across the Internet worldwide rather than locally on your desktop, notebook
computer or mobile device. Cloud computing allows you to increase or decrease comput-
ing resources to meet your needs at any given time, which is more cost-effective than pur-
chasing your own hardware to provide enough storage and processing power to meet
occasional peak demands. Cloud computing also saves money by shifting to the service
provider the burden of managing computing resources (such as installing and upgrading
the software, security, backups and disaster recovery).
The apps you use daily are heavily dependent on various cloud-based services. These
use massive clusters of computing resources (computers, processors, memory, storage, etc.)
and databases that communicate over the Internet with each other and the apps you use. A
service that provides access to itself over the Internet is known as a web service. As of 2023,
Amazon Web Services (AWS; 33% market share), Microsoft Azure (22%) and Google
Cloud Platform (GCP; 11%) account for about two-thirds of the cloud-services market.75
Other top cloud vendors include IBM Cloud, Oracle, VMWare, Salesforce and Alibaba.76

1.12.4 The Internet of Things (IoT)


The Internet is no longer just a network of computers—it’s an Internet of Things (IoT).
A thing is any device with an IP address and the ability to send, and in some cases receive,
data automatically over the Internet. Such things include:
• cars with transponders for paying tolls,
• monitors for parking-space availability in a garage,
• heart monitors implanted in humans,
• water-quality monitors,
• smart meters that report energy usage,
• radiation detectors,

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

• item trackers in warehouses,


• mobile apps that can track your movements,
• smart thermostats that adjust room temperatures based on weather forecasts and
activity in the home,
• intelligent home appliances, and
• many more.
According to IOT Analytics, which provides market research and insights for the Internet
of Things, there were 12.2 billion active IoT devices in 2021, and that is expected to grow
to 27 billion in 2025.77

1.12.5 Edge Computing


IoT is an example of edge computing,78 in which data processing and storage occurs on or
close to the network-connected devices that produce the data—that is, at the edge of the net-
work. Edge computing often is used in “intelligent applications that require continuous
monitoring and rapid response to dynamic conditions or high-volume data streams.”79 It
enables devices to process data and make decisions locally. For example, if a self-driving car
loses its Internet connection, it must still be able to make the decisions that enable it to drive
safely. Edge computing is used in many fields, including autonomous vehicles, smart power
grids, healthcare devices, agriculture, clean energy, industrial automation and more.

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++

• Rapid (https://rapidapi.com) claims to be the world’s largest API hub, listing


thousands of free and paid APIs. Rapid also provides tools to help companies
build and distribute their own APIs.
• APILayer (https://apilayer.com) lists 94 web services. All have free tiers with
no credit card required.
• Any API (https://any-api.com/) lists over 1400 web services in 34 categories.

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

1.13.1 Virtual Reality (VR)


Virtual reality (VR) typically refers to simulated, three-dimensional (3D) environments
that you interact with using:
• non-immersive VR—in which you view the 3D environment in two-dimen-
sional space using your computer’s screen,
• semi-immersive VR—in which you view the 3D environment in two-dimen-
sional space using large displays, such as big-screen TVs or video walls, or

80. Neal Stephenson. Snow Crash. Bantam Books, 1993. p. 24.


81. “Metaverse.” Wikipedia. Wikimedia Foundation. Accessed March 18, 2023. https://en.wikipe-
dia.org/wiki/Metaverse.
82. Jackie Wiles, “What Is a Metaverse? And Should You Be Buying In?” October 21, 2022. Accessed
March 18, 2023. https://www.gartner.com/en/articles/what-is-a-metaverse.
83. Hanna Hryshkevich, “How AI and the Metaverse Work Together.” February 2, 2023. Accessed March
27, 2023. https://www.aitimejournal.com/how-ai-and-the-metaverse-work-together/.
1.13 Metaverse 45

• 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.

1.13.2 Augmented Reality (AR)


Augmented reality (AR) projects real-time computer-generated content—such as images,
sound, video, animation and more—onto what you see in the real world, typically via
devices with built-in cameras, like smartphones, tablets and computerized glasses that
enable you to see both the real world and virtual content at the same time.84,85
One of the most popular examples of augmented reality is the mobile game app
Pokémon Go™ in which Pokémon characters are projected onto real-world locations that
you find via the GPS in your mobile devices.86
Other uses include:
• In sports like baseball and hockey, broadcasters help you follow the baseball or
puck by displaying a line that traces the path of a baseball pitch or the path of a
hockey puck as it’s passed around the ice.
• National Football League® broadcasts display colored lines over the field, showing
the line of scrimmage and where the team needs to reach for a first down.
• Navigation apps can display real-time navigation and traffic information onto real-
world maps and street-level views.
• Home decoration apps can show you what a room would look like after you
repaint it or add specific furniture items.
• Clothing retailers often can show you what you’d look like in a particular cloth-
ing item you’re considering purchasing.
• Museums can make exhibits more interactive by displaying information about a
specific exhibit you are viewing.
Many companies are working on AR glasses and headsets.87 For example, at the 2022
Google I/O conference, Google unveiled their AR glasses that translate text in real-time
and project the translations onto the lenses.88

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.3 Mixed Reality


Mixed reality is similar to augmented reality but takes it further by enabling you to inter-
act with the virtual objects projected into your real-world view. In that sense, mixed reality
combines aspects of both augmented reality and virtual reality. Like virtual reality, the best
mixed-reality experiences typically require a headset.89,90 The term extended reality
encompasses virtual reality, augmented reality and mixed reality.91

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).

1.13.5 Bitcoin and Cryptocurrency


“A cryptocurrency is a digital or virtual currency secured by cryptography.”95 Cryptocur-
rency (or Crypto) is stored in digital wallets and generally uses blockchain technology for

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.7 Non-Fungible Tokens (NFTs)


Non-fungible tokens (NFTs)101 are blockchain-based “cryptographically unique tokens
that are linked to digital or physical content, providing proof of ownership.” They’re com-
monly used to enable individuals to own unique items, such as digital or physical artwork
and photographs; limited edition digital collectibles; virtual real estate and goods in games
and the Metaverse; physical real estate; intellectual property; and digital books.102
Some artwork NFTs have sold for massive amounts of money:103
• The most expensive NFT ever sold was Pak’s “The Merge,” purchased by 29,983
individual buyers for $91.8 million—each buyer owns a small portion of the NFT.
• The most expensive NFT ever sold to one buyer was “Everydays: The First 5000
Days” by digital artist Mike “Beeple” Winkelmann, which sold for $69.3 million.

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.

1.14 Software Development Technologies


As you develop software, you’ll frequently encounter the following buzzwords:
• Refactoring: Reworking programs to make them clearer and easier to maintain
while preserving their correctness and functionality and sometimes improving
performance. Many IDEs contain built-in refactoring tools to do major portions
of the reworking automatically.107
• Design patterns: Proven architectures for constructing flexible and maintainable
object-oriented software. The field of design patterns tries to enumerate those
recurring patterns, encouraging software designers to reuse them to develop better-
quality software faster, with less money, time and effort.108
• Software Development Kits (SDKs): The tools, libraries and documentation
developers use to program applications. For example, SDKs can help you create
applications for specific operating systems, gaming platforms, cloud platforms,
and more.109
• Version Control Systems (VCS): Tools that enable you to manage and keep
track of the changes you make in software as you develop it over time. According
to StackOverflow’s 2022 Developer Survey, Git—the technology behind
GitHub—is by far the most widely used version control system, with almost 94%
of developers saying they use it.110
• Agile software development: A software-development process that focuses on
developing high-quality software iteratively and incrementally, with constant

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.

1.15 How Big Is Big Data?


For computer scientists and data scientists, understanding how to obtain, store, process
and extract value from data is as crucial as writing effective programs. According to a 2016
IBM article, approximately 2.5 quintillion bytes (2.5 exabytes) of data are created daily,116
and 90% of the world’s data was created in the previous two years.117 The Internet is
responsible for much of this data generation. According to IDC, the global data supply
will reach 175 zettabytes (equal to 175 trillion gigabytes or 175 billion terabytes) annually
by 2025.118 Consider the following real-world examples of various popular data measures.

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

Petabytes, Exabytes and Zettabytes


There are over four billion people online, creating about 2.5 quintillion bytes of data each
day124—that’s 2500 petabytes (each petabyte is 1024 terabytes) or 2.5 exabytes (each exabyte
is 1024 petabytes). A March 2016 AnalyticsWeek article stated that by 2021 there would be
over 50 billion devices connected to the Internet (most of them through the Internet of
Things; Section 1.12.4) and, by 2020, there would be 1.7 megabytes of new data produced
per second for every person on the planet.125 At today’s population of 8.023 billion peo-
ple126, that’s about 13.55 petabytes of new data per second, 813 petabytes per minute,
48,780 petabytes (48.78 exabytes) per hour, or 1171 exabytes per day—that is, 1.171 zetta-
bytes (ZB) per day (each zettabyte is 1024 exabytes). That’s the equivalent of 5.73 million
hours of 4K video every day or approximately 121 billion photos every day!

119.“Audio File Size Calculations.” Accessed March 18, 2023. https://www.audiomountain.com/


tech/audio-file-size.html.
120.“DVD.” Wikipedia. Wikimedia Foundation. Accessed March 18, 2023. https://en.wikipe-
dia.org/wiki/DVD.
121.“Ultra HD Blu-ray.” Wikipedia. Wikimedia Foundation. Accessed March 18, 2023. https://
en.wikipedia.org/wiki/Ultra_HD_Blu-ray.
122.“History of hard disk drives.” Wikipedia. Wikimedia Foundation. Accessed March 18, 2023. https://
en.wikipedia.org/wiki/History_of_hard_disk_drives.
123.Jakob Han, “Nimbus Data 100TB SSD – World’s Largest SSD.” March 29, 2018. Accessed March
18, 2023. https://www.cined.com/nimbus-data-100tb-ssd-worlds-largest-ssd/.
124.Aditya Rayaprolu, “How Much Data Is Created Every Day in 2020?” February 27, 2023. Accessed
March 18, 2023. https://techjury.net/blog/how-much-data-is-created-every-day/#gref.
125.Vishal Kumar, “Big Data Facts.” Accessed March 18, 2023. https://analyticsweek.com/content/
big-data-facts/.
126.“Current World Population.” Accessed March 18, 2023. https://www.worldometers.info/
world-population/.
1.15 How Big Is Big Data? 51

Additional Big-Data Stats


For a real-time sense of big data, check out https://www.worldometers.info/, with var-
ious statistics, including that day’s numbers of Google searches, Tweets and e-mails sent.
Some other interesting big-data facts:
• Every hour, YouTube users upload 30,000 hours of video, and almost 1 billion
hours of video are watched on YouTube every day.127
• Every second, there are 103,777 GBs (or 103.777 TBs) of Internet traffic, 9204
tweets sent, 87,015 Google searches and 86,617 YouTube videos viewed.128
• On Facebook each day, there are 3.2 billion “likes” and comments,129 and 5 bil-
lion emojis sent via Facebook Messenger.130
Domo, Inc.’s infographic called “Data Never Sleeps” shows interesting statistics
regarding how much data is generated every minute, including:131
• 66,000 photos posted on Instagram.
• 500 hours of video uploaded to YouTube.
• 1.7 million Facebook posts.
• 2.43 million snaps on SnapChat.
• 1 million hours of streaming video viewed.
• 347,200 tweets sent on Twitter.
• 104,600 hours spent in Zoom meetings.Processing the World’s Data Requires
Lots of Electricity
A 2015 article stated that energy use for processing the world’s data was growing at 20%
per year and consuming approximately 3–5% of the world’s power. The article said that
total data-processing power consumption could reach 20% by 2025.132
Another enormous electricity consumer is the blockchain-based cryptocurrency Bit-
coin. Processing just one Bitcoin transaction uses approximately the same amount of
energy as powering the average American home for a week. The energy use comes from
the process Bitcoin “miners” use to prove that transaction data is valid.133
Morgan Stanley predicted in 2018 that “the electricity consumption required to cre-
ate cryptocurrencies this year could actually outpace the firm’s projected global electric

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.

1.15.1 Big-Data Analytics


The term “data analysis” was coined in 1962,137 though people have been analyzing data
using statistics for thousands of years, going back to the ancient Egyptians.138 The term
“big data” was coined around 1987.139
Consider four of the “V’s of big data”:140,141
1. Volume—the data the world is producing is growing exponentially.
2. Velocity—the speed at which data is being produced, the speed at which it moves
through organizations and the speed at which data changes are growing quick-
ly.142,143,144

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

3. Variety—today’s data includes characters, digits, punctuation and special charac-


ters, as well as images, audios, videos and data from an exploding number of In-
ternet of Things sensors in our homes, businesses, vehicles, cities and more.
4. Veracity—the validity of the data—is it complete and accurate? Can we trust that
data when making crucial decisions? Is it real?
Digital data storage has become so vast in capacity, and so cheap and small, that we
can now conveniently and economically retain all the digital data we’re creating.145 That’s
big data. To get a sense of big data’s scope in industry, government and academia, check
out the high-resolution graphic (click it to zoom for easier readability)146 at:
https://mattturck.wpenginepowered.com/wp-content/uploads/2021/12/
2021-MAD-Landscape-v3.pdf

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

Some data-science use cases

assisting people with disabilities human genome sequencing ride-sharing


automated closed captioning identity-theft prevention robo financial advisors
brain mapping improved inventory control self-driving cars
cancer diagnosis/treatment intelligent assistants sentiment analysis
computer vision location-based services similarity detection
crime prevention malware detection smart homes
CRISPR gene editing marketing analytics smart meters
crop-yield improvement medical device monitoring smart thermostats
customer service agents natural-language translation smart traffic control
data visualization personalized medicine spam detection
diagnostic medicine phishing elimination stock market forecasting
dynamic driving routes pollution reduction summarizing text
electronic health records precision medicine theft prevention
emotion detection preventative medicine trend spotting
facial recognition preventing disease outbreaks visual product search
fraud detection recommendation systems voice recognition
health outcome improvement reducing energy use weather forecasting

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++

1.16 AI—at the Intersection of Computer Science and


Data Science
When a baby first opens its eyes, does it “see” its parent’s faces? Does it understand any
notion of what a face is—or even what a simple shape is? Babies must “learn” the world
around them. That’s what artificial intelligence (AI) technology called machine learning
does. It looks at massive amounts of data and learns from it. AI technologies are being used
to play games, implement computer-vision applications, enable self-driving cars, enable
robots to learn to perform new tasks, diagnose medical conditions, translate speech to other
languages in near real-time, create chatbots that can respond smoothly and accurately to arbi-
trary questions after being trained on massive text databases called large language models,
and much more. Who’d have guessed just a few years ago that artificially intelligent self-driv-
ing cars would be allowed on our roads—or even become common? The ultimate goal of the
AI field is artificial general intelligence—the ability to perform any task that humans can.150

1.16.1 Artificial Intelligence (AI)


Two definitions of artificial intelligence (AI)151 are:
• “a branch of computer science dealing with the simulation of intelligent behavior
in computers” and
• “the capability of a machine to imitate intelligent human behavior.”
The term AI was coined by John McCarthy in 1956. AI-based systems now permeate our
daily lives. Examples include computer vision, speech recognition, natural language transla-
tion, recommender systems (such as Amazon recommending products you might like or
Netflix recommending shows and movies you might like), automated game-playing systems,
self-driving cars, and more recent remarkable tools like the ChatGPT chatbot that carries on
conversations almost indistinguishable from human conversations and the Dall-E 2 image
generator that creates original images when given only text descriptions.152
For many decades, AI has been a field with problems and no solutions. That’s because
once a particular problem is solved, people say, “Well, that’s not intelligence; it’s just a
computer program that tells the computer exactly what to do.” However, with AI tech-
niques like machine learning (Section 1.16.4) and deep learning (Section 1.16.5), we’re
not pre-programming solutions to specific problems. Instead, we’re having our computers
solve problems by learning from data—and, typically, lots of it. Many of the most inter-
esting and challenging problems are being pursued with deep learning. Google alone has
more than a thousand deep-learning projects underway.153,154
150.“Artificial general intelligence.” Wikipedia. Wikimedia Foundation. Accessed March 18, 2023.
https://en.wikipedia.org/wiki/Artificial_general_intelligence.
151.“artificial intelligence.” Merriam-Webster.com. 2023. Accessed March 18. 2023. https://www.mer-
riam-webster.com/dictionary/artificial%20intelligence.
152.“Artificial intelligence.” Wikipedia. Wikimedia Foundation. Accessed March 18, 2023. https://
en.wikipedia.org/wiki/Artificial_intelligence.
153.Kelly Gonsalves, “Google has more than 1,000 artificial intelligence projects in the works.” Accessed
March 18, 2023. https://theweek.com/speedreads/654463/google-more-than-1000-artifi-
cial-intelligence-projects-works.
154.Tiernan Ray, “Google says 'exponential' growth of AI is changing nature of compute.” Accessed
March 18, 2023. https://www.zdnet.com/article/google-says-exponential-growth-of-ai-
is-changing-nature-of-compute/.
1.16 AI—at the Intersection of Computer Science and Data Science 55

1.16.2 Artificial General Intelligence (AGI)


Artificial general intelligence (AGI)155 refers to artificial intelligence that can “carry out
any task that humans are capable of.”156,157 Experts disagree on when or if artificial general
intelligence might become a reality—from as soon as this decade, to sometime in the next
100 years, to never.158,159

1.16.3 Artificial Intelligence Milestones


Several artificial intelligence milestones have captured people’s attention and imagination,
made the general public start thinking that AI is real and made businesses think about
commercializing it:
• In a 1997 match between IBM’s DeepBlue computer system and chess Grandmas-
ter Gary Kasparov, DeepBlue became the first computer to beat a reigning world
chess champion under tournament conditions.160 IBM loaded DeepBlue with
hundreds of thousands of grandmaster chess games. DeepBlue could use brute
force to evaluate up to 200 million moves per second!161 This is big data at work.
IBM received the Carnegie Mellon University Fredkin Prize, which in 1980 offered
$100,000 to the creators of the first computer to beat a world chess champion.162
• In 2011, IBM’s Watson beat the two best human Jeopardy! players in a $1 million
match. Watson simultaneously used hundreds of language-analysis techniques to
locate correct answers in 200 million pages of content (including all of Wikipedia),
requiring four terabytes of disk storage.163,164 Watson was trained with AI
machine-learning and reinforcement-learning (Section 1.16.6) techniques.165

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

1.16.4 Machine Learning


Machine learning is “a subfield of artificial intelligence that gives computers the ability to
learn without explicitly being programmed.”170 Machine learning typically uses pre-
defined algorithms to build models that learn from training data. Those models can then
be used to make predictions.171 For example, given labeled training data that contains
legitimate e-mails and junk (also called spam) e-mails, a machine-learning model can learn
from the training data, then be used to classify e-mails it has never “seen” as junk or not
junk. E-mail apps like Microsoft’s Outlook and Google’s Gmail use techniques like this
to move junk emails out of your inbox.

1.16.5 Deep Learning


Deep learning is a subset of machine learning that involves building artificial neural net-
works, which use “algorithms inspired by the structure and function of the brain.”172 The
term “deep” comes from the number of software “layers” in an artificial neural network—
the more layers, the deeper the network. The network learns more from its training data as

166.“A Brief History of Go.” Accessed March 18, 2023. http://www.usgo.org/brief-history-go.


167.Nsikan Akpan, “Google artificial intelligence beats champion at world’s most complicated board
game.” Accessed March 18, 2023. https://www.pbs.org/newshour/science/google-artifi-
cial-intelligence-beats-champion-at-worlds-most-complicated-board-game.
168.John Carl Villanueva, “How Many Atoms Are There in the Universe?” Accessed March 18, 2023.
https://www.universetoday.com/36302/atoms-in-the-universe/.
169.Samuel Gibbs, “AlphaZero AI beats champion chess program after teaching itself in four hours.”
Accessed March 18, 2023. https://www.theguardian.com/technology/2017/dec/07/alphazero-
google-deepmind-ai-beats-champion-program-teaching-itself-to-play-four-hours.
170.Sara Brown “Machine learning, explained.” April 21, 2021. Accessed March 18, 2023. https://
mitsloan.mit.edu/ideas-made-to-matter/machine-learning-explained.
171.“Machine learning.” Wikipedia. Wikimedia Foundation. Accessed March 18, 2023. https://
en.wikipedia.org/wiki/Machine_learning.
172. Jason Brownlee, “What is deep learning?” August 16, 2019. Accessed March 18, 2023. https://
machinelearningmastery.com/what-is-deep-learning/.
1.16 AI—at the Intersection of Computer Science and Data Science 57

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

1.16.6 Reinforcement Learning


Reinforcement learning175 is a subset of machine learning in which algorithms learn from
their environment, similar to how humans learn—for example, a video game enthusiast
learning a new game or a baby learning to walk or recognize its parents. The algorithm
implements an agent that learns by trying to perform a task, receiving feedback about suc-
cess or failure, making adjustments then trying again. The goal is to maximize the reward.
The agent receives a positive reward for doing a right thing and a negative reward (that is,
a punishment) for doing a wrong thing. The agent uses this information to determine the
next action to perform and must try to maximize the reward.

1.16.7 Generative AI—ChatGPT and Dall-E 2


Generative AI describes algorithms that can generate new content—including text,
images, audio and video—based on prompts provided by a user as input.176,177

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.

181.“GPT-.4” Accessed March 23, 2023. https://openai.com/research/gpt-4.


182.“Bard.” Accessed March 25, 2023. https://bard.google.com/.
183.Vilius Petkauskas, “ChatGPT’s answers could be nothing but a hallucination.” March 6, 2023. Accessed
March 25, 2023. https://cybernews.com/tech/chatgpts-bard-ai-answers-hallucination/.
184.“Turing test.” Wikipedia. Wikimedia Foundation. Accessed March 25, 2023. https://en.wikipe-
dia.org/wiki/Turing_test.
185.“Dall-E 2.” Accessed March 18, 2023. https://openai.com/product/dall-e-2.
186.“Dall-E.” Wikipedia. Wikimedia Foundation. Accessed March 18, 2023. https://en.wikipe-
dia.org/wiki/DALL-E.
1.17 Wrap-Up 59

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

l) Microsoft’s primary language for the Metaverse is .


m) The that objects come from are essentially reusable software compo-
nents.
n) The protocol for communicating over the ARPANET became known as the
.
o) TCP ensured that messages, consisting of sequentially number pieces called
were properly delivered from sender to receiver, arrived intact and
were reassembled in the correct order.
p) In the Internet of Things (IoT) a “thing” is any device with a(n) and
the ability to send, and sometimes receive, data automatically over the Internet.
q) The applications-development methodology of enables you to rapidly
develop powerful software applications by combining (often free) complemen-
tary web services and various forms of information feeds.
r) typically refers to simulated, 3D environments that you interact with.
s) is a software-based ledger distributed over nodes on the Internet.
t) A is a digital or virtual currency secured by cryptography.
u) are blockchain-based “cryptographically unique tokens linked to dig-
ital or physical content, providing proof of ownership.”
v) is by far the most widely used version control system.
w) The “four Vs of big data are , , , and .
x) Some people feel that the ultimate problem to be solved in AI is .
y) ChatGPT is an example of the field of .
1.5 State which of the following are true and which are false. If false, explain why.
a) Computing costs are dropping rapidly due to impressive developments in hard-
ware, software and Internet technologies.
b) For decades, computer power approximately doubled inexpensively every year.
This remarkable trend is called Moore’s law.
c) Taking full advantage of multi-core architecture requires writing multithreaded
applications.
d) Any computer can directly understand only its own assembly language.
e) The software that contains the core operating-system components is called the
kernel.
f) iOS is the most widely used mobile-phone operating system.
g) C++ is the premiere language for building high-performance business-critical
and mission-critical operating systems.
h) The programming language most closely associated with the expression “write
once, run anywhere” is Java.
i) Swift is widely used to add programmability to web pages, such as animations
and user interactivity.
j) As the ARPANET evolved, to enable the huge variety of networking hardware
and software to intercommunicate, ARPA developed the Internet Protocol
(IP), which created a true “network of networks.”
k) Cloud computing allows you to increase or decrease computing resources to
meet your needs at any given time.
l) IoT is an example of edge computing.
62 Chapter 1 Intro to Computers and C++

m) Augmented reality (AR) projects real-time computer-generated content onto


what you see in the real world.
n) 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.”
o) Forbes defines Web3 as “the centralized Internet__ built on distributed tech-
nologies like blockchain ... rather than on servers owned by individuals or cor-
porations.”
p) By some estimates, processing just one Bitcoin transaction uses approximately
the same amount of energy as powering the average American home for one
month.
q) AI is often called a field with solutions but no problems.
r) In machine learning, computers are explicitly programmed with human exper-
tise to solve a particular problem.
s) OpenAI’s Dall-E 2 can generate original images from text descriptions.
1.6 (Clock as an Object) Clocks are among the world’s most common objects. Discuss
how each of the following terms and concepts applies to the notion of a clock: class, object,
instantiation, data member, reuse, member function, inheritance (consider, for example,
an alarm clock), base class and derived class.
1.7 (Self-Driving Cars) Just a few years ago, the notion of driverless vehicles on our
streets would have seemed impossible. Many of the technologies you’ll read about in this
book are making self-driving cars possible. Today, they’re already common in some areas.
a) If you hailed a taxi and a driverless taxi stopped for you, would you get into the
back seat? Would you feel comfortable telling it where you want to go and
trusting it would get you there? What safety measures would you want in place?
b) What if two self-driving cars approached a one-lane bridge from opposite di-
rections? What protocol should they go through to determine which car should
proceed?
c) What if you’re behind a car stopped at a red light, the light turns green, and the
car doesn’t move? You honk, and nothing happens. You get out of your car and
notice that there’s no driver. What would you do?
d) If a police officer pulls over a speeding self-driving car in which you’re the only
passenger, who—or what entity—should pay the ticket?
e) One especially serious concern with self-driving vehicles is that they might be
hacked. What if the hacker sets the speed high (or low), which could be dan-
gerous. What if the hacker locked all the doors then set the vehicle to drive off
in the wrong direction?
1.8 (Research: Artificial General Intelligence) One of the most ambitious goals in the
field of AI is to achieve artificial general intelligence—the point at which machine intelli-
gence would equal human intelligence. Research this intriguing topic. When is this fore-
cast to happen? What are some ethical issues this raises? Human intelligence seems to be
stable over long periods. Powerful computers with artificial general intelligence could con-
ceivably (and quickly) evolve intelligence far beyond that of humans. Research and discuss
the issues this raises.
Exercises 63

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.

■ Understand basic memory


concepts.
■ Use arithmetic operators.

■ Understand the precedence of


arithmetic operators.
■ Write decision-making
statements.
■ Use relational and equality
operators.
■ Begin appreciating the
“Objects Natural” learning
approach by conveniently
creating and using powerful
objects of the C++ standard
library’s string class even
before you learn to code your
own custom classes in later
chapters.
66 Chapter 2 Intro to C++20 Programming
Outline
2.1 Introduction 2.7 Decision Making: Equality and
2.2 First Program in C++: Displaying a Line Relational Operators
of Text 2.8 Objects Natural Case Study:
2.3 Modifying Our First C++ Program Creating and Using Objects of
2.4 Another C++ Program: Adding Integers Standard-Library Class string
2.5 Memory Concepts 2.9 Wrap-Up
2.6 Arithmetic Exercises

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.

The “Objects Natural” Learning Approach


In your programs, you’ll create and use many objects of preexisting carefully-developed-
and-tested classes that enable you to perform significant tasks with minimal code, even in
the book’s earliest chapters. These classes typically come from:
• the C++ standard library,
• platform-specific libraries (such as those provided by Microsoft for creating Win-
dows applications or by Apple for creating macOS applications), and
• free third-party libraries created by the massive open-source communities that
have developed around key programming languages.
To help you appreciate this programming style even in the book’s introductory chapters,
you’ll conveniently create and use objects of preexisting C++ standard library classes with-
out yet knowing how to create your own custom classes. We call this the “Objects Natu-
ral” approach. You’ll begin by creating and using string objects in this chapter’s final
example. Beginning in Chapter 9, you’ll craft valuable custom classes for your own use and
for reuse by other programmers.

Compiling and Running Programs


For instructions on compiling and running programs, see the test-drives in Chapter 1.

2.2 First Program in C++: Displaying a Line of Text


Consider a simple program that displays a line of text (Fig. 2.1). The line numbers are not
part of the program.
2.2 First Program in C++: Displaying a Line of Text 67

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++!

Fig. 2.1 | Text-printing program.

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. */

#include Preprocessing Directive


Line 3
#include <iostream> // enables program to output data to the screen

is a preprocessing directive—a message to the C++ preprocessor, which the compiler


invokes before compiling the program. This line notifies the preprocessor to include in the
program the contents of the input/output stream header <iostream>. This header is a file
containing information the compiler requires when compiling any program that outputs
data to the screen or inputs data from the keyboard using C++’s stream input/output. The
program in Fig. 2.1 outputs data to the screen. Chapter 5 discusses headers in more detail,
and Chapter 19 explains the contents of <iostream> in more detail. Forgetting to include
<iostream> in a program that inputs data from the keyboard or outputs data to the screen Err
causes the compiler to issue an error message.
68 Chapter 2 Intro to C++20 Programming

Blank Lines and Whitespace


Line 4 is a blank line. Blank lines, spaces and tabs make programs easier to read. Together,
these characters are known as whitespace—they’re usually ignored by the compiler.

The main Function


Line 6
int main() {

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

The std Namespace


The std:: before cout is required when we use names that we’ve brought into the pro-
gram from standard-library headers like <iostream>. The notation std::cout specifies
that we are using the name cout, which belongs to namespace std.1 We discuss name-
spaces in Chapter 16. For now, include std:: before each mention of cout. We’ll soon
introduce using declarations and the using directive, which will enable you to omit std::
before each use of a name in the std namespace.

The Stream Insertion Operator and Escape Sequences


When used with cout, the << operator is the stream insertion operator. The value to the
operator’s right (the right operand) is inserted in the output stream. Note that << points
toward where the data goes. A string’s characters are typically displayed exactly as typed
between the quotes. However, the characters \n are not displayed in Fig. 2.1’s output. The
backslash (\) is an escape character. When C++ encounters a backslash in a string, it com-
bines the next character with the backslash to form an escape sequence. The escape
sequence \n means newline. It causes the cursor—that is, the current screen-position indi-
cator—to move to the beginning of the next line on the screen. Some common escape
sequences are shown in the following table:

Escape sequence Description

\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.

The return Statement


Line 9
return 0; // indicate that program ended successfully

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.

2.3 Modifying Our First C++ Program


The next two examples modify the program of Fig. 2.1. The first displays text on one line
using multiple statements. The second displays text on several lines using one statement.

Displaying a Single Line of Text with Multiple Statements


Figure 2.2 performs stream insertion in multiple statements (lines 7–8) yet produces the
same output as Fig. 2.1. Each stream insertion resumes displaying where the previous one
stopped. Line 7 displays Welcome, followed by a space. This string did not end with \n, so
line 8 begins displaying on the same line immediately following the space.

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++!

Fig. 2.2 | Displaying a line of text with multiple statements.

Displaying Multiple Lines of Text with a Single Statement


A single statement can display multiple lines by using additional newline characters, as in
line 7 of Fig. 2.3. Each time the \n (newline) escape sequence is encountered in the output
stream, the screen cursor is positioned at the beginning of the next line. To get a blank line
in your output, place two newline characters back to back, as in line 7.

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

Answer: std::cout << "Hello\n\nWorld\n";

2.4 Another C++ Program: Adding Integers


Our next program obtains two integers typed by a user at the keyboard, computes their sum
and outputs the result using std::cout. Figure 2.4 shows the program and sample inputs
and outputs. In sample executions, our convention is to show the user’s input in bold.

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

Enter first integer: 45


Enter second integer: 72
Sum is 117

Fig. 2.4 | Addition program that displays the sum of two integers. (Part 2 of 2.)

Variable Declarations and Braced Initialization


Lines 8–10
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)

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.

Declaring Multiple Variables at Once


Variables of the same type may be declared in one declaration. For example, we could have
declared and initialized all three variables using a comma-separated list as follows:
int number1{0}, number2{0}, sum{0};

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

Identifiers and Camel-Case Naming


A variable name (such as number1) may be any valid identifier. An identifier is a series of
characters consisting of letters, digits and underscores ( _ ) that does not begin with a digit
and is not a keyword. C++ is case-sensitive—uppercase and lowercase letters are different.
So, a1 and A1 are different identifiers.
C++ allows identifiers of any length. Do not begin an identifier with an underscore
and a capital letter or two underscores—C++ compilers use such names for their own pur-
poses internally.
By convention, variable-name identifiers begin with a lowercase letter, and every word
in the name after the first word begins with a capital letter. For example, firstNumber
starts its second word, Number, with a capital N. This naming convention is known as camel
case because the uppercase letters stand out like a camel’s humps. Choosing meaningful
identifiers helps make a program self-documenting—a person can understand the pro-
gram simply by reading it rather than referring to program comments or external docu-
mentation. Avoid using abbreviations in identifiers. Although this may require you to type
more keystrokes, it improves program readability.

Placement of Variable Declarations


Variable declarations can be placed almost anywhere in a program, but they must appear
before the variables are used. For example, the declaration in line 8
int number1{0}; // first integer to add (initialized to 0)

could have been placed immediately before line 13:


std::cin >> number1; // read first integer from user into number1

the declaration in line 9:


int number2{0}; // second integer to add (initialized to 0)

could have been placed immediately before line 16:


std::cin >> number2; // read second integer from user into number2

and the declaration in line 10:


int sum{0}; // sum of number1 and number2 (initialized to 0)

could have been placed immediately before line 18:


sum = number1 + number2; // add the numbers; store result in sum

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

Obtaining the First Value from the User


Line 12
std::cout << "Enter first integer: "; // prompt user for data
74 Chapter 2 Intro to C++20 Programming

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.

Obtaining the Second Value from the User


Line 15
std::cout << "Enter second integer: "; // prompt user for data

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

obtains a value for variable number2 from the user.

Calculating the Sum of the Values Input by the User


The assignment statement in line 18
sum = number1 + number2; // add the numbers; store result in sum

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.

Displaying the Result


Line 20
std::cout << "Sum is " << sum << "\n"; // display sum

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.

2.5 Memory Concepts


Variable names such as number1, number2 and sum correspond to locations in the computer’s
memory. Every variable has a name, a type, a size (determined by the type) and a value.
In the addition program of Fig. 2.4, when the following statement (line 13) executes
std::cin >> number1; // read first integer from user into number1

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

The variables’ locations are not necessarily adjacent in memory.


After the program obtains values for number1 and number2, it adds these values and
places the total into the variable sum. The statement (line 18)
sum = number1 + number2;
76 Chapter 2 Intro to C++20 Programming

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:

Operation Arithmetic operator Algebraic expression C++ expression

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

Parentheses for Grouping Subexpressions


Parentheses are used in C++ expressions in the same manner as in algebraic expressions.
For example, to multiply x times the quantity y + z, we write x * (y + z).
Rules of Operator Precedence
C++ applies the operators in arithmetic expressions in a precise order determined by the
following rules of operator precedence, which are generally the same as those in algebra:
1. Expressions in parentheses evaluate first. Parentheses are said to be at the “highest
level of precedence.” In cases of nested or embedded parentheses, as in the fol-
lowing statement, expressions in the innermost pair of parentheses evaluate first:
(a * (b + c))
2. Multiplication, division and remainder operations evaluate next. In an expression
containing several of these operations, they’re applied from left to right. These
three operators have the same level of precedence.
3. Addition and subtraction operations evaluate last and are applied from left to
right. Addition and subtraction have the same level of precedence.
You can view the complete operator precedence chart at https://en.cppreference.com/
w/cpp/language/operator_precedence. Caution: In an expression with two sets of paren-
theses “on the same level,” such as such as (a + b) * (c - d), the C++ Standard does not spec-
ify the order in which these parenthesized subexpressions will evaluate.
Operator Grouping
When we say that C++ applies certain operators from left to right, we are referring to the
operators’ grouping (sometimes called associativity). For example, in the expression
a + b + c
the addition operators (+) group from left-to-right as if we parenthesized the expression as
(a + b) + c. Most C++ operators of the same precedence group from left to right. We’ll see
that some operators group from right to left.
Sample Algebraic and C++ Expressions
Now consider several expressions in light of the rules of operator precedence. Each exam-
ple lists an algebraic expression and its C++ equivalent. The following is an example of an
arithmetic mean (average) of five terms:
a+b+c+d+e
Algebra: m = -------------------------------------
5
C++: m = (a + b + c + d + e) / 5;

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.

Evaluation of a Second-Degree Polynomial


To develop a better understanding of the rules of operator precedence, consider the eval-
uation of a second-degree polynomial y = ax2 + bx + c:
y = a * x * x + b * x + c;

6 1 2 4 3 5

There is no arithmetic operator for exponentiation in C++, so we’ve represented x 2 as


x * x. The circled numbers under the statement indicate the order in which C++ applies
the operators. The assignment operator is applied last because its precedence is lowest
among the operators in the statement.
Suppose variables a, b, c and x in the preceding second-degree polynomial are initial-
ized as follows: a = 2, b = 3, c = 7 and x = 5. The following diagram illustrates the order in
which the operators are applied and the final value of the expression:
Step 1. y = 2 * 5 * 5 + 3 * 5 + 7; (Leftmost multiplication)
2 * 5 is 10

Step 2. y = 10 * 5 + 3 * 5 + 7; (Leftmost multiplication)


10 * 5 is 50

Step 3. y = 50 + 3 * 5 + 7; (Multiplication before addition)


3 * 5 is 15

Step 4. y = 50 + 15 + 7; (Leftmost addition)


50 + 15 is 65

Step 5. y = 65 + 7; (Last addition)


65 + 7 is 72

Step 6. y = 72 (Low-precedence assignment—place 72 in y)

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)

2.7 Decision Making: Equality and Relational Operators


We now introduce C++’s if statement, which allows a program to perform different
actions based on whether a condition is true or false. Conditions in if statements can be
formed by using the relational operators and equality operators in the following table:

Algebraic relational C++ relational or Sample C++


or equality operator equality operator condition Meaning of C++ condition

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

≤ <= x <= y x is less 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

Using the if Statement


The program of Fig. 2.5 (followed by several executions) uses six if statements to compare
two integers input by the user. If a given if statement’s condition is true, the output state-
ment in the body of that if statement executes. If the condition is false, the output state-
ment in the body is skipped.

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

Enter two integers to compare: 3 7


3 != 7
3 < 7
3 <= 7

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

Enter two integers to compare: 22 12


22 != 12
22 > 12
22 >= 12

Enter two integers to compare: 7 7


7 == 7
7 <= 7
7 >= 7

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

Variable Declarations and Reading the Inputs from the User


Lines 11–12
int number1{0}; // first integer to compare (initialized to 0)
int number2{0}; // second integer to compare (initialized to 0)

declare the variables used in the program and initialize them to 0.


Line 15
cin >> number1 >> number2; // read two integers from user

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.

Braces and Blocks


Each if statement in Fig. 2.5 contains a single body statement that’s indented to enhance
readability. Also, notice that we’ve enclosed each body statement in a pair of braces, { },
creating what’s called a compound statement or a block.
You don’t need to use braces around single-statement bodies, but you must include
the braces around multiple-statement bodies. Forgetting to enclose multiple-statement
Err bodies in braces leads to errors. To avoid such errors, as a rule, always enclose an if state-
ment’s body statement(s) in braces. Also, indent the statement(s) in an if statement’s
block to enhance readability.

Err Common Logic Error: Placing a Semicolon after a Condition


Placing a semicolon immediately after the right parenthesis of the condition in an if state-
ment is often a logic error (although not a syntax error). The semicolon causes the body
of the if statement to be empty, so the if statement performs no action, regardless of
whether or not its condition is true. Worse yet, the original body statement of the if state-
ment now becomes a statement in sequence with the if statement and always executes,
often causing the program to produce incorrect results. All three of our preferred compilers
issue a warning for this logic error.

Splitting Lengthy Statements


A lengthy statement may be spread over several lines. If you must do this, choose mean-
ingful breaking points, such as after a comma in a comma-separated list or after an oper-
ator in a lengthy expression. If a statement is split across two or more lines, it’s a good
practice to indent all subsequent lines.

Operator Precedence and Grouping


Except for the assignment operator =, all the operators presented in this chapter group from
left to right. Assignments (=) group from right to left. So, an expression such as x = y = 0
evaluates as if it had been written x = (y = 0), which first assigns 0 to y, then assigns to x
the result of that assignment—that is, the value of y, which is now 0.
Refer to the complete operator-precedence chart at https://en.cppreference.com/
w/cpp/language/operator_precedence when writing expressions containing many oper-
ators. Confirm that the operators in the expression are performed in the order you expect.
If you’re uncertain about the order of evaluation in a complex expression, break the expres-
sion into a sequence of smaller statements or use parentheses to force the order of evalua-
tion, just as you’d do in an algebraic expression.
2.8 Creating and Using Objects of Standard-Library Class string 83

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.

2.8 Objects Natural Case Study: Creating and Using


Objects of Standard-Library Class string
Throughout this book, we emphasize using valuable preexisting classes from the C++ stan-
dard library and various libraries from the C++ open-source community. You’ll focus on
knowing what libraries are out there, choosing the ones you’ll need for your applications,
creating objects from existing library classes and making those objects exercise their capa-
bilities. By Objects Natural, we mean that you’ll be able to conveniently create and pro-
gram with powerful objects even before you learn to create your own custom classes in
Chapter 9.
You’ve already worked with C++ objects—specifically the cout and cin objects,
which encapsulate the mechanisms for output and input, respectively. These objects were
created for you behind the scenes using classes from the header <iostream>. In this sec-
tion, you’ll create and interact with objects of the C++ standard library’s string3 class.

Test-Driving Class string


Classes cannot execute by themselves. A Person object can drive a Car object by telling it
what to do (go faster, go slower, turn left, turn right, etc.) without knowing how the car’s
internal mechanisms work. Similarly, the main function can “drive” a string object by
calling its member functions—without knowing how the class is implemented. In this
sense, main in the following program is referred to as a driver program. Figure 2.6’s main
function test-drives several string objects.

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 }

s1: "happy"; length: 5


s2: " birthday"; length: 9
s3: ""; length: 0

The results of comparing s2 and s1:


s2 == s1: false
s2 != s1: true

Testing s3.empty():
s3 is empty; assigning to s3;
s3: "happy birthday"

s1 starts with "ha": true


s2 starts with "ha": false
s1 ends with "ay": false
s2 ends with "ay": true

Fig. 2.6 | Standard library string class test program.


2.8 Creating and Using Objects of Standard-Library Class string 85

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.

string Member Function length


Lines 13–15 output each string and its length. The string class’s length member func-
tion returns the number of characters stored in a particular string object. In line 13, the
expression
s1.length()

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

Comparing string Objects with the Equality Operators


Like numbers, strings can be compared with one another. Lines 18–20 compare s2 to s1
using the equality operators—string comparisons are case sensitive.5
Usually, when you output a condition’s value, C++ displays 0 for false or 1 for true.
The stream manipulator boolalpha (line 18) from the <iostream> header tells the output
stream to display condition values more naturally as the words false or true.

string Member Function empty


Line 25 calls string member function empty, which returns true if the string is empty—
that is, the length of the string is 0. Otherwise, empty returns false. The object s3 was
initialized “by default” to the empty string, so it is indeed empty, and the body of the if
statement will execute.

string Concatenation and Assignment


Line 27 assigns a new value to s3 produced by “adding” the strings s1 and s2 using the +
operator—known as string concatenation. After the assignment, s3 contains the charac-
ters of s1 followed by the characters of s2—"happy birthday". Line 28 outputs s3 to
demonstrate that the assignment worked correctly.

C++20 string Member Functions starts_with and ends_with


Lines 32–35 demonstrate C++20 string member functions starts_with and ends_with,
which return true if the string starts with or ends with a specified substring, respectively;
otherwise, they return false. Lines 32 and 33 show that s1 starts with "ha", but s2 does
not. Lines 34 and 35 show that s1 does not end with "ay" but s2 does.

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

Finally, we introduced our “Objects Natural” approach to learning C++ by creating


objects of the C++ standard library class string and interacting with them using equality
operators and string member functions. In subsequent chapters, you’ll create and use many
objects of existing classes to accomplish significant tasks with minimal amounts of code.
Then, in Chapters 9–11, you’ll create your own custom classes. You’ll see that C++ enables
you to “craft valuable classes.” In the next chapter, we begin our introduction to control
statements, which specify the order in which a program’s actions are to be performed.

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

a) Declare the variables c, thisIsAVariable, q76354 and number to be of type int


(in one statement) and initialize each to 0.
b) Prompt the user to enter an integer. End your prompting message with a colon
(:) followed by a space, and leave the cursor positioned after the space.
c) Read an integer from the user at the keyboard and store it in int variable age.
d) If the variable number is not equal to 7, print "The variable number is not
equal to 7".
e) Print "This is a C++ program" on one line.
f) Print "This is a C++ program" on two lines. End the first line with C++.
g) Print "This is a C++ program" with each word on a separate line.
h) Print "Enter two numbers".
i) Assign the product of variables b and c to variable a.
j) State that a program performs a payroll calculation (i.e., use text that helps to
document a program).
k) Input three integer values from the keyboard into integer variables a, b and c.
2.5 Identify and correct the errors in each of the following statements (assume that the
statement using std::cout; is used):
a) if (c < 7); {
cout << "c is less than 7\n";
}
b) if (c => 7) {
cout << "c is equal to or greater than 7\n";
}

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.17 What does the following code print?


cout << "*\n**\n***\n****\n*****\n";

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

This is called a cast operation. The expression static_cast<int>('A') converts the


character 'A' to its integer equivalent 65 (on systems that use the ASCII character set or
Unicode character set). Write a program that prints the integer equivalent of a character
the user enters at the keyboard. Store the input in a variable of type char. Test your pro-
gram several times using uppercase letters, lowercase letters, digits and special characters
(such as $).
2.23 (Digits of an Integer) Write a program that inputs a five-digit integer, separates the
integer into its digits and prints them with three spaces between each. For example, if the
user types in 42339, the program should print:

4 2 3 3 9

[Hint: Use the integer division and remainder operators.]


Exercises 91

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:

integer square cube


0 0 0
1 1 1
2 4 8
3 9 27
4 16 64
5 25 125
6 36 216
7 49 343
8 64 512
9 81 729
10 100 1000

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

Addition Program Pseudocode


Let’s look at a pseudocode example that might help a programmer create the addition pro-
gram of Fig. 2.4. The following pseudocode corresponds to the algorithm that inputs two
integers from the user, adds them and displays their sum. We show the complete pseudo-
code listing here. We’ll show how to create pseudocode from a problem statement later in
the chapter.

1 Prompt the user to enter the first integer


2 Input the first integer
3
4 Prompt the user to enter the second integer
5 Input the second integer
6
7 Add first integer and second integer, store result
8 Display result

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.

3.4 Control Structures


Typically, program statements execute one after the other in the order in which they’re
written. This process is called sequential execution. Various C++ statements, which we’ll
soon discuss, enable you to specify that the next statement to execute is not necessarily the
next one in sequence. This is called transfer of control.
During the 1960s, it became clear that the indiscriminate use of transfers of control
was the root of many problems experienced by software development groups. The blame
was pointed at the goto statement (used in most programming languages of the time),
which allows you to specify a transfer of control to one of a wide range of destinations in
a program.
The research of Böhm and Jacopini1 demonstrated that programs could be written
without any goto statements. The challenge for the era’s programmers was shifting their
styles to “goto-less programming.” The term structured programming became almost

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.

3.4.1 Sequence Structure


The sequence structure is built into C++. Unless directed otherwise, statements execute
one after the other in the order they appear in the program—that is, in sequence. The fol-
lowing UML2 activity diagram illustrates a typical sequence structure in which two calcu-
lations are performed in order:

Corresponding C++ statement:


add grade to total
total = total + grade;

Corresponding C++ statement:


add 1 to counter
counter = counter + 1;

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.

3.4.2 Selection Statements


C++ has three types of selection statements. The if selection statement performs (selects)
an action (or group of actions) if a condition is true or skips it if the condition is false. The
if…else selection statement performs an action (or group of actions) if a condition is true
and performs a different action (or group of actions) if the condition is false. The switch
selection statement (Chapter 4) performs one of many different actions (or groups of
actions), depending on the value of an expression.
The if statement is called a single-selection statement because it selects or ignores a
single action (or group of actions). The if…else statement is called a double-selection
statement because it selects between two different actions (or groups of actions). The
switch statement is called a multiple-selection statement because it selects among many
different actions (or groups of actions).

3.4.3 Iteration Statements


C++ provides four iteration statements—also called repetition statements or looping
statements—for performing statements repeatedly while a loop-continuation condition
remains true. The iteration statements are the while, do…while, for and range-based
for. The while and for statements perform their action (or group of actions) zero or more
times. If the loop-continuation condition is initially false, the action (or group of actions)
does not execute. The do…while statement performs its action (or group of actions) one
or more times. Chapter 4 presents the do…while and for statements. Chapter 6 presents
the range-based for statement.

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

alignas alignof and and_eq asm


auto bitand bitor bool break
case catch char char16_t char32_t
class compl const const_cast constexpr
3.4 Control Structures 99

C++ keywords (Cont.)

continue decltype default delete do


double dynamic_cast else enum explicit
export extern false final float
for friend goto if import
inline int long module mutable
namespace new noexcept not not_eq
nullptr operator or or_eq override
private protected public register reinterpret_cast
return short signed sizeof static
static_assert static_cast struct switch template
this thread_local throw true try
typedef typeid typename union unsigned
using void volatile virtual wchar_t
while xor xor_eq

Keywords new in C++20


char8_t concept consteval constinit co_await
co_return co_yield requires

3.4.4 Summary of Control Statements


C++ has only three kinds of control structures, which from this point forward, we refer to
as control statements:
• sequence,
• selection (if, if…else and switch) and
• iteration (while, do…while, for and range-based for).
You form every program by combining these statements as appropriate for the algorithm
you’re implementing. We can model each control statement as an activity diagram. Each
diagram contains initial and final states representing a control statement’s entry and exit
points. Single-entry/single-exit control statements make it easy to build readable pro-
grams—we simply connect the exit point of one to the entry point of the next using con-
trol-statement stacking. There’s only one other way in which you may connect control
statements—control-statement nesting, in which one control statement appears inside
another. Thus, algorithms in C++ programs are constructed from only three kinds of con-
trol statements combined in only two ways. This is the essence of simplicity.

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.

3.5 if Single-Selection Statement


We introduced the if single-selection statement briefly in Section 2.7. Programs use selec-
tion statements to choose among alternative courses of action. For example, suppose that
the passing grade on an exam is 60. The following pseudocode represents an if statement
that tests the condition “student’s grade is greater than or equal to 60”:
if student’s grade is greater than or equal to 60
print “Passed”
If this condition is true, the statement prints “Passed”—otherwise, the print statement is
ignored. Indenting the second line of this selection statement is optional but recom-
mended for clarity—it emphasizes that the print statement is in the if statement’s body.
The preceding pseudocode may be written in C++ as
if (studentGrade >= 60) {
cout << "Passed";
}

The C++ code corresponds closely to the pseudocode.

bool Data Type


In Chapter 2, you created conditions using the relational or equality operators. Actually,
any expression that evaluates to zero or nonzero can be used as a condition. Zero is treated
as false, and nonzero is treated as true. C++ also provides the data type bool for Boolean
variables that can hold only the values true and false—each is a C++ keyword. The com-
piler can implicitly convert true to 1 and false to 0.

UML Activity Diagram for an if Statement


The following UML activity diagram illustrates the single-selection if statement.

[studentGrade >= 60]


print “Passed”
[studentGrade < 60]
3.6 if…else Double-Selection Statement 101

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.";
}

3 (Fill-in) A diamond, or decision symbol, in an activity diagram indicates that a deci-


sion is to be made. The workflow continues along a path determined by the symbol’s asso-
ciated .
Answer: guard conditions.

3.6 if…else Double-Selection Statement


The if single-selection statement performs an indicated action only when the condition
is true. The if…else double-selection statement allows you to specify an action to per-
form when the condition is true and another action when the condition is false. For exam-
ple, the following pseudocode represents an if…else statement that prints “Passed” if the
student’s grade is greater than or equal to 60 but prints “Failed” if it’s less than 60:
if student’s grade is greater than or equal to 60
print “Passed”
else
print “Failed”
In either case, after printing occurs, the next statement in sequence is “performed.” The
preceding if…else pseudocode statement can be written in C++ as
102 Chapter 3 Algorithm Development and Control Statements: Part 1

if (studentGrade >= 60) {


cout << "Passed";
}
else {
cout << "Failed";
}

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.

UML Activity Diagram for an if…else Statement


The following diagram illustrates the flow of control in the preceding if…else statement:

[studentGrade < 60] [studentGrade >= 60]


print “Failed” print “Passed”

3.6.1 Nested if…else Statements


A program can test multiple cases by placing if…else statements inside other if…else
statements to create nested if…else statements. For example, the following pseudocode
represents a nested if…else statement that prints "A" for exam grades greater than or
equal to 90, "B" for grades 80 to 89, "C" for grades 70 to 79, "D" for grades 60 to 69 and
"F" for all other grades. We use shading to highlight the nesting:

if student’s grade is greater than or equal to 90


print “A”
else
if student’s grade is greater than or equal to 80
print “B”
else
if student’s grade is greater than or equal to 70
print “C”
else
if student’s grade is greater than or equal to 60
print “D”
else
print “F”
3.6 if…else Double-Selection Statement 103

This pseudocode may be written in C++ as:

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";
}
}
}
}

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.

Syntax and Logic Errors


The compiler catches syntax errors, such as when one brace in a block is left out of the
program. A logic error, such as an incorrect calculation, has its effect at execution time. A
fatal logic error causes a program to fail and terminate prematurely. A nonfatal logic error
allows a program to continue executing but causes it to produce incorrect results.

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).

3.6.3 Conditional Operator (?:)


C++ provides the conditional operator (?:), which can be used in place of an if…else
statement. This can make your code shorter and clearer. The conditional operator is C++’s
only ternary operator (i.e., an operator that takes three operands). Together, the operands
and the ?: symbol form a conditional expression. For example, the following statement
prints the conditional expression’s value:
cout << (studentGrade >= 60 ? "Passed" : "Failed");
3.7 while Iteration Statement 105

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.";
}

3.7 while Iteration Statement


An iteration statement allows you to specify that a program should repeat an action while
some condition remains true. The pseudocode statement
106 Chapter 3 Algorithm Development and Control Statements: Part 1

while there are more items on my shopping list


purchase next item and cross it off my list
describes the iteration during a shopping trip. The condition “there are more items on my
shopping list” may be true or false. If it’s true, the action “purchase next item and cross it
off my list” is performed. This action will be performed repeatedly while the condition
remains true. The statement(s) contained in the while iteration statement constitute its
body, which may be a single statement or a block. Eventually, the condition will become
false (when the shopping list’s last item has been purchased and crossed off). At this point,
the iteration terminates, and the first statement after the iteration statement executes.
As a while iteration statement example, consider the following program segment that
finds the first power of 3 larger than 100:
int product{3};

while (product <= 100) {


product = 3 * product;
}

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).

UML Activity Diagram for a while Statement


The following while statement UML activity diagram introduces the merge symbol:

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};

while (product <= 1000000) {


product = 2 * product;
n = n + 1;
}

cout << "First power of 2 greater than 1000000 is " << product
<< "\nwhich is 2 to the power of " << n << "\n";

First power of 2 greater than 1000000 is 1048576


which is 2 to the power of 20

3.8 Formulating Algorithms: Counter-Controlled Iteration


To illustrate how algorithms are developed, we solve two variations of a problem that aver-
ages student grades. Consider the following problem statement:
A class of ten students took a quiz. The quiz grades (integers in the range 0–100)
are available to you. Determine the class average on the quiz.
The class average is equal to the sum of the grades divided by the number of students. The
program must input each grade, total all the grades entered, perform the averaging calcu-
lation and print the result.

3.8.1 Pseudocode Algorithm with Counter-Controlled Iteration


Let’s use pseudocode to list the actions to execute and specify the order in which they
should execute. We use counter-controlled iteration to input the grades one at a time.
This technique uses a variable called a counter (or control variable) to control the number
of times a set of statements will execute. Counter-controlled iteration is often called defi-
nite iteration because the number of iterations is known before the loop begins executing.
In this example, iteration terminates when the counter exceeds 10. This section presents
the following fully developed pseudocode algorithm and a corresponding C++ program
(Fig. 3.1) that implements the algorithm. In Section 3.9, we demonstrate how to develop
pseudocode algorithms from scratch.
108 Chapter 3 Algorithm Development and Control Statements: Part 1

1 set total to zero


2 set grade counter to one
3
4 while grade counter is less than or equal to ten
5 prompt the user to enter the next grade
6 input the next grade
7 add the grade into the total
8 add one to the grade counter
9
10 set the class average to the total divided by ten
11 print the class average

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.

3.8.2 Implementing Counter-Controlled Iteration


In Fig. 3.1, the main function calculates the class average with counter-controlled itera-
tion. It allows the user to enter 10 grades, then calculates and displays the average.

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

Total of all 10 grades is 846


Class average is 84

Fig. 3.1 | Solving the class-average problem using counter-controlled iteration. (Part 2 of 2.)

Local Variables in main


Lines 8, 9, 14 and 21 declare int variables total, gradeCounter, grade and average,
respectively. Variable grade stores the user input. A variable declared in a block (such as a
function’s body) is a local variable that can be used only from the line of its declaration to
the closing right brace of the block. A local variable’s declaration must appear before the
variable is used. Variable grade—declared at line 14 the while loop’s body—can be used
only in that block.

Initializing Variables total and gradeCounter


Lines 8–9 declare and initialize total to 0 and gradeCounter to 1. These initializations
occur before the variables are used in calculations. Initialize each total and counter, either
in its declaration or in an assignment statement. Totals are typically initialized to 0 and
counters are typically initialized to 0 or 1, depending on their use. We’ll show examples of
when to use 0 or 1.

Reading 10 Grades from the User


The while statement (lines 12–18) continues iterating as long as gradeCounter’s value is
less than or equal to 10. Line 13 displays the prompt "Enter grade: ". Line 15 inputs the
grade entered by the user and assigns it to variable grade. Then line 16 adds the new grade
entered by the user to the total and assigns the result to total, replacing its previous
value. Line 17 adds 1 to gradeCounter to indicate that the program has processed a grade
and is ready to input the next grade from the user. Incrementing gradeCounter eventually
causes it to exceed 10, which terminates the loop.

Calculating and Displaying the Class Average


When the loop terminates, line 21 performs the averaging calculation in the average vari-
able’s initializer. Line 24 displays the text "Total of all 10 grades is " followed by vari-
110 Chapter 3 Algorithm Development and Control Statements: Part 1

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.

3.8.3 Integer Division and Truncation


This example’s average calculation produces an int result. The program’s sample execu-
tion shows that the sum of the grades is 846—when divided by 10, this should yield 84.6.
Numbers like 84.6 containing decimal points are floating-point numbers. However, in
the class-average program, total / 10 produces the integer 84 because total and 10 are
both integers. Dividing two integers results in integer division—any fractional part of the
calculation is truncated. The next section shows how to obtain a floating-point result from
the averaging calculation. For example, 7 / 4 yields 1.75 in conventional arithmetic but
Err truncates to 1 in integer arithmetic rather than rounding to 2. Assuming that integer divi-
sion rounds (rather than truncates) can lead to incorrect results.

3.8.4 Arithmetic Overflow


In Fig. 3.1, line 16
total = total + grade; // add grade to total

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.

3.8.5 Input Validation


When a program receives input from the user, various problems might occur. For example,
line 15 of Fig. 3.1
cin >> grade; // input next grade

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};

while (count < 5) {


count = count + 1;
cout << "count is :" << count << "\n";
}

Answer:
int count{0};

while (count < 5) {


count = count + 1;
cout << "count is :" << count << "\n";
}

count is: 1
count is: 2
count is: 3
count is: 4
count is: 5

3.9 Formulating Algorithms: Sentinel-Controlled


Iteration
Let’s generalize Section 3.8’s class-average problem. Consider the following problem:
Develop a class-averaging program that processes grades for an arbitrary number
of students each time it is run.
In the previous class-average example, the problem statement specified the number of stu-
dents, so the number of grades (10) was known in advance. For this problem, we do not
know how many grades the user will enter during the program’s execution. The program
must process an arbitrary number of grades.
112 Chapter 3 Algorithm Development and Control Statements: Part 1

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.

3.9.1 Top-Down, Stepwise Refinement: The Top and First Refinement


We approach this class-averaging program with a technique called top-down, stepwise
refinement, which is essential to the development of well-structured programs. We begin
with a pseudocode representation of the top—a single statement that conveys the overall
function of the program:
determine the class average for the quiz
The top is, in effect, a complete representation of a program. Unfortunately, the top rarely
conveys sufficient detail from which to write a C++ program. So we now begin the refine-
ment process. We divide the top into a series of smaller tasks and list these in the order in
which they’ll be performed. This results in the following first refinement:
initialize variables
input, sum and count the quiz grades
calculate and print the class average
This refinement uses only statements in sequence—the steps listed should execute in
SE order, one after the other. Like the top, each refinement is a complete specification of the
algorithm—only the level of detail varies.

3.9.2 Proceeding to the Second Refinement


Sometimes, the first refinement in the top-down process might be all you need. Here, we
must provide more detail, so we proceed to the second refinement, in which we commit
to specific variables. We need
• a running total of the numbers,
• a count of how many numbers we’ve processed,
• a variable to receive each grade entered by the user and
• a variable to hold the calculated average.
3.9 Formulating Algorithms: Sentinel-Controlled Iteration 113

The pseudocode statement


initialize variables
can be refined as follows:
initialize total to zero
initialize counter to zero
Only the variables total and counter need to be initialized before they’re used. The variables
average and grade (for the calculated average and the user input, respectively) need not be
initialized, as their values will be replaced by a calculation or user inputs. Many program-
mers, nevertheless, choose to initialize all variables—as you’ll see later in the book, this can
help avoid subtle errors.
The pseudocode statement
input, sum and count the quiz grades
requires iteration to input each grade. We do not know the number of grades in advance,
so we’ll use sentinel-controlled iteration. The user enters grades one at a time. After the
last grade, the user enters the sentinel value. The program tests for the sentinel value after
each grade is input and terminates the loop when the user enters the sentinel value. The
second refinement of the preceding pseudocode statement is:
prompt the user to enter the first grade
input the first grade (possibly the sentinel)
while the user has not yet entered the sentinel
add this grade into the running total
add one to the grade counter
prompt the user to enter the next grade
input the next grade (possibly the sentinel)
We simply indent the statements under the while to show that they belong to its body.
Again, pseudocode is only an informal program development aid.
The pseudocode statement
calculate and print the class average
can be refined as follows:
if the counter is not equal to zero
set the average to the total divided by the counter
print the average
else
print “No grades were entered”
We’re careful here to test for the possibility of division by zero—a logic error that, if unde- Err
tected, would cause the program to fail or produce invalid output. 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 allowing the
calculation to proceed. Here is the complete second refinement of the pseudocode for the
class-average problem:
114 Chapter 3 Algorithm Development and Control Statements: Part 1

1 initialize total to zero


2 initialize counter to zero
3
4 prompt the user to enter the first grade
5 input the first grade (possibly the sentinel)
6
7 while the user has not yet entered the sentinel
8 add this grade into the running total
9 add one to the grade counter
10 prompt the user to enter the next grade
11 input the next grade (possibly the sentinel)
12
13 if the counter is not equal to zero
14 set the average to the total divided by the counter
15 print the average
16 else
17 print “No grades were entered”

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.

3.9.3 Implementing Sentinel-Controlled Iteration


Figure 3.2 implements sentinel-controlled iteration. Although each grade entered by the
user is an integer, the average calculation will likely produce a floating-point number,
which an int cannot represent. C++ provides types float, double and long double to
store floating-point numbers:
• A double variable typically stores numbers with larger magnitude and finer detail
than a float—that is, more digits to the right of the decimal point, also known
as the number’s precision.
• Similarly, a long double variable typically stores values with larger magnitude
and more precision than double.
To calculate a floating-point average in this example, we’ll store the total as a double—
C++’s default type for floating-point literals, such as -7.2, 0.0 or 98.6.
3.9 Formulating Algorithms: Sentinel-Controlled Iteration 115

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 }

Enter grade or -1 to quit: 97


Enter grade or -1 to quit: 88
Enter grade or -1 to quit: 72
Enter grade or -1 to quit: -1

Total of the 3 grades entered is 257


Class average is 85.67

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

Enter grade or -1 to quit: -1


No grades were entered

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.

3.9.4 Mixed-Type Expressions and Implicit Type Promotions


If at least one grade was entered, line 32
double average{total / gradeCounter};

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-

You might also like