Instant Download Readings From Programming With C++ 1st Edition Kyla Mcmullen - Ebook PDF PDF All Chapters
Instant Download Readings From Programming With C++ 1st Edition Kyla Mcmullen - Ebook PDF PDF All Chapters
com
https://ebooksecure.com/download/readings-from-programming-
with-c-ebook-pdf-2/
OR CLICK BUTTON
DOWLOAD EBOOK
https://ebooksecure.com/download/readings-from-programming-with-
c-ebook-pdf/
https://ebooksecure.com/download/programming-with-stm32-getting-
started-with-the-nucleo-board-and-c-c-ebook-pdf/
http://ebooksecure.com/product/ebook-pdf-programming-problem-
solving-and-abstraction-with-c/
https://ebooksecure.com/download/programming-in-c-ebook-pdf/
(eBook PDF) C++ Programming: From Problem Analysis to
Program Design 7th
http://ebooksecure.com/product/ebook-pdf-c-programming-from-
problem-analysis-to-program-design-7th/
http://ebooksecure.com/product/original-pdf-c-programming-from-
problem-analysis-to-program-design-8th/
https://ebooksecure.com/download/c-programming-from-problem-
analysis-to-program-design-ebook-pdf/
https://ebooksecure.com/download/programming-and-problem-solving-
with-python-ebook-pdf/
http://ebooksecure.com/product/ebook-pdf-starting-out-with-c-
from-control-structures-to-objects-9th-edition/
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.
Another random document with
no related content on Scribd:
“For the present,” wrote the secretary to Rodgers,[326] “it is
desirable that with the force under your command you remain in such
position as to enable you most conveniently to receive further more
extensive and more particular orders, which will be conveyed to you
through New York. But as it is understood that there are one or more
British cruisers on the coast in the vicinity of Sandy Hook, you are at
your discretion free to strike them, returning immediately after into
port. You are free to capture or destroy them.”
These orders reached New York June 21. Rodgers in his fine
frigate the “President,” with the “Hornet,” 18, was eager to sail. The
hope of capturing the “Belvidera,” which had long been an
intolerable annoyance to New York commerce, was strong both in
the Navy Department and in the navy; but the chance of obtaining
prize money from the British West India convoy, just then passing
eastward only a few days’ sail from the coast, added greatly to the
commodore’s impatience.[327] Decatur’s squadron arrived off Sandy
Hook June 19. June 21, within an hour after receiving the secretary’s
orders of June 18, the whole fleet, including two forty-four and one
thirty-eight-gun frigates, with the “Hornet” and the “Argus,” stood
out to sea.
The secretary might have spared himself the trouble of giving
further orders, for many a week passed before Rodgers and Decatur
bethought themselves of his injunction to return immediately into
port after striking the “Belvidera.” They struck the “Belvidera” within
forty-eight hours, and lost her; partly on account of the bursting of
one of the “President’s” main-deck guns, which blew up the
forecastle deck, killing or wounding sixteen men, including
Commodore Rodgers himself, whose leg was broken; partly, and
according to the British account chiefly, on account of stopping to
fire at all, when Rodgers should have run alongside, and in that case
could not have failed to capture his enemy. Whatever was the
reason, the “Belvidera” escaped; and Rodgers and Decatur, instead
of returning immediately into port as they had been ordered, turned
in pursuit of the British West India convoy, and hung doggedly to the
chase without catching sight of their game, until after three weeks’
pursuit they found themselves within a day’s sail of the British
Channel and the convoy safe in British waters.
This beginning of the naval war was discouraging. The American
ships should not have sailed in a squadron, and only their good luck
saved them from disaster. Rodgers and Decatur showed no regard to
the wishes of the Government, although had they met with
misfortune, the navy would have lost its last hope. Yet if the two
commodores had obeyed the secretary’s commands their cruise
would probably have been in the highest degree disastrous. The
Government’s true intentions have been a matter of much dispute;
but beyond a doubt the President and a majority of his advisers
inclined to keep the navy within reach at first,—to use them for the
protection of commerce, to drive away the British blockaders; and
aware that the British naval force would soon be greatly increased,
and that the American navy must be blockaded in port, the
Government expected in the end to use the frigates as harbor
defences rather than send them to certain destruction.
With these ideas in his mind Secretary Hamilton, in his orders of
June 18, told Rodgers and Decatur that “more extensive” orders
should be sent to them on their return to New York. A day or two
afterward Secretary Gallatin complained to the President that these
orders had not been sent.
“I believe the weekly arrivals from foreign ports,” said Gallatin,
[328] “will for the coming four weeks average from one to one-and-a-
half million dollars a week. To protect these and our coasting vessels,
while the British have still an inferior force on our coasts, appears to
me of primary importance. I think that orders to that effect, ordering
them to cruise accordingly, ought to have been sent yesterday, and
that at all events not one day longer ought to be lost.”
June 22 the orders were sent according to Gallatin’s wish. They
directed Rodgers with his part of the squadron to cruise from the
Chesapeake eastwardly, and Decatur with his ships to cruise from
New York southwardly, so as to cross and support each other and
protect with their united force the merchantmen and coasters
entering New York harbor, the Delaware, and the Chesapeake.
Rodgers and Decatur were then beginning their private cruise across
the ocean, and never received these orders until the commerce they
were to protect either reached port in safety or fell into British
hands.
Probably this miscarriage was fortunate, for not long after
Rodgers and Decatur passed the Banks the British Vice-Admiral
Sawyer sent from Halifax a squadron to prevent the American navy
from doing what Secretary Hamilton had just ordered to be done.
July 5 Captain Broke, with his own frigate the “Shannon,” 38, the
“Belvidera,” 36, the “Africa,” 64, and “Æolus,” 32, put to sea from
Halifax and was joined, July 9, off Nantucket by the “Guerriere,” 38.
Against such a force Rodgers and Decatur, even if together, would
have risked total destruction, while a success would have cost more
than it was worth. The Americans had nothing to gain and
everything to lose by fighting in line-of-battle.
As Broke’s squadron swept along the coast it seized whatever it
met, and July 16 caught one of President Jefferson’s 16-gun brigs,
the “Nautilus.” The next day it came on a richer prize. The American
navy seemed ready to outstrip the army in the race for disaster. The
“Constitution,” the best frigate in the United States service, sailed
into the midst of Broke’s five ships. Captain Isaac Hull, in command
of the “Constitution,” had been detained at Annapolis shipping a new
crew, until July 5,[329]—the day when Broke’s squadron left Halifax;
—then the ship got under way and stood down Chesapeake Bay on
her voyage to New York. The wind was ahead and very light. Not till
July 10 did the ship anchor off Cape Henry lighthouse,[330] and not
till sunrise of July 12 did she stand to the eastward and northward.
Light head-winds and a strong current delayed her progress till July
17, when at two o’clock in the afternoon, off Barnegat on the New
Jersey coast, the lookout at the masthead discovered four sails to
the northward, and two hours later a fifth sail to the northeast. Hull
took them for Rodgers’s squadron. The wind was light, and Hull
being to windward determined to speak the nearest vessel, the last
to come in sight. The afternoon passed without bringing the ships
together, and at ten in the evening, finding that the nearest ship
could not answer the night signal, Hull decided to lose no time in
escaping.
Then followed one of the most exciting and sustained chases
recorded in naval history. At daybreak the next morning one British
frigate was astern within five or six miles, two more were to
leeward, and the rest of the fleet some ten miles astern, all making
chase. Hull put out his boats to tow the “Constitution;” Broke
summoned the boats of his squadron to tow the “Shannon.” Hull
then bent all his spare rope to the cables, dropped a small anchor
half a mile ahead, in twenty-six fathom water, and warped his ship
along. Broke quickly imitated the device, and slowly gained on the
chase. The “Guerriere” crept so near Hull’s lee-beam as to open fire,
but her shot fell short. Fortunately the wind, though slight, favored
Hull. All night the British and American crews toiled on, and when
morning came the “Belvidera,” proving to be the best sailer, got in
advance of her consorts, working two kedge-anchors, until at two
o’clock in the afternoon she tried in her turn to reach the
“Constitution” with her bow guns, but in vain. Hull expected capture,
but the “Belvidera” could not approach nearer without bringing her
boats under the “Constitution’s” stern guns; and the wearied crews
toiled on, towing and kedging, the ships barely out of gunshot, till
another morning came. The breeze, though still light, then allowed
Hull to take in his boats, the “Belvidera” being two and a half miles
in his wake, the “Shannon” three and a half miles on his lee, and the
three other frigates well to leeward. The wind freshened, and the
“Constitution” drew ahead, until toward seven o’clock in the evening
of July 19 a heavy rain-squall struck the ship, and by taking skilful
advantage of it Hull left the “Belvidera” and “Shannon” far astern;
yet until eight o’clock the next morning they were still in sight
keeping up the chase.
Perhaps nothing during the war tested American seamanship
more thoroughly than these three days of combined skill and
endurance in the face of an irresistible enemy. The result showed
that Hull and the “Constitution” had nothing to fear in these
respects. There remained the question whether the superiority
extended to his guns; and such was the contempt of British naval
officers for American ships, that with this experience before their
eyes they still believed one of their 38-gun frigates to be more than
a match for an American forty-four, although the American, besides
the heavier armament, had proved his capacity to out-sail and out-
manœuvre the Englishman. Both parties became more eager than
ever for the test. For once, even the Federalists of New England felt
their blood stir; for their own President and their own votes had
called these frigates into existence, and a victory won by the
“Constitution,” which had been built by their hands, was in their eyes
a greater victory over their political opponents than over the British.
With no halfhearted spirit, the sea-going Bostonians showered well-
weighed praises on Hull when his ship entered Boston harbor, July
26, after its narrow escape; and when he sailed again, New England
waited with keen interest to learn his fate.
Hull could not expect to keep command of the “Constitution.”
Bainbridge was much his senior, and had the right to a preference in
active service. Bainbridge then held and was ordered to retain
command of the “Constellation,” fitting out at the Washington Navy
Yard; but Secretary Hamilton, July 28, ordered him to take command
also of the “Constitution” on her arrival in port. Doubtless Hull
expected this change, and probably the expectation induced him to
risk a dangerous experiment; for without bringing his ship to the
Charlestown Navy Yard, but remaining in the outer harbor, after
obtaining such supplies as he needed, August 2, he set sail without
orders, and stood to the eastward. Having reached Cape Race
without meeting an enemy he turned southward, until on the night
of August 18 he spoke a privateer, which told him of a British frigate
near at hand. Following the privateersman’s directions the
“Constitution” the next day, August 19, at two o’clock in the
afternoon, latitude 41° 42´, longitude 55° 48´, sighted the
“Guerriere.”
The meeting was welcome on both sides. Only three days before,
Captain Dacres had entered on the log of a merchantman a
challenge to any American frigate to meet him off Sandy Hook. Not
only had the “Guerriere” for a long time been extremely offensive to
every seafaring American, but the mistake which caused the “Little
Belt” to suffer so seriously for the misfortune of being taken for the
“Guerriere” had caused a corresponding feeling of anger in the
officers of the British frigate. The meeting of August 19 had the
character of a preconcerted duel.
The wind was blowing fresh from the northwest, with the sea
running high. Dacres backed his main-top-sail and waited. Hull
shortened sail and ran down before the wind. For about an hour the
two ships wore and wore again, trying to get advantage of position;
until at last, a few minutes before six o’clock, they came together
side by side, within pistol-shot, the wind almost astern, and running
before it they pounded each other with all their strength. As rapidly
as the guns could be worked, the “Constitution” poured in broadside
after broadside, double-shotted with round and grape,—and, without
exaggeration, the echo of these guns startled the world. “In less
than thirty minutes from the time we got alongside of the enemy,”
reported Hull,[331] “she was left without a spar standing, and the
hull cut to pieces in such a manner as to make it difficult to keep her
above water.”
That Dacres should have been defeated was not surprising; that
he should have expected to win was an example of British arrogance
that explained and excused the war. The length of the “Constitution”
was 173 feet; that of the “Guerriere” was 156 feet; the extreme
breadth of the “Constitution” was 44 feet; that of the “Guerriere”
was 40 feet, or within a few inches in both cases. The “Constitution”
carried thirty-two long 24-pounders, the “Guerriere” thirty long 18-
pounders and two long 12-pounders; the “Constitution” carried
twenty 32-pound carronades, the “Guerriere” sixteen. In every
respect, and in proportion of ten to seven, the “Constitution” was
the better ship; her crew was more numerous in proportion of ten to
six. Dacres knew this very nearly as well as it was known to Hull, yet
he sought a duel. What he did not know was that in a still greater
proportion the American officers and crew were better and more
intelligent seamen than the British, and that their passionate wish to
repay old scores gave them extraordinary energy. So much greater
was the moral superiority than the physical, that while the
“Guerriere’s” force counted as seven against ten, her losses counted
as though her force were only two against ten.
Dacres’ error cost him dear, for among the “Guerriere’s” crew of
two hundred and seventy-two, seventy-nine were killed or wounded;
and the ship was injured beyond saving before Dacres realized his
mistake, although he needed only thirty minutes of close fighting for
the purpose. He never fully understood the causes of his defeat, and
never excused it by pleading, as he might have done, the great
superiority of his enemy.[332]
Hull took his prisoners on board the “Constitution],” and after
blowing up the “Guerriere” sailed for Boston, where he arrived on
the morning of August 30. The Sunday silence of the Puritan city
broke into excitement as the news passed through the quiet streets
that the “Constitution” was below, in the outer harbor, with Dacres
and his crew prisoners on board. No experience of history ever went
to the heart of New England more directly than this victory, so
peculiarly its own; but the delight was not confined to New England,
and extreme though it seemed it was still not extravagant, for
however small the affair might appear on the general scale of the
world’s battles, it raised the United States in one half hour to the
rank of a first-class Power in the world.
Hull’s victory was not only dramatic in itself, but was also
supremely fortunate in the moment it occurred. The “Boston Patriot”
of September 2, which announced the capture of the “Guerriere,”
announced in the next column that Rodgers and Decatur, with their
squadron, entered Boston harbor within four-and-twenty hours after
Hull’s arrival, returning empty-handed after more than two months
of futile cruising; while in still another column the same newspaper
announced “the melancholy intelligence of the surrender of General
Hull and his whole army to the British General Brock.” Isaac Hull was
nephew to the unhappy General, and perhaps the shattered hulk of
the “Guerriere,” which the nephew left at the bottom of the Atlantic
Ocean, eight hundred miles east of Boston, was worth for the
moment the whole province which the uncle had lost, eight hundred
miles to the westward; it was at least the only equivalent the people
could find, and they made the most of it. With the shock of new life,
they awoke to the consciousness that after all the peace teachings
of Pennsylvania and Virginia, the sneers of Federalists and
foreigners; after the disgrace of the “Chesapeake” and the surrender
of Detroit,—Americans could still fight. The public had been taught,
and had actually learned, to doubt its own physical courage; and the
reaction of delight in satisfying itself that it still possessed the
commonest and most brutal of human qualities was the natural
result of a system that ignored the possibility of war.
Hull’s famous victory taught the pleasures of war to a new
generation, which had hitherto been sedulously educated to think
only of its cost. The first taste of blood maddens; and hardly had the
“Constitution” reached port and told her story than the public
became eager for more. The old Jeffersonian jealousy of the navy
vanished in the flash of Hull’s first broadside. Nothing would satisfy
the craving of the popular appetite but more battles, more British
frigates, and more daring victories. Even the cautious Madison was
dragged by public excitement upon the element he most heartily
disliked.
The whole navy, was once more, September 1, safe in port,
except only the “Essex,” a frigate rated at thirty-two but carrying
forty-four guns, commanded by Captain David Porter. She left New
York, July 3, with orders,[333] dated June 24, to join Rodgers, or
failing this to cruise southwardly as far as St. Augustine. June 11 she
met a convoy of seven transports conveying a battalion of the First
Regiment, or Royal Scots, from the West Indies to reinforce Prevost
and Brock in Canada. Porter cut out one transport. With the aid of
another frigate he could have captured the whole, to the great
advantage of Dearborn’s military movements; but the British
commander managed his convoy so well that the battalion escaped,
and enabled Prevost to strengthen the force at Niagara which
threatened and defeated Van Rensselaer. August 13 the British 20-
gun sloop-of-war “Alert” came in sight, bore down within short
pistol-shot, and opened fire on the “Essex.” Absurd as the idea
seemed, the British captain behaved as though he hoped to capture
the American frigate, and not until Porter nearly sunk him with a
broadside did the Englishman strike his colors. After taking a number
of other prizes, but without further fighting, September 7 Porter
brought his ship back to the Delaware River.
The return of the “Essex” to port, September 7, brought all the
national vessels once more under the direct control of the
Department. Nearly every ship in the service was then at Boston.
The three forty-fours—the “Constitution,” “United States,” and
“President”—were all there; two of the thirty-eights—the “Congress”
and “Chesapeake”—were there, and the “Constellation” was at
Washington. The “Adams,” 28, was also at Washington; but the
“Hornet,” 18, and “Argus,” 16, were with Rodgers and Decatur at
Boston. The “Syren,” 16, was at New Orleans; the “Essex,” 32, and
the “Wasp,” 18, were in the Delaware.
Carried away by Hull’s victory, the Government could no longer
hesitate to give its naval officers the liberty of action they asked, and
which in spite of orders they had shown the intention to take. A new
arrangement was made. The vessels were to be divided into three
squadrons, each consisting of one forty-four, one light frigate, and
one sloop-of-war. Rodgers in the “President” was to command one
squadron, Bainbridge in the “Constitution” was to command another,
and Decatur in the “United States” was to take the third.[334] Their
sailing orders, dated October 2,[335] simply directed the three
commodores to proceed to sea: “You are to do your utmost to annoy
the enemy, to afford protection to our commerce, pursuing that
course which to your best judgment may under all circumstances
appear the best calculated to enable you to accomplish these objects
as far as may be in your power, returning into port as speedily as
circumstances will permit consistently with the great object in view.”
Before continuing the story of the frigates, the fate of the little
“Wasp” needs to be told. Her career was brief. The “Wasp,” a sloop-
of-war rated at eighteen guns, was one of President Jefferson’s
additions to the navy to supply the loss of the “Philadelphia;” she
was ship-rigged, and armed with two long 12-pounders and sixteen
32-pound carronades. She carried a crew of one hundred and thirty-
seven men, commanded by Captain Jacob Jones, a native of
Delaware, lieutenant in the “Philadelphia” when lost in the war with
Tripoli. The “Wasp” was attached to Rodgers’s squadron, and
received orders from the commodore to join him at sea. She sailed
from the Delaware October 13, and when about six hundred miles
east of Norfolk, October 17, she fell in with the British 18-gun brig
“Frolic,” convoying fourteen merchantmen to England. The two
vessels were equal in force, for the “Frolic’s” broadside threw a
weight of two hundred and seventy-four pounds, while that of the
“Wasp” threw some few pounds less; the “Frolic” measured, by
British report,[336] one hundred feet in length, the “Wasp” one
hundred and six; their breadth on deck was the same; and although
the “Wasp’s” crew exceeded that of her enemy, being one hundred
and thirty-five men against one hundred and ten, the British vessel
had all the men she needed, and suffered little from this inferiority.
The action began at half-past eleven in the morning, the two sloops
running parallel, about sixty yards apart, in a very heavy sea, which
caused both to pitch and roll so that marksmanship had the most
decisive share in victory. The muzzles of the guns went under water,
and clouds of spray dashed over the crews, while the two vessels
ran side by side for the first fifteen minutes. The British fire cut the
“Wasp’s” rigging, while the American guns played havoc with the
“Frolic’s” hull and lower masts. The vessels approached each other
so closely that the rammers of the guns struck the enemy’s side, and
at last they fell foul,—the “Wasp” almost squarely across the
“Frolic’s” bow. In the heavy sea boarding was difficult; but as soon
as the “Wasp’s” crew could clamber down the “Frolic’s” bowsprit,
they found on the deck the British captain and lieutenant, both
severely wounded, and one brave sailor at the wheel. Not twenty of
the British crew were left unhurt, and these had gone below to
escape the American musketry. The “Wasp” had only ten men killed
and wounded. The battle lasted forty-three minutes.
If the American people had acquired a taste for blood, the battle
of the “Wasp” and “Frolic” gratified it, for the British sloop was
desperately defended, and the battle, won by the better
marksmanship of the Americans, was unusually bloody. Captain
Jones lost the full satisfaction of his victory, for a few hours
afterward the “Poictiers,” a British seventy-four, came upon the two
disabled combatants and carried both into Bermuda; but the
American people would have been glad to part with their whole navy
on such terms, and the fight between the “Wasp” and the “Frolic”
roused popular enthusiasm to a point where no honors seemed to
satisfy their gratitude to Captain Jones and his crew.
The “Wasp’s” brilliant career closed within a week from the day
she left the Delaware. A week afterward another of these ship-duels
occurred, which made a still deeper impression. Rodgers and
Decatur sailed from Boston October 8, with the “President,” the
“United States,” “Congress,” and “Argus,” leaving the “Constitution,”
“Chesapeake,” and “Hornet” in port. Rodgers in the “President,” with
the “Congress,” cruised far and wide, but could find no enemy to
fight, and after making prize of a few merchantmen returned to
Boston, December 31. The “Argus” also made some valuable prizes,
but was chased by a British squadron, and only by excellent
management escaped capture, returning Jan. 3, 1813, to New York.
Decatur in the “United States,” separating from the squadron
October 12, sailed eastward to the neighborhood of the Azores,
until, October 25, he sighted a sail to windward. The stranger made
chase. The wind was fresh from south-southeast, with a heavy sea.
Decatur stood toward his enemy, who presently came about, abreast
of the “United States” but beyond gunshot, and both ships being
then on the same tack approached each other until the action began
at long range. The British ship was the 38-gun frigate “Macedonian”
commanded by Captain Carden, and about the same force as the
“Guerriere.” At first the “United States” used only her long 24-
pounders, of which she carried fifteen on her broadside, while the
“Macedonian” worked a broadside of fourteen long 18-pounders. So
unequal a contest could not continue. Not only was the American
metal heavier, but the American fire was quicker and better directed
than that of the Englishman; so that Carden, after a few minutes of
this experience, bore down to close. His manœuvre made matters
worse. The carronades of the “United States” came into play; the
“Macedonian’s” mizzen-mast fell, her fore and main top-mast were
shot away, and her main-yard; almost all her rigging was cut to
pieces, and most of the guns on her engaged side were dismounted.
She dropped gradually to leeward, and Decatur, tacking and coming
up under his enemy’s stern, hailed, and received her surrender.
The British ship had no right to expect a victory, for the disparity
of force was even greater than between the “Constitution” and
“Guerriere;” but in this case the British court-martial subsequently
censured Captain Carden for mistakes. The battle lasted longer than
that with the “Guerriere,” and Decatur apologized for the extra hour
because the sea was high and his enemy had the weather-gauge
and kept at a distance; but the apology was not needed. Decatur
proved his skill by sparing his ship and crew. His own loss was
eleven men killed and wounded; the “Macedonian’s” loss was nine
times as great. The “United States” suffered little in her hull, and her
spars and rigging suffered no greater injury than could be quickly
repaired; while the “Macedonian” received a hundred shot in her
hull, and aloft nothing remained standing but her fore and main
masts and her fore-yard.
Decatur saved the “Macedonian,” and brought her back to New
London,—the only British frigate ever brought as a prize into an
American port. The two ships arrived December 4, and from New
London the “Macedonian” was taken to New York and received in
formal triumph. Captain Jones of the “Wasp” took command of her
in reward for his capture of the “Frolic.”
Before the year closed, the “Constitution” had time for another
cruise. Hull at his own request received command of the Navy Yard
at Charlestown, and also took charge of the naval defences in New
York harbor, but did not again serve at sea during the war. The
“Constitution” was given to Captain Bainbridge, one of the oldest
officers in the service. A native of New Jersey, Bainbridge
commanded the “Philadelphia” when lost in the Tripolitan war, and
was held for eighteen months a prisoner in Tripoli. In 1812, when he
took command of the “Constitution,” though a year older than Hull
and five years older than Decatur, he had not yet reached his fortieth
year, while Rodgers, born in 1771, had but lately passed it. The
difference in age between these four naval officers and the four chief
generals—Dearborn, Wilkinson, Wade Hampton, and William Hull—
was surprising; for the average age of the naval commanders
amounted barely to thirty-seven years, while that of the four
generals reached fifty-eight. This difference alone accounted for
much of the difference in their fortune, and perhaps political
influence accounted for the rest.
Bainbridge showed no inferiority to the other officers of the
service, and no one grumbled at the retirement of Hull. The
“Constitution” sailed from Boston, October 25, with the “Hornet.”
The “Essex,” then in the Delaware, was ordered to join the squadron
at certain specified ports in the south Atlantic, and sailed October
28, expecting a very long cruise. December 13 Bainbridge arrived at
San Salvador, on the coast of Brazil, where he left the “Hornet” to
blockade the “Bonne Citoyenne,” a British 18-gun sloop-of-war
bound to England with specie. Cruising southward, within sight of
the Brazilian coast, in latitude 13° 6´ south, Bainbridge sighted the
British frigate “Java,” a ship of the same tonnage as the “Guerriere,”
throwing a slightly heavier broadside and carrying a large crew of
four hundred and twenty-six men, if the American account was
correct. Bainbridge tacked and made sail off shore, to draw the
stranger away from a neutral coast; the British frigate followed him,
until at half-past one o’clock in the afternoon Bainbridge shortened
sail, tacked again, and stood for his enemy. Soon after two o’clock
the action began, the two ships being on the same tack, the “Java”
to windward and the better sailer, and both fighting their long-range
guns. The British frigate insisted upon keeping at a distance, obliging
Bainbridge after half an hour to risk the danger of being raked; and
at twenty minutes before three o’clock the “Constitution” closed
within pistol-shot.[337] At ten minutes before three the ships were
foul, the “Java’s” jibboom in the “Constitution’s” mizzen rigging; and
from that point the battle became slaughter. In fifteen minutes the
“Java’s” bowsprit, fore-mast, and main top-mast were cut away, and
a few minutes after four o’clock she ceased firing. Her captain,
Lambert, was mortally wounded; the first lieutenant was wounded;
forty-eight of her officers and crew were dead or dying; one hundred
and two were wounded; little more than a hulk filled with wreck and
with dead or wounded men floated on the water.
The “Constitution” had but twelve men killed and twenty-two
wounded, and repaired damages in an hour. Owing perhaps to the
death of Captain Lambert the reports of the battle were more
contradictory than usual, but no one disputed that although the
“Java” was to windward and outsailed the American frigate, and
although her broadside counted as nearly nine against her enemy’s
ten,—for the “Constitution” on this cruise carried two guns less than
in her fight with the “Guerriere,”—yet the “Java” inflicted no more
damage than she ought to have done had she been only one fourth
the size of the American frigate, although she was defended more
desperately than either the “Guerriere” or the “Macedonian.”
With this battle the year ended. Bainbridge was obliged to blow
up his prize, and after landing and paroling his prisoners at San
Salvador sailed for Boston, where he arrived in safety, February 27,
1813. During the six months the war had lasted the little United
States navy captured three British frigates, besides the 20-gun
“Alert” and the 18-gun “Frolic;” privateers by scores had ravaged
British commerce, while the immense British force on the ocean had
succeeded only in capturing the little “Nautilus,” the 12-gun brig
“Vixen,” and the “Wasp.” The commerce of America had indeed
suffered almost total destruction; but the dispute was to be decided
not so much by the loss which England could inflict upon America, as
by that which America could inflict upon England.
CHAPTER XVIII.
In such a war the people of the United States had only
themselves to fear; but their dangers were all the more formidable.
Had the war deeply disturbed the conditions of society, or brought
general and immediate distress, government and Union might easily
have fallen to pieces; but in the midst of military disaster and in
plain sight of the Government’s incompetence, the general public
neither felt nor had reason to fear much change in the routine of
life. Commerce had long accustomed itself to embargoes,
confiscations, and blockades, and ample supplies of foreign goods
continued to arrive. The people made no serious exertions; among a
population exceeding seven millions, not ten thousand men entered
the military service. The militia, liable to calls to the limit of one
hundred thousand, served for the most part only a few weeks in the
autumn, went home in whole regiments when they pleased,[338] and
in the East refused to go out at all. The scarcity of men was so great
that even among the sea-goingclass, for whose rights the war was
waged, only with the utmost difficulty and long delays, in spite of
bounties and glory, could sailors be found to man half-a-dozen
frigates for a three-months cruise, although the number of privateers
was never great.
The nation as a whole saw nothing of actual warfare. While
scarcely a city in Europe had escaped capture, and hardly a province
of that continent was so remote as not to be familiar with invading
armies or to have suffered in proportion to its resources, no
American city saw or greatly feared an enemy. The rich farms of
New York, New Jersey, Pennsylvania, and Virginia produced their
usual harvests, and except on exposed parts of the coast the
farmers never feared that their crops might be wasted by
manœuvring armies, or their cattle, pigs, and poultry be disturbed
by marauders. The country was vast, and quiet reigned throughout
the whole United States. Except at the little point of Niagara,
occupied by a few hundred scattered farmers, and on the extreme
outskirts of Ohio and Indiana, the occupations and industries of life
followed in the main their daily course.
The country refused to take the war seriously. A rich nation with
seven million inhabitants should have easily put one hundred
thousand men into the field, and should have found no difficulty in
supporting them; but no inducement that the Government dared
offer prevailed upon the people to risk life and property on a
sufficient scale in 1812. The ranks of the army were to be filled in
one of two ways,—either by enlistment in the regular service for five
years, with pay at five dollars a month, sixteen dollars bounty, and
on discharge three months pay and one hundred and sixty acres of
land; or by volunteer organizations to the limit of fifty thousand men
in all, officered under State laws, to serve for one year, with the pay
of regular troops but without bounty, clothed, and in case of cavalry
corps mounted, at their own expense. In a society where the day-
laborers’ wages were nowhere less than nine dollars a month,[339]
these inducements were not enough to supply the place of
enthusiasm. The patriotic citizen who wished to serve his country
without too much sacrifice, chose a third course,—he volunteered
under the Act of Congress which authorized the President to call one
hundred thousand State militia into service for six months; and upon
this State militia Dearborn, Hull, Van Rensselaer, and Smyth were
obliged chiefly to depend.
If the war fever burned hotly in any part of the country Kentucky
was the spot. There the whole male population was eager to prove
its earnestness. When Henry Clay returned to Lexington after the
declaration of war, he wrote to Monroe[340] that he was almost
alarmed at the ardor his State displayed; about four hundred men
had been recruited for the regular army, and although no one had
volunteered for twelve months, the quota of six-months militia was
more than supplied by volunteers.
“Such is the structure of our society, however,” continued Clay,
“that I doubt whether many can be engaged for a longer term than
six months. For that term any force whatever which our population
can afford may be obtained. Engaged in agricultural pursuits, you are
well aware that from about this time, when the crop is either secured
in the barn or laid by in the field until the commencement of the
spring, there is leisure for any kind of enterprise.”
Clay feared only that these six-months militia corps, which had
armed and equipped themselves for instant service, might not be
called out. His friends were destined not to be disappointed, for
early in August pressing letters arrived from Hull’s army at Detroit
begging reinforcements, and the governor of Kentucky at once
summoned two thousand volunteers to rendezvous, August 20, at
Newport, opposite Cincinnati. This reinforcement could not reach
Detroit before the middle of September, and the difficulties already
developed in Hull’s path showed that the war could not be finished
in a single campaign of six months; but the Kentuckians were not on
that account willing to lengthen their term of service even to one
year.
The danger revealed by Hull’s position threw a double obstacle in
the way of public energy, for where it did not check, it promised to
mislead enthusiasm, and in either case it shook, if it did not destroy,
confidence in the national government. The leaders of the war party
saw their fears taking shape. Henry Clay wrote without reserve to
Monroe,[341]—
“Should Hull’s army be cut off, the effect on the public mind would
be, especially in this quarter, in the highest degree injurious. ‘Why did
he proceed with so inconsiderable a force?’ was the general inquiry
made of me. I maintained that it was sufficient. Should he meet with
a disaster, the predictions of those who pronounced his army
incompetent to its object will be fulfilled; and the Secretary of War, in
whom already there unfortunately exists no sort of confidence, cannot
possibly shield Mr. Madison from the odium which will attend such an
event.”
Clay was right in thinking that Eustis could not shield Madison;
but from the moment that Eustis could no longer serve that purpose,
Clay had no choice but to shield the President himself. When the
threatened disaster took place, victims like Eustis, Hull, Van
Rensselaer, Smyth, were sacrificed; but the sacrifice merely prepared
new material for other and perhaps worse disasters of the same
kind. In Kentucky this result was most strongly marked, for in their
irritation at the weakness of the national Government the
Kentuckians took the war into their own hands, appointed William
Henry Harrison to the command of their armies, and attempted to
conquer Canada by a campaign that should not be directed from
Washington. August 25 Clay described the feelings of his State by a
comparison suggesting the greatest military misfortunes known in
history:[342]
“If you will carry your recollections back to the age of the
Crusaders and of some of the most distinguished leaders of those
expeditions, you will have a picture of the enthusiasm existing in this
country for the expedition to Canada and for Harrison as commander.”