Full Download Readings from Programming with C++ 1st Edition Kyla Mcmullen PDF DOCX
Full Download Readings from Programming with C++ 1st Edition Kyla Mcmullen PDF DOCX
com
https://ebookmeta.com/product/readings-from-programming-
with-c-1st-edition-kyla-mcmullen/
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/mechanical-behavior-of-materials-
fundamentals-analysis-and-calculations-huda/
ebookmeta.com
Rick Steves Europe Through the Back Door The Travel Skills
Handbook 39th Edition Rick Steves
https://ebookmeta.com/product/rick-steves-europe-through-the-back-
door-the-travel-skills-handbook-39th-edition-rick-steves/
ebookmeta.com
https://ebookmeta.com/product/chemistry-for-engineering-students-
brown-and-holme/
ebookmeta.com
https://ebookmeta.com/product/blaze-1st-edition-delilah-mohan/
ebookmeta.com
https://ebookmeta.com/product/skywave-book-i-the-rorschach-explorer-
missions-1st-edition-k-patrick-donoghue/
ebookmeta.com
https://ebookmeta.com/product/modern-physics-kenneth-s-krane/
ebookmeta.com
Medicine Hands Massage Therapy for People with Cancer
Gayle Mcdonald Ms Lmt
https://ebookmeta.com/product/medicine-hands-massage-therapy-for-
people-with-cancer-gayle-mcdonald-ms-lmt/
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
And a Bristol man named Bowen, after fourteen Breton pirates had
come ashore near Tenby to obtain victuals, acted with such
smartness that he was able to have the whole lot captured and put
into prison. And John Wynter, another Bristolian, knowing that the
pirates were hovering about for those ships bound for the fair,
promptly manned a ship, embarked fifty soldiers, as well as the able
seamen, and cruised about ready to swoop down on the first pirate
ship which showed up on the horizon. The full details of these men
and what they did would make interesting reading if they were
obtainable; but we know that of the above-mentioned fourteen, one,
John du Laerquerac, was captain of the Breton craft. On being
arrested he stoutly denied that he had ever “spoiled” English ships.
That was most certainly a bare-faced lie, and presently Peter
Dromyowe, one of his own mariners, confessed that he himself had
robbed one Englishman; whereupon Laerquerac made a confession
that, as a matter of fact, he had taken ships’ ropes, sailors’ wearing
apparel, five pieces of wine, a quantity of fish, a gold crown in
money and eleven silver halfpence or pence, as well as four daggers
and a “couverture”!
It was because the English merchants complained that they lost so
much of their imports and exports by depredations from the ships of
war belonging to Biscay, Spain, the Low Countries, Normandy,
Brittany and elsewhere, that Henry viii. had been prevailed upon to
send Sir John Dudley, his Vice-Admiral, to sea with a small fleet of
good ships. Dudley’s orders were to cruise between the Downs on
the east and St. Michael’s Mount on the west—in other words, the
whole length of the English Channel—according as the wind should
serve. In addition, he was to stand off and on between Ushant and
Scilly and so guard the entrance to the Channel. Furthermore, he
was to look in at the Isle of Lundy in the Bristol Channel—for both
Lundy and the Scillies were famous pirate haunts—and after having
so done he was to return and keep the narrow seas. Dudley was
especially admonished to be on the look out to succour any English
merchant ships, and should he meet with any foreign merchant craft
which, under the pretence of trading, were actually robbing the
King’s subjects, he was to have these foreigners treated as absolute
pirates and punished accordingly.
For the state of piracy had become so bad that the King “can no
longer suffer it.” So also Sir Thomas Dudley, as well as Sir John, was
busily employed in the same preventive work. On the 10th of August
of that same year, 1537, he wrote to Cromwell that he had at
Harwich arrested a couple of Frenchmen who two years previously
had robbed a poor English skipper’s craft off the coast of Normandy,
and this Englishman had in vain sued in France for a remedy, since
the pirates could never be captured. But there were so many of
these corsairs being now taken that it was a grave problem as to
how they should be dealt with. “If they were all committed to ward,”
wrote Sir Thomas, “as your letters direct, they would fill the gaol.”
Then he adds: “They would fain go and leave the ship behind them,
which only contains ordnance, and no goods or victuals to find
themselves with. If they go to gaol, they are like to perish of hunger,
for Englishmen will do no charity to them. They are as proud naves
as I have talked with.”
Eleven days later came the report from Sir John Dudley of his
experiences in the Channel. He stated that while on his way home
he encountered a couple of Breton ships in the vicinity of St. Helen’s,
Isle of Wight, where he believed they were lying in wait for two
Cornish ships “that were within Porchemouthe haven, laden with tin
to the value of £3000.” Portsmouth is, of course, just opposite St.
Helen’s, and on more than one occasion in naval history was the
latter found a convenient anchorage by hostile ships waiting for
English craft to issue forth from the mainland. But when these
Breton pirates espied Dudley’s ships coming along under sail, they
“made in with Porchemouthe,” where Dudley’s men promptly
boarded them and placed them under arrest, with the intention of
bringing them presently to the Thames. Dudley had no doubt
whatever that these were pirates, but at a later date the French
ambassador endeavoured to show that there was no foundation for
such a suspicion. These two French crafts, he sought to persuade,
were genuine merchantmen who had discharged their cargo at “St.
Wallerie’s” (that is to say, St. Valery-sur-Somme), but had been
driven to the Isle of Wight by bad weather, adding, doubtless as a
subtle hint, that they had actually rescued an Englishman chased by
a Spaniard. It is possible that the Frenchmen were telling the truth,
though unless the wind had come southerly and so made it
impossible for these bluff-bowed craft to beat into their port, it is
difficult to believe that they could not have run into one of their own
havens. At any rate, it was a yarn which Dudley’s sailors found not
easy to accept.
This was no isolated instance of the capture of Breton craft. In the
year 1532 a Breton ship named the Mychell, whose owner was one
Hayman Gillard, her master being Nicholas Barbe of St. Malo, was
encountered by a crew of English seamen who entertained no
doubts whatsoever as to her being anything else than a pirate. Their
suspicions were made doubly sure when they found her company to
consist of nine Bretons and five Scots. They arrested her at sea, and
when examined she was found well laden with wool, cloth and salt
hides. Some French pirate ships even went so far as to wear the
English flag of St. George, with the red cross on a white ground.
This not unnaturally infuriated English seamen, especially when it
was discovered that the Bretons had also carried Englishmen as their
pilots and chief mariners, and were training them to become experts
in piracy.
But there were times when English seamen and merchants were
able to “get their own back” with interest, as the following incident
will show. At the beginning of June, in the year 1538, an English
merchant, Henry Davy, freighted a London ship named the Clement,
which was owned by one Grenebury, who lived in Thames Street,
and dispatched her with orders to proceed to the “Bay in Breteyne.”
She set forth under the command of a man named Lyllyk, the ship’s
purser being William Scarlet, a London clothworker. Seven men
formed her crew, but when off Margate they took on board nine
more. They then proceeded down Channel and took on board
another four from the shore, but espying a Flemish ship of war they
deemed it prudent to get hold of the coast of Normandy as soon as
possible. In the “mayne” sea—by which I understand the English
Channel near the mainland of the Continent—they descried coming
over the waves three ships, and these were found to be Breton
merchantmen.
This caused some discussion on board the Clement, and Davy, the
charterer, who had come with the ship, remarked to the skipper
Lyllyk that they had lost as much as £60 in goods, which had been
captured by Breton pirates at an earlier date, and had never been
able to obtain compensation in France in spite of all their
endeavours. Any one who has any imagination and a knowledge of
seafaring human nature, can easily picture Lyllyk and his crew
cordially agreeing with Davy’s point of view, and showing more than
a mere passive sympathy. The upshot of the discussion was that
they resolved to take the law into their own hands and capture one
of these three ships.
The resolution was put into effect, so that before long they had
become possessed of the craft. The Breton crew were rowed ashore
in a boat and left there, and after collecting the goods left behind,
the Englishmen stowed them in the hold of the Clement. A prize
crew, consisting of a man whose name was Comelys, and four
seamen, were placed in charge of the captured ship, which now got
under way. The Clement, too, resumed her voyage, and made for
Peryn in Cornwall, where she was able to sell, at a good price, the
goods taken out of the Breton. The gross amount obtained was
divided up among the captors, and though the figures may not seem
very large, yet the sum represented the equivalent of what would be
to-day about ten times that amount of money. Henry Davy, being
the charterer, received £17; the master, the mate, the quarter-
master and the purser received each thirty shillings, while the
mariners got twenty shillings apiece. Lyllyk and nine of the crew
then departed, while Davy, Scarlet, Leveret the carpenter and two
others got the ship under way, sailed up Channel and brought the
Clement back to the Thames, where they delivered her to the wife of
the owner.
But Englishmen were not always so fortunate, and the North Sea
pirates were still active, in spite of the efforts which had been made
by English kings in previous centuries. In 1538 the cargo ship
George Modye put to sea with goods belonging to a company of
English merchant adventurers, consisting of Sir Ralph Waryn, “good
Mr. Lock and Rowland Hyll” and others. She never reached her port
of destination, however, for the Norwegian pirates pillaged her and
caused a loss to the adventurers of £10,000, whereupon, after
complaint had been made, Cromwell was invoked to obtain letters
from Henry viii. to the kings of Denmark, France and Scotland that
search might be duly made. There was, in fact, a good deal of luck,
even yet, as to whether a ship would ever get to the harbour
whither she was sent. In September 1538 we find Walter Herbart
complaining that twice since Candlemas he had been robbed by
Breton pirates. But, a week later, it is recorded that some pirates,
who had robbed peaceable ships bound from Iceland, had been
chased by John Chaderton and others of Portsmouth and captured
about this time.
And it was not always that Englishmen dealt with these foreigners
in any merciful manner, regardless of right or wrong. I have already
emphasised the fact that, as regards the question of legality, there
was little to choose between the seamen of any maritime nation.
Rather it was a question of opportunity, and the very men who to-
day complained bitterly of the robbery of their ships and cargoes
might to-morrow be found performing piracy themselves. A kind of
sea-vendetta went on, and in the minds of the mariners the only sin
was that of being found out. So we notice that, in the spring of
1539, an instance of a Breton ship being captured by English
corsairs who, according to the recognised custom of the sea,
forthwith threw overboard the French sailors. These were all
drowned except one who, “as if by a miracle, swam six miles to
shore.” So says the ancient record, though it is difficult to believe
that even a strong swimmer could last out so long after being badly
knocked about. The Bretons had their revenge this time, for
complaint was made to the chief justices, who within fifteen days
had the culprits arrested and condemned, and six of them were
executed on the 19th of May. Before the end of the month Francis i.
wrote to thank the English king for so promptly dealing with the
culprits.
Bearing in mind the interest which Henry viii. took in nautical
matters and in the welfare of his country generally; recollecting, too,
the determination with which he pursued any project to the end
when once his mind had been made up, we need not be surprised to
find that a few months later in that year this resolute monarch again
sent ships—this time a couple of barks of 120 and 90 tons
respectively—“well manned and ordnanced” to scour the seas for
these pirate pests that inflicted so many serious losses on the Tudor
merchants.
A little earlier in that year Vaughan had written to Cromwell that
he had spoken with one who lately had been a “common passenger”
in hoys between London and Antwerp and knew of certain pirates
who intended to capture the merchant ships plying between those
two ports. Valuable warning was given concerning one of these
roving craft. She belonged to Hans van Meghlyn, who had fitted out
a ship of the “portage” of 20 lasts and 45 tons burthen. She was
manned by a crew of thirty, her hull was painted black with pitch,
she had no “foresprit,” and her foremast leaned forward like a
“lodeman’s” boat. (“Lodeman” was the olden word for pilot—the
man who hove the lead.) Cromwell was advised that this craft would
proceed first to Orfordness (the natural landfall for a vessel to make
when bound across the North Sea from the Schelde), and thence
she would proceed south and lie in wait for ships at the mouth of
the Thames. In order to be ready to pillage either the inward or
outward bound craft which traded with London, this pirate would
hover about off White Staple (Whitstable). Vaughan’s informant
thought that sometimes, however, she would change her locality to
the Melton shore in order to avoid suspicion, and he advised that it
would be best to capture her by means of three or four well-manned
oyster boats. There was also another “Easterling” (that is, one from
the east of Germany or the Baltic) pirate who had received his
commission from the Grave of Odenburg. This rover was named
Francis Beme and was now at Canfyre with his ship, waiting for the
Grave of Odenburg’s return from Brussels with money. But the
warning news came in time, and in order to prevent the English
merchant ships from falling into the sea-rovers’ hands, the former
were ordered by proclamation to remain in Antwerp from Ash
Wednesday till Easter.
CHAPTER IV
THE CORSAIRS OF THE SOUTH
Uruj with his one craft attacked the two galleys of Pope Julius
II laden with goods from Genoa. His officers remonstrated
with Uruj on the desperate venture, but to enforce his
commands and prevent any chance of flight he had the oars
thrown overboard. He then attacked and overcame the
galleys.
For a time Tunis seemed to be the most alluring spot in every
way: and strategically it was ideal for the purpose of rushing out and
intercepting the traffic passing between Italy and Africa. He came to
terms with the Sultan of Tunis, and, in return for one-fifth of the
booty obtained, Uruj was permitted to use this as his headquarters,
and from here he began with great success to capture Italian
galleys, bringing back to Tunis both booty and aristocratic prisoners
for perpetual exile. The women were cast into the Sultan’s harem,
the men were chained to the benches of the galleys.
One incident alone would well illustrate the daring of Uruj, who
had now been joined by his brother. The story is told by Mr. Stanley
Lane Poole in his history of the Barbarian corsairs, that one day,
when off Elba, two galleys belonging to Pope Julius ii. were coming
along laden with goods from Genoa for Civita Vecchia. The disparity
and the daring may be realised when we state that each of these
galleys was twice the size of Uruj’s craft. The Papal galleys had
become separated, and this made matters easier for the corsair. In
spite of the difference in size, he was determined to attack. His
Turkish crew, however, remonstrated and thought it madness, but
Uruj answered this protestation by hurling most of the oars
overboard, thus making escape impossible: they had to fight or die.
This was the first time that Turkish corsairs had been seen off
Elba, and as the Papal galley came on and saw the turbaned heads,
a spirit of consternation spread throughout the ship. The corsair
galley came alongside, there was a volley of firing, the Turkish men
leapt aboard, and before long the ship and the Christians were
captured. The Christians were sent below, and the Papal ship was
now manned by Turks who disguised themselves in the Christians’
clothes. And now they were off to pursue the second galley. As they
came up to her the latter had no suspicion, but a shower of arrows
and shot, followed by another short, sharp attack, made her also a
captive. Into Tunis came the ships, and the capture amazed both
Barbarian corsair and the whole of Christendom alike. The fame of
Uruj spread, and along the whole coast of North Africa he was
regarded with a wonder mingled with the utmost admiration. He
became known by the name Barbarossa, owing to his own physical
appearance, the Italian word rossa signifying red, and barba
meaning a beard. He followed up this success by capturing next year
a Spanish ship with 500 soldiers. And there were other successes, so
that in five years he had eight vessels. But Tunis now became too
small for him, so for a time he moved to the island of Jerba, on the
east coast of Tunis, and from there he again harassed Italy.
Such was the fame of Barbarossa that he was invited to help the
Moors. It chanced that the Moslem king of Bujeya had been driven
out of his city by the Spaniards, and the exile appealed to
Barbarossa to assist him in regaining his own. The reward offered to
the Turk was that, in the event of victory, Barbarossa should
henceforth be allowed the free use of Bujeya, the strategic
advantage of this port being that it commanded the Spanish sea.
The Turk accepted the invitation on these terms, and having now a
dozen galleys, with ample armament, in addition to 1000 Turkish
soldiers, as well as a number of renegades and Moors, he landed
before the town in August of 1512. Here he found the King ready
with his 3000 troops, and they proceeded to storm the bastion, in
which an all too weak Spanish garrison had been left. Still, for eight
days the Spaniards held out, and then when a breach was made and
a fierce assault was being carried out, Barbarossa had the
misfortune to have his left arm amputated, so, Bujeya being now left
alone, Barbarossa and his brother put to sea again. They had not
won the victory, but they had captured a rich Genoese galley full of
merchandise. Barbarossa took her back with him to his
headquarters, and while he recovered from his wounds his brother
Kheyr-ed-din acted in his stead.
Not unnaturally the Genoese were angered at the loss of their fine
galliot and sent forth Andrea Doria, the greatest Christian admiral,
with a dozen galleys to punish the Turks. The Christians landed
before Tunis, drove Kheyr-ed-din back into Tunis, and took away to
Genoa one-half of Barbarossa’s ships. Kheyr-ed-din now proceeded
to Jerba to build other ships as fast as possible, and as soon as his
wounds allowed him, Barbarossa here joined him. Meanwhile the
Moors were still chafing at their inability to get even with the
Spaniards, and once more an attempt was made to take Bujeya,
though unsuccessfully, and the corsair’s ships were burnt lest they
might fall into the hands of the enemy.
At length the Barbarossas resolved to quit Tunis and Jerba, for
they had now chosen to settle at Jijil, sixty miles to the east of
Bujeya. Their fame had come before them; the inhabitants were
proud to welcome the brother corsairs who had done many
wonderful things by land and sea, and before long the elder
Barbarossa was chosen as their Sultan. In 1516 died Ferdinand, and
about this time the Algerine Moors declined any longer to pay tribute
to Spain. To Barbarossa came an invitation to aid these inhabitants
of Algiers in driving the Spanish garrison from their fort. The
invitation was accepted, 6000 men and sixteen galliots were got
together. Arrived before the fortress of Algiers, Barbarossa offered a
safe conduct to the garrison if they would surrender, but the latter’s
reply was merely to remind the corsair of Bujeya. Then for twenty
days Barbarossa battered away at the fortress, but without making a
breach, and meanwhile the Moors began to regret that they had
asked the red beard to aid them. But it would be less easy to turn
them out now that once these dare-devils had set foot on their
territory. Barbarossa knew this and waxed insolent. The Algerines
made common cause with the soldiers in the fortress, and a general
rising against the red beard was planned. But they had reckoned
without their guest. For Barbarossa had spies at work and became
informed of this plot.
Whilst at prayers one Friday in the mosque, Barbarossa had the
gates closed, the conspirators brought before him one by one, and
then after twenty-two of them had been put to death there was an
end to this plotting against the corsair of Lesbos. Barbarossa
increased in power, in the number of his galleys, in the extent of his
territory and in the number of his subjects, so that by now he had
become Sultan of Middle Barbary. Practically the whole of that
territory marked on our modern maps of Algeria was under his sway.
Step by step, leaping from one success to another, ignoring his
occasional reverses, he had risen from a mere common pirate to the
rank of a powerful Sultan. So potent had he become, in fact, that he
was able to make treaties with other Barbarian Sultans, and all the
summer season his galleys were scouring the seas bringing back
increased wealth and more unfortunate Christian prisoners. Richly
laden merchant ships from Genoa, from Naples, from Venice, from
Spain set forth from home, and neither the ships nor their contents
were ever permitted to return or to reach their ports of destination.
However, the time came when the Christian States could no longer
endure this terrible condition of affairs. And Charles v. was moved to
send a strong force to deal with the evil. Ten thousand seasoned
troops were sent in a large fleet of galleys to Northern Africa, and at
last the wasp was killed. For Barbarossa, with his 1500 men, was
defeated, and he himself was slain while fighting boldly.
Unfortunately the matter ended there, and the troops, instead of
pressing home their victory and wiping the Barbarian coast clean of
this Moorish dirt, left Algiers severely alone and returned to their
homes. Had they, instead, ruthlessly sought out this lawless piratical
brood, the troublesome scourge of the next three centuries would
probably never have caused so many European ships and so many
English and foreign sailors and others to end their days under the
lash of tyrannical monsters.
CHAPTER V
THE WASPS AT WORK
But there was a third great Barbarian corsair to complete this terrible trio.
Uruj and Kheyr-ed-din we have known. There is yet to be mentioned Dragut,
who succeeded to the latter. He too was a Moslem who had been born in a
coast village of Asia Minor, opposite the island of Rhodes. His early life is that
of most pirates. He went to sea when quite young, was devoted to his
profession, was filled with ambition, became an expert pilot and later became
a skipper of his own craft. Then, feeling the call of the wild, he devoted
himself to piracy and rose to notoriety.
But the turning-point in his career came when he joined himself to the
service of Kheyr-ed-din, who appointed Dragut to the entire command of a
dozen of the corsair king’s galleys. Henceforward his life was that of his
master, ravaging the Italian coasts, pillaging Mediterranean ships and
dragging thousands of lives away into slavery. Two years after the battle of
Prevesa, Dragut was in fame second only to Kheyr-ed-din, and another Doria
—the nephew of Andrea—was sent forth to capture this new wasp of the sea.
Doria succeeded in throwing his net so well that off the Corsican coast he was
able to bring back Dragut as prisoner, and for the next four years the ex-
corsair was condemned to row as a slave in a Christian galley, until on a day
his late master Kheyr-ed-din came sailing into Genoa. During his active,
pillaging life he had obtained plenty of riches, so it was nothing for him to pay
3000 ducats and thus redeem from slavery a man who had been particularly
useful to his own schemes.
And from this day until Dragut fell fighting in 1565, he followed in the
footsteps of the man who brought him his release. When Kheyr-ed-din died,
the Turkish Sultan appointed Dragut as admiral of the Ottoman fleet. Like
Barbarossa, Dragut’s first object was to obtain a base in Northern Africa, and
eventually he was able to capture the town of “Africa” or Mehedia, to the east
of Tunis. His next proceeding was to fortify this place. The news came to the
ears of Charles v. that this had happened. The two Barbarossas were dead,
but there was another almost as pernicious. Was this pestilence of piracy
never to cease? Andrea Doria was an old man now, but he was bidden by
Charles to go after Dragut, and he went. Nor was he sorry for an opportunity
of wiping out his own undistinguished action at Prevesa. Dragut was away
harrying the coasts of Spain, and his nephew Aisa was left in charge of
“Africa.” Meanwhile Doria searched for him along the African coast, came to
“Africa,” but after losing some men and with great damage to his own ship,
Doria, as the season was getting late, returned home.
But the following June, Doria with his fleet arrived off Mehedia, besieged
the city, and, after an expenditure of great effort, took it, capturing Aisa.
Mehedia was lost, but Dragut was still at large. He repaired to
Constantinople and thence to Jerbah, the island off the east coast of Tunis.
Hither also came Andrea Doria and hemmed the corsair in. At last the pirate
was in a trap, but like many another clever rascal he found a way out with
consummate cleverness. What he did may briefly be summed up as follows:
Outside were the waiting Christian fleet, which was merely amused by the
sight of a new fort becoming daily greater. But these earthworks were just so
much bluff. For Dragut, by means of these, was able to conceal what was
being done on the other side. With marvellous ingenuity he had caused a road
to be made across the island to the sea on the other side; he had laid down a
surface of well-greased planks, and under the further cover of darkness had
made his men drag his galleys across till they were launched into the sea on
the opposite coast. The rest was easy, and the corsair fleet once more
escaped, having fooled Dorea in a manner that amazed him. To add
impudence to insult, Dragut at once captured a Sicilian galley on its way to
Dorea, containing Muley Hassan, Sultan of Tunis. The latter was promptly sent
as a present to the Sultan of Turkey, who allowed him to end his days in
prison.
Of the rest of the acts of this corsair we have but little space to speak. It is
sufficient if we say that he well bore the mantle which had fallen to him from
the shoulders of Barbarossa. He continued his scourging of the seas, he
fought gallantly, he laid waste and he captured prisoners for slavery. Power
and dominion came to him as to his predecessors, and before long he was the
ruler of Tripoli and more than ever the enemy of the Christian race. Finally he
died at the siege of Malta, but he in turn was succeeded by Ali Basha of
Algiers, who conquered the kingdom of Tunis, captured Maltese galleys, and
showed that the old corsair spirit was still alive.
But the day of reckoning was at hand, and there was to be settled in one of
the most momentous events of history a debt that had long been owing to
the Christians. Of all the decisive battles of the world few stand out more
conspicuously than the battle of Lepanto. In spite of all the great maritime
expeditions which had been sent to put down piracy in the Mediterranean, the
evil had recurred again and again. There were two reasons why Christian
Europe was determined to beat these corsairs: firstly, the latter were natural
enemies because they were Moslems; but, secondly, they were the worst type
of pirates. All the losses of Christian lives, goods and ships merely increased
the natural hatred of these Mohammedans. And in Lepanto we see the last
great contest in which these truculent corsairs fought as a mighty force.
Thereafter there were repeated piratical attacks by these men, but they of a
more individualistic nature than proceeding from an enormous organisation.
Lepanto was fought sixteen years before the Elizabethans defeated the
Armada. Before we say anything of the contest itself it is necessary to remind
the reader that whereas in the contest which took place in the waters that
wash England, the bulk of the ships were sail-propelled and had high
freeboard (with some exceptions), yet at Lepanto it was the reverse. The
fighting ship of the Mediterranean from the very earliest times had always
been of the galley type, even though it contained variations of species. And
never was this characteristic more clearly manifested than at the battle of
which we are now to speak. There were galleys and galleasses, but though
the former were certainly somewhat big craft, yet the latter were practically
only big editions of the galley.
The value of Lepanto is twofold. It proved to the world that the great
Ottoman Empire was not invincible on sea. It showed also that in spite of all
that the cleverest corsair seamen could do, there were sufficient unity and
seamanlike ability in Christian Europe to defeat the combined efforts of
organised piracy and Mohammedanism. No one can deny that Ali Basha
distinguished himself as a fine admiral at this battle, yet he was not on the
side of victory. When he found himself defeated there fell simultaneously the
greatest blow which organised piracy had received since it established itself
along the southern shores of the Mediterranean. Lepanto was no mere
isolated event; it was the logical outcome of the conflict between Christianity
on the one hand and Mohammedanism with piracy on the other. It is as unfair
to omit the consideration of Moslemism from the cause of this battle as it
were to leave out the fact of piracy.
The solidarity of the Christian expedition was formed by what was called
the Holy League, embracing the ships of the Papal States, Spain and Venice.
The unity of the opposing side was ensured by the fidelity of the Barbarian
corsairs to the Sultan of Turkey. In supreme command of the former was Don
John of Austria, son of that Charles v. who had done so much to oust these
corsair wasps. The Christian fleet numbered about three hundred, of which
two-thirds were galleys, and they collected at Messina. The scene where the
battle was to take place was already historic. It was practically identical with
that of Prevesa, of which we have already spoken, and with that of the
classical Actium in 31 b.c., though exactly it was a little to the south of where
Prevesa had been fought. Just as in the latter Kheyr-ed-din had fought against
Andrea Doria, so now Dragut was to fight against John Andrea Doria. The
Moslem strength may be gauged from the statement that it contained 250
galleys plus a number of smaller ships. But just as Prevesa had been marked
by little fighting but much manœuvring, so Lepanto was distinguished by an
absence of strategy and a prevalence of desperate, hard hitting. Whatever
strategy was displayed belonged to Ali Basha. The galleasses of the Christian
side dealt wholesale death into the Moslems, though Andrea’s own flagship
suffered severely in the fight. Spanish, Venetian and Maltese galleys fought
most gallantly, but Ali Basha, after capturing the chief of the Maltese craft,
was obliged to relinquish towing her, and himself compelled to escape from
the battle. At least 5000 Christians perished at Lepanto, but six times that
amount were slaughtered of the Moslems, together with 200 of the latter’s
ships. The corsairs had rendered the finest assistance, but they had failed
with distinction.
Christian craft had won the great day, and never since that autumn day in
1571 have the pirates of Barbary attained to their previous dominion and
organised power. Ali returned to Constantinople, and even the next year was
again anxious to fight his late enemies, though no actual fighting took place.
Still another year later Tunis was taken from the Turks by Don John of Austria.
For nine years after the event of Lepanto, Ali Basha lived on, and, like his
predecessors, spent much of his time harrying the Christian coastline of
southern Italy. There were many pirates for long years after his death, but
with the decease of Ali Basha closed the grand period of the Moslem corsairs.
It had been a century marked by the most amazing impudence on the part of
self-made kings and tyrants. But if it showed nothing else, it made perfectly
clear what enormous possibilities the sea offered to any man who had enough
daring and self-confidence in addition to that essential quality of sea-sense.
From mere common sailormen these four great corsairs—the two
Barbarossas, Dragut and Ali Basha—rose to the position of autocrats and
admirals. Mere robbers and bandits though they were, yet the very mention of
their names sent a shudder through Christendom. And it was only the
repeated and supreme efforts of the great European powers which could
reduce these pirate kings into such a condition that honest ships could pursue
their voyages with any hope of reaching their destined ports. Surely, in the
whole history of lawlessness, there never were malefactors that prospered for
so long and to such an extent!