100% found this document useful (1 vote)
24 views

Full Download Readings from Programming with C++ 1st Edition Kyla Mcmullen PDF DOCX

Kyla

Uploaded by

hostipia45
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
100% found this document useful (1 vote)
24 views

Full Download Readings from Programming with C++ 1st Edition Kyla Mcmullen PDF DOCX

Kyla

Uploaded by

hostipia45
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 65

Download Full Version ebook - Visit ebookmeta.

com

Readings from Programming with C++ 1st Edition


Kyla Mcmullen

https://ebookmeta.com/product/readings-from-programming-
with-c-1st-edition-kyla-mcmullen/

OR CLICK HERE

DOWLOAD NOW

Discover More Ebook - Explore Now at ebookmeta.com


Instant digital products (PDF, ePub, MOBI) ready for you
Download now and discover formats that fit your needs...

Start reading on any device today!

Readings from Programming with C++ 1st Edition Kyla


Mcmullen

https://ebookmeta.com/product/readings-from-programming-with-c-1st-
edition-kyla-mcmullen/

ebookmeta.com

Mnemonics for Radiologists and FRCR 2B Viva Preparation A


Systematic Approach Aug 15 2013 _ 1908911956 _ CRC Press
1st Edition Yoong
https://ebookmeta.com/product/mnemonics-for-radiologists-and-
frcr-2b-viva-preparation-a-systematic-approach-
aug-15-2013-_-1908911956-_-crc-press-1st-edition-yoong/
ebookmeta.com

Ergodic theory geometry and dynamics 1st Edition C


Mcmullen

https://ebookmeta.com/product/ergodic-theory-geometry-and-
dynamics-1st-edition-c-mcmullen/

ebookmeta.com

Mechanical Behavior of Materials: Fundamentals, Analysis,


and Calculations Huda

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

Chemistry for Engineering Students Brown And Holme

https://ebookmeta.com/product/chemistry-for-engineering-students-
brown-and-holme/

ebookmeta.com

Blaze 1st Edition Delilah Mohan

https://ebookmeta.com/product/blaze-1st-edition-delilah-mohan/

ebookmeta.com

Skywave Book I The Rorschach Explorer Missions 1st Edition


K Patrick Donoghue

https://ebookmeta.com/product/skywave-book-i-the-rorschach-explorer-
missions-1st-edition-k-patrick-donoghue/

ebookmeta.com

Modern Physics Kenneth S. Krane

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

C++ KYLA McMULLEN


Elizabeth matthews
June Jamrich Parsons

Australia • Brazil • Canada • Mexico • Singapore • United Kingdom • United States

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

Technical Editor: John Freitas Library of Congress Control Number: 2020922802

Developmental Editor: Lisa Ruffolo ISBN: 978-0-357-63775-3

Vice President, Marketing – Science, Technology,


Cengage
& Math: Jason Sakos
200 Pier 4 Boulevard
Senior Director, Marketing: Michele McTighe Boston, MA 02210
USA
Marketing Manager: Cassie L. Cloutier

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

prefacexiii Build Tools 22


The Toolset 22
Module 1 Compilers 23
COMPUTATIONAL THINKING 1 Preprocessors and Linkers 24
Virtual Machines 25
Algorithms2 Interpreters 26
Algorithm Basics 2 Debugging Tools 27
Programming Algorithms 2 Programming Errors 27
“Good” Algorithms 3 Syntax Errors 28
Selecting and Creating Algorithms 4 Runtime Errors 29
Decomposition4 Semantic Errors 29
Decomposition Basics 4 Debugging Utilities 30
Structural Decomposition 5 IDEs and SDKs 32
Functional Decomposition 6 Integrated Development Environments 32
Object-Oriented Decomposition 7 Software Development Kits 32
Dependencies and Cohesion 7
Summary 33
Pattern Identification 8
Key Terms  34
Pattern Identification Basics 8
Repetitive Patterns 8
Module 3
Classification Patterns 9
Abstraction9 LITERALS, VARIABLES, AND
Abstraction Basics 9 CONSTANTS35
Classes and Objects 10
Literals36
Black Boxes 11
Numeric Literals 36
Levels of Abstraction 12
Character and String Literals 37
Summary12 Tricky Literals 38
Key Terms  13 Variables and Constants 38
Variables 38
Module 2 Constants 40
PROGRAMMING TOOLS 15 The Memory Connection 41
Assignment Statements 41
Programming Languages 16 Declaring Variables  41
Hello World! 16 Initializing Variables 42
Programming Language Basics 16 Assigning Variables 43
Syntax and Semantics 17
Input and Output 44
Core Elements 19
Your Toolbox 19 Input to a Variable  44
Output from a Variable 46
Coding Tools 20
Program Editors 20 Summary 46
Basic Structure 21 Key Terms  47

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

Module 8 Pass by Reference 161


Namespaces 162
Arrays 125
Summary 163
Array Basics 126
Key Terms 163
Magic Rectangles 126
Array Characteristics 127
Array Use Cases 128 Module 10
One-Dimensional Arrays 128 Recursion 165
Initialize Numeric Arrays 128
Key Components of Recursion 165
Initialize String Arrays 130
The Recursive Mindset 165
Array Input and Output 130 Recursion Basics 167
Output an Array Element 130 When to Use Recursion 171
Index Errors 131
Using Recursion to Solve Complex
Traverse an Array 132
Problems 171
Input Array Elements 133
Designing Recursive Structures 171
Array Operations 135 Linear Recursion 174
Change an Array Element 135 Branching Recursion 175
Find an Array Element 135
Managing Memory during Recursion 179
Sum Array Elements 137
Memory Management 179
Two-Dimensional Arrays 137 Stable Recursion 182
Two-Dimensional Array Basics 137
Summary 183
Initialize a Two-Dimensional Array 138
Output a Two-Dimensional Array 139 Key Terms 183
Sum Array Columns and Rows 141
Summary 143 Module 11
Key Terms 144 Exceptions 185
Defining Exceptions 185
Module 9 Errors in Code 185
Functions 145 Exception Types 187

Function Basics 146 Dealing with Exceptions 189


Function Classifications 146 Handling Others’ Exceptions 189
Programmer-Defined Functions 146 Try and Catch Blocks 189
Flow of Execution 147 Using Exceptions 198
Function Advantages 147 Throwing Exceptions 198
Void Functions 148 When to Bail 202
Void Function Basics 148 Summary 203
Function Pseudocode 149
Key Terms 203
Functions with Parameters 150
Function Parameters 150
Module 12
Function Arguments 150
The Handoff 152 File Operations 205
Return Values 153 File Input and Output 206
Return Values 153 The Purpose of Files 206
Return Type 156 Anatomy of a File 210
Function Signature 157 File Usage 212
Scope 157 Processing a File 214
Scope Basics 157 Accessing Files 214
Pass by Value 160 Streaming and Buffering 214

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

Module 17 The Find Method 346


The Insert Method 347
Polymorphism 309
Summary 350
The Purpose of Polymorphism 309
Key Terms 351
Flexibility While Coding 309
Dynamic Binding Under the Hood 314
Polymorphism Basics 314 Module 20
Classes Within Classes 314 Stacks and Queues 353
Objects as Other Objects 315 Stacks 353
Virtual Functions 316 Stack Basics 353
Anticipating Customization 316 Stack Use Cases 355
Abstract Classes 317 Built-in Stacks 356
Summary 318 Code a Stack 357

Key Terms 318


Queues 362
Queue Basics 362
Module 18 Queue Use Cases 363
Code a Queue 364
Templates 319
Summary 369
Template Basics 319
Key Terms 369
Data Abstraction 319
Template Structure and Use 322
Module 21
Tricky Templating 328
Advanced Templating 328
Trees and Graphs 371
Templated Objects as Arguments 330 Nonlinear Data Structures 371
Templates as a Problem-Solving Linear versus Nonlinear Structures 371
Approach 331 Nonlinear Building Blocks 373
Designing a Template 331 Tree Structures 373
When to Use Templates 331 Tree Basics 373
Summary 331 Tree Properties 376
Trees as Recursive Structures 376
Key Terms 332
Solving Problems Using Trees 379
Module 19 Tree Applications 379
Linked List Data Data Storage in Trees 380
Graph Structures 387
Structures 333
Graph Basics 387
Linked List Structures 334 Directed and Undirected Graphs 388
Data Structure Selection 334 Solving Problems with Graphs 388
Data Structure Implementation 335 Graph Applications 388
Linked List Basics 336 Computing Paths 389
Types of Linked Lists 337
Summary 394
Singly Linked Lists 337
Doubly Linked Lists 338 Key Terms 394
Circular Linked Lists 339
Linked List Characteristics 339 Module 22
Code a Linked List 342 Algorithm Complexity
The Node Class 342 and Big-O Notation 395
The LinkedList Class 343
The Append Method 343 Big-O Notation 396
Linked List Traversal 345 Algorithm Complexity 396

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

Asymptotic Analysis 397 Quicksort 438


Asymptotic Notation 398 Defining the Quicksort Algorithm 438
Time Complexity 398 Quicksort Properties 446
Big-O Metrics 398 Merge Sort 447
Constant Time 399 Defining the Merge Sort Algorithm 447
Linear Time 399 Merge Sort Properties 453
Quadratic Time 400
Summary 454
Logarithmic Time 401
Key Terms 454
Space Complexity 403
Memory Space 403 Module 25
Constant Space Complexity 404
Linear Space Complexity 404 Processor Architecture 455
Complexity Calculations 405 Processor Organization 456
Line-by-Line Time Complexity 405 Integrated Circuits 456
Combine and Simplify 406 Moore’s Law 458
A Mystery Algorithm 407 CPUs 458
Low-Level Instruction Sets 459
Summary 409
Microprocessor Instruction Sets 459
Key Terms 409 RISC and CISC 460
Machine Language 460
Module 23 Assembly Language 461

Search Algorithms 411 Microprocessor Operations 462


Processing an Instruction 462
Using Search Algorithms 412 The Instruction Cycle 462
Search Basics 412 High-Level Programming Languages 464
Performing a Linear Search 413 Evolution 464
Looking for a Needle in a Haystack 413 Teaching Languages 465
Evaluating Search Time 416 The C Family 465
Web Programming Languages 466
Performing a Binary Search 416 Characteristics 466
Shrinking the Search Space 416 Advantages and Disadvantages 467
Implementing Binary Search 418
Summary 467
Using Regular Expressions
Key Terms 468
in Search Algorithms 423
Specifying a Search Pattern 423 Module 26
Regular Expression Search Operators 423
Data Representation 469
Summary 426
Bits and Bytes 470
Key Terms 426
Digital Data 470
Bits 471
Module 24 Bytes 472
Sorting Algorithms 427 Binary 474
Binary Numbers 474
Qualities of Sorting Algorithms 428 Binary to Decimal 475
Ordering Items 428 Decimal to Binary 476
Time Complexity in Sorting Algorithms 428 Binary Addition 477
Sorting Properties 430 Negative Numbers 478
Bubble Sort 431 Hexadecimal 480
Defining the Bubble Sort Algorithm 431 Colors 480
Bubble Sort Properties 437 Hexadecimal Numbers 481

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

Binary-Hex-Binary Conversions 481 Speech Synthesis 516


Hex-Decimal Conversion 482 Designing Programs for Voice User Interfaces 517
Information Density 483 Virtual Environment Interfaces 517
ASCII and Unicode 483 Virtual Environments 517
ASCII 483 Virtual Environment Interface Components 518
Extended ASCII 484 Programming the Virtual Interface 519
Unicode 485 Accessibility and Inclusion 520
Memory Allocation 486 Accessibility Guidelines 520
Memory and Storage 486 Inclusive Design 521
Storage Devices 487 Summary 524
Memory 487
Key Terms 524
Summary 489
Key Terms 489
Module 29
Software Development
Module 27
Methodologies 525
Programming Paradigms 491
Software Development 526
Imperative and Declarative Paradigms 492
The Software Development Life Cycle 526
Think Outside the Box 492
Efficiency, Quality, and Security 527
The Procedural Paradigm 493 The Waterfall Model 528
Procedural Basics 493
Structured Analysis and Design 528
Characteristics of Procedural Programs 494
Waterfall Advantages and Disadvantages 529
Procedural Paradigm Applications 496
The Agile Model 530
The Object-Oriented Paradigm 497
Incremental Development 530
Objects, Classes, and Methods 497
Agile Methodologies 530
Characteristics of Object-Oriented Programs 499
Agile Advantages and Disadvantages 531
Object-Oriented Applications 501
Coding Principles 532
Declarative Paradigms 501
Efficient Coding 532
Declarative Basics 501
Modularized Code 533
Characteristics of the Declarative
Clean Coding 534
Paradigm 504
Secure Coding 534
Applications for Declarative Paradigms 504
Success Factors 536
Summary 505 Testing 536
Key Terms 505 Levels of Testing 536
Unit Testing 537
Module 28 Integration Testing 538
System Testing 539
User Interfaces 507 Acceptance Testing 539
User Interface Basics 508 Regression Testing 539
UI and UX 508 Summary 540
UI Components 508
Key Terms 540
Selecting a UI 510
Command-Line User Interfaces 510
Module 30
Command-Line Basics 510
Command-Line Program Design 510 Pseudocode, Flowcharts,
Graphical User Interfaces 512 and Decision Tables 541
GUI Basics 512 Pseudocode 542
GUI Program Design 514
From Algorithms to Pseudocode 542
Voice User Interfaces 515 Pseudocode Basics 544
Voice Interface Basics 515 Pseudocode Guidelines 545
Speech Recognition 515 Writing Pseudocode 547

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

Flowcharts 548 UML Diagram Parts 558


Flowchart Basics 548 Class Diagram Basics 558
Drawing Flowcharts 548 Use Case Diagram Basics 559
Flowchart Tools 549 Sequence Diagrams 561
Decision Tables 551 Using UML to Structure Programs 562
Decision Table Basics 551 UML Associations 562
List the Conditions 551 Translating UML to Code 564
List All Possible Alternatives 552 Summary 568
Specify Results and Rules 552
Interpret Rules 553 Key Terms 568
Optimize the Rules 554
Check for Completeness and Accuracy 555
GLOSSARY 569
Summary 555
index 583
Key Terms 556

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

Welcome to Readings from Programming with C11.


This text includes the stand-alone lessons and read-
C11 Version
ings from MindTap for Programming with C11 and is We recommend downloading the latest version of
intended to be used in conjunction with the MindTap C11 before beginning this text. C1114 was used to
Reader for a complete learning experience. test all C11 code presented in the module figures.

MindTap Overview MindTap Features


Programming with C 11 presents conceptual, lan- In addition to the readings included within this text,
guage-agnostic narrative with language-specific assets, the MindTap includes the following:
ungraded C11 coding Snippets, language-agnostic test Course Orientation: Custom videos and readings pre-
banks, and additional instructor resources. The goal of pare students for the material and coding experiences
this digital product is to develop content around the they will encounter in their course.
concepts that are essential for understanding Com-
Videos: Animated videos demonstrate new program-
puter Science from a language-agnostic perspective.
ming terms and concepts in an easy-to-understand for-
Learners will gain a foundational understanding of
mat, increasing student confidence and learning.
procedural programming, computer science concepts,
and object-oriented programming. Instructors have Coding Snippets: These short, ungraded coding activities
identified the need for language-agnostic, conceptual are embedded within the MindTap Reader and provide
content that can be paired with hands-on practice in students an opportunity to practice new programming
a specific language. This 31-module text is designed to concepts “in-the-moment.” Additional language-specific
provide that conceptual content paired with language- “bridge content” helps transition the student from con-
specific examples and hands-on learning activities in ceptual understanding to application of C11 code.
C11. Language-specific Examples: Figures within the nar-
rative illustrate the application of general concepts in
C11 code.
Course Objectives:
• Develop a foundational knowledge of
coding principles, vocabulary, and core Instructor & Student Resources
concepts. Additional instructor and student resources for
• Use new foundational knowledge to this product are available online. Instructor assets
learn C11 programming skills. include an Instructor’s Manual, Teaching Online
• Practice emerging coding skills in a low- Guide, ­PowerPoint® slides, and a test bank powered
risk environment. by ­Cognero®. Student assets include source code
• Apply learned concepts and skills to files and coding Snippets ReadMe. Sign up or sign in
assignments/activities that mimic real- at www.cengage.com to search for and access this
world experiences and environments. product and its online resources.

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.

Connect to the site’s login page.


Enter your user ID.
Enter your password.
Wait for a text message containing a PIN
to arrive on your smartphone.
On the site’s the login page, enter the PIN.

Figure 1-1 Steps for two-factor authentication

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:

• A recipe for baking brownies


• The steps for changing a tire
• The instructions for pairing a smart watch with your phone
• The payment process at an online store
• The procedure for posting a tweet

Programming Algorithms (1.1.2, 1.1.3, 1.1.5)


Algorithms are also an important tool for programmers. A programming algorithm is a set of steps that speci-
fies the underlying logic and structure for the statements in a computer program. You can think of programming
algorithms as the blueprints for computer programs.
A computer program is a set of instructions, written in a programming language such as C++, Python, or
Java, that performs a specific task when executed by a digital device. A computer program is an implementation
of an algorithm.

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!

“Good” Algorithms (1.1.6, 1.1.7)


Computer scientists are interested in designing what they call “good” algorithms. A good algorithm tends
to produce a computer program that operates efficiently, quickly, and reliably. Good algorithms have these
characteristics:
Input: The algorithm applies to a set of specified inputs.
Output: The algorithm produces one or more outputs.
Finite: The algorithm terminates after a finite number of steps.
Precise: Each step of the algorithm is clear and unambiguous.
Effective: The algorithm successfully produces the correct output.

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.

Is there input? Yes.

Get the last number in the series (10).


Divide 10 by 2 to get a RESULT. Are the steps precise and
Add 10 + 1 to get a SUM. unambiguous? Yes.
Multiply the RESULT by the SUM to
Does the algorithm terminate? Does the algorithm produce
produce a total.
Yes, after the fourth step. the correct output?
Yes, it is 55.
Is there output? Yes.

Figure 1-2 Is this a good algorithm?

Selecting and Creating Algorithms (1.1.8, 1.1.9, 1.1.10)


Before coding, programmers consider various algorithms that might apply to a problem. You can come up with
an algorithm in three ways:
Use a standard algorithm. Programmers have created effective algorithms for many computing
tasks, such as sorting, searching, manipulating text, encrypting data, and finding the shortest path.
When you are familiar with these standard algorithms, you can easily incorporate them in programs.
Perform the task manually. When you can’t find a standard algorithm, you can formulate an
algorithm by stepping through a process manually, recording those steps, and then analyzing their
effectiveness.
Apply computational thinking techniques. Computational thinking is a set of techniques designed
to formulate problems and their solutions. You can use computational thinking techniques such as
decomposition, pattern identification, and abstraction to devise efficient algorithms. Let’s take a look
at these techniques in more detail.

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

Account balance Deposits

iStock.com/vector.S
Pay bills Withdrawals

Transfer money

Figure 1-3 A mobile banking app handles many


interacting tasks

Structural Decomposition (1.2.2, 1.2.3, 1.2.4, 1.2.7)


The first step in decomposition is to identify structural units that perform distinct tasks. Figure 1-4 illustrates
how you might divide a mobile banking app into structural units, called modules.

Mobile banking

Passcode/challenge Account Payments and


Secure login
question changes management transfers

Two-factor
Balances Bill pay
authentication

Fingerprint Mobile check


Alerts
sign-in deposits

Direct Money
deposits transfers

Figure 1-4 Structural decomposition diagram

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

Q Which module of the hierarchy chart is not fully decomposed?


A The module for modifying passwords and challenge questions could be further decomposed
into two modules: one module that allows users to change their passwords and one for
changing their challenge questions.

Here are some tips for creating a structural decomposition diagram:

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

Functional Decomposition (1.2.5)


Functional decomposition breaks down modules into smaller actions, processes, or steps. Figure 1-5 illustrates
a functional decomposition of the two-factor authentication module.

Verify login attempts

Verify password Verify PIN

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

Look up Compare Look up Generate


stored entered Handle user text Nodes in green are
user ID and date with mismatches mobile message specific enough to
password stored data number with PIN become steps in an
algorithm.

Nodes in yellow
require further
decomposition.

Figure 1-5 Functional decomposition diagram

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

Object-Oriented Decomposition (1.2.6)


Another way to apply decomposition to a module is to look for logical and physical objects that a computer
program will manipulate. Figure 1-6 illustrates an object-oriented decomposition of the two-factor authentica-
tion module.

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

Attribute: Valid user ID


Attribute: Valid password Attributes
Attribute: Mobile number describe an
object.

Figure 1-6 Object-oriented decomposition diagram

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.

Dependencies and Cohesion (1.2.8)


You might wonder if there is a correct way to decompose a problem or task. In practice, there may be several
viable ways to apply decomposition, but an effective breakdown minimizes dependencies and maximizes cohe-
sion among the various parts.
The principles of decomposition are:

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

1.3 PATTERN IDENTIFICATION


Pattern Identification Basics (1.3.1, 1.3.2)
The Amaze-Your-Friends math trick for quickly adding numbers from 1 to 10 is very simple:
Get the last number in the series (10).
Divide 10 by 2 to get a result.
Add 10 1 1 to get a sum.
Multiply the result by the sum.

Q Try the algorithm yourself. What is your answer?


A If your math is correct, your answer should be 55.

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.

Repetitive Patterns (1.3.3)


In addition to fill-in-the-blank patterns, you might also find repetitive patterns as you analyze tasks and problems.
Think about this algorithm, which handles logins to a social media site:
Get a user ID.
Get a password.
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, get the password again.
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.

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

Q How many repetition patterns do you recognize?


A Two lines are repeated three times:
If the password is not correct, get the password again.
If the password is correct, allow access.

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.

Classification Patterns (1.3.4, 1.3.5)


Everyone who subscribes to a social media site has a set of login credentials. Here are Lee’s and Priya’s:
Lee’s login credentials: Priya’s login credentials:
Lee’s user ID: LeezyBranson@gmail.com Priya’s user ID: PriyaMontell@gmail.com
Lee’s password: MyCat411 Priya’s password: ouY52311v
Lee’s mobile number: 415-999-1234 Priya’s mobile number: 906-222-0987
The series of attributes that define each user’s login credentials have a pattern of similarities. Each user
has three attributes: a user ID, a password, and a mobile number. By recognizing this pattern, you can create a
template for any user’s login credentials like this:
User ID: ____________________
Password: ____________________
Mobile number: ____________________
You can often discover classification patterns in the attributes that describe any person or object. Identify-
ing classification patterns can help you design programs that involve databases because the template identifies
fields, such as User ID, that contain data.
Classification patterns also come in handy if you want to design programs based on the interactions among
a variety of objects, rather than a step-by-step algorithm. In some programming circles, templates are called
classes because they specify the attributes for a classification of objects. For example, people classified as social
media subscribers have attributes for login credentials. Vehicles classified as cars have attributes such as color,
make, model, and VIN number. Businesses classified as restaurants have a name, hours of operation, and a menu.

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

Add ____________________ 1 1 to get a sum.


Multiply the result by the sum.
In this algorithm, the blank line is an abstraction that represents the last number in the sequence. An abstraction
hides details, simplifies complexity, substitutes a generalization for something specific, and allows an algorithm to
work for multiple inputs.
Abstraction is a key element of computational thinking and helps programmers in a multitude of ways.
If you’ve programmed before, you’ll recognize that in the Amaze-Your-Friends algorithm, the blanks could
become a variable with a name such as last_number. Result and sum are also variables because they represent
values that change depending on the numbers in the sequence
Get the last_number
Divide last_number by 2 to get a result.
Add last_number 1 1 to get a sum.
Multiply the result by the sum.
A variable is an abstraction because rather than representing a specific number, it can be used to represent
many different numbers.

Classes and Objects (1.4.4, 1.4.5)


Abstraction has uses other than identifying variables. It is important for understanding how to represent real-
world and conceptual objects. Remember the pattern you discovered for social media login credentials? With a
little modification, it becomes a template that can be applied to any subscriber:
Class: LoginCredentials
Attribute: user_ID
Attribute: user_password
Attribute: mobile_number
The LoginCredentials class is an abstraction that contains a set of attributes. The class was formed by
abstracting away, or removing, details for any specific subscriber.
Abstractions are handy for any programs that deal with real-world objects in addition to technology objects,
such as login credentials.

Q Can you envision a class that’s an abstraction of the collection of objects shown in Figure 1-7?
Budnyi/Shutterstock.com

12 oz water glass 5 oz martini glass 8 oz wine glass 10 oz water goblet

Figure 1-7 Abstract the details from this collection of glassware

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

When, in the year 1516, Hadrian, Cardinal St. Chryogon, wrote to


Wolsey bitterly lamenting that from Taracina right away to Pisa
pirates, consisting of Turks and African Moors, were swarming the
sea, he was scarcely guilty of any exaggeration. Multifarious and
murderous though the pirates of Northern Europe had long since
shown themselves, yet it is the Mediterranean which, throughout
history, and more especially during the sixteenth century, has earned
the distinction of being the favourite and most eventful sphere of
robbery by sea.
You may ask how this came about. It was no longer the case of
the old Cilicians or the Balearic Islanders coming into activity once
more. On the contrary, the last-mentioned people, far from being
pirates in the sixteenth century, were actually pillaged than pillagers.
A new element had now been introduced, and we enter upon a
totally different sphere of the piratical history. Before we seek to
inquire into the origin and development of this new force which
comes across the pages of history, let us bear in mind the change
which had come over the Mediterranean. During the classical times
piracy was indeed bad enough, because, among other things, it
interfered so seriously with the corn ships which carried the means
of sustenance. But in those days the number of freight ships of any
kind was infinitesimal compared with the enormous number of
fighting craft that were built by the Mediterranean nations. And
however much Greece and Rome laboured to develop the warlike
galley, yet the evolution of the merchant ship was sadly neglected,
partly, no doubt, because of the risks which a merchant ship ran and
partly because the centuries of fighting evoked little encouragement
for a ship of commerce.
During the centuries which followed the downfall of the Roman
Empire it must not be supposed that the sea was bereft of pirates.
As we have already seen, the decay of Rome was commensurate
with the revival of piracy. But with the gradual spread of southern
civilisation the importance of and the demand for commercial ships,
as differentiated from fighting craft, increased to an unheard-of
extent. No one requires to be reminded of the rise to great power of
Venice and Genoa and Spain. They became great overseas traders
within limits, and this postulated the ships in which goods could be
carried. So it came to this that crossing and recrossing the
Mediterranean there were more big-bellied ships full of richer
cargoes and traversing the sea with greater regularity than ever had
been in the history of the world. And as there will always be robbers
when given the opportunity, either by sea or by land, irrespective of
race or time, so when this amount of wealth was now afloat the sea-
robber had every incentive to get rich quickly by a means that
appealed in the strongest terms to an adventurous temperament.
In Italy the purely warlike ship had become so obsolete that, in
the opinion of some authorities, it was not till about the middle of
the ninth century that these began to be built, at any rate as regards
that great maritime power, Venice. She had been too concerned with
the production and exchange of wealth to centre her attention on
any species of ship other than those which would carry freights. But
so many defeats had she endured at the hands of the Saracens and
pirates that ships specially suitable for combat had, from the year
841, to be built. The Saracens hailed from Arabia, and it is notable
that at that time the Arabian sailors who used to sail across the
Indian Ocean were far and away the most scientific navigators in the
whole world, many of their Arabic terms still surviving in nautical
terminology to this day. Indeed, the modern mariner who relies so
much on nautical instruments scarcely realises how much he owes to
these early seamen. Just as the Cilicians and others had in olden
times harassed the shores of the Mediterranean, so now the
Saracens made frequent incursions into Sardinia, Corsica, Sicily, as
well as intercepting the ships of the Adriatic.
Let us remember that both in the north and south of Europe the
sailing seasons for century after century were limited to that period
which is roughly indicated between the months of April and the end
of September. Therefore the pirate knew that if he confined his
attentions to that period and within certain sea-areas, he would be
able to encompass practically the whole of the world’s sea-borne
trade. These sailing periods were no arbitrary arrangement: they
were part of the maritime legislation, and only the most daring and,
at the same time, most lawless merchant skippers ventured forth in
the off-season.
Realising that the mariner had in any lengthy voyage to contend
not merely with bad weather but probably with pirates, the
merchant pilots were instructed to know how to avoid them. For
instance, their main object should be to make the merchant ship as
little conspicuous on the horizon as possible. Thus, after getting
clear of the land, the white sail should be lowered and a black one
hoisted instead. They were warned that it was especially risky to
change sail at break of day when the rising sun might make this
action easily observable. A man was to be sent aloft to scan the sea,
looking for these rovers and keep a good look out. That black sail
was called the “wolf,” because it had the colour and cunning of such
an animal. At night, too, similar precautions were employed against
any danger of piratical attack, strict silence being absolutely
enforced, so that the boatswain was not even allowed to use his
whistle, nor the ship’s bell to be sounded. Every one knows how
easily a sound carries on the sea, especially by night, so the utmost
care was to be exercised lest a pirate hovering about might have the
rich merchant ship’s presence betrayed to her avaricious ears.
But the Saracens, whose origin I have just mentioned, must not
be confused with the Barbarian corsairs. It is with the latter—the
grand pirates of the South—that I pass on now to deal. So powerful
did they become that it took the efforts of the great maritime
powers of Europe till the first quarter of the nineteenth century
before they could exterminate this scourge: and even to-day, in this
highly civilised century, if you were to be becalmed off the coast of
North Africa in a sailing yacht, you would soon find some of the
descendants of these Barbarian corsairs coming out with their
historic tendency to kill you and pillage your ship. If this statement
should seem to any reader somewhat incredible, I would refer him
to the captain of any modern steamship who habitually passes that
coast: and I would beg also to call to his attention the incident a few
years ago that occurred to the famous English racing yacht Ailsa,
which was lying becalmed somewhere between Spain and Africa. But
for a lucky breeze springing up, her would-be assailants might have
captured a very fine prize.
I shall use the word Moslem to mean Mussulman, or
Mohammedan, or Moor, and I shall ask the reader to carry his mind
back to the time when Ferdinand and Isabella turned the Moors out
from Spain, and sent them across the straits of Gibraltar back to
Africa. For seven hundred years these Moors had lived in the Iberian
peninsula. It must be admitted in fairness that these Moors were
exceedingly gifted intellectually, and there are ample evidences in
Spain to this day of their accomplishments. On the other hand, it is
perfectly easy to appreciate the desire of a Christian Government to
banish these Mohammedans from a Catholic country. Equally
comprehensible is the bitter hatred which these Moors for ever after
manifested against all Christians of any nation, but against the
Spanish more especially.
What were these Spanish Moors, now expatriated, to do? They
spread themselves along the North African coast, but it was not
immediately that they took to the sea; when, however, they did so
accustom themselves it was not as traders but as pirates of the
worst and most cruel kind. The date of their expulsion from Granada
was 1492, and within a few years of this they had set to work to
become avenged. The type of craft which they favoured was of the
galley species, a vessel that was of great length, in proportion to her
extreme shallowness, and was manned by a considerable number of
oarsmen. Sail power was employed but only as auxiliary rather than
of main reliance. Such a craft was light, easily and quickly
manœuvred, could float in creeks and bays close in to the shore, or
could be drawn up the beach if necessary. In all essential respects
she was the direct lineal descendant of the old fighting galleys of
Greece and Rome. From about the beginning of the sixteenth
century till the battle of Lepanto in 1571 the Moslem corsair was at
his best as a sea-rover and a powerful racial force. And if he was still
a pest to shipping after that date, yet his activities were more of a
desultory nature. Along the Barbarian coast at different dates he
made himself strong, though of these strongholds Algiers remained
for the longest time the most notorious.
In considering these Moslem corsairs one must think of men who
were as brutal as they were clever, who became the greatest galley-
tacticians which the world has ever seen. Their greed and lust for
power and property were commensurate with their ability to obtain
these. Let it not be supposed for one moment that during the grand
period these Moorish pirate leaders were a mere ignorant and
uncultured number of men. On the contrary, they possessed all the
instincts of a clever diplomatist, united to the ability of a great
admiral and an autocratic monarch. Dominating their very existence
was their bitter hatred of Christians either individually or as nations.
And though a careful distinction must be made between these
Barbarian corsairs and the Turks, who were often confused in the
sixteenth-century accounts of these rovers, yet from a very early
stage the Moorish pirates and the Turks assisted each other. You
have only to remember that they were both Moslems; to remind
yourself that the downfall of Constantinople in 1453 gave an even
keener incentive to harass Christians; and to recollect that though
the Turks were great fighters by land yet they were not seamen.
They had an almost illimitable quantity of men to draw upon, and for
this as well as other reasons it was to the Moors’ interests that there
should be a close association with them.
During the fifteenth and especially the sixteenth centuries there
was in general European use a particular word which instantly
suggested a certain character that would stink in the nostrils of any
Christian, be he under the domination of Elizabeth or Charles v. This
word was “renegade,” which, of course, is derived from the Latin
nego, I deny. “Renegade,” or, as the Elizabethan sailors often used it,
“renegado” signifies an apostate from the faith—a deserter or
turncoat. But it was applied in those days almost exclusively to the
Christian who had so far betrayed his religion as to become a
Moslem. In the fifteenth century a certain Balkan renegade was
exiled from Constantinople by the Grand Turk. From there he
proceeded to the south-west, took up his habitation in the island of
Lesbos in the Ægean Sea, married a Christian widow and became
the father of two sons, named respectively Uruj and Kheyr-ed-din.
The renegade, being a seaman, it was but natural that the two sons
should be brought up to the same avocation.
Having regard to the ancestry of these two men, and bearing in
mind that Lesbos had long been notorious for its piratical
inhabitants, the reader will in no wise be surprised to learn that
these two sons resolved to become pirates too. They were presently
to reach a state of notoriety which time can never expunge from the
pages of historical criminals. For the present let us devote our
attention to the elder brother, Uruj. We have little space to deal with
the events of his full life, but this brief sketch may suffice. The
connection of these two brothers with the banished Moors is that of
organisers and leaders of a potential force of pirates. Uruj, having
heard of the successes which the Moorish galleys were now
attaining, of the wonderful prizes which they had carried off from
the face of the sea, felt the impulse of ambition and responded to
the call of the wild. So we come to the year 1504, and we find him
in the Mediterranean longing for a suitable base whence he could
operate; where, too, he could haul his galleys ashore during the
winter and refit.
A Daring Attack

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 if Barbarossa was dead, his sagacious brother Kheyr-ed-din


was ready to take up his work, and he proceeded on more scientific
principles. He began by sending an ambassador to Constantinople,
and begged protection for the province of Algiers. This, having been
granted, he was appointed officially, in 1519, Governor of Algiers.
His next step was to reinforce his garrisons at different parts of the
coast and so secure his territory from attacks by sea. And in order to
make for safety on the southern or landward side, he entered into
alliances with the leading Arabian tribes up-country.
He was thus about as secure as it was possible for human
diplomacy and organisation to achieve. His ships could still go on
their piratical cruises and return with little enough risk. In vain did
the Spaniards send an Armada against him. The men indeed landed,
but they were driven back, and a storm springing up did the rest.
Gradually more and more seaports fell into the net of this corsair, so
there were plenty of harbours to run for, plenty of safe shelters
whither to bring the valuable prizes. It was not merely the middle or
the eastern end of the Mediterranean which was now harassed, but
the west end. Those were the days, you will remember, when Spain
was developing the rich resources of the New World, so there was a
great opportunity for the Barbarian pirates to go out some little
distance into the Atlantic and capture the West Indiamen homeward
bound for Cadiz with gold and other treasures. And in addition to
these prizes, no less than the merchantmen of Italy, Kheyr-ed-din
occasionally made raids on the Spanish coast or even carried off
slaves from the Balearic Islands. From end to end these Algerine
corsairs were thus masters of the Mediterranean. No commercial
ship could pass on her voyages in any safety—even Spanish
flagships found themselves being brought captive into Algiers.
True, the small Spanish garrison still remained in Algiers, and
because it was immured within a very strong fortress it held out. The
time now came for this to be attacked with great vigour. For a period
of fifteen days it was bombarded, and at length, after a most
stubborn resistance, it was overcome. The stronghold was then
pulled down, and Christian prisoners who in the summer season had
rowed chained to their seats in the corsair galleys, were in the off-
season employed to build with these stones the great mole to
protect the harbour of Algiers from the western side. It was a
stupendous undertaking, and seven thousand of these unhappy
creatures accomplished the work in most of two years.
Nothing succeeds like success, and the corsair prospered in power
and possession to such an extent that he was pre-eminent. This
naturally attracted to his dominion many thousands of other
followers, and there was thus established not a mere small colony of
pirates, but a grand corsair kingdom where the industry of sea-
robbery was well organised with its foundries and dockyards, and
with every assistance to agriculture, and a firm, hard government to
keep the land in fit and proper cultivation.
And now yet another invitation came to Kheyr-ed-din. Andrea
Doria had defeated the Turks at Patras and in the Dardanelles. Like
the policy of the corsairs, after each victory the Christian admiral
employed the infidel captives to work at the oars of his galleys. Thus
it was that the Sultan of Turkey—Solyman the Magnificent—realising
that the Christian admiral was draining the best Turkish seafaring
men, determined to invite Kheyr-ed-din to help him against Andrea
Doria. So one of the Sultan’s personal guard was dispatched to
Algiers requesting Barbarossa to come to Constantinople and place
himself at the head of the Ottoman navy. Barbarossa accepted this
as he had accepted other invitations, seeing that it was to his own
interest, and in August 1533 left Algiers with seven galleys and
eleven other craft. On the way he was joined by sixteen more craft
belonging to a pirate named Delizuff, but before they had got to the
end of the voyage Delizuff was killed in an attack on a small island
named Biba. There followed some friction between the men of the
deceased pirate and those of Barbarossa, and finally one dark night
the ships of Delizuff stole away from Barbarossa’s fleet.
Eventually this Sultan of Algiers, with his ships, arrived at
Constantinople. The case stood thus. The Ottoman subject was an
excellent man to fight battles by land, but not by sea. Barbarossa
was a true fighting seaman: therefore let him do for us that which
we ourselves cannot do. He was only three years short of becoming
an octogenarian, yet this veteran corsair was as able as he was
wicked, and so, after the Ottoman dockyards in the following year
had provided him with additional ships, Barbarossa set forth from
Constantinople and began by sacking Reggio, burning Christian ships
and carrying off their crews. Thence he laid waste the coast until he
came to Naples, and altogether made 11,000 Christians prisoners,
and returned to the Bosphorus with an abundance of spoil and
slaves. Sardinia, too, was depleted of wealth and humanity till it was
almost bereft of both, and at last the fleet arrived before Tunis, to
the amazement of the inhabitants. To condense a long story it may
be said at once that, after some fighting, Tunis found itself now in
submission to him who was also Sultan of Algiers and commander-
in-chief of the Ottoman fleet. But trouble was brewing.
Again Christendom was moved to action. The successes of this all-
conquering King of Corsairs were endangering the world, so the
great Charles v. set on foot most elaborate preparations to cope with
the evil. The preparations were indeed slow, but they were sure and
they were extensive. But there was just one disappointing fact.
When Francis the First, King of France, was invited to take his share
in this great Christian expedition it is as true as it is regrettable to
have to record the fact, that not only did he decline, but he actually
betrayed the news of these impending activities to Barbarossa. This
news was not welcome even to such a hardened old pirate, but he
set to work in order to be ready for the foe, employed the Christian
prisoners in repairing the fortifications of Tunis, summoned help to
his standard from all sides, all united in the one desire to defeat and
crush utterly any Christian force that might be sent against the
followers of Mahomet. Spies kept him informed of the latest
developments, and from Algiers came all the men that could possibly
be spared. And finally, when all preparations had been made, there
was on the one side the mightiest Christian expedition about to meet
the greatest aggregation of Moslems. By the middle of June the
invaders reached the African coast and found themselves before
Tunis. It was to be a contest of Christian forces against infidels: it
was to represent an attempt once and for all to settle with the
greatest pirate even the Mediterranean had ever witnessed. It was,
if possible, to set free the hordes of brother-Christians from the
tyrannous cruelty of a despotic corsair. Of those who now came over
the sea, many had lost wife, or sister, or father, or son, or brother at
the hands of these heathens. For once, at last, this great Christian
Armada had the sea to itself: the wasps had retreated into their
nest.
So the attack began simultaneously from the land and from the
sea. The men on shore and those in the galleys realised they were
battling in no ordinary contest but in a veritable crusade. Twenty-five
thousand infantry and six hundred lancers, with their horses, had
been brought across the sea in sixty-two galleys, a hundred and fifty
transports, as well as a large number of other craft.[1] The Moslems
had received assistance from along the African coast and from the
inland tribes. Twenty thousand horsemen, as well as a large quantity
of infantry, were ready to meet the Christians. The Emperor Charles
v. was himself present, and Andrea Doria, the greatest Christian
admiral, was there opposed to the greatest admiral of the Moslems.
Needless to say the fight was fierce, but at last the Christians
were able to make a breach in the walls not once but in several
places, and the fortress had to be vacated. Tunis was destined to fall
into Christian hands. Barbarossa realised this now full well. What
hurt him most was that he was beaten at his own game: his own
beloved galleys were to fall into the enemies’ hands. Presently the
corsairs were routed utterly, and Barbarossa with only about three
thousand of his followers escaped by land. Now inside Tunis were no
fewer than 20,000 Christian prisoners. These now succeeded in
freeing themselves of their fetters, opened the gates to the
victorious army, and the latter, unable to be controlled, massacred
the people they had been sent against right and left. The 20,000
Christians were rescued, the victory had been won, the corsair had
been put to flight, and Muley Hassan, a mere puppet, was restored
to his kingdom of Tunis by Charles v. on conditions, amongst which
it was stipulated that Muley Hassan should liberate all Christian
captives who might be in his realm, give them a free passage to
their homes, and no corsair should be allowed again to use his ports
for any purpose whatsoever.
This was the biggest blow which Barbarossa had ever received.
But brute though he was, cruel tyrant that he had shown himself,
enemy of the human race though he undoubtedly must be reckoned,
yet his was a great mind, his was a spirit which was only impelled
and not depressed by disasters. At the end of a pitiful flight, he
arrived farther along the African coast at the port of Bona, where
there remained just fifteen galleys which he had kept in reserve. All
else that was his had gone—ships, arsenal, men. But the sea being
his natural element, and piracy his natural profession, he began at
once to embark. But just then there arrived fifteen of the Christian
galleys, so Barbarossa, not caring for conflict, drew up his galleys
under the fort of Bona, and the enemy deemed it prudent to let the
corsair alone, and withdrew. Soon after Barbarossa put to sea and
disappeared, when Andrea Doria with forty galleys arrived on the
scene too late.
Just as on an earlier occasion already narrated, the Christian
expedition made the mistake of not pressing home their victory and
so settling matters with the pirates for good and all. Algiers had
been drained so thoroughly of men that it was really too weak to
resist an attack. But no; the Christians left that alone, although they
took Bona. About the middle of August Charles re-embarked his men
and, satisfied with the thrashing he had given these pirates,
returned home. But Barbarossa proceeded to Algiers, where he got
together a number of galleys and waited till his former followers—or
as many as had survived battle and the African desert—returned to
him. If Moslem piracy had been severely crushed, it was not unable
to revive, and, before long, Barbarossa with his veterans was afloat
again, looting ships at sea, and carrying off more prisoners to
Algiers. For this piracy was like a highly infectious disease. You might
think for a time that it was stamped out, that the world had been
cleansed of it, but in a short time it would be manifest that the evil
was as prevalent as ever.
Once more he was summoned to visit Soliman the Magnificent;
once more the arch-corsair sped to Constantinople to receive
instructions to deal with the conquering Christians. Andrea Doria was
at sea, burning Turkish ships, and only this Sultan of Algiers could
deal with him. So away Barbarossa went in his customary fashion,
raiding the Adriatic towns, sweeping the islands of the Archipelago,
and soon he returned to Constantinople with 18,000 slaves, to say
nothing of material prizes. Money was obtained as easily as human
lives, and the world marvelled that this corsair admiral, this scourge
of the sea, this enemy of the Christian race, should, after a crushing
defeat, be able to go about his dastardly work, terrifying towns and
ships as though the expedition of Charles v. had never been sent
forth.
But matters were again working up to a crisis. If the corsair
admiral was still afloat, so was Andrea Doria, the great Christian
admiral. At the extreme south-west corner of the Epirus, on the
Balkan side of the Adriatic, and almost opposite the heel of Italy, lies
Prevesa. Hither in 1569 came the fleets of the Cross and the
Crescent respectively. The Christian ships had been gathered
together at the Island of Corfu, which is thirty or forty miles to the
north-west of Prevesa. Barbarossa came, assisted by all the great
pirate captains of the day, and among them must be mentioned
Dragut, about whom we shall have more to say later.
But Prevesa, from a spectacular standpoint, was disappointing. It
was too scientific, too clearly marked by strategy and too little
distinguished by fighting. If the reader has ever been present at any
athletic contest where there has been more skill than sport, he will
know just what I mean. It is the spirit of the crowd at a cricket
match when the batsman is all on the defensive and no runs are
being scored. It is manifested in the spectators’ indignation at a
boxing match when neither party gets in a good blow, when there is
an excess of science, when both contestants, fairly matched and
perhaps overtrained and nervous of the other’s prowess, hesitate to
go in for hard-hitting, so that in the end the match ends in a draw.
It was exactly on this wise at Prevesa. Andrea Doria and
Barbarossa were the two great champions of the ring. Neither was
young; both had been trained by years of long fighting. They were
as fairly matched as it was possible to find a couple of great
admirals. Each realised the other’s value; both knew that for
spectators they had the whole of Europe—both Christian and
Moslem. Victory to the one would mean downfall to the other, and
unless a lucky escape intervened, one of the two great admirals
would spend the rest of his life rowing his heart out as a galley-
slave. Certainly it was enough to make the boxers nervous and
hesitating. They were a long time getting to blows, and there was
but little actually accomplished. There was an unlucky calm on the
sea, and the Galleon of Venice was the centre of the fighting which
took place. It was the splendid discipline on board this big craft, it
was the excellence of her commander and the unique character of
her great guns which made such an impression on Barbarossa’s fleet
that although the Galleon was severely damaged, yet at the critical
time when the corsairs might have rushed on board and stormed her
as night was approaching, for once in his life the great nerve of the
corsair king deserted him. No one was more surprised than the
Venetians when they found the pirate not pressing home his attack.
True, the latter had captured a few of the Christian ships, but these
were a mere handful and out of all proportion to the importance of
the battle. He had been sent forth to crush Andrea Doria and the
Christian fleet; he had failed so to do.
Next day, with a fair wind, Andrea Doria made away. The honour
of the battle belonged to the Galleon of Venice, but for Barbarossa it
was a triumph because, with an inferior force, he had put the
Christian admiral to flight. Doria’s ship had not been so much as
touched, and yet Barbarossa had not been taken prisoner. That was
the last great event in the career of Kheyr-ed-din, and he died in
1548 at Constantinople as one of the wickedest and cruellest
murderers of history, the greatest pirate that has ever lived, and one
of the cleverest tacticians and strategists the Mediterranean ever
bore on its waters. There has rarely lived a human being so bereft of
the quality of mercy, and his death was received by Christian Europe
with a sigh of the greatest relief.
In the whole history of piracy there figure some remarkably clever
and consummate seamen. Like many another criminal they had such
tremendous natural endowments that one cannot but regret that
they began badly and continued. The bitterest critic of this Moslem
monster cannot but admire his abnormal courage, resource; his
powers of organisation and his untameable determination. The pity
of it all is that all this should have been wasted in bringing misery to
tens of thousands, in dealing death and robbery and pillage.
CHAPTER VI
GALLEYS AND GALLANTRY

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!

You might also like