PDF Readings from Programming with C++ 1st Edition Kyla Mcmullen download
PDF Readings from Programming with C++ 1st Edition Kyla Mcmullen download
com
https://ebookmeta.com/product/readings-from-programming-
with-c-1st-edition-kyla-mcmullen-2/
OR CLICK HERE
DOWLOAD NOW
https://ebookmeta.com/product/readings-from-programming-with-c-1st-
edition-kyla-mcmullen/
ebookmeta.com
https://ebookmeta.com/product/ergodic-theory-geometry-and-
dynamics-1st-edition-c-mcmullen/
ebookmeta.com
https://ebookmeta.com/product/frontiers-of-supercomputing-ii-karyn-r-
ames-editor/
ebookmeta.com
https://ebookmeta.com/product/blender-basics-classroom-tutorial-book-
based-on-the-blender-2-7x-series-5th-edition-james-chronister/
ebookmeta.com
https://ebookmeta.com/product/feudal-institutions-as-revealed-in-the-
assizes-of-romania-the-law-code-of-frankish-greece-peter-w-topping-
editor/
ebookmeta.com
https://ebookmeta.com/product/reeds-vhf-dsc-handbook-1st-edition-sue-
fletcher/
ebookmeta.com
Programming with
Copyright 2022 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part. Due to electronic rights, some third party content may be suppressed from the eBook and/or eChapter(s).
Editorial review has deemed that any suppressed content does not materially affect the overall learning experience. Cengage Learning reserves the right to remove additional content at any time if subsequent rights restrictions require it.
This is an electronic version of the print textbook. Due to electronic rights restrictions,
some third party content may be suppressed. Editorial review has deemed that any suppressed
content does not materially affect the overall learning experience. The publisher reserves the right
to remove content from this title at any time if subsequent rights restrictions require it. For
valuable information on pricing, previous editions, changes to current editions, and alternate
formats, please visit www.cengage.com/highered to search by ISBN#, author, title, or keyword for
materials in your areas of interest.
Important Notice: Media content referenced within the product description or the product
text may not be available in the eBook version.
Copyright 2022 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part. Due to electronic rights, some third party content may be suppressed from the eBook and/or eChapter(s).
Editorial review has deemed that any suppressed content does not materially affect the overall learning experience. Cengage Learning reserves the right to remove additional content at any time if subsequent rights restrictions require it.
Readings from Programming with C++ © 2022 Cengage Learning, Inc.
Kyla McMullen, Elizabeth Matthews, WCN: 02-300
June Jamrich Parsons
Unless otherwise noted, all content is © Cengage.
SVP, Higher Education Product Management:
ALL RIGHTS RESERVED. No part of this work covered by the copyright herein
Erin Joyner
may be reproduced or distributed in any form or by any means, except as
VP, Product Management: Thais Alencar permitted by U.S. copyright law, without the prior written permission of the
copyright owner.
Product Team Manager: Kristin McNary
Associate Product Manager: Tran Pham For product information and technology assistance, contact us at
Cengage Customer & Sales Support, 1-800-354-9706
Product Assistant: Tom Benedetto
or support.cengage.com.
Learning Designer: Mary Convertino
Senior Content Manager: Maria Garguilo For permission to use material from this text or product, submit all requests
online at www.cengage.com/permissions.
Digital Delivery Lead: David O’Connor
Marketing Development Manager: Cengage is a leading provider of customized learning solutions with
Samantha Best employees residing in nearly 40 different countries and sales in more than
125 countries around the world. Find your local representative at
Product Specialist: Mackenzie Paine
www.cengage.com.
IP Analyst: Ashley Maynard
To learn more about Cengage platforms and services, register or access
IP Project Manager: Cassidie Parker your online learning solution, or purchase materials for your course, visit
www.cengage.com.
Production Service: SPi Global
Notice to the Reader
Designer: Erin Griffin Publisher does not warrant or guarantee any of the products described
Cover Image Source: echo3005/ShutterStock.com herein or perform any independent analysis in connection with any of the
product information contained herein. Publisher does not assume, and
expressly disclaims, any obligation to obtain and include information other
than that provided to it by the manufacturer. The reader is expressly warned
to consider and adopt all safety precautions that might be indicated by the
activities described herein and to avoid all potential hazards. By following
the instructions contained herein, the reader willingly assumes all risks in
connection with such instructions. The publisher makes no representations or
warranties of any kind, including but not limited to, the warranties of fitness
for particular purpose or merchantability, nor are any such representations
implied with respect to the material set forth herein, and the publisher takes
no responsibility with respect to such material. The publisher shall not be
liable for any special, consequential, or exemplary damages resulting, in
whole or part, from the readers’ use of, or reliance upon, this material.
Printed in Mexico
Print Number: 01 Print Year: 2020
Copyright 2022 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part. Due to electronic rights, some third party content may be suppressed from the eBook and/or eChapter(s).
Editorial review has deemed that any suppressed content does not materially affect the overall learning experience. Cengage Learning reserves the right to remove additional content at any time if subsequent rights restrictions require it.
Brief Contents
prefacexiii Module 17
Polymorphism 309
Module 1
Computational Thinking 1 Module 18
Templates 319
Module 2
Programming Tools 15 Module 19
Linked List Data Structures 333
Module 3
Literals, Variables, and Constants 35 Module 20
Stacks and Queues 353
Module 4
Numeric Data Types and Expressions 49 Module 21
Trees and Graphs 371
Module 5
Character and String Data Types 63 Module 22
Algorithm Complexity and Big-O Notation 395
Module 6
Decision Control Structures 83 Module 23
Search Algorithms 411
Module 7
Repetition Control Structures 103 Module 24
Sorting Algorithms 427
Module 8
Arrays 125 Module 25
Processor Architecture 455
Module 9
Functions 145 Module 26
Data Representation 469
Module 10
Recursion 165 Module 27
Programming Paradigms 491
Module 11
Exceptions 185 Module 28
User Interfaces 507
Module 12
File Operations 205 Module 29
Software Development Methodologies 525
Module 13
Classes and Objects 231 Module 30
Pseudocode, Flowcharts, and Decision Tables 541
Module 14
Methods 245 Module 31
Unified Modeling Language 557
Module 15
Encapsulation 271
GLOSSARY 569
Module 16 Index 583
Inheritance 291
Copyright 2022 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part. Due to electronic rights, some third party content may be suppressed from the eBook and/or eChapter(s).
Editorial review has deemed that any suppressed content does not materially affect the overall learning experience. Cengage Learning reserves the right to remove additional content at any time if subsequent rights restrictions require it.
Table of Contents
Copyright 2022 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part. Due to electronic rights, some third party content may be suppressed from the eBook and/or eChapter(s).
Editorial review has deemed that any suppressed content does not materially affect the overall learning experience. Cengage Learning reserves the right to remove additional content at any time if subsequent rights restrictions require it.
Table of Contents v
Module 4 Module 6
Numeric Data Types and Decision Control
Expressions 49 Structures 83
Primitive Data Types 50 If-Then Control Structures 84
Data Types 50 Control Structures 84
Primitive Data Types 50 Decision Logic 85
Composite Data Types 51 If-Then Structures 85
Numeric Data Types 52 Relational Operators 87
Integer Data Types 52 The Equal Operator 87
Floating-Point Data Types 53 Using Relational Operators 88
Mathematical Expressions 54 Boolean Expressions and Data Types 89
Arithmetic Operators 54 Multiple Conditions 91
Order of Operations 56 If-Then-Else Structures 91
Compound Operators 56 Nested-If Structures 93
Numeric Data Type Conversion 58 Else If Structures 96
Convert Integers and Floating-Point Numbers 58 Fall Through 97
Rounding Quirks 59 Conditional Logical Operators 100
Formatting Output 60 The AND Operator 100
Formatted Output 60 The OR Operator 101
Formatting Parameters 60 Summary 102
Summary 62 Key Terms 102
Key Terms 62
Module 7
Module 5 Repetition Control
CHARACTER AND STRING DATA TYPES 63 Structures 103
Character Data Types 64 Count-Controlled Loops 104
Working with Character Data 64 Loop Basics 104
Character Memory Allocation 65 Control Statements 105
Digits 66 For-Loops 105
Character Output Format 67 User-Controlled Loops 108
Character Manipulation 68
Counters and Accumulators 109
String Data Types 69 Loops That Count 109
Working with String Data 69 Loops That Accumulate 111
Escape Characters 70
String Indexes 71
Nested Loops 112
Loops Within Loops 112
String Functions 72
Inner and Outer Loops 113
String Manipulation 72
String Length 72 Pre-Test Loops 116
Change Case 73 While-Loops 116
Find the Location of a Character 74 Infinite Loops 117
Retrieve a Substring 75 Breaking Out of Loops 118
Concatenation and Typecasting 76 Post-Test Loops 120
Concatenated Output 76 Do-Loops 120
Concatenated Variables 77 Test Conditions and Terminating
Coercion and Typecasting 78 Conditions 123
Summary 80 Summary 124
Key Terms 81 Key Terms 124
Copyright 2022 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part. Due to electronic rights, some third party content may be suppressed from the eBook and/or eChapter(s).
Editorial review has deemed that any suppressed content does not materially affect the overall learning experience. Cengage Learning reserves the right to remove additional content at any time if subsequent rights restrictions require it.
vi Programming with C++
Copyright 2022 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part. Due to electronic rights, some third party content may be suppressed from the eBook and/or eChapter(s).
Editorial review has deemed that any suppressed content does not materially affect the overall learning experience. Cengage Learning reserves the right to remove additional content at any time if subsequent rights restrictions require it.
Table of Contents vii
Reading from a File 216 Method Cascading and Method Chaining 263
Opening a File for Reading 216 Calling Multiple Methods on the Same Object 263
Reading from a File 218 Using Constructors 266
Closing a File 222 Specifying How to Construct an Object 266
Closing Files after Use 222 Constructing an Object from Another Object 268
Trying to Close a File 222 Summary 269
Creating and Writing New Files 222
Key Terms 269
Creating a File 222
Opening a File for Writing 223 Module 15
Writing to and Appending a File 224
Anticipating Exceptions 228 Encapsulation 271
Summary 229 Components of Class Structure 271
Key Terms 230 Data Hiding 271
Designing Objects 273
Self-Reference Scope 276
Module 13 Accessor and Mutator Context 277
Classes and Objects 231 Viewing Data from an Object 277
Classes in Object-Oriented Programming 232 Changing Data in an Object 278
Representing the Real World with Code 232 Using Constructors 280
Using Classes 232 Parameters and Arguments 280
Class Components 233 Default Parameters and Constructor
Using Objects 236 Overloading 281
Creating Objects 236 Encapsulation Enforcement
Objects as Variables 238 with Access Modifiers 283
Object-Oriented Features and Principles 238 Access Modifiers 283
Using Static Elements in a Class 239 Public Variables and Methods 283
Private Variables and Methods 284
Static Member Variables 239
Static Methods 240 Interfaces and Headers 286
Static Classes 241 Interfaces 286
Characteristics of Objects Programming an Interface 287
in Object-Oriented Programs 242 Summary 290
Object Identity 242 Key Terms 290
Object State 242
Object Behavior 243 Module 16
Summary 244 Inheritance 291
Key Terms 244 Using Inheritance 291
Creating Classes from Other Classes 291
Module 14 Family Trees in OOP 292
Methods 245 Levels of Access 295
Necessary Components for Inheritance 296
Using Methods 245
Defining a Parent Class 296
Why Use Methods? 245 Defining a Child Class 297
Anatomy of a Method 251
Creating a Child Class That Inherits
Using Methods 251
from a Parent Class 298
Changing the Default Behavior
Inheritance Syntax 298
of an Object 255 Customizing Behavior 301
Using Objects as Regular Variables 255
Overloading Methods 258 Summary 307
Setting One Object to Equal Another 262 Key Terms 307
Copyright 2022 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part. Due to electronic rights, some third party content may be suppressed from the eBook and/or eChapter(s).
Editorial review has deemed that any suppressed content does not materially affect the overall learning experience. Cengage Learning reserves the right to remove additional content at any time if subsequent rights restrictions require it.
viii Programming with C++
Copyright 2022 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part. Due to electronic rights, some third party content may be suppressed from the eBook and/or eChapter(s).
Editorial review has deemed that any suppressed content does not materially affect the overall learning experience. Cengage Learning reserves the right to remove additional content at any time if subsequent rights restrictions require it.
Table of Contents ix
Copyright 2022 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part. Due to electronic rights, some third party content may be suppressed from the eBook and/or eChapter(s).
Editorial review has deemed that any suppressed content does not materially affect the overall learning experience. Cengage Learning reserves the right to remove additional content at any time if subsequent rights restrictions require it.
x Programming with C++
Copyright 2022 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part. Due to electronic rights, some third party content may be suppressed from the eBook and/or eChapter(s).
Editorial review has deemed that any suppressed content does not materially affect the overall learning experience. Cengage Learning reserves the right to remove additional content at any time if subsequent rights restrictions require it.
Table of Contents xi
Module 31
Unified Modeling Language 557
Purpose of Unified Modeling
Language (UML) 557
Communicating Ideas to Other Programmers 557
Copyright 2022 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part. Due to electronic rights, some third party content may be suppressed from the eBook and/or eChapter(s).
Editorial review has deemed that any suppressed content does not materially affect the overall learning experience. Cengage Learning reserves the right to remove additional content at any time if subsequent rights restrictions require it.
Copyright 2022 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part. Due to electronic rights, some third party content may be suppressed from the eBook and/or eChapter(s).
Editorial review has deemed that any suppressed content does not materially affect the overall learning experience. Cengage Learning reserves the right to remove additional content at any time if subsequent rights restrictions require it.
Preface
Copyright 2022 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part. Due to electronic rights, some third party content may be suppressed from the eBook and/or eChapter(s).
Editorial review has deemed that any suppressed content does not materially affect the overall learning experience. Cengage Learning reserves the right to remove additional content at any time if subsequent rights restrictions require it.
Copyright 2022 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part. Due to electronic rights, some third party content may be suppressed from the eBook and/or eChapter(s).
Editorial review has deemed that any suppressed content does not materially affect the overall learning experience. Cengage Learning reserves the right to remove additional content at any time if subsequent rights restrictions require it.
About the Authors
Dr. Kyla McMullen is a tenure-track faculty member published research in the areas of procedural genera-
in the University of Florida’s Computer & Information tion, video game enjoyment factors, and freshwater
Sciences & Engineering Department, specializing in algae identification with HCI.
Human-Centered Computing. Her research interests June Jamrich Parsons is an educator, digital book
are in the perception, applications, and development pioneer, and co-author of Texty and McGuffey Award-
of 3D audio technologies. Dr. McMullen has authored winning textbooks. She co-developed the first com-
over 30 manuscripts in this line of research and is the mercially successful multimedia, interactive digital
primary investigator for over 2 million dollars’ worth textbook; one that set the bar for platforms now
of sponsored research projects. being developed by educational publishers. Her
Dr. Elizabeth A. Matthews is an Assistant Professor of career includes extensive classroom teaching, prod-
Computer Science at Washington and Lee University. uct design for eCourseware, textbook authoring for
She has taught computer science since 2013 and has Course Technology and Cengage, Creative Strategist
been an active researcher in human–computer inter- for MediaTechnics Corporation, and Director of Con-
action and human-centered computing. Matthews has tent for Veative Virtual Reality Labs.
Copyright 2022 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part. Due to electronic rights, some third party content may be suppressed from the eBook and/or eChapter(s).
Editorial review has deemed that any suppressed content does not materially affect the overall learning experience. Cengage Learning reserves the right to remove additional content at any time if subsequent rights restrictions require it.
Copyright 2022 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part. Due to electronic rights, some third party content may be suppressed from the eBook and/or eChapter(s).
Editorial review has deemed that any suppressed content does not materially affect the overall learning experience. Cengage Learning reserves the right to remove additional content at any time if subsequent rights restrictions require it.
Acknowledgments
The unique approach for this book required a seasoned friends who help me to remain sane, remind me of who
team. Our thanks to Maria Garguilo who ushered the I am, and never let me forget whose I am.
manuscripts through every iteration and kept tight Elizabeth Matthews: I want to thank my parents,
rein on the schedule; to Mary E. Convertino who sup- Drs. Geoff and Robin Matthews, for their support and
plied her expertise in learning design; to Lisa R
uffolo understanding in my journey. I would also like to thank
for her excellent developmental edit; to Courtney my advisor, Dr. Juan Gilbert, for seeing my dream to
Cozzy who coordinated the project; to Kristin McNary the end. Finally, I would like to thank my cats, Oreo
for her leadership in Cengage’s computing materials; and Laptop, who made sure that writing this book was
to Rajiv Malkan (Lone Star College) for his instruc- interrupted as often as possible.
tional input; to Wade Schofield (Liberty University) June Jamrich Parsons: Computer programming can
for his reviewing expertise; and to John Freitas for his be a truly satisfying experience. The reward when a
meticulous code review. It was a pleasure to be part program runs flawlessly has to bring a smile even
of this professional and talented team. We hope that to the most seasoned programmers. Working with
instructors and students will appreciate our efforts three programming languages for this project at the
to provide this unique approach to computer science same time was certainly challenging but provided
and programming. insights that can help students understand com-
Kyla McMullen: Above all things, I would like to thank putational thinking. I’ve thoroughly enjoyed work-
God for giving me the gifts and talents that were uti- ing with the team to create these versatile learning
lized to write this book. I would like to thank my amaz- resources and would like to dedicate my efforts to
ing husband Ade Kumuyi for always being my rock, my mom, who has been a steadfast cheerleader for
sounding board, and biggest cheerleader. I thank my me throughout my career. To the instructors and stu-
parents, Rita and James McMullen for all of their sacri- dents who use this book, my hope is that you enjoy
fices to raise me. Last but not least, I thank my spirited programming as much as I do.
Copyright 2022 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part. Due to electronic rights, some third party content may be suppressed from the eBook and/or eChapter(s).
Editorial review has deemed that any suppressed content does not materially affect the overall learning experience. Cengage Learning reserves the right to remove additional content at any time if subsequent rights restrictions require it.
Copyright 2022 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part. Due to electronic rights, some third party content may be suppressed from the eBook and/or eChapter(s).
Editorial review has deemed that any suppressed content does not materially affect the overall learning experience. Cengage Learning reserves the right to remove additional content at any time if subsequent rights restrictions require it.
MODULE
1
COMPUTATIONAL
THINKING
LEARNING OBJECTIVES:
1.1 ALGORITHMS 1.2.3 Differentiate the concepts of algorithms and
decomposition.
1.1.1 Define the term “algorithm” as a series of steps for
solving a problem or carrying out a task. 1.2.4 Identify examples of structural decomposition.
1.1.2 State that algorithms are the underlying logic for 1.2.5 Identify examples of functional decomposition.
computer programs. 1.2.6 Identify examples of object-oriented decomposition.
1.1.3 Define the term “computer program.” 1.2.7 Provide examples of decomposition in technology
1.1.4 Provide examples of algorithms used in everyday applications.
technology applications. 1.2.8 Explain how dependencies and cohesion relate to
1.1.5 Confirm that there can be more than one algorithm decomposition.
for a task or problem and that some algorithms 1.3 PATTERN IDENTIFICATION
may be more efficient than others.
1.3.1 Define the term “pattern identification” as a technique
1.1.6 Explain why computer scientists are interested in for recognizing similarities or characteristics among
algorithm efficiency. the elements of a task or problem.
1.1.7 List the characteristics of an effective algorithm. 1.3.2 Identify examples of fill-in-the-blank patterns.
1.1.8 Write an algorithm for accomplishing a simple, 1.3.3 Identify examples of repetitive patterns.
everyday technology application.
1.3.4 Identify examples of classification patterns.
1.1.9 Write an alternate algorithm for an everyday
technology task. 1.3.5 Provide examples of pattern identification in the real
world and in technology applications.
1.1.10 Select the more efficient of the two algorithms you
have written. 1.4 ABSTRACTION
1.2 DECOMPOSITION 1.4.1 Define the term “abstraction” as a technique for
generalization and for simplifying levels of complexity.
1.2.1 Define the term “decomposition” as a technique for
dividing a complex problem or solution into smaller 1.4.2 Explain why abstraction is an important computer
parts. science concept.
1.2.2 Explain why decomposition is an important tool for 1.4.3 Provide an example illustrating how abstraction can
computer scientists. help identify variables.
Copyright 2022 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part. Due to electronic rights, some third party content may be suppressed from the eBook and/or eChapter(s).
Editorial review has deemed that any suppressed content does not materially affect the overall learning experience. Cengage Learning reserves the right to remove additional content at any time if subsequent rights restrictions require it.
2 PROGRAMMING WITH C++
1.4.4 Provide examples of technology applications that 1.4.6 Explain how the black box concept is an
have abstracted or hidden details. implementation of abstraction.
1.4.5 Provide an example illustrating the use of a class as 1.4.7 Identify appropriate levels of abstraction.
an abstraction of a set of objects.
1.1 ALGORITHMS
Algorithm Basics (1.1.1, 1.1.4)
A password might not be enough to protect your online accounts. Two-factor authentication adds an extra layer
of protection. A common form of two-factor authentication sends a personal identification number (PIN) to your
cell phone. To log in, you perform the series of steps shown in Figure 1-1.
The procedure for two-factor authentication is an example of an algorithm. In a general sense, an algorithm
is a series of steps for solving a problem or carrying out a task.
Algorithms exist for everyday tasks and tasks that involve technology. Here are some examples:
Copyright 2022 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part. Due to electronic rights, some third party content may be suppressed from the eBook and/or eChapter(s).
Editorial review has deemed that any suppressed content does not materially affect the overall learning experience. Cengage Learning reserves the right to remove additional content at any time if subsequent rights restrictions require it.
Module 1 Computational Thinking 3
Q Programming algorithms tell the computer what to do. Can you tell which of these algorithms
is a programming algorithm?
Algorithm 1: Algorithm 2:
Connect to the website’s login page. Prompt the user to enter a user ID.
Enter your user ID. Prompt the user to enter a password.
Enter your password. Make sure that the user ID and password match.
Wait for a text message containing a PIN to If the user ID and password match:
arrive on your smartphone. Generate a random PIN.
On the website’s login page, enter the PIN. Send the PIN to user’s phone.
Prompt the user to enter the PIN.
If the PIN is correct:
Allow access.
A Algorithm 1 is not a programming algorithm because it outlines instructions for the user.
Algorithm 2 is a programming algorithm because it specifies what the computer is supposed
to do. When you formulate a programming algorithm, the instructions should be for the
computer, not the user.
There can be more than one programming algorithm for solving a problem or performing a task, but some
algorithms are more efficient than others.
Q Here are two algorithms for summing the numbers from 1 to 10. Which algorithm is more
efficient?
Algorithm 1: Algorithm 2:
Add 1 1 2 to get a total. Get the last number in the series (10).
Repeat these steps nine times: Divide 10 by 2 to get a result.
Get the next number. Add 10 1 1 to get a sum.
Add this number to the total. Multiply the result by the sum.
A Both algorithms contain four instructions, but Algorithm 2 is more efficient. You can use it to
amaze your friends by quickly calculating the total in only four steps. Algorithm 1 is also four
lines long, but two of the instructions are repeated nine times. Counting the first step, that’s
19 steps to complete this task!
Copyright 2022 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part. Due to electronic rights, some third party content may be suppressed from the eBook and/or eChapter(s).
Editorial review has deemed that any suppressed content does not materially affect the overall learning experience. Cengage Learning reserves the right to remove additional content at any time if subsequent rights restrictions require it.
4 PROGRAMMING WITH C++
When formulating an algorithm, you can easily check to make sure it satisfies all the criteria for a good algo-
rithm. You can see how these criteria apply to an algorithm in Figure 1-2.
1.2 DECOMPOSITION
Decomposition Basics (1.2.1)
A mobile banking app contains many components. It has to provide a secure login procedure, allow users to
manage preferences, display account balances, push out alerts, read checks for deposit, and perform other tasks
shown in Figure 1-3.
The algorithm for such an extensive app would be difficult to formulate without dividing it into smaller parts,
a process called decomposition. When devising an algorithm for a complex problem or task, decomposition can
help you deal with smaller, more manageable pieces of the puzzle.
Copyright 2022 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part. Due to electronic rights, some third party content may be suppressed from the eBook and/or eChapter(s).
Editorial review has deemed that any suppressed content does not materially affect the overall learning experience. Cengage Learning reserves the right to remove additional content at any time if subsequent rights restrictions require it.
Module 1 Computational Thinking 5
Fraud alerts
Change user
Secure login
preferences
iStock.com/vector.S
Pay bills Withdrawals
Transfer money
Mobile banking
Two-factor
Balances Bill pay
authentication
Direct Money
deposits transfers
Structural decomposition is a process that identifies a hierarchy of structural units. At the lowest levels
of the hierarchy are modules, indicated in yellow in Figure 1-4, that have a manageable scope for creating
algorithms.
Copyright 2022 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part. Due to electronic rights, some third party content may be suppressed from the eBook and/or eChapter(s).
Editorial review has deemed that any suppressed content does not materially affect the overall learning experience. Cengage Learning reserves the right to remove additional content at any time if subsequent rights restrictions require it.
6 PROGRAMMING WITH C++
• Use a top-down approach. The nodes at the top break down into component parts in the nodes below them.
• Label nodes with nouns and adjectives, rather than verbs. For example, “Account management” is the
correct noun phrase, rather than a verb phrase, such as “Manage accounts.”
• Don’t worry about sequencing. Except for the actual login process, the components in a mobile bank-
ing system could be accessed in any order. This is a key difference between an algorithm and decom-
position. An algorithm specifies an order of activities, whereas decomposition specifies the parts of
a task.
Validate Compare
Generate Send PIN
Prompt for Prompt for user ID and Prompt user user-entered Handle
one-time to
user ID password password for PIN PIN to mismatches
PIN mobile
match generated PIN
Nodes in yellow
require further
decomposition.
Notice how the levels of the functional decomposition diagram get more specific until the nodes in the lowest
levels begin to reveal instructions that should be incorporated in an algorithm.
Here are some tips for constructing functional decomposition diagrams and deriving algorithms from them:
• Label nodes with verb phrases. In contrast to the nodes of a structural decomposition diagram, the
nodes of a functional decomposition are labeled with verb phrases that indicate “what” is to be done.
• Sequence from left to right. Reading left to right on the diagram should correspond to the sequence in
which steps in the algorithm are performed.
Copyright 2022 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part. Due to electronic rights, some third party content may be suppressed from the eBook and/or eChapter(s).
Editorial review has deemed that any suppressed content does not materially affect the overall learning experience. Cengage Learning reserves the right to remove additional content at any time if subsequent rights restrictions require it.
Module 1 Computational Thinking 7
Each node
represents an
object.
PIN generator
Methods
Login screen Attribute: One-time PIN describe what an
object can do.
Attribute: Entered user ID Method: Generate random PIN
Attribute: Entered password Method: Send PIN to mobile
number
Method: Display login boxes
Method: Verify entered user ID
and password
Method: Verify PIN
Method: Handle mismatches
Valid user
An object-oriented decomposition does not produce a hierarchy. Instead it produces a collection of objects
that can represent people, places, or things.
Tips for object-oriented decomposition:
• Node titles are nouns. Each node in the object-oriented decomposition diagram is labeled with a noun.
• Attributes are nouns. A node can contain a list of attributes, which relate to the characteristics of an object.
• Methods are verb phrases. An object can also contain methods, which are actions that an object can
perform. You may need to devise an algorithm for each method.
• Sketch in connection arrows. Connection arrows help you visualize how objects share data.
• Minimize dependencies. Although input and output may flow between nodes, changing the instructions
in one module or object should not require changes to others.
• Maximize cohesion. Each object or module contains attributes, methods, or instructions that perform a
single logical task or represent a single entity.
Copyright 2022 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part. Due to electronic rights, some third party content may be suppressed from the eBook and/or eChapter(s).
Editorial review has deemed that any suppressed content does not materially affect the overall learning experience. Cengage Learning reserves the right to remove additional content at any time if subsequent rights restrictions require it.
8 PROGRAMMING WITH C++
Now, what if the challenge is to add the numbers from 1 to 200? That algorithm looks like this:
Get the last number in the series (200).
Divide 200 by 2 to get a result.
Add 200 1 1 to get a sum.
Multiply the result by the sum.
Notice a pattern? This fill-in-the-blank algorithm works for any number:
Get the last number in the series (____________________).
Divide ____________________ by 2 to get a result.
Add ____________________ 1 1 to get a sum.
Multiply the result by the sum.
The process of finding similarities in procedures and tasks is called pattern identification. It is a useful com-
putational thinking technique for creating algorithms that can be used and reused on different data sets. By recog-
nizing the pattern in the Amaze-Your-Friends math trick, you can use the algorithm to find the total of any series
of numbers.
Copyright 2022 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part. Due to electronic rights, some third party content may be suppressed from the eBook and/or eChapter(s).
Editorial review has deemed that any suppressed content does not materially affect the overall learning experience. Cengage Learning reserves the right to remove additional content at any time if subsequent rights restrictions require it.
Module 1 Computational Thinking 9
Recognizing this repetition, you can streamline the algorithm like this:
Get a password.
Repeat three times:
If the password is correct, allow access.
If the password is not correct, get the password again.
If the password is correct, allow access.
If the password is not correct, lock the account.
1.4 ABSTRACTION
Abstraction Basics (1.4.1, 1.4.2, 1.4.3)
Think back to the Amaze-Your-Friends math trick. By identifying a pattern, you formulated a general algorithm
that works for a sequence of any length, whether it is a sequence of 1 to 10 or 1 to 200.
Get the last number in the series (____________________).
Divide ____________________ by 2 to get a result.
Copyright 2022 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part. Due to electronic rights, some third party content may be suppressed from the eBook and/or eChapter(s).
Editorial review has deemed that any suppressed content does not materially affect the overall learning experience. Cengage Learning reserves the right to remove additional content at any time if subsequent rights restrictions require it.
10 PROGRAMMING WITH C++
Q Can you envision a class that’s an abstraction of the collection of objects shown in Figure 1-7?
Budnyi/Shutterstock.com
Copyright 2022 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part. Due to electronic rights, some third party content may be suppressed from the eBook and/or eChapter(s).
Editorial review has deemed that any suppressed content does not materially affect the overall learning experience. Cengage Learning reserves the right to remove additional content at any time if subsequent rights restrictions require it.
Another Random Document on
Scribd Without Any Related Topics
outside which they are not to be seen. This adds very much to the
interest of slow travelling, as it keeps you constantly on the watch,
and you are rewarded by always seeing something fresh. The trying
thing about it is that if you do not buy the thing you want directly you
see it, most likely you will never have another chance.
It is amusing to watch the harvesting of the peanuts which is now
going on. Owing to the clayey nature of the soil, it is impossible to
sieve them as in Shantung, so whole families establish themselves
in a field, attended by their poultry and pigs, which are picketed out
over the surface of the ground. This has been already dug up and
cleared by the gatherers, but the family gleans what has been
overlooked, and the poultry and pigs again glean what they may
have left. Little Chinese children sit in baskets, but at a very tender
age they begin to share the toils of their elders. It is astonishing to
see the loads of salt, coal, or firewood which some of these tiny
creatures manage to carry with a manly energy. There must be a
good deal of country life in this district, for there are numbers of nice-
looking farms situated on the hilltops (as in the sketch of “Sunlight
and Mist”), surrounded by haystacks and vegetable gardens and
clumps of the useful bamboo. The bamboo seems to be used for
every possible purpose, and many of the implements made from it
are as ingenious as they are simple. Take, for instance, the rake; one
end of the bamboo rod is split, the ends bent, and a tiny bit of plaiting
spreads the prongs out fan shape. A greater variety of baskets, too,
is made from bamboos than I have ever seen elsewhere, and they
are used for a much larger number of purposes than at home.
As we plodded along the rice-fields one morning, after about an
hour’s walk we came to a wayside booth, where our men stopped for
their first snack of food, and some particularly fresh-looking eggs
tempted us to join their meal. The salesman proceeded to poach
them, and would have added sugar if we had not stopped him.
Declining chopsticks, I was provided with a nice little pottery spoon,
and my friend took possession of a saucer about the size of a penny
(commonly used for sauce) for the same purpose. Long strings of
mules passed us, carrying taxes in the shape of small basket-loads
of bullion, accompanied by a military escort. The leading mules were
gaily decorated with flags, showing that they were on government
duty. The road was bad and slippery, and our men soon decided to
shorten the day’s journey by one-third, which we declined to allow,
having already spared their strength by walking for several hours; we
agreed, however, to shorten the stage to a certain extent. The
natural result was that we found a horrible inn with only two tiny
rooms at our disposal, an inner one being already occupied by
several people. We agreed to remain there only on one condition—
that these people should be put elsewhere; and we found the three
cells were more than filled by ourselves and our staff. There were no
windows, but there was plenty of ventilation. The house was like a
large barn, the end of which was divided off by a thin partition, in the
centre of which was a round door. This part was again subdivided
into three cubicles. The outer part of the barn was like a big
restaurant, and after a while the many inhabitants rolled themselves
up like sausages in the wadded quilts provided by the inn, and
bestowed themselves as comfortably as might be on tables or
benches, and comparative silence reigned for a few hours. Happily,
the rain stopped, for there was quite enough open space in the roof
above my head and in the walls for us to study astronomy had it
been a clear night. We found it unnecessary to have our pan of
charcoal taken out at nights, for there was always a lovely breeze to
carry away any fumes there might be.
In this district the beds are made of straw, covered with a
bamboo matting, and are not uncomfortable; but we always felt
happier when we got a plain wooden bedstead like a large, low table.
We passed a night at an interesting large town called Shun King
Fu, and were greatly charmed with the lovely silks we saw being
made there, and the silver work. Everywhere the people were busy
with the various processes of silk-making. Hand-looms, of course,
are used, and we saw the most exquisite golden shades of silk in all
stages of manufacture. It is, however, never sold in its natural golden
colour, or white (as that is the Chinese mourning), unless some
European succeeds in getting hold of a piece in its unfinished state.
Some of the natural dyes are wonderfully brilliant, but unfortunately
none of them seemed to be fast colours. The red and yellow
vegetable dyes and indigo are grown in the province of Szechwan,
but, sad to say, aniline dyes have been introduced, and are
becoming more and more common.
The missionaries who were entertaining us kindly sent out to a
silk merchant to bring pieces for us to select from, as it is not very
usual for ladies to go out shopping in this city. When we had chosen
what we wanted, the silk had to be weighed, instead of measured, to
ascertain what the price was. The merchant, who brought lovely
embroidery silks for sale, had neat little scales in a case with which
to weigh the skeins. A long discussion as to the price ensued, as it
had gone up since our hosts bought similar silks a month before, and
no valid reason could be produced for the change. Of course the
system of bargaining is universal, and we were thankful to have
some one to tell us what the price ought to have been and to do the
bargaining for us. Next the silversmith was summoned, and he
brought a trayful of various silver ornaments, ready to be inlaid with
kingfishers’ feathers. This is an art peculiar to China; in fact, no one
but a Chinaman would have the patience requisite for doing it. The
effect is that of the most brilliant, iridescent, blue-green enamel, and
usually beads or red-coloured glass or coral are introduced instead
of jewels. It is particularly effective when combined with jade. This
jewelry was also sold by weight, and we had to leave our purchases
to be “feathered” and sent after us, as everything of that sort is only
made to order. Brides frequently wear a sort of crown made of silver
and kingfishers’ feathers, which looks extremely effective. There are
some fine examples of this work in the Chinese Section of the South
Kensington Museum.
We were told that we must make an early start next day, as it
was a very long stage—between thirty and thirty-five miles—so we
were up betimes, and ready at six o’clock. Luck was decidedly
against us. First one of the coolies said he was ill and could not go,
so another had to be got, which delayed us nearly an hour. The
morning was very grey, and a cold drizzle soon set in. My chair-
bearers fell down even before we got outside the city, and the road
became more and more sticky every moment. The men hate cold
water, and had to walk round every puddle, which took up a great
deal of time. The ground is composed of a particularly sticky clay,
which is perhaps the reason why not only the cattle but also the
funny little black pigs wear straw sandals when they travel.
After our chairs had been upset more than once we decided that
it was less unpleasant to walk, and the soldiers came valiantly to the
rescue when the road was specially difficult, as in the case of long
flights of slippery steps. Sometimes they gave us a hand, and
sometimes they clutched an elbow to save us. The descriptions of
slippery places and the perils of the road, as given in the Book of
Psalms, were perpetually before our mental vision. Nothing could
more accurately describe Chinese roads in wet weather. The coolies
tied little metal things on to their sandals, which was somewhat of a
help, but we felt almost thankful when at midday the rain settled into
a steady downpour; for, though it was rather dreary, it was less
slippery. There were a large number of chairs on the road, and some
as important-looking as our own. This was the only bit of the journey
when we travelled like mandarins, but we lacked the smart military
uniforms of the mandarins’ coolies; ours were the most disreputable,
ragged-looking crew, and much less satisfactory as carriers than
those we had in Shantung or Yünnan. In the nine days that we had
been travelling from Wanhsien we had only once met a four-bearer
chair, but now we were nearing the capital—Chengtu—the road was
much more crowded with traffic of all sorts. The last stage of the
journey is through comparatively level country. After a breakneck
descent from the mountains we entered the plain in which Chengtu
is situated. It is about ninety miles in length by forty broad, and has
been well described as a garden. Colonel Manifold estimates that it
contains a population of 1700 to the square mile, and there are
seventeen cities in it. The old familiar groan of wheelbarrows greeted
our ears once more, though the type is slightly different here from
that of Shantung; they are much smaller and only accommodate one
person, or (as we frequently saw) one fat pig, lying on his back, with
his legs in the air. The seat is immediately behind the wheel, and it
looks decidedly comic to see a woman, wearing tight pink trousers,
with a leg cocked jauntily on either side of the wheel.
SUNLIGHT AND MIST IN THE MOUNTAINS
C
HENGTU is unquestionably the cleanest city in China, and
probably is the most progressive and enlightened of any
purely native city. The streets are broad and well kept, and
the foreigner can walk anywhere without the slightest fear of
molestation. At almost every street corner there is a policeman, and
many of them have sentry-boxes. They are neatly dressed in a sort
of European uniform, and are decidedly clean and civil. They wear a
kind of small black sailor-hat, and the smarter ones wear black
thread gloves of native manufacture and carry stout walking-sticks.
Altogether, they are the best type of police we met. There are no
beggars with their hideous whine and incomparable dirt. This is a
magnificent triumph for the head magistrate, as a few years ago they
numbered twenty thousand in Chengtu; but he was determined to
put an end to the system, and has entirely succeeded. We met a
large school of boys neatly dressed, and were told that these were
the children of the beggars, whom he had collected into a large
school, where they are taught trades at the expense of the
municipality.
On the day of our arrival a kind friend offered to take us round
the city. For the first time since leaving Shanghai, we found we could
go on a real shopping expedition, and we had a glorious afternoon of
it. It would be hard to find a more fascinating place than Chengtu for
shopping. The curio shops had much that was attractive, though
nothing of any great value. We were told that we must proceed with
great caution if we wished to get things at a reasonable price; and
fortunately we were able to discuss in an unknown tongue, which
was a great advantage to us in dealing with the shopkeepers. Our
method of procedure was as follows:—firstly, to look with interest at
all the things we did not want, such as a baby’s feeding-bottle or old
beer-bottles; secondly, to point out all the flaws in anything that we
did want, turning up our noses till they were nearly out of joint;
thirdly, to ask the prices of many things, and to exclaim “Ai-ah” in an
incredulous tone on hearing the price of the things that we wanted to
purchase. Then we named a price about five times below what was
asked. Finally we left the shop and strolled away up the street, while
our kind friend further discussed the matter with the shopkeeper, we
having previously arranged with him in English how high we were
willing to go. On an average we got the things at about half the price
named originally, but sometimes we got them considerably cheaper.
There was not much old china to be seen, but a few bronzes and a
good deal of interesting brass, mostly modern. Chengtu is a great
place for the manufacture of horn things, especially lanterns, which
are most ingeniously constructed. The sheets of horn are joined by
being melted together, and Hosie gives a most interesting
description in his trade report of the way that these and other things
are made in Chengtu. There is a great manufacture of masks, and of
whole heads of the same kind, which are painted brilliant colours,
especially pink. In another street it is interesting to watch the sacred
money being made. Outside each shop a tree trunk is set up about
six feet high; the top of it is carved to form a mould, the shape of a
silver shoe. Into this the paper—made from bamboo or rice straw—is
beaten into shape with a hammer by a man standing upon the
counter in order to reach up to it. The basket-shops, too, are most
enticing, and here they make the largest baskets I have ever seen,
about four feet high and about two yards in diameter. This is the
place from which loofah comes; it is the inside of a peculiar kind of
melon. Chengtu is the great trade centre, too, for spices and musk,
furs, &c., which come from Tibet; but the great trade of the place is in
silks, as in the days of Marco Polo—and these were brought to the
house another day for us to see. The figured crêpe de Chine was
beautiful, and the shades were different from those to be seen at
home. I got a lovely figured brocade at about 3s. 9d. per yard, and
crêpe de Chine at 1s. 6d. You can see these silks being woven in
numbers of the dark-looking houses, and the design is made by a
person sitting above the loom, almost in the roof. Another charming
industry is that of ribbons and braids, which are made on the most
ingenious little machines. The people sit outside their doors working
at them, as you see the women with their lace bobbins in European
countries.
The people seem a poor, cheerful, thrifty folk, and there is an air
of prosperous activity throughout the whole city. Many parts of it are
extremely picturesque, and there are beautiful trees of various kinds
shading the wide thoroughfares. In the evening our attention was
attracted by tall poles, with lights placed so high up that they could
have been of no possible use to anybody. We found that they were
put up by pious persons to light the “orphan spirits”—that is to say, to
show the way home to people who had died away from their own
city.
The following day we visited the famous Buddhist monastery,
enclosed by a wall above which rose lofty trees. Passing through the
fine entrance, we faced a large gilt Buddha in a narrow shrine; back
to back with this, and divided off by a thin partition, was another
figure of the Buddha, facing the court. Here the Abbot received us
most courteously, and sent for his secretary to show us round. The
accompanying diagram shows the ordinary sort of arrangement both
of temples and monasteries. The temples generally form a group of
buildings separated from one another by courts one behind the other
in a straight line, the principal buildings forming the ends, and minor
buildings running along the sides of the courts. The hall of meditation
of the monks was an imposing room with seats along the walls, on
which the monks sit cross-legged, looking very much like Buddhas.
Everything was beautifully clean in the dining-hall, which was filled
with long tables, on which three bowls and a pair of chopsticks were
placed at intervals for each monk. In the kitchen we saw an
enormous boiler, where over a bushel of rice is cooked for each
meal, to supply the appetites of a hundred and fifty monks. A large
wooden fish acts as a gong for summoning the monks to meals, and
another gong is used to summon them to tea.
PLAN OF MONASTERY, CHENGTU
W
E reached the riverside—it looked merely a stream—and
found our boat, with the luggage already aboard, looking
most unpromising, despite the efforts of our men. It was a
small river craft about eight feet broad. Bamboo matting not more
than five feet high formed our house-room, with a few planks for a
door in front. Fragments of matting made a partial screen in the
centre. The floor was of a rudimentary character, just a few boards
with large gaps between them, through which one could study the
depth of water over which our luggage was precariously poised on
low props. In order to prevent all our small things from dropping
through the floor, we spread over it our invaluable sheets of oil-
cotton (a kind of waterproof largely used everywhere in China), and
fastened up a curtain at each end of the tiny boat to secure a small
amount of privacy. There was just space for our two carrying-chairs
and our mattresses. One of the chairs we used as a wardrobe, and
the other as a store-cupboard. The bamboo chairs we had procured
at the penitentiary of Chengtu, despite the advice of our friends, as
we found sedan-chairs very irksome, and decided that open ones
would be more comfortable and enable us to see the country better.
With long fur coats and foot muffs we felt that we could brave the
cold, and there was always the resource of walking if we got too
chilly. We never for a moment regretted our decision, and we found
that the men carried the open chairs far better than the heavy closed
ones. We profited at once by the exchange, as they were able to be
used for going to Mount Omi, and we were carried some distance up
the mountain. Under the seat was a box in which we could carry all
our small things, and the coolies hung their coats, hats, &c., on the
back.
As our room was so small we sat mostly on the floor, so as to
have everything within reach without getting up. The cooking was a
somewhat difficult matter, as the brazier on which it was done was
only six inches in diameter, and rather apt to burn a hole in the floor
if it was heated sufficiently to do any cooking. We were glad of its
warmth, as the weather was very cold. Chopsticks were evidently the
correct fireirons, and are just the right size to match the charcoal.
With practice I got fairly expert at making palatable dishes, as
naturally the range of the menu was much limited. From this time
onward I did all the cooking, and I cannot help attributing to this fact
mainly the excellent health we enjoyed throughout the whole journey.
It was on his way from Chang Te to Mount Omi that the
unfortunate Lieutenant Brooke was murdered by Lolos about a year
later than we were there. We were strongly warned about the care
requisite in dealing with Lolos, and told that it was imprudent even to
mention the name in public, as it is considered a term of reproach. It
was suggested that we should spell it if desirous of speaking of
them. Their country is marked on the maps as “Independent Lolos,”
and covers about 11,000 square miles: no Chinaman dare penetrate
into it without the safe-conduct of a Lolo. Their speech, dress,
customs, religion, and laws are entirely different from those of the
Chinese. No one has yet come into sufficiently close contact with
them to ascertain even approximately the number of Lolo tribes in
existence at the present time, speaking different dialects. What was
true at the time that Baber explored Western Szechwan is equally
true to-day—that practically nothing is known about them. He gives a
graphic description of the Lolos whom he met, which I quote at
length: “They are far taller than the Chinese; taller probably than any
European people. During the journey we must have met hundreds of
them, but we never saw one who could be called, even from an
English standard, short or undersized. They are almost without
exception remarkably straight-built, with thin muscular limbs. Their
chests are deep, as becomes mountaineers: the speed and
endurance with which they scale their native mountains is a prodigy
and a proverb for the Chinese. Their handsome oval faces, of a
reddish brown among those most exposed to the weather, are
furnished with large, level eyes, prominent but not exaggerated