You are on page 1of 67

Readings from Programming with C++ -

eBook PDF
Visit to download the full and correct content document:
https://ebooksecure.com/download/readings-from-programming-with-c-ebook-pdf-2/
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.
Module 1 Computational Thinking 11

A The glassware class could have these attributes:


Class: Glassware
Attribute: Color
Attribute: Capacity
Attribute: Style

Black Boxes (1.4.6)


To drive a car, you don’t have to know exactly what goes on under the hood. The engine is essentially a “black
box” that you control using a few simple inputs such as the gas pedal, brake, and steering wheel. The details of the
engine are hidden. In computer science terminology, these details have been “abstracted away.” See Figure 1-8.

You can drive a car without


knowing the details of what’s
under the hood.

Figure 1-8 The controls for a car are an abstraction of


its detailed mechanics

In concept, a black box is anything that accepts some type of input and performs a specific process to
­produce output without requiring an understanding of its internal workings. See Figure 1-9.

Something goes on inside.

Something goes in.

Something comes out.

Black box

Figure 1-9 Black box abstraction

The black-box concept of abstraction is a fundamental aspect of computer science. Think about it. C
­ omputer
programs are abstractions. For example, you can use a social media app without knowing anything about the
programming that makes it work. The icons that you touch on the screen abstract away the details of the under-
lying programming.
Programmers make extensive use of abstraction within programs by creating a set of instructions that func-
tions like a black box. For example, you could bundle the instructions that handle login attempts into a black
box like the one in Figure 1-10.
Programming languages also have built-in abstractions that perform standard tasks. For example, the built-in
random function generates a random number when given a range, such as 1–100. You can incorporate the random
function in a program without knowing how it works internally.

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.
12 PROGRAMMING WITH C++

Look up stored user ID and


User ID
password.
password
Compare stored user ID and
password to entered user ID Allow or deny access
and password.
If they match, allow access.

Black box

Figure 1-10 A login abstraction

Levels of Abstraction (1.4.7)


After you get the hang of abstraction, you’ll see examples of this computational thinking concept everywhere.
Applying the correct level of abstraction to your programs may take a little practice.
A level of abstraction relates to the amount of detail that is hidden. Abstracting out too much detail can
make a program too generalized. Neglecting abstraction can produce programs that are too specific to work with
a wide variety of data. See Figure 1-11.

Too specific Just right Too abstract

Figure 1-11 Levels of abstraction

With experience, you’ll be able to identify useful abstractions and gauge the correct level of abstraction
to use.

SUMMARY
• Computational thinking techniques help programmers define problems, find solutions, delineate tasks,
and devise algorithms.
• An algorithm is a series of steps for solving a problem or carrying out a task. Programming algorithms
are the blueprints for computer programs.
• Standard algorithms exist for many computing tasks. When an algorithm does not exist, you can step
through a process manually and record the steps, or apply computational thinking techniques, such as
decomposition, pattern identification, and abstraction.
• Decomposition divides a complex problem or task into manageable units.
• Pattern identification reveals sequences and repetitive tasks that can lead to algorithm efficiencies.
• Abstraction is a key computer science concept that suppresses details, substitutes a generalization for
something specific, and allows an algorithm to work for multiple inputs.

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 13

Key Terms
abstraction computer program objects
algorithm decomposition object-oriented decomposition
attributes Functional decomposition pattern identification
classes level of abstraction programming algorithm
classification patterns methods Structural decomposition
Computational thinking modules

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

2
PROGRAMMING TOOLS
LEARNING OBJECTIVES:
2.1 PROGRAMMING LANGUAGES 2.3.5 Explain the purpose of a linker.
2.1.1 Explain the significance of the Hello World! program. 2.3.6 Associate virtual machines with Java and
bytecode.
2.1.2 Reiterate that programming languages are used to
create software. 2.3.7 Explain how an interpreter works.
2.1.3 Name some popular programming languages. 2.3.8 Differentiate between source code, bytecode,
object code, and executable code.
2.1.4 Distinguish between syntax and semantics in the
context of programming languages.
2.4 DEBUGGING TOOLS
2.1.5 Identify the key characteristics common to
2.4.1 Explain the purpose of debugging.
programming languages.
2.4.2 List common syntax errors.
2.1.6 Explain options for accessing programming
language implementations. 2.4.3 List common runtime errors.
2.1.7 Identify programming tools. 2.4.4 List common logic errors.
2.4.5 Classify program errors as syntax errors, logic
2.2 CODING TOOLS
errors, or runtime errors.
2.2.1 Define a program editor as the tool used to enter
2.4.6 Classify a debugger as utility software that allows
program code.
programmers to walk through the code of a target
2.2.2 List the types of editors that can be used for program to find errors.
coding.
2.4.7 List handy features provided by a debugger.
2.2.3 List some handy features of code editors and
explain how they help programmers create 2.5 IDEs AND SDKs
clean code.
2.5.1 List the purpose and typical features of an
2.2.4 Identify the basic structure and syntactical integrated development environment (IDE).
elements for a program written in the
2.5.2 Explain how IDEs support visual programming.
programming language you use.
2.5.3 Confirm that some IDEs are installed locally, while
2.3 BUILD TOOLS other IDEs are accessed online.
2.3.1 Explain the purpose of build tools. 2.5.4 Identify popular IDEs.
2.3.2 Explain the difference between source code and 2.5.5 List the purpose and typical features of a software
object code. development kit (SDK).
2.3.3 Describe how a compiler works. 2.5.6 Provide examples of SDK functionality.
2.3.4 Explain the purpose of a preprocessor. 2.5.7 Identify popular SDKs.

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.
16 PROGRAMMING WITH C++

2.1 PROGRAMMING LANGUAGES


Hello World! (2.1.1)
Hola! Bonjour! Hi! Ciao! Namaste! Salaam! Nihau! Greetings like these are the first thing you learn when studying
a spoken language. Programmers have a similar starting point. It is the Hello World! program.
Hello World! is without doubt the most famous computer program of all time. It has been written in every one
of the 7001 programming languages. It is typically the first program written by aspiring programmers.

Q Take a look at the Hello World! programs in Figure 2-1. They are written in three popular
programming languages, C11, Java, and Python. What differences can you identify?

Hello World! in C++ Hello World! in Java Hello World! in Python

#include <iostream> class HelloWorld { print("Hello World!")


using namespace std; public static void main(String[] args) {
int main() System.out.println("Hello World!");
{ }
cout <<"Hello World!"; }
return 0;
}

Figure 2-1 Hello World in C11, Java, and Python

A You probably noticed the following differences:


Length: Some Hello World! programs required more instructions than others.
Punctuation: Some programs used lots of curly brackets and semicolons.
Wording: One program used the word cout where the other programs used System.out.
println and print.
Complexity: Some programs seemed easier to interpret than others.

A lot of backstory is bundled into the Hello World! program that can be applied to learning a programming
language. Let’s unbundle this famous program to discover the basics about your programming language.

Programming Language Basics (2.1.2, 2.1.3)


A programming language is a notation for specifying the steps in an algorithm that are supposed to be per-
formed by a digital device. Programming languages such as C11, Java, and Python are classified as high-level
programming languages because they provide a way for you as a programmer to compose human-readable
instructions that direct the operations performed by a computing device.
How does your programming language stack up to other popular languages and where does it shine? Check
out the list in Figure 2-2.
Using a high-level programming language, you can specify a set of instructions that correspond to the steps
in an algorithm. Each instruction is referred to as a statement. The set of statements you generate using a pro-
gramming language is called program code, or simply code. Your code can become a computer program, which
can be distributed as computer software, desktop applications, web apps, and mobile apps.

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 2 Programming Tools 17

Logo Programming Where It Shines


Language

Consumer-facing web development, server-side web


JavaScript
development

Server-side web development, scripting, machine learning,


Python
data science, desktop applications, robotics

Server-side web development, desktop applications, mobile


Java
development, Internet of Things

Systems programming, embedded applications, Internet of


C
Things

Systems programming, game development, desktop


C++
applications embedded applications, robotics

PHP Server-side web development

Swift Desktop and mobile applications for Apple devices

Desktop applications, game development, virtual reality,


C#
mobile development

Ruby Server-side web development

Server-side web development, systems programming,


Go
Internet of Things

Figure 2-2 Popular programming languages

Syntax and Semantics (2.1.4)


When learning a programming language, where do you start? Programming languages have two key elements:
semantics and syntax.
Semantics refers to the meaning and validity of program statements. In a natural language, such as English,
it is perfectly fine to say, “Let’s start the game” or “Let’s start the car,” but “Let’s start the pen” doesn’t make any
sense. It is not semantically valid.
Programming languages include keywords, such as print and cout. These words are a subset of a program-
ming language’s reserved words, which are reserved for special purposes. You cannot use reserved words when
you create names for variables, functions, or classes in your programs.
One aspect of learning a programming language is to become familiar with its keywords and their use. When
learning C11, for example, you’ll need to remember that cout sends output to a display device. But if you’re
learning Java, the keyword is System.out.println. In Python the keyword is print. Figure 2-3 lists keywords
that are common to many programming languages.

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.
18 PROGRAMMING WITH C++

Keyword Purpose
int Define a value as an integer.
float Define a value as a floating-point number.
char Define something as a letter, numeral, punctuation mark, or symbol.
class Define the characteristics of a person, place, or thing.
new Create an object based on the characteristics of a class.
if Execute program statements when a condition is true.
then
else
case Specify several alternative conditions or decisions.
switch
for Begin a section of code that repeats one or more times.
while
do
return Bring a value back from a function.
import Incorporate a prewritten code module in a program.
try Catch errors and handle them gracefully.

Figure 2-3 Keywords common to programming languages

Q Suppose you want to code a program to output “Hello World!” 10 times. What keyword could
you use?

A Figure 2-3 lists the for, while, and do keywords for specifying code that repeats one or
more times.

You’ll acquire a vocabulary of keywords for your programming language gradually. Language references
provide a list of keywords and examples of their use. You can find language references online. In fact, it is often
helpful to create or find a “cheat sheet” of keywords to keep beside your computer as you learn a new language.
The syntax of a programming language is equivalent to the grammar rules of a written language, such as
English or Cyrillic. Syntax defines the order of words and the punctuation you are required to use when compos-
ing statements.
Various programming languages use different punctuation syntax. One of the early steps in learning a
programming language is to get a handle on its syntax.
Remember the different use of punctuation in the C11, Java, and Python Hello World! programs? Take a closer
look in Figure 2-4 and notice how punctuation helps to separate and structure the statements in a C11 program.

C++ Program
Statements end with a
#include <iostream>
semicolon.
using namespace std;
int main()
{
Curly braces for (int i = 1; i <= 10, i++)
separate blocks of {
statements. These cout << "Hello World!" << endl;
braces set off the cout << "Hola Mundo!" << endl;
statements in the }
return 0; Statements between
main() function.
} braces are indented.

Figure 2-4 C++ syntax style

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 2 Programming Tools 19

Like C11, Java also uses lots of punctuation. Figure 2-5 points out how the commonly used style for placing
curly braces in Java is slightly different from C11. However, either style works equally well as long as the braces
are paired. The key is consistency in the project you are working on.

Curly braces separate


blocks of statements.
Java Program Notice how the opening
class HelloWorld { brace is at the end of
public static void main(String[ ] args) { the line. This is an
System.out.println("Hello World!"); alternative style for the
System.out.println("Hola Mundo!"); placement of braces.
}
}
Statements end with a
semicolon.
Statements in a block
are indented.

Figure 2-5 Java syntax style

Python uses quite a different approach to punctuation. See if you can spot the differences in Figure 2-6.

Python Program
The colon indicates
for count in range(0, 10): the beginning of a
print("Hello World!") block of statements.
print("Hola Mundo!") Python does not use
Statements
braces.
in a block
are indented.
Pressing Enter or
Return marks the end
of a statement.

Figure 2-6 Python syntax style

In C11 and Java, statements are enclosed in a structure of curly braces and each statement ends with a semi-
colon. In contrast, Python uses indents to structure statements, and the linefeed that is generated when you press
the Enter key marks the end of a statement. Remember the punctuation style for the language that you are using.

Core Elements (2.1.5)


Although programming languages have differing syntax and semantics, they have common elements. If you look
for the ways that your programming language implements the elements in the following list, you will be well on
your way through the initial learning curve.
Variables that can be assigned values and structures
Arithmetic operators that can be used to perform calculations
Keywords that perform operations such as print or append
Data types that define values and text
Branching controls that change the sequence in which statements are executed
Repetition controls that repeat a series of statements
Syntax rules for constructing valid statements
Terminology for describing the components of a language and their functions

Your Toolbox (2.1.6, 2.1.7)


Before you can write your Hello World! program, you need access to tools for coding instructions and executing
them on a digital device. These tools are sometimes referred to as software development platforms, programming
platforms, or development environments.

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.
20 PROGRAMMING WITH C++

Programming tools are available as system utility software that can be installed on your computer. Another
option is to use an online programming app.
Your programming toolbox includes the following essentials:
Coding tools provide a way for you to codify an algorithm.
Build tools transform your code into a binary format that a computer can execute.
Debugging tools help you test programs and track down errors.
You can acquire these programming tools as individual components, or you can look for a comprehensive
development environment. Let’s explore these tools in more detail to find out how they can help you develop
brilliant programs.

2.2 CODING TOOLS


Program Editors (2.2.1, 2.2.2, 2.2.3)
Coding tools provide you with a way to express an algorithm using the vocabulary of a programming language.
Just how much of the code you have to manually type depends on your development platform. Here are the
options:
Visual platform: You might have the option of arranging visual elements that represent various
statements, as shown in Figure 2-7.

This column contains


your program. It consists
of visual components,
each representing a
statement.

You can drag Here is the statement


Source: scratch.mit.edu

components from the left that displays “Hello


column into your World!”
program. After dragging,
you can customize the
component, like changing
“Hello!” to “Hello World!”

Figure 2-7 Visual programming

Word processor: Despite the attraction of visual programming tools, you will likely end up typing
some if not all of the statements for your programs. For that task, you could use a word processor, but
it embeds all kinds of codes for formatting and font effects which can’t be included in your high-level
code.

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 2 Programming Tools 21

Text editor: A text editor such as Windows Notepad can produce plain ASCII text, but offers no
features designed to help programmers. Using a generic text editor is a bare-bones approach. There
are much better coding tools.
Code editor: A code editor is a type of text editor specially designed for entering high-level
programming code. It can help you correctly use punctuation and indents, as well as remember
variable names and ensure that you use valid keywords. Some handy features of code editors are
highlighted in Figure 2-8.

Color coding helps you


recognize keywords,
directives, and
punctuation.

Punctuation monitoring
ensures that the braces
are paired. Autocomplete displays a
list of keywords as you
begin to type.

Source: Visual Studio


Figure 2-8 Visual Studio code editor

When using a code editor, you can simply type your commands. As you type, pay attention to color coding,
autocomplete, and other helpful cues that the editor offers.

Basic Structure (2.2.4)


A programming language has structural and syntax conventions for writing code. When you become familiar with
these conventions, they will be the underlying foundation for most of the programs you create. Browse through
the following list before you try to identify the conventions in the next figure.
Comments: A comment provides an explanation of your code. At the beginning of a program, you can rou-
tinely include a comment with the program title and your name. Comments can be included anywhere in your
code to annotate aspects of the program that might not be clear to other programmers who test or modify your
code. Computers ignore comments as they are intended for documentation only.
Directives: A directive tells the computer how to handle the program rather than how to perform an algo-
rithm. For example, a directive might specify the name of an external file that is supposed to be incorporated
with the rest of your program code. Directives may begin with keywords such as #include, import, or using.
main() function: Many programming languages use main() to denote the entry point for program execution.
The line of code following main() corresponds to the first step in the algorithm you designed for a problem or
task.

Copyright 2022 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part. Due to electronic rights, some third party content may be suppressed from the eBook and/or eChapter(s).
Editorial review has deemed that any suppressed content does not materially affect the overall learning experience. Cengage Learning reserves the right to remove additional content at any time if subsequent rights restrictions require it.
22 PROGRAMMING WITH C++

Statements: Just as human-readable text is divided into sentences and paragraphs, your code should be
divided into statements and blocks. A program statement is similar to a sentence; it contains one instruction. In
languages such as C11 and Java, statements end with a semicolon. In Python, you end a statement by pressing
the Enter or Return key.
Code blocks: A code block is similar to a paragraph; it contains multiple statements that have a specific
purpose. In C++ and Java, you use braces (also known as curly brackets) to enclose code blocks. In Python, code
blocks are indented.

Q Take a look at Figure 2-9 and see if you can identify comments, directives, the main()
function, statements, and code blocks.

//Hello World! in English and Spanish


#include <iostream>
using namespace std;
int main()
{
for (int i = 1; i <= 10, i++)
{
cout << "Hello World!" << endl;
cout << "Hola Mundo!" << endl;
}
return 0;
}

Figure 2-9 Find the structural and syntax


conventions in this code

A The comment is //Hello World! in English and Spanish.


There are two directives: #include <iostream> and using namespace std.
The main() function is labeled int main().
Every line of the program is a statement.
The for..return statement is one block. The two cout statements form a block within the
for..return block.

2.3 BUILD TOOLS


The Toolset (2.3.1)
The high-level code that you produce using an editor cannot be directly executed by a computer’s micropro-
cessor. Microprocessors have a machine language instruction set based on binary codes. There is no print
instruction in the microprocessor’s instruction set, for example.

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 2 Programming Tools 23

Before a program can run, your code has to be converted into machine code consisting of machine language
instructions. This executable code is stored in an executable file that can be run, processed, and executed by
the microprocessor. Build tools convert your code into a program that a computer can execute.
As a programmer, you’ll eventually want to package your programs and distribute them so that they can be
installed on a digital device and run with a click, just like the Hola Mundo! program in Figure 2-10.

Hola Mundo!

Source: Microsoft Corporation


program

Figure 2-10 Hola Mundo! installed on a Windows computer

A little background about build tools can help you understand some of the weird statements, such as
#include<iostream>, that you have to include in programs. Also, a passing knowledge of build tools such as
compilers, preprocessors, linkers, virtual machines, and interpreters will help you hold your own at late-night
parties in Silicon Valley.

Compilers (2.3.2, 2.3.3)


A compiler translates code written in one programming language into another language. The original code is
called source code, and the code a compiler produces is called object code. Object code is stored in a standalone
file that is separate from the file that holds your source code. See Figure 2-11.

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.
24 PROGRAMMING WITH C++

Your source code Object code

Hello.cpp Hello.o

#include <iostream> 00010010 10100010


using namespace std; 10100101 11110000
int main() 01010100 10101010
Compiler conversion
{ 00101010 11010101
cout << "Hello World!"; 10101010 10001010
return 0; 10101010 10101011
} 00010101 10101011
00000001 10101010
10001010 10101010

Figure 2-11 When the compiler creates machine code, the resulting file is
executable

Q If a compiler is converting C11 code into machine code, what is the source code and what is
the object code?

A The C11 code is the source code. The machine code is the object code.

Preprocessors and Linkers (2.3.4, 2.3.5)


The journey from source code to an executable program doesn’t usually happen in one magical step. Your source
code may be analyzed by a preprocessor and combined with other code by a linker.
A preprocessor is a software utility that performs housekeeping tasks before the compiler gets to work.
Experienced programmers can creatively use preprocessors to make source programs easy to compile for vari-
ous software platforms.
For languages such as C11, even basic programs require preprocessing and preprocessor directives such
as #include<iostream> to be routinely included in the program code. After these directives are carried out
by the preprocessor, they can be ignored by the compiler.
A linker is a software utility that converts one or more object files into a binary executable file. Linking takes
place after compiling. Your source code is the main object file for linking, but you can specify additional object
files that you’ve created or that are available from third parties. When you see the keyword import, it is a clue
that an external file needs to be linked in.
Figure 2-12 can help you visualize the build process when a preprocessor and linker are involved.
Preprocessing and linking are not consistent for all programming languages. Your takeaways are:

• Several steps are required to convert your code into a file containing an executable program.
• You may have to include preprocessor directives in your code.

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 2 Programming Tools 25

The preprocessor executes


directives, such as
#include<iostream>

Hola.cpp

The compiler
converts the source
code to object code
Your source
code
Hola.cpp

The linker combines


modules and generates
machine code
Source code
plus iostream
Hola.o

Hola.exe

Figure 2-12 Preprocessing, compiling, and linking the Hola Mundo! program

Virtual Machines (2.3.6)


The product of a compiler is not necessarily machine code. Some compilers convert source code into semi-
compiled code called bytecode. Software called a virtual machine converts the bytecode into machine code
as the program executes.
What’s the point of a virtual machine? The Java Virtual Machine (JVM) offers some insight. The backstory is
that an executable file designed to run on a computer with the Microsoft Windows operating system won’t work
on a computer running macOS. You could develop one version of a program for Microsoft Windows and one for
macOS. Or, you can use the Java programming language to create one version of the program and compile it to
bytecode.
You can distribute the same bytecode to Windows and Mac users. Windows users have the Windows version
of the JVM. Mac users have another version. The virtual machine software converts the bytecode into code that
works on the host platform. Figure 2-13 can help you understand how the JVM works and the value of bytecode.

Copyright 2022 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part. Due to electronic rights, some third party content may be suppressed from the eBook and/or eChapter(s).
Editorial review has deemed that any suppressed content does not materially affect the overall learning experience. Cengage Learning reserves the right to remove additional content at any time if subsequent rights restrictions require it.
Another random document with
no related content on Scribd:
Considerable railway construction is talked of, but the only
immediate probability is of a road from the port of Castilletes on the
Gulf of Venezuela to a coal property near Lake Maracaibo, belonging
to the Caribbean Coal Company. A port is to be constructed
admitting vessels of 35 feet draft, the present depth being 16 feet.
The railway 93 miles long of standard gauge is to have a one way
capacity of 10,000 tons daily, with maximum freight charges lower
than any at this time on existing lines. As no port charges of any kind
are to be collected, if the construction and mining development are
carried out as expected, it will be a most important industrial
development for Venezuela which may affect the trade of Curaçao
and Maracaibo. As this port will be but 595 miles from Colon, and as
the coal is said to be of the best quality, it is important for ships
making use of the Canal.
The Venezuelan Government now gives generous concessions to
foreign companies or individuals, undertaking railway construction.

Other Methods of Communication

Roads. Aside from the railways, a meagre supply for a country of


its size, other means of transportation are inadequate. Street
railways exist in the chief cities: Caracas, Valencia, La Guaira,
Puerto Cabello, Maracaibo, Bolívar, Barquisimeto, Carúpano, and
Cumaná. The great water power available for electric traction and for
other purposes should be largely developed in future. Some
automobile and cart roads exist, 1636 miles at the end of 1919, but
to a large extent transportation is over bridle paths or caminos.
An excellent automobile road leads from La Guaira to Caracas.
From the capital such roads branch in several directions. One goes
east to Guatire, two south to Ocumare del Tuy, one of these with a
branch south from Cua. A good road leads through Maracay to
Valencia; from midway, a branch leads south through Villa de Cura to
Ortiz in Guárico, from which point construction is being continued to
Calabozo, the capital, and thence to San Fernando, capital of Apure.
Another road leads from Ocumare de la Costa to Maracay.
From Puerto Cabello one may go by auto to Valencia and to
Guigüe, south of the lake; also from the port to San Felipe and
Barquisimeto.
From the city of Maracaibo a road goes north to San Rafael near
the mouth of the Channel, and one southwest to Perija, west of the
centre of the Lake, passing two petroleum sites.
From the terminus of the Táchira Railway, Uracá, a road leads to
San Cristóbal, and one to Cúcuta in Colombia. From Motatán a good
wagon road goes to Trujillo. Pack animals serve from El Vigia to
Mérida. In the east there is the long road from San Felix on the
Orinoco to El Callao and Tumeremo.
Other roads are in construction or planned for the immediate
future. From Coro a road is to go south and southwest to Trujillo and
beyond, and one near the coast to Altagracia on the Maracaibo
Channel, northeast of that city. Several roads will branch from
Barquisimeto and from Valencia, the most important, one from
Valencia southwest to San Carlos, Guanare, Barinas, and San
Cristóbal. Shorter local roads will serve Cumaná and Carúpano.
Considerable activity has recently been manifested in road
building; and bridges, long sadly lacking over mountain torrents,
have been constructed. Some deeper streams have ferries.
River communication and lake service are important in many
sections. Of Venezuela’s nearly 500 rivers, 74 are said to be
navigable a distance of 6000 miles, 4000 in the Orinoco Basin.
Especially in Bolívar and Amazonas communication is by river, but in
other States also it is important. The Orinoco is a natural highway
600 miles to Pericos and the Atures Rapids. There is regular weekly
service to San Fernando de Apure. There is traffic along the Apure,
Arauca, and Meta Rivers, the last two in Colombia; but the affluents
on the north side of the Orinoco are too variable in depth to permit
regular service, and those on the south are too broken by cataracts.
On Maracaibo Lake are plenty of craft, both steam and sailing
vessels, two main lines of the former running from Maracaibo, one
along the west side of the Lake and up the Catatumbo to
Encontrados and the Táchira Railway, the other to La Ceiba and the
Motatán Railway going towards Trujillo on the east side; a smaller
boat runs around the south side of the Lake and up the Escalante to
Santa Bárbara. From Encontrados a line of small steamers runs up
the Zulia to Villamizar.
CHAPTER XI
VENEZUELA: RESOURCES AND INDUSTRIES

Agriculture

The Agricultural Zone, according to late statistics, covers the


greater part of that section of the Republic which lies between the
sea and the Orinoco Plains: about 100,000 square miles, only one
third of which is tilled. The section has great fertility of soil, and with
its varying elevation and climate it is adapted to the production of
everything needful for man or beast. Twenty per cent of the
population is employed in agricultural pursuits. With the introduction
of new methods and modern machinery a vast development and
great wealth should ensue. At present the chief products are coffee,
cacao, and sugar, with tobacco, cotton, corn, wheat, vanilla, etc., and
a great variety of fruits and vegetables.
Coffee, as in Colombia, is called a product of the temperate clime,
growing at an altitude of 1500-6500 feet but best at 3000. A tree is
said to live 50 years and to produce a quarter to a half a pound
annually. About $16,000,000 are invested in the industry; there are
approximately 260,000,000 trees. Venezuela claims to be second in
coffee production, exporting over 100,000,000 pounds in 1919.
Cacao needs a warmer climate than coffee, and moist air; hence it
grows well on slopes near the sea having a temperature of 80°. But it
is found and cultivated in other parts, growing wild in Guayana and
near the upper Orinoco. Where cultivated, 80 trees to the acre are
approved, of course at first shaded. After five years two crops a year,
in June and December, are expected. Trees average a life of 40
years, with an annual production of 220-250 pounds an acre. About
16 seeds are enclosed in a long red and yellow pod, which turns
purple when ripe. After being gathered, they are heaped in piles on
the ground, left a few days to ferment and burst, when the seeds are
shelled, washed, and housed. There are two grades here, the criollo
or native, of very high grade, growing in valleys near the sea, and
the trinitario, imported from Trinidad. The Chuao Plantation is said to
produce cacao of a particularly sweet and fine quality, which is
generally exported to France. Over $12,000,000 are invested in the
business. In production Venezuela is third. There are more than
5000 plantations.
Sugar. The sugar industry is rapidly developing. New mills with
modern machinery have been erected and more acres are planted.
A mill at Maracay can crush nearly 1800 tons of cane daily, with an
output of sugar of 80 tons. Four species of cane are cultivated, the
indigenous, the criolla, most largely, as being sweeter and otherwise
giving good results. The reaping is arranged so that the grinding may
be constant throughout the year. The canes near Lake Valencia are
longer and thicker, with more juice but less sweetness. The best
quality of sugar is produced near Guatire, three hours by motor from
Caracas; the largest quantity on two plantations near Lake
Maracaibo, each having a daily output of 800 tons.
There are four varieties of products: sugar, brown sugar, alcohol,
and rum, all of which many large plantations are equipped to
produce. Of the two near Bobures, Zulia, one has 5000 acres under
cultivation, the other nearly as much. The total capital invested is
above $10,000,000. An increasing foreign market is expected.
Tobacco is grown in many sections, thriving in humid fertile soil. It
develops in six months, but requires great care. There is much
variety in the quality, some being strong and heavy, some delicate
with fine flavor and aroma. A little is exported to Havana and there
mixed for making cigarettes. The annual production, above 3000
tons, might be increased.
Cotton grows wild in many parts of the country, and is cultivated in
a number of States. The average crop is about 4,000,000 pounds of
seeded cotton, half of which is raised in Aragua and Carabobo. Zulia
produces the best cotton, with longer fibre, nearly one-fifth of the
crop. Lara, Portuguesa, and the States of the East supply the rest.
The cotton is sown in June or July and harvested in the dry season,
December to March. It is freshly planted every year in connection
with vegetables, the receipts from which cover the cost except for
that of gathering; so that the industry furnishes a desirable
opportunity for immigrants with small or no capital. About $200,000
are invested in cotton growing.
Coconuts are indigenous in Venezuela; and in the regions of
Zulia, Carabobo, Bolívar, Barcelona, and Cumaná, there are broad
plantations. Over $1,000,000 is invested.
Wheat is grown to some extent and fine crops are produced; but
much more land is available in the high table-lands and valleys of
Western Venezuela so that home consumption could easily be
supplied. With improved methods, machinery, etc., it might even
become a staple export.
Corn is cultivated everywhere in all kinds of soil from sea level up
to 9000 feet, but it grows best between 1500 and 3000 feet. About
75,000 acres are devoted to its production; 150,000 tons are raised,
some being exported. It is the real bread plant of the country
especially in the interior.
Beans in large variety are produced, black beans being greatly in
demand and some exported.
Indigo was once cultivated and in 1802 was exported to the value
of $2,500,000, but its production was abandoned owing to higher
returns from coffee.
Vanilla grows well in the rich lands of Falcón, Lara, Bolívar,
Zamora, and Anzoátegui. Its cultivation might be developed.

Forestry

The forest resources are inexhaustible but hardly touched, the


zone comprising about half of Venezuela of which 98 per cent is
virgin territory. Nearly three-quarters of this area is public land, over
100,000 square miles. With more capital and labor, better means of
transport, and modern implements and machinery a great
development will result. The chief forest products are rubber, balatá,
tonka beans, divi-divi, and various medicinal plants. There are many
dyeing and tanning plants, and gums and resins abound. In the
forests a great amount of timber exists including the finest varieties;
but as usual these are scattered, and with present facilities, difficult
to get out with a profit. Of the 600 species of wood 5-10 per cent are
marketable. 145 varieties used for ornamental purposes and 20
kinds of woods and barks suitable for dyeing and tanning were
exhibited at the Chicago Exposition in 1893. The great mora tree,
three feet in diameter, is excellent for ship building; mahogany,
rosewood, and other trees of hard wood abound.
Rubber, chiefly of the hevea variety, is found and exported both
from the Casiquiare-Amazon section and more from Yuruary in East
Bolívar. It is cultivated near Ocumare del Tuy, each tree there giving
460 grams of juice, 95 per cent pure rubber. Several million people
are needed to exploit the industry, in which $1,200,000 has been
invested.
Balatá, procured from forest trees in a manner similar to rubber, is
allied to gutta percha, and is employed with this for many purposes.
Divi-divi, one of the best and cheapest plants for tannin, grows
wild throughout the country, chiefly along the coast and on the edge
of the llanos at the foot of the south slope of the Coast Mountains.
Hot lowlands with a minimum average of rain suit it best. It grows to
a height of 20-30 feet. The brown pods three inches long contain 30-
40 per cent of tannin, sometimes even 50. The seeds have little. In
wet weather the tannin is liable to sudden fermentation especially in
electrical storms, when the tanning is impeded, and the leather may
be stained. Some trees 90 years old still produce a full crop. Near
Cumaná, a tree may yield 275 pounds a year, but in the west, 25-50
pounds only. It is an extremely cheap source of tannin though not
largely used. Venezuela probably has more frequent stands of this
tree than any other country. 5000 men are said to leave Ciudad
Bolívar yearly for its collection in the interior. As cultivated in
Curaçao plantations, the pods have 20 per cent more tannin and
bring 25 per cent higher price.
The Mangrove bark is another important source of tannin; the tree
growing in swampy ground is useful in reclaiming land at the ocean’s
edge. The bark has 22-33 per cent tannin, the leaves nearly 20, the
wood some. The stands are unlimited in number.
The Tonka Bean, a black almond with delicious perfume, is the
fruit of the serrapia tree. The beans are used in the preparation of
chewing tobacco and in making perfumes. The price varies from 50
cents to $5 a pound. This is a staple of great value in the Orinoco
forests, but many gatherers die of fever or starve. A few concessions
have been granted for the cultivation of tonka trees, in the public
lands of the Caura district. In one year over $700,000 worth of the
beans were exported.
Chicle, used to make chewing gum, comes from the sap of a tree
called pendare which has a delicious fruit, sapodilla. The tree may
be tapped continuously 8-15 years. The sap is boiled in the forest.
The Caoba or mahogany tree grows from sea level to about 3000
feet. It may be seen along the streets of Valencia. It grows to a
height of 130 feet with a diameter of four feet at the base. It is
exported to Europe and to the United States.
The Moriche Palm grows in clumps on the llanos. From the sap
the Indians make wine, vinegar, oil, soap, starch; and from the
leaves, hats, clothes, hammocks, baskets, mats, etc.
Fibre plants of superior quality exist in great variety and quantity.
Among these are the cocuiza sisal called equal or superior to the
sisal (hemp) of Yucatan; ramie, jipijapa, flax, and other varieties.
Plants for making paper grow in profusion, desirable for use rather
than wood to save the destruction of forests. The most abundant and
desirable is bamboo, but many other plants are serviceable including
the residue from sugar cane. The by-product of three tons of sugar
would be roughly two tons of fibre, worth about $120. Bitter cane and
other rushes might be so used, either exported as pulp, or in some
localities made into paper.

Cattle Industry
Goats have been spoken of as raised with great profit on the well
adapted lands near Barquisimeto, comparatively high, and on
lowlands in the regions of Coro and Maracaibo.
Cattle. The cattle industry has still greater possibilities. The
pastoral zone extends from Barrancas to Colombia and from the
Vichada River to the mountains in Carabobo. While a portion of the
llanos like those in Colombia suffers from severe drought in the
summer, and though in places the grass is thin, in this immense
region there is room for an enormous number of cattle where the
grasses are rich. Hence stock raising can be carried on to great
advantage. There is some difficulty in transportation, but this is
gradually improving, and with the erection of more packing and
slaughter houses, and with improvements in breeding, the industry
has a sure future. Some stock raisers, especially General Gomez,
have made great efforts for improvement, importing full blooded
cattle of different breeds to produce a better kind, perfectly adapted
to the climate of Venezuela. Modern methods are being employed,
and in the valley of Maracay a large number of live stock is fattened
ready to supply the 500 cattle daily killed at Puerto Cabello by the
Refrigerating Company which exports them. A new packing house is
to be erected at Turiamo. It is reported that a contract has been
made for 200,000 acres to be colonized by Germans, who wish to
control the meat packing industry. The number of cattle in Venezuela
is estimated at 3,000,000.
Sheep, horses, hogs are also raised in the valley of Maracay;
acclimated specimens of special breeds have been obtained for
reproduction in other parts of the country. At present horses and
mules are raised in comparatively small numbers.

Mining

There is hardly a precious metal or valuable mineral which does


not exist in Venezuela, though little has been done to exploit them.
Gold, silver, copper, iron, lead, antimony, tin, quicksilver, asphalt,
petroleum, coal, sulphur, asbestos, platinum, diamonds, and other
precious stones are found; 25 years ago 226 deposits had been
located: 62 gold, 29 coal, 14 copper, 10 iron, etc.
Gold, the most exported metal, while found in every State, has
been chiefly sought and profitably worked in Guayana, where in the
Yuruary region considerable mining has been done. True alluvial
belts are found, zones of shale, and quartz veins. The alluvial
deposits known are mainly near the British Guiana border in the
Cuyuni and El Dorado districts. Placer gold exists along the Caroni
River and in smaller tributaries of the Orinoco above Ciudad Bolívar.
The rock formation shows the gold to be in stingers and crystalline
grains of arsenical pyrite, from which the placers and pockets have
been formed.
The quartz veins are more northerly near El Callao, where
$50,000,000 are said to have been produced in thirty odd years. One
mine in the Yuruari district has yielded 35,000 ounces. Metal is found
in pockets 50-100 feet deep about 150 miles from the Orinoco. An
English company has mining claims west of El Callao, where the ore
is treated with quicksilver and cyanide, yielding 1-4 ounces per ton.
Another company is working on the La Paz Bonanza, where 10,000
ounces were taken out by crude methods from rich veinlets and
pockets almost at the surface. Several other companies are
engaged, French and Venezuelan, one along the Cicapra River, a
branch of the upper Yuruari. It is estimated that several million cubic
yards with an average yield of $1.00 each are here available at a
cost of 50 cents per yard. With better transportation and other
facilities this section may come into the front rank of gold mining
districts in South America. At present it is said to be better adapted
to individual operators than to large companies. The climate is not
unhealthful if suitable precautions are taken. The country is well
wooded except near Callao. The average yearly production of gold is
900,000 grams.
Copper is known to exist in several States: Falcón, Carabobo,
Mérida, Lara, a rich deposit in the northern part of Cojedes; but the
only one vigorously and very profitably operated is that of Aroa in
Yaracuy, where dividends have been 75-350 per cent. Near Nirgua
in the same State other copper mines have been worked.
Coal is found in various sections. Where outcroppings occur in
Táchira, Mérida, and Trujillo small operations have been carried on.
There are other deposits but the principal mines worked are in Sucre
and Falcón. Naricual, 16 miles from Barcelona, has produced the
most coal, but not of a very good quality. It is used on local steamers
and railways, and some, with pitch from Trinidad, is made into
briquettes. A little west, another mine with coal of better quality has
been opened within five miles of tide water on the bank of a river.
The mines of Falcón near Coro have been developed further and
production is increasing. Coke ovens have been established. Coal is
found in several places near Lake Maracaibo. In the deposit 60 miles
northwest of Maracaibo the coal is of high grade, better than Middle
West coal and equal to the Pocahontas; hard, bright, black, excellent
for steaming. Some veins are 8-20 feet thick, and when the railway
to Castilletes is completed the annual export is expected to reach
500,000 tons. Lignite, bituminous, and semi-anthracite varieties are
found.
Iron ore deposits occur in the eastern hills or mountains south of
the Delta, but in the Delta Territory at Imataca. It is 67 per cent pure
and almost free from sulphur and phosphorus. In 1914 some
Americans secured options. Iron is also found near Coro, Barinas,
Barcelona, and Cumaná.
Salt is found on the island of Coche, on the peninsula of Araya
near Cumaná, in the vicinity of Barcelona and of Maracaibo, and
elsewhere.
Sulphur appears to exist in commercial quantities about 11 miles
inland from Corúpano; and other minerals have been observed in
various States.
Diamonds and Pearls. There are said to be diamond mines in the
Orinoco region. Pearl fishing is carried on among the islands, about
1600 persons being so engaged. Rakes are now used as diving is
prohibited. Recently $600,000 worth were exported within a few
months.
Asphalt, found in the Bermudez Pitch Lake five miles from
Guanoco in the State of Sucre, is an important source of wealth. This
lake, the largest known deposit in the world (1100 acres), has more
than ten times the area of the famous Trinidad Lake, though it is not
so deep. It is regarded as the residue of evaporated petroleum, the
asphalt here representing the outflow of 80,000,000 barrels of oil.
The flow continues, the oil spreading over the lake and replenishing
it. This with active seepages near indicates enormous oil bearing
formations below.
The General Asphalt Company and its subsidiaries have a 30 year
lease of nearly 12,000 acres including the lake. The structure of the
lake includes faulting, folding, and fracturing of strata, with
formations of black shale, sandstone, and fossiliferous limestone, the
last supposed to be the source of the oil, and the sandstone its
reservoir, whence from pressure of gas it escapes to the surface. A
narrow gauge railway is in use. From lack of transport hardly 20,000
tons of asphalt were shipped from Bermudez Lake in 1920
compared with over 40,000 in 1919; from Trinidad Lake, about
70,000 in 1919 and over 108,000 in 1920. In the Bermudez
concession is a large asphalt deposit 100-200 yards across, on the
Island of Capure in the Orinoco Delta.
In the Maracaibo Basin are other beds. One near the Lake at
Inciarte, 27 miles from navigable water, is 94 per cent pure; but
transportation is difficult.
The Petroleum prospects of Venezuela are excellent. The chief
work accomplished is in the Maracaibo Basin, which is regarded as
one of petroleum as well as of water. Many companies are engaged
in development work. After two years of preliminary examination by
35 experienced geologists, the Caribbean Petroleum Company
selected 1000 areas averaging 1250 acres each for further
investigation. Of these they now retain 250, covering 312,500 acres.
With a lease concession for 30 years, a tax of eight cents an acre is
paid annually and a royalty equal to about ten per cent on oil shipped
from the country. On one section, the Mene Grande Field, ten miles
east of Lake Maracaibo to which a road through swamps was built,
about a dozen wells have been drilled, in all of which oil has been
found. The first were capped, but with present facilities flow is
permitted. The character of the oil improves with depth. Three
55,000-barrel steel tanks have been erected, and pumping stations
on the field and at the port. A pipe line was laid 11 miles to the shore
at San Lorenzo, where, 70 miles southeast of Maracaibo, storage
tanks and a refinery were built. The latter, now in operation, will
refine every grade of oil except lubricants. The capacity is 2000
barrels daily (42 gallons each). One well is said to rank in output with
some of the Mexican. Much of the oil is now used by some
Venezuelan railways, and by industries of the country. Part of the
crude oil is carried by three barges and eight converted monitors of
450-500 tons each to a refinery at Curaçao, which has larger storage
tanks, pumping station, etc. The refinery has been running 1000 tons
of crude oil daily, but can take care of 4000 tons. The swift current of
the Maracaibo Channel makes management of the monitors difficult.
This Company has other wells at Perija, 50 miles west of the Lake.
The first, which struck oil at 1227 feet, was shut in. One in the Limón
Field, drilled to 2752 feet, was abandoned.
Other companies have concessions for work near the Lake, at the
east, south, and southwest. One was hampered by wild Indians,
compelling the employment of armed guards, another by extremely
unhealthful conditions; but both after some unsuccessful work have
found promising wells. The Colon Developing Company, with a large
property 100 miles west of Encontrados and near the Colombian
border, has struck oil at less than 1300 feet, close to the Rio de Oro.
Two thousand barrels of high grade oil were produced within 24
hours, but as no facilities for transport existed the well was capped.
This oil is said to be of quality superior to that east of the Lake, which
is better than the Mexican.
East of the Lake, another field, north of the Mene Grande, is
owned by the Venezuelan Oil Concessions. Wells drilled here have
passed through three oil bearing sands; the deeper, the better and
lighter the oil. One has spouted 80 feet high; another over the top of
the derrick. An area of several square miles is proved. This
Company has 3000 square miles of oil bearing land near the Lake
for 50 years. In Mexico wells producing 100,000 barrels a day are
seen. The general manager of this Company believes the
Venezuelan wells will be bigger.
The Venezuelan Falcón Oil Syndicate, which has a 50 year
concession of over 2000 square miles in Falcón, expects to open up
many fields. Pipe lines could converge and refineries be installed
within 50 miles of the farthest point. The first well drilled is 37 miles
from the seaboard. Motor tractors are employed. The British
Controlled Oilfields has taken over the Bolívar Concessions, which
has the right to bore in 7,000,000 acres in Falcón.
On the Island of Trinidad 362,800 barrels of crude petroleum were
produced in 1920. Near this Island, corresponding to the oil region at
the northwest of Venezuela, is one at the northeast around the Gulf
of Paria, especially at the south, and comprising the Orinoco Delta.
Here is found the heavier form of petroleum in large quantities.
Some wells have been drilled on the Peninsula of Paria with no good
result. The Guanoco Field, south, is believed to cover the axis and
flanks of the Guanoco anticlines, of which the southern is thought to
be responsible for the great oil seepages of the Asphalt Lake. The
field is believed to extend 60 miles southwest, to and beyond the
San Juan River. The first well was drilled (1912) in the Lake. Heavy
oil, specific gravity 1.02, was found under enormous gas pressure,
making operations difficult. Production of 1000 barrels a day was
secured at 615 feet, but the well was closed to avoid waste. Later it
produced in three months 50,000 barrels. Other wells have been
drilled in the vicinity, also on Pedernales Island in the Delta; the oil
from the latter of lighter gravity. For some purposes the heavy oil is
of special value. It is too heavy to pump, but the strong gas pressure
makes it available. The areas are swampy, difficult to work, and
unhealthful.

Manufactures

As might be expected, the manufacturing industries of Venezuela


are few in number and rely in the main on a protective tariff for
existence. The principal articles made are cotton goods, paper,
glass, cement, cordage, soap, candles, shoes, alpargatas, leather
goods, cigars, cigarettes, etc. The five cotton factories produce 80
per cent of the ordinary cloth consumed in the country. In Mérida are
woolen and hat factories. In Caracas good furniture is made,
macaroni, paper, etc. There is a paper factory also at Maracay. Ten
miles from Caracas the waterfall of Naiguatá, over 3000 feet, makes
available 30,000 horse power, of which 9000 is used.

Investments

Among the various opportunities for the investment of foreign


capital, including all of the industries mentioned, the safest are
agriculture and stock raising; perhaps also small factories. Land is so
cheap that little capital is needed for the agriculturist unless
engaging on a very large scale. Coffee, cacao, sugar cane, castor
beans, and many other articles may be raised with profit. Factories
large or small may be operated to advantage. Cumaná and Puerto
Cabello are good places for canning tropical fruits. Oil may be
extracted for edible or industrial purposes from coconuts, peanuts,
and other fruits or vegetables. Chocolate may be made, cotton mills
established. A mill is suggested for Margarita, where fine cotton is
grown. Rope and bag factories might employ Venezuelan cocuiza or
henequen to make the 2,000,000 bags needed annually in the
country. Saw mills at Cumaná, Maracaibo, La Ceiba, Tucacas, etc.,
would be extremely useful.
Large capitalists may find opportunities for the construction of
public utilities such as street railways, electric light and power plants,
water works, sewers; also in bridge building, railway construction,
etc. Some might be interested in mining, especially of iron, which is
found favorably located for transportation within half a mile of a
navigable river about 50 miles from the mouth of the Orinoco. To
individuals with small capital the gold region would be more
attractive. An important development of the large deposits of bauxite
is attracting much attention.
CHAPTER XII
GUIANA AS A WHOLE: BRITISH GUIANA

The name Guiana has been applied to the entire country between
the Orinoco and the Amazon. We have observed that in Venezuela
the region south of the Orinoco is called the Guiana Highlands. We
shall notice later that the section south of the dividing mountain
range and north of the Amazon as far west as the Rio Negro is called
Brazilian Guiana; but the country which is more strictly Guiana is
east and north of these, though here, too, adjectives are applied as
there are three divisions: British, Dutch, and French Guiana, the
British on the west, the French farthest east.

Area

The area of them all is about 170,000 square miles, of which


British Guiana has 90,000, Dutch 46,000, and French 33,000 square
miles.
As these countries are colonies instead of republics their
governments are naturally different.
Although sighted by Columbus in 1498 and visited not long
afterward by traders, as there was a large Indian population, the
country was settled later than Venezuela and Colombia. After
various vicissitudes the earliest colonies were abandoned. The
difficulties of the later settlements, the changes, insurrections,
massacres, wars, and troubles of various kinds following are too
numerous to recount, and we come immediately to conditions of the
present time.

Physical Characteristics

The three divisions of Guiana are similar, having first a low marshy
coast land, rising at the back very slightly for a distance of 10 to 40
miles. A broader, more elevated tract of sandy or clayey soil follows
with a still higher region in the rear. Of the southern section the
eastern part is almost all forest, the central and southwest portions
have more grass clad savannas, which might support thousands of
cattle if there were any way to get them out. There is a vast network
of water ways, many rivers in their lower sections near the coast
being connected by caños. The forest varies, being dense in river
bottoms and thin on sandy soils. The longest river, the Essequibo, is
about 600 miles, others a little less. At from 50 to 100 miles inland,
all the rivers are blocked by rapids, but some are accessible to large
vessels as far as these. There are various hills and mountains, the
highest, the Pacaraima Range, marking in part the boundary with
Venezuela, the Acarai Mountains with Brazil; the two form the water
shed between the Amazon, the Orinoco, and the Essequibo rivers.
Mt. Roraima, altitude 8635 feet, rising as a red rock 1500 feet above
the forest, is said to have as its top a tableland of 12 square miles.
Several other mountains are from 7000 to 8000 feet high. Ranges of
hills and mountains from 2000 to 3000 feet traverse the country
elsewhere. In Dutch and French Guiana are almost impenetrable
forests, less explored than those of British Guiana, especially
towards the south. A splendid waterfall is the Kaieteur, nearly five
times as high as Niagara, 741 feet, with 81 feet of cataracts just
below, in the midst of lovely tropical vegetation. Many other beautiful
falls of less height, and cascades provide an immense amount of
water power.
The climate is considered good in most places though there is
large rain-fall, at Georgetown averaging 93 inches a year, in some
places 100; but there is no yellow fever, and other diseases except in
certain localities may be guarded against.

British Guiana

Area. This colony has an area of 90,000 square miles, exceeding


that of Great Britain, a sea coast of 270 miles, and a depth varying
from 300 to 535 miles.
The Population according to the official report of 1919 is 310,000.
Boundary. British Guiana has the Atlantic Ocean on the
northeast, Dutch Guiana east, the Corentyn River serving most of
the way as the boundary line; Brazil is on the south, and Brazil and
Venezuela are west.
The Government is practically that of a Crown Colony with a
Governor who has almost absolute power. He is assisted by a
legislative council which has no great influence.
The Population is mixed, East Indians and negroes forming by far
the greater proportion of the total, some mestizos, Chinese, Indians,
and 10,000 whites. The large majority of the people live in the
coastal belt. Many negroes were brought from Africa as slaves, who,
after their emancipation, in large numbers refused to work on the
plantations as before. East Indians were then brought in, who though
not so strong are more industrious and have better health than those
of other races; for one reason because they dress to suit the climate,
draping themselves with a few yards of cotton cloth in a really artistic
manner. The native Indian is useful to the traveler as boatman,
wood-cutter, or huntsman, also to gold diggers, and seekers of
balatá. Some of the half civilized are fairly reliable. If they become
friends they are of great value. The wild Indians are disappearing,
perhaps going farther back.
Education is mainly carried on by religious denominations, with
missions in outlying districts; 224 schools receive government
assistance; there is one government free school in Georgetown
where students may be prepared for English universities or for
ordinary fields of labor. Of course there is full religious liberty, but the
government subsidizes the principal churches, especially the English
and Scotch, in the country the parishes alternating. The Roman
Catholic and the Methodist churches also receive annual grants.
Other denominations are represented, but receive no assistance
except in some cases for schools.
The Post Office is up to date with telephone (1800 miles of wire),
telegraph (575 miles), and savings bank attachments, the last having
over a million dollars on deposit. There is cable communication with
the West Indies and wireless. British money is not in general use;
dollars and cents according to the decimal system of America are
the common currency. The weights and measures are naturally
British like our own.
The Capital of British Guiana, Georgetown, population 54,000,
located at the mouth of the Demerara River, is a tropical garden city
with broad streets, interesting stores, a club, a museum, a curious
market. On account of dampness the houses are all built on pillars.
The city has 50 miles of paved streets with good tramways, etc.

Ports and Transportation

The chief ports of the Guianas are the three capitals, which are
connected with the outside world by the West Indies Mail Services of
the three mother countries, while other steamship lines run regularly
to London, Liverpool, and Glasgow. There is mail service with
Canada and regular steamers from New York. Coast and river
steamers ply regularly along the coast of British Guiana from the
northwest extremity to the Berbice River, at the mouth of which is the
city of New Amsterdam, called a smaller Georgetown, not very far
from the boundary of Dutch Guiana. The country has 95 miles of
railway, 450 of navigable rivers, 39 miles of canals, and 322 of good
roads.
A railway 60 miles long connects Georgetown with New
Amsterdam, i.e., it reaches a point on the Berbice River opposite the
latter city. Five miles of this road from Georgetown to Plaisance,
completed and opened for traffic in 1848, is actually the oldest
railway in South America. Another 19 mile line goes from Vreeden
Hook opposite Georgetown on the Demerara River to Greenwich
Park on the Atlantic at the mouth of the Essequibo. Another short
line running through primeval forest has been laid from Wismar on
the Demerara, 65 miles from its mouth, to Rockstone on the
Essequibo to give access to the upper part of the latter river above
extensive and dangerous rapids, and further to the Potaro and other
gold fields. The Road, besides passenger and tourist traffic handles
a variety of timber. Its owners, (Sprostons Ltd.), who employ over
1000 men, maintain a coast and river service, and own a foundry,
lumber yard, etc. A railway to the Brazil boundary, long planned,
would open up the interior and its valuable resources. From
Rockstone, launches run 90 miles up the river to Potaro Landing. A
service was to be organized to the Kaieteur Falls on the Potaro
River.
Ferries cross the mouths of the three principal rivers, the
Essequibo, the Demerara, and the Berbice. The estuary of the
Essequibo River is 15 miles wide. It contains several large islands,
on some of which are plantations. Vessels drawing less than 20 feet
can enter the river and go up 50 miles. The mouth of the Demerara
River, two miles wide, has a sand bar prohibiting the entrance of
vessels drawing more than 19 feet. To such as enter, the river is
navigable for 70 miles. The Berbice River, two miles wide at its
mouth, is navigable 105 miles for vessels drawing 12 feet and 175
miles for boats drawing 7 feet. The Corentyn River with an estuary
14 miles wide is navigable for 150 miles; this river is the boundary
between British and Dutch Guiana. Roads good enough for
automobiles and carriages, which use them, extend from the
Corentyn River along the coast some miles beyond the mouth of the
Essequibo and a few miles up the rivers.

Resources

At present agriculture and mining are the leading industries.

Agriculture

Sugar, the chief source of revenue for the colony, in slavery days
brought great wealth to the planters; but after the emancipation
some estates were divided, the negroes refused to work steadily if at
all, and production greatly declined. At length East Indians who were
imported helped to revive the industry. Of 105,000 agricultural
laborers 73,000 are East Indians. The plantations are mostly in the
coastal lowlands where 77,000 acres are cultivated. Attention to the
dams needed to keep out the sea in front and water from the morass
at the side, also to the drainage ditches, necessary on account of the

You might also like