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

Brief C Late Objects 3rd Edition Cay Horstmann download

The document provides information about the 'Brief C++ Late Objects 3rd Edition' by Cay Horstmann, which serves as an introduction to C++ programming focusing on essential concepts and effective learning. It highlights features such as step-by-step guidance, practice exercises, and a modern approach to teaching C++ with updated content. Additionally, it mentions the availability of related educational resources and interactive learning options through an Enhanced E-Text format.

Uploaded by

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

Brief C Late Objects 3rd Edition Cay Horstmann download

The document provides information about the 'Brief C++ Late Objects 3rd Edition' by Cay Horstmann, which serves as an introduction to C++ programming focusing on essential concepts and effective learning. It highlights features such as step-by-step guidance, practice exercises, and a modern approach to teaching C++ with updated content. Additionally, it mentions the availability of related educational resources and interactive learning options through an Enhanced E-Text format.

Uploaded by

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

Brief C Late Objects 3rd Edition Cay Horstmann

download

https://ebookmeta.com/product/brief-c-late-objects-3rd-edition-
cay-horstmann/

Download more ebook from https://ebookmeta.com


We believe these products will be a great fit for you. Click
the link to download now, or visit ebookmeta.com
to discover even more!

Big C late objects 3rd Edition Cay S. Horstmann

https://ebookmeta.com/product/big-c-late-objects-3rd-edition-cay-
s-horstmann/

Java For Everyone Late Objects Cay S Horstmann

https://ebookmeta.com/product/java-for-everyone-late-objects-cay-
s-horstmann/

Big Java Late Objects Enhanced eText 2nd Edition Cay S.


Horstmann

https://ebookmeta.com/product/big-java-late-objects-enhanced-
etext-2nd-edition-cay-s-horstmann/

Human Behavior and the Social Environment: Shifting


Paradigms in Essential Knowledge for Social Work
Practice 7th Edition Joe Schriver

https://ebookmeta.com/product/human-behavior-and-the-social-
environment-shifting-paradigms-in-essential-knowledge-for-social-
work-practice-7th-edition-joe-schriver/
The Wiley Blackwell Companion to Hinduism 2nd Edition
Gavin Flood

https://ebookmeta.com/product/the-wiley-blackwell-companion-to-
hinduism-2nd-edition-gavin-flood/

Drag Queen of Scots The hilarious and heartwarming


memoir from the UK s favourite drag queen 1st Edition
Lawrence Chaney

https://ebookmeta.com/product/drag-queen-of-scots-the-hilarious-
and-heartwarming-memoir-from-the-uk-s-favourite-drag-queen-1st-
edition-lawrence-chaney/

Twisted Hate An Enemies with Benefits Romance Ana Huang

https://ebookmeta.com/product/twisted-hate-an-enemies-with-
benefits-romance-ana-huang/

Medical Persuasion Understanding the Impact on Medical


Argumentation Vic Velanovich

https://ebookmeta.com/product/medical-persuasion-understanding-
the-impact-on-medical-argumentation-vic-velanovich/

Handbook of Pain Medicine 2e 2nd Edition G P Dureja

https://ebookmeta.com/product/handbook-of-pain-medicine-2e-2nd-
edition-g-p-dureja/
The Quantum Human Karen Curry Parker

https://ebookmeta.com/product/the-quantum-human-karen-curry-
parker/
BriefC++
Cay Horstmann

Late Objects
3/e
BriefC++
Late Objects
3/e
BriefC++ Late Objects
3/e

Cay Horstmann
San Jose State University
PUBLISHER Laurie Rosatone
EDITORIAL DIRECTOR Don Fowley
DEVELOPMENTAL EDITOR Cindy Johnson
ASSISTANT DEVELOPMENT EDITOR Ryann Dannelly
EXECUTIVE MARKETING MANAGER Dan Sayre
SENIOR PRODUCTION EDITOR Laura Abrams
SENIOR CONTENT MANAGER Valerie Zaborski
EDITORIAL ASSISTANT Anna Pham
SENIOR DESIGNER Tom Nery
SENIOR PHOTO EDITOR Billy Ray
PRODUCTION MANAGEMENT Cindy Johnson
COVER IMAGE © Monty Rakusen/Getty Images

This book was set in Stempel Garamond LT Std by Publishing Services, and printed and bound by Quad/
Graphics, Versailles. The cover was printed by Quad/Graphics, Versailles.

This book is printed on acid-free paper. ∞

Founded in 1807, John Wiley & Sons, Inc. has been a valued source of knowledge and understanding for more
than 200 years, helping people around the world meet their needs and fulfill their aspirations. Our company is
built on a foundation of principles that include responsibility to the communities we serve and where we live
and work. In 2008, we launched a Corporate Citizenship Initiative, a global effort to address the environmental,
social, economic, and ethical challenges we face in our business. Among the issues we are addressing are carbon
impact, paper specifications and procurement, ethical conduct within our business and among our vendors,
and community and charitable support. For more information, please visit our website: www.wiley.com/go/
citizenship.

Copyright © 2018, 2012, 2009 John Wiley & Sons, Inc. All rights reserved.

No part of this publication may be reproduced, stored in a retrieval system or transmitted in any form or by
any means, electronic, mechanical, photocopying, recording, scanning or otherwise, except as permitted under
Sections 107 or 108 of the 1976 United States Copyright Act, without either the prior written permission of
the Publisher, or authorization through payment of the appropriate per-copy fee to the Copyright Clearance
Center, Inc. 222 Rosewood Drive, Danvers, MA 01923, website www.copyright.com. Requests to the Publisher
for permission should be addressed to the Permissions Department, John Wiley & Sons, Inc., 111 River Street,
Hoboken, NJ 07030-5774, (201) 748-6011, fax (201) 748-6008, website http://www.wiley.com/go/permissions.

Evaluation copies are provided to qualified academics and professionals for review purposes only, for use in
their courses during the next academic year. These copies are licensed and may not be sold or transferred to a
third party. Upon completion of the review period, please return the evaluation copy to Wiley. Return instruc-
tions and a free of charge return shipping label are available at www.wiley.com/go/returnlabel. If you have
chosen to adopt this textbook for use in your course, please accept this book as your complimentary desk copy.
Outside of the United States, please contact your local representative.

ISBN 13: 978-1-119-40042-4

The inside back cover will contain printing identification and country of origin if omitted from this page. In
addition, if the ISBN on the back cover differs from the ISBN on this page, the one on the back cover is correct.

Printed in the United States of America.

10 9 8 7 6 5 4 3 2 1
P R E FA C E

This book is an introduction to C++ and computer programming that focuses on


the essentials—and on effective learning. The book is designed to serve a wide range
of student interests and abilities and is suitable for a first course in programming for
computer scientists, engineers, and students in other disciplines. No prior program-
ming experience is required, and only a modest amount of high school algebra is
needed.
Here are the key features of this book:

Present fundamentals first.


This book uses the C++ programming language as a vehicle for introducing com-
puter science concepts. A substantial subset of the C++ language is covered, focusing
on the modern features of standard C++ that make students productive. The book
takes a traditional route, first stressing control structures, procedural decomposition,
and array algorithms. Objects are used when appropriate in the early chapters. Stu-
dents start designing and implementing their own classes in Chapter 9.

Guidance and worked examples help students succeed.


Beginning programmers often ask “How do I start? Now what do I do?” Of course,
an activity as complex as programming cannot be reduced to cookbook-style instruc-
tions. However, step-by-step guidance is immensely helpful for building confidence
and providing an outline for the task at hand. “Problem Solving” sections stress the
importance of design and planning. “How To” guides help students with common
programming tasks. Additional Worked Examples are available in the E-Text or
online.
Tip: Source files for all of the program examples in the book, including the Worked
Examples, are provided with the source code for this book. Download the files to
your computer for easy access as you work through the chapters.
Practice makes perfect.
Of course, programming students need to be able to implement nontrivial programs,
but they first need to have the confidence that they can succeed. The Enhanced E-Text
immerses students in activities designed to foster in-depth learning. Students don’t
just watch animations and code traces, they work on generating them. The activities
provide instant feedback to show students what they did right and where they need
to study more. A wealth of practice opportunities, including code completion ques-
tions and skill-oriented multiple-choice questions, appear at the end of each section,
and each chapter ends with well-crafted review exercises and programming projects.
Problem solving strategies are made explicit.
Practical, step-by-step illustrations of techniques help students devise and evaluate
solutions to programming problems. Introduced where they are most relevant, these
strategies address barriers to success for many students. Strategies included are:
• Algorithm Design (with pseudocode)
• First Do It By Hand (doing sample calculations by hand)
• Flowcharts

v
vi Preface

• Selecting Test Cases


• Hand-Tracing
• Storyboards
• Solve a Simpler Problem First
• Reusable Functions
• Stepwise Refinement
• Adapting Algorithms
• Discovering Algorithms by Manipulating Physical Objects
• Draw a Picture (pointer diagrams)
• Tracing Objects (identifying state and behavior)
• Discovering Classes
A visual approach motivates the reader and eases navigation.
Photographs present visual analogies that explain
the nature and behavior of computer concepts.
Step-by-step figures illustrate complex program
operations. Syntax boxes and example tables pres-
ent a variety of typical and special cases in a com-
pact format. It is easy to get the “lay of the land” by
browsing the visuals, before focusing on the textual
material.
Focus on the essentials while being
© Terraxplorer/iStockphoto.
technically accurate.
An encyclopedic coverage is not helpful for a Visual features help the reader
beginning programmer, but neither is the oppo- with navigation.
site—reducing the material to a list of simplistic
bullet points. In this book, the essentials are presented in digestible chunks, with sep-
arate notes that go deeper into good practices or language features when the reader is
ready for the additional information. You will not find artificial over-simplifications
that give an illusion of knowledge.
Reinforce sound engineering practices.
A multitude of useful tips on software quality and common errors encourage the
development of good programming habits. The focus is on test-driven development,
encouraging students to test their programs systematically.
Engage with optional engineering and business exercises.
End-of-chapter exercises are enhanced with problems from scientific and business
domains. Designed to engage students, the exercises illustrate the value of program-
ming in applied fields.
Preface vii

New to This Edition


Updated for Modern Versions of C++
A number of features of the C++ 2011 and C++ 2014 standards are described either as
recommended “best practice” or as Special Topics.

New and Reorganized Topics


The book now supports two pathways into object-oriented programming and inher-
itance. Pointers and structures can be covered before introducing classes. Alterna-
tively, pointers can be deferred until after the implementation of classes.
A sequence of Worked Examples and exercises introduces “media computa-
tion”—generating and modifying images, sounds, and animations.

Lower-Cost, Interactive Format


This third edition is published as a lower-cost Enhanced E-Text that supports active
learning through a wealth of interactive activities. These activities engage and prepare
students for independent programming and the Review Exercises, Practice Exercises,
and Programming Projects at the end of each E-Text chapter. The Enhanced E-Text
may also be bundled with an Abridged Print Companion, which is a bound book that
contains the entire text for reference, but without exercises or practice material.
Interactive learning solutions are expanding every day, so to learn more about
these options or to explore other options to suit your needs, please contact your
Wiley account manager (www.wiley.com/go/whosmyrep) or visit the product information
page for this text on wiley.com (http://wiley.com/college/sc/horstmann).
The Enhanced E-Text is designed to enable student practice without the instructor
assigning the interactivities or recording their scores. If you are interested in assign-
ing and grading students’ work on them, ask your Wiley Account Manager about the
online course option implemented in the Engage Learning Management System. The
Engage course supports the assignment and automatic grading of the interactivities.
Engage access includes access to the Enhanced E-Text.

Features in the Enhanced E-Text


The interactive Enhanced E-Text guides students from the basics to writing complex
programs. After they read a bit, they can try all of the interactive exercises for that
section. Active reading is an engaging way for students to ensure that students are
prepared before going to class.
There five types of interactivities:
Code Walkthrough Code Walkthrough activities ask students to trace through a
segment of code, choosing which line will be executed next and entering the new
values of variables changed by the code’s execution. This activity simulates the hand-
tracing problem solving technique taught in Chapters 3 and 4—but with immediate
feedback.
viii Preface

Example Table Example table activities make the student the active participant in
building up tables of code examples similar to those found in the book. The tables
come in many different forms. Some tables ask the student to determine the output of
a line of code, or the value of an expression, or to provide code for certain tasks. This
activity helps students assess their understanding of the reading—while it is easy to
go back and review.
Algorithm Animation An algorithm animation shows the essential steps of an
algorithm. However, instead of passively watching, students get to predict each step.
When finished, students can start over with a different set of inputs. This is a surpris-
ingly effective way of learning and remembering algorithms.
Rearrange Code Rearrange code activities ask the student to arrange lines of code
by dragging them from the list on the right to the area at left so that the resulting code
fulfills the task described in the problem. This activity builds facility with coding
structure and implementing common algorithms.
Object Diagram Object diagram activities ask the student to create a memory
diagram to illustrate how variables and objects are initialized and updated as sample
code executes. The activity depicts variables, objects, and references in the same way
as the figures in the book. After an activity is completed, pressing “Play” replays the
animation. This activity goes beyond hand-tracing to illuminate what is happening in
memory as code executes.
Code Completion Code completion activities ask the student to finish a partially-
completed program, then paste the solution into CodeCheck (a Wiley-based online
code evaluator) to learn whether it produces the desired result. Tester classes on the
CodeCheck site run and report whether the code passed the tests. This activity serves
as a skill-building lab to better prepare the student for writing programs from scratch.

A Tour of the Book


This book is intended for a two-semester introduction to programming that may also
include algorithms and data structures. The organization of chapters offers the same
flexibility as the previous edition; dependencies among the chapters are also shown
in Figure 1.

Part A: Fundamentals (Chapters 1–8)


The first six chapters follow a traditional approach to basic programming concepts.
Students learn about control structures, stepwise refinement, and arrays. Objects are
used only for input/output and string processing. Input/output is first covered in
Chapter 2, which may be followed by an introduction to reading and writing text
files in Section 8.1.
In a course for engineers with a need for systems and embedded programming,
you will want to cover Chapter 7 on pointers. Sections 7.1 and 7.4 are sufficient for
using pointers with polymorphism in Chapter 10.
File processing is the subject of Chapter 8. Section 8.1 can be covered sooner for
an introduction to reading and writing text files. The remainder of the chapter gives
additional material for practical applications.
Preface ix

Part B: Object-Oriented Design (Chapters 9–10)


After students have gained a solid foundation, they are ready to tackle the implemen-
tation of classes. Chapters 9 and 10 introduce the object-oriented features of C++.
Chapter 9 introduces class design and implementation. Chapter 10 covers inheritance
and polymorphism. By the end of these chapters, students will be able to implement
programs with multiple interacting classes.
Any subset of these chapters can be incorporated into a custom print version of
this text; ask your Wiley sales representative for details, or visit customselect.wiley.com
to create your custom order.

Appendices
Appendices A and B summarize C++ reserved words and operators. Appendix C
lists character escape sequences and ASCII character code values. Appendix D docu-
ments all of the library functions and classes used in this book.
Appendix E contains a programming style guide. Using a style guide for program-
ming assignments benefits students by directing them toward good habits and reduc-
ing gratuitous choice. The style guide is available in electronic form on the book’s
companion web site so that instructors can modify it to reflect their preferred style.
Appendix F, available in the E-Text, introduces common number systems used in
computing.

Fundamentals
1. Introduction
Object-Oriented Design

2. Fundamental
Data Types

3. Decisions

4. Loops

A gentle
introduction to recursion
5. Functions is optional.
Section 8.1
contains the core
material
6. Arrays
6. Iteration
and Vectors

7. Pointers 8. Streams 9. Classes

Sections 10. Inheritance


7.1 and 7.4 are
required

Figure 1 Chapter Dependencies


x Preface

Web Resources
This book is complemented by a complete suite of online resources. Go to www.wiley.
com/go/bclo3 to visit the online companion sites, which include

• Source code for all example programs in the book and its Worked Examples, plus
additional example programs.
• Worked Examples that apply the problem-solving steps in the book to other
realistic examples.
• Lecture presentation slides (for instructors only).
• Solutions to all review and programming exercises (for instructors only).
• A test bank that focuses on skills, not just terminology (for instructors only). This
extensive set of multiple-choice questions can be used with a word processor or
imported into a course management system.
• “CodeCheck” assignments that allow students to work on programming prob-
lems presented in an innovative online service and receive immediate feedback.
Instructors can assign exercises that have already been prepared, or easily add
their own. Visit http://codecheck.it to learn more.

Pointers in the print


companion describe what
students will find in their WORKED EXAMPLE 2.1
Computing Travel Time
E-Text or online.
Learn how to develop a hand calculation to compute the time that
a robot requires to retrieve an item from rocky terrain. See your
.
E-Text or visit wiley.com/go/bclo3
Courtesy of NASA.

EXAMPLE CODE See how_to_1/scores_vector in your companion code for a solution using vectors instead of arrays.
Walkthrough xi

A Walkthrough of the Learning Aids


The pedagogical elements in this book work together to focus on and reinforce key
concepts and fundamental principles of programming, with additional tips and detail
organized to support and deepen these fundamentals. In addition to traditional
features, such as chapter objectives and a wealth of exercises, each chapter contains
elements geared to today’s visual learner.

106 Chapter 4 Loops

4.3 The for Loop


Throughout each chapter,
It often happens that you want to execute a sequence of
margin notes show where The for loop is
used when a statements a given number of times. You can use a while
value runs from a loop that is controlled by a counter, as in the following
new concepts are introduced starting point to an
ending point with a
example:
and provide an outline of key ideas. constant increment
or decrement.
counter = 1; // Initialize the counter
while (counter <= 10) // Check the counter
{
cout << counter << endl;
counter++; // Update the counter
}

Because this loop type is so common, there is a special


form for it, called the for loop (see Syntax 4.2).
for (counter = 1; counter <= 10; counter++)
{
© Enrico Fianchini/iStockphoto.
cout << counter << endl;
}
You can visualize the
Some people call this loop count-controlled. In contrast, for loop as an orderly
the while loop of the preceding section can be called an sequence of steps.
event-controlled loop because it executes until an event
occurs (for example, when the balance reaches the target). Another commonly-used
Annotated syntax boxes term for a count-controlled loop is definite. You know from the outset that the loop
body will be executed a definite number of times––ten times in our example. In con-
provide a quick, visual overview trast, you do not know how many iterations it takes to accumulate a target balance.
Such a loop is called indefinite.
of new language constructs.
Syntax 4.2 for Statement

These three
expressions should be related.
See Programming Tip 4.1.

Annotations explain This initialization The loop is This update is


required components happens once
before the loop starts.
executed while
this condition is true.
executed after
each iteration.
and point to more information for (int i = 5; i <= 10; i++)

on common errors or best practices The variable i is


{
sum = sum + i;
This loop executes 6 times.
associated with the syntax. defined only in this
for loop.
}
See Programming Tip 4.3.

The for loop neatly groups the initialization, condition, and update expressions
together. However, it is important to realize that these expressions are not executed
together (see Figure 3).

Analogies to everyday objects are


used to explain the nature and behavior
of concepts such as variables, data
Like a variable in a computer types, loops, and more.
program, a parking space has
an identifier and contents.
xii Walkthrough

Memorable photos reinforce


analogies and help students
remember the concepts. pie(fruit) pie(fruit)

A recipe for a fruit pie may say to use any kind of fruit.
Here, “fruit” is an example of a parameter variable.
Apples and cherries are examples of arguments.

Problem Solving sections teach


techniques for generating ideas and
6.5 Problem Solving: Discovering Algorithms by Manipulating Physical Objects 277
evaluating proposed solutions, often
using pencil and paper or other Now how does that help us with our problem, switching the first and the second
half of the array?
artifacts. These sections emphasize Let’s put the first coin into place, by swapping it with the fifth coin. However, as
C++ programmers, we will say that we swap the coins in positions 0 and 4:
that most of the planning and problem
solving that makes students successful
happens away from the computer.

Next, we swap the coins in positions 1 and 5:

HOW TO 1.1
Describing an Algorithm with Pseudocode
This is the first of many “How To” sections in this book that give you step-by-step proce-
dures for carrying out important tasks in developing computer programs.
Before you are ready to write a program in C++, you need to develop an algorithm—a
method for arriving at a solution for a particular problem. Describe the algorithm in pseudo-
code––a sequence of precise steps formulated in English. To illustrate, we’ll devise an algo-
rithm for this problem:
How To guides give step-by-step
Problem Statement You have the choice of buying one guidance for common programming
of two cars. One is more fuel efficient than the other, but also
more expensive. You know the price and fuel efficiency (in miles tasks, emphasizing planning and
per gallon, mpg) of both cars. You plan to keep the car for ten
years. Assume a price of $4 per gallon of gas and usage of 15,000 testing. They answer the beginner’s
miles per year. You will pay cash for the car and not worry about
financing costs. Which car is the better deal? © dlewis33/Getty Images. question, “Now what do I do?” and
Step 1 Determine the inputs and outputs. integrate key concepts into a
In our sample problem, we have these inputs: problem-solving sequence.
• purchase price1 and fuel efficiency1, the price and fuel efficiency (in mpg) of the first car
• purchase price2 and fuel efficiency2, the price and fuel efficiency of the second car

WORKED EXAMPLE 1.1


Writing an Algorithm for Tiling a Floor

Problem Statement Your task is to tile a rectangular bathroom floor with alternating Worked Examples apply
black and white tiles measuring 4 × 4 inches. The floor dimensions, measured in inches, are
multiples of 4. the steps in the How To to
Step 1 Determine the inputs and outputs.
a different example, showing
The inputs are the floor dimensions (length × width), how they can be used to
measured in inches. The output is a tiled floor.
Step 2 Break down the problem into smaller tasks.
plan, implement, and test
A natural subtask is to lay one row of tiles. If you can a solution to another
solve that task, then you can solve the problem by lay-
ing one row next to the other, starting from a wall, until programming problem.
you reach the opposite wall.
How do you lay a row? Start with a tile at one wall.
If it is Names
Table 3 Variable white, putin
a black
C++ one next to it. If it is black, put
a white one next to it. Keep going until you reach the
Variable Name wall. The row will contain width / 4 tiles.
opposite Comment © rban/iStockphoto.

Step 3 Describe each subtask in pseudocode.


can_volume1 Variable names consist of letters, numbers, and the underscore
character.
x In mathematics, you use short variable names such as x or y. This is
legal in C++, but not very common, because it can make programs
harder to understand (see Programming Tip 2.1). Example tables support beginners
!
Can_volume Caution: Variable names are case sensitive. This variable name is with multiple, concrete examples.
different from can_volume.
These tables point out common
6pack Error: Variable names cannot start with a number.

can volume Error: Variable names cannot contain spaces.


errors and present another quick
double Error: You cannot use a reserved word as a variable name. reference to the section’s topic.
ltr/fl.oz Error: You cannot use symbols such as . or /
Walkthrough xiii

Consider the function call illustrated in Figure 3:


double result1 = cube_volume(2); Progressive figures trace code
• The parameter variable side_length of the cube_volume function is created. ❶
• The parameter variable is initialized with the value of the argument that was
segments to help students visualize
passed in the call. In our case, side_length is set to 2. ❷ the program flow. Color is used
• The function computes the expression side_length * side_length * side_length,
which has the value 8. That value is stored in the variable volume. ❸ consistently to make variables and
• The function returns. All of its variables are removed. The return value is trans-
ferred to the caller, that is, the function calling the cube_volume function. ❹
other elements easily recognizable.

1 Function call result1 =


double result1 = cube_volume(2);

1 Initialize counter
side_length = for (counter = 1; counter <= 10; counter++)
{
cout << counter << endl;
2 Initializing function parameter variable counter = 1 }
result1 =
double result1 = cube_volume(2);
2 Check condition
side_length = for (counter = 1; counter <= 10; counter++)
2
{
cout << counter << endl;
counter = 1 }
3 About to return to the caller result1 =

3 Execute loop body


for (counter = 1; counter <= 10; counter++)
side_length = 2 {
double volume = side_length * side_length * side_length;
return volume; cout << counter << endl;
volume = 8 counter = 1 }

4 After function call result1 = 8 4 Update counter


for (counter = 1; counter <= 10; counter++)
double result1 = cube_volume(2); {
cout << counter << endl;
counter = 2 }
Figure 3 Parameter Passing

5 Check condition again


for (counter = 1; counter <= 10; counter++)
{
cout << counter << endl;
counter = 2 }

Figure 3 Execution of a for Loop


Optional engineering exercises
engage students with applications
from technical fields. Engineering P7.12 Write a program that simulates the control
software for a “people mover” system, a set of
driverless trains that move in two concentric
circular tracks. A set of switches allows trains
to switch tracks.
In your program, the outer and inner tracks
should each be divided into ten segments.
Each track segment can contain a train that
moves either clockwise or counterclockwise.
sec02/cube.cpp A train moves to an adjacent segment in its track or, if that segment is occupied, to
the adjacent segment in the other track.
1 #include <iostream>
2 Define a Segment structure. Each segment has a pointer to the next and previous
3 using namespace std; segments in its track, a pointer to the next and previous segments in the other track,
4
5 /**
6 Computes the volume of a cube.
7 @param side_length the side length of the cube
8 @return the volume
9 */
10 double cube_volume(double side_length)
11 {
12 double volume = side_length * side_length * side_length;
13 return volume;
14 }
15
16 int main()
Program listings are carefully
17
18
{
double result1 = cube_volume(2); designed for easy reading,
double result2 = cube_volume(10);
19
20 cout << "A cube with side length 2 has volume " << result1 << endl; going well beyond simple
21 cout << "A cube with side length 10 has volume " << result2 << endl;
22 color coding. Functions are set
23 return 0;
24 } off by a subtle outline.
Program Run
A cube with side length 2 has volume 8
A cube with side length 10 has volume 1000

EXAMPLE CODE See sec04 of your companion code for another implementation of the earthquake program that you
Additional example programs
saw in Section 3.3. Note that the get_description function has multiple return statements.
are provided with the companion
code for students to read, run,
and modify.
xiv Walkthrough

Common Errors describe the kinds Common Error 2.1


Using Undefined Variables
of errors that students often make, You must define a variable before you use it for the first time. For example, the following
with an explanation of why the errors sequence of statements would not be legal:
double can_volume = 12 * liter_per_ounce;
occur, and what to do about them. double liter_per_ounce = 0.0296;
In your program, the statements are compiled in order. When the compiler reaches the first
statement, it does not know that liter_per_ounce will be defined in the next line, and it reports
an error.

Programming Tip 3.6


Hand-Tracing
A very useful technique for understanding whether a program
works correctly is called hand-tracing. You simulate the pro-
gram’s activity on a sheet of paper. You can use this method with
pseudocode or C++ code.
Get an index card, a cocktail napkin, or whatever sheet of
Programming Tips explain paper is within reach. Make a column for each variable. Have the
program code ready. Use a marker, such as a paper clip, to mark
good programming practices, the current statement. In your mind, execute statements one at a
time. Every time the value of a variable changes, cross out the old
and encourage students to be value and write the new value below the old one.
© thomasd007/iStockphoto.

For example, let’s trace the tax program with the data from the
more productive with tips and program run in Section 3.4. In lines 13 and 14, tax1 and tax2 are
Hand-tracing helps you
understand whether a
initialized to 0. program works correctly.
techniques such as hand-tracing. 6 int main()
7 {
8 const double RATE1 = 0.10; marital
9 const double RATE2 = 0.25; tax1 tax2 income status
10 const double RATE1_SINGLE_LIMIT = 32000;
11 const double RATE1_MARRIED_LIMIT = 64000; 0 0
12
13 double tax1 = 0;
14 double tax2 = 0;
15

In lines 18 and 22, income and marital_status are initialized by input statements.
16 double income;
17 cout << "Please enter your income: ";
18 cin >> income; marital
19 tax1 tax2 income status
20 cout << "Please enter s for single, m for married: ";
21 string marital_status; 0 0 80000 m
22 cin >> marital_status;
23

Because marital_status is not "s", we move to the else


branch of the outer if statement (line 36).
24 if (marital_status == "s")
25 {
26 if (income <= RATE1_SINGLE_LIMIT)
27
28
{ Special Topic 6.5
tax1 = RATE1 * income;
29
30
}
else The Range-Based for Loop
31 {
32 C++ 11 introduces a convenient syntax for visiting all elements in a “range” or sequence of ele-
tax1 = RATE1 * RATE1_SINGLE_LIMIT;
ments. This loop displays all elements in a vector:
vector<int> values = {1, 4, 9, 16, 25, 36};
for (int v : values)
{
cout << v << " ";
}

Special Topics present optional In each iteration of the loop, v is set to an element of the vector. Note that you do not use an
index variable. The value of v is the element, not the index of the element.
topics and provide additional If you want to modify elements, declare the loop variable as a reference:
for (int& v : values)
explanation of others. {
v++;
}
This loop increments all elements of the vector.
You can use the reserved word auto, which was introduced in Special Topic 2.3, for the type
of the element variable:
for (auto v : values) { cout << v << " "; }
The range-based for loop also works for arrays:
int primes[] = { 2, 3, 5, 7, 11, 13 };
for (int p : primes)
{
cout << p << " ";
}
Computing & Society 7.1 Embedded Systems The range-based for loop is a convenient shortcut for visiting or updating all elements of a
vector or an array. This book doesn’t use it because one can achieve the same result by looping
An embedded sys- would feel comfortable upgrading the duced in large volumes. Thus, the pro-
tem is a computer software in their washing machines grammer of an embedded system has
over index values. But if you like the more concise form, and use C++ 11 or later, you should
system that controls a device. The or automobile engines. If you ever a much larger economic incentive to certainly consider using it.
device contains a processor and other handed in a programming assignment conserve resources than the desktop
EXAMPLE CODE See special_topic_5 of your companion code for a program that demonstrates the range-based
hardware and is controlled by a com- that you believed to be correct, only to software programmer. Unfortunately, for loop.
puter program. Unlike a personal have the instructor or grader find bugs trying to conserve resources usually
computer, which has been designed in it, then you know how hard it is to makes it harder to write programs that
to be flexible and run many different write software that can reliably do its work correctly.
computer programs, the hardware task for many years without a chance C and C++ are commonly used
and software of an embedded system of changing it. Quality standards are languages for developing embedded
are tailored to a specific device. Com- especially important in devices whose systems.
puter controlled devices are becom- failure would destroy property or
ing increasingly common, ranging endanger human life. Many personal
from washing machines to medical computer purchasers buy computers Computing & Society presents social
equipment, cell phones, automobile that are fast and have a lot of stor-
engines, and spacecraft.
Several challenges are specific to
age, because the investment is paid
back over time when many programs
and historical topics on computing—for
programming embedded systems.
Most importantly, a much higher stan-
are run on the same equipment. But
the hardware for an embedded device
interest and to fulfill the “historical and
dard of quality control applies. Ven-
dors are often unconcerned about
is not shared––it is dedicated to one
device. A separate processor, memory,
social context” requirements of the
bugs in personal computer software,
because they can always make you
and so on, are built for every copy of
the device. If it is possible to shave a ACM/IEEE curriculum guidelines.
install a patch or upgrade to the next few pennies off the manufacturing © Courtesy of Professor Prabal Dutta.
version. But in an embedded system, cost of every unit, the savings can add
that is not an option. Few consumers up quickly for devices that are pro- The Controller of an Embedded System
Walkthrough xv

Interactive activities in the E-Text


engage students in active reading as they…

Trace through a code segment

Build an example table

Explore common algorithms

Arrange code to fulfill a task

Complete a program and Create a memory diagram


get immediate feedback
Another Random Scribd Document
with Unrelated Content
she was absolutely calm and collected. She stepped into the waiting auto,
was driven to the American Embassy, placed the money in our vault, and
promptly returned to the school. Again Mrs. Morgenthau solemnly
ascended the stairs with the sisters. This time they took her to the gallery of
the Cathedral, which stood behind the convent, but could be entered
through it. One of the sisters lifted up a tile from a particular spot in the
floor, and again disclosed a heap of gold coins. This was secreted on Mrs.
Morgenthau’s clothes, and once more she walked past the gendarmes, out
into the rain, and was driven rapidly to the Embassy. In these two trips my
wife succeeded in getting the money of the sisters to a place where it would
be safe from the Turks.
Between Mrs. Morgenthau’s trips Bedri had arrived. He told me that
Talaat had himself given the order for closing all the institutions and that
they had intended to have the entire job finished before nine o’clock. I have
already said that the Turks have a sense of humour; but to this statement I
should add that it sometimes manifests itself in a perverted form. Bedri now
seemed to think that locking more than seventy Catholic sisters in two
rooms and turning two hundred young and carefully nurtured girls into the
streets of Constantinople was a great joke.
“We were going at it early in the morning and have it all over before you
heard anything about it,” he said with a laugh. “But you seem never to be
asleep.”
“You are very foolish to try to play such tricks on us,” I said. “Don’t you
know that I am going to write a book? If you go on behaving this way, I
shall put you in as the villain.”
This remark was an inspiration of the moment; it was then that it first
occurred to me that these experiences might prove sufficiently interesting
for publication. Bedri took the statement seriously, and it seemed to have a
sobering effect.
“Do you really intend to write a book?” he asked, almost anxiously.
“Why not?” I rejoined. “General Lew Wallace was minister here—didn’t
he write a book? ‘Sunset’ Cox was also minister here—didn’t he write one?
Why shouldn’t I? And you are such an important character that I shall have
to give you a part. Why do you go on acting in a way that will make me
describe you as a very bad man? These sisters here have always been your
friends. They have never done you anything but good; they have educated
many of your daughters; why do you treat them in this shameful fashion?”
This plea produced an effect; Bedri consented to postpone execution of
the order until we could get Talaat on the wire. In a few minutes I heard
Talaat laughing over the telephone.
“I tried to escape you,” he said, “but you have caught me again. Why
make such a row about this matter? Didn’t the French themselves expel all
their nuns and monks? Why shouldn’t we do it?”
After I had remonstrated over this indecent haste Talaat told Bedri to
suspend the order until we had had a chance to talk the matter over.
Naturally this greatly relieved Mère Elvira and the sisters. Just as we were
about to leave, Bedri suddenly had a new idea. There was one detail which
he had apparently forgotten.
“We’ll leave the Sion sisters alone for the present,” he said, “but we
must get their money.”
Reluctantly I acquiesced in his suggestion—knowing that all the
valuables were safely reposing in the American Embassy. So I had the
pleasure of standing by and watching Bedri and his associates search the
whole establishment. All they turned up was a small tin box containing a
few copper coins, a prize which was so trifling that the Turks disdained to
take it. They were much puzzled and disappointed, and from that day to this
they have never known what became of the money. If my Turkish friends
do me the honour of reading these pages, they will find that I have
explained here for the first time one of the many mysteries of those exciting
days.
As some of the windows of the convent opened on the court of the
Cathedral, which was Vatican property, we contended that the Turkish
Government could not seize it. Such of the sisters as were neutrals were
allowed to remain in possession of the part that faced the Vatican land,
while the rest of the building was turned into an Engineers’ School. We
arranged that the French nuns should have ten days to leave for their own
country; they all reached their destination safely, and most are at present
engaged in charities and war work in France.
My jocular statement that I intended to write a book deeply impressed
Bedri, and, in the next few weeks, he repeatedly referred to it. I kept
banteringly telling him that, unless his behaviour improved, I should be
forced to picture him as the villain. One day he asked me, in all seriousness,
whether he could not do something that would justify me in portraying him
in a more favourable light. This attitude gave me an opportunity I had been
seeking for some time. Constantinople had for many years been a centre for
the white-slave trade and a particularly vicious gang was then operating
under cover of a fake synagogue. A committee, organized to fight this crew,
had made me an honorary chairman. I told Bedri that he now had the
chance to secure a reputation; because of the war, his powers as Prefect of
Police had been greatly increased and a little vigorous action on his part
would permanently rid the city of this disgrace. The enthusiasm with which
Bedri adopted my suggestion and the thoroughness and ability with which
he did the work entitle him to the gratitude of all decent people. In a few
days every white-slave trader in Constantinople was scurrying for safety;
most were arrested, a few made their escape; such as were foreigners, after
serving terms in jail, were expelled from the country. Bedri furnished me
photographs of all the culprits and they are now on file in our State
Department. I was not writing a book at that time, but I felt obliged to
secure some public recognition for Bedri’s work. I therefore sent his
photograph, with a few words about his achievement, to the New York
Times, which published it in a Sunday edition. That a great American
newspaper had recognized him in this way delighted Bedri beyond words.
For months he carried in his pocket the page of the Times containing his
picture, showing it to all his friends. This event ended my troubles with the
Prefect of Police; for the rest of my stay we had very few serious clashes.
CHAPTER XIV

WANGENHEIM AND THE BETHLEHEM STEEL COMPANY—A HOLY WAR


THAT WAS MADE IN GERMANY

A
LL this time I was increasing my knowledge of the modern German
character, as illustrated in Wangenheim and his associates. In the early
days of the war, the Germans showed their most ingratiating side to
Americans; as time went on, however, and it became apparent that public
opinion in the United States almost unanimously supported the Allies, and
that the Washington Administration would not disregard the neutrality laws
in order to promote Germany’s interest, this friendly attitude changed and
became almost hostile.
The grievance to which the German Ambassador constantly returned
with tiresome iteration was the old familiar one—the sale of American
ammunition to the Allies. I hardly ever met him that he did not speak about
it. He was constantly asking me to write to President Wilson, urging him to
declare an embargo; of course, my contention that the commerce in
munitions was entirely legitimate made no impression. As the struggle at
the Dardanelles became more intense, Wangenheim’s insistence on the
subject of American ammunition grew. He asserted that most of the shells
used at the Dardanelles had been made in America and that the United
States was really waging war on Turkey.
One day, more angry than usual, he brought me a piece of shell. On it
clearly appeared the inscription “B.S.Co.”
“Look at that!” he said. “I suppose you know what ‘B.S.Co.’ means?
That is the Bethlehem Steel Company! This will make the Turks furious.
And remember that we are going to hold the United States responsible for
it. We are getting more and more proof, and we are going to hold you to
account for every death caused by American shells. If you would only write
home and make them stop selling ammunition to our enemies, the war
would be over very soon.”
I made the usual defense, and called Wangenheim’s attention to the fact
that Germany had sold munitions to Spain in the Spanish War, but all this
was to no purpose. All that Wangenheim saw was that American supplies
formed an asset to his enemy; the legalities of the situation did not interest
him. Of course I refused point blank to write to the President about the
matter.
A few days afterward an article appeared in the Ikdam discussing
Turkish and American relations. This contribution, for the greater part, was
extremely complimentary to America; its real purpose, however, was to
contrast the present with the past, and to point out that our action in
furnishing ammunition to Turkey’s enemies was hardly in accordance with
the historic friendship between the two countries. The whole thing was
evidently written merely to get before the Turkish people a statement almost
parenthetically included in the final paragraph. “According to the report of
correspondents at the Dardanelles it appears that most of the shells fired by
the British and French during the last bombardment were made in
America.” At this time the German Embassy controlled the Ikdam, and was
conducting it entirely in the interest of German propaganda. A statement of
this sort, instilled into the minds of impressionable and fanatical Turks,
might have the most deplorable consequences. I therefore took the matter
up immediately with the man whom I regarded as chiefly responsible for
the attack—the German Ambassador.
At first Wangenheim asserted his innocence; he was as bland as a child
in protesting his ignorance of the whole affair. I called his attention to the
fact that the statements in the Ikdam were almost identically the same as
those which he had made to me a few days before; that the language in
certain spots, indeed, was almost a repetition of his own conversation.
“Either you wrote that article yourself,” I said, “or you called in the
reporter and gave him the leading ideas.”
Wangenheim saw that there was no use in further denying the
authorship.
“Well,” he said, throwing back his head, “what are you going to do about
it?”
This Tweed-like attitude rather nettled me and I resented it on the spot.
“I’ll tell you what I am going to do about it,” I replied, “and you know
that I will be able to carry out my threats. Either you stop stirring up anti-
American feeling in Turkey or I shall start a campaign of anti-German
sentiment here.
“You know, Baron,” I added, “that you Germans are skating on very thin
ice in this country. You know that the Turks don’t love you any too well. In
fact, you know that Americans are more popular here than you are.
Supposing that I go out, tell the Turks how you are simply using them for
your own benefit—that you do not really regard them as your allies, but
merely as pawns in the game which you are playing. Now, in stirring up
anti-American feeling here you are touching my softest spot. You are
exposing our educational and religious institutions to the attacks of the
Turks. No one knows what they may do if they are persuaded that their
relatives are being shot down by American bullets. You stop this at once, or
in three weeks I will fill the whole of Turkey with animosity toward the
Germans. It will be a battle between us, and I am ready for it.”
Wangenheim’s attitude changed at once. He turned around, put his arm
on my shoulder, and assumed a most conciliatory, almost affectionate,
manner.
“Come, let us be friends,” he said. “I see that you are right about this. I
see that such attacks might injure your friends, the missionaries. I promise
you that they will be stopped.”
From that day the Turkish press never made the slightest unfriendly
allusion to the United States. The abruptness with which the attacks ceased
showed me that the Germans had evidently extended to Turkey one of the
most cherished expedients of the Fatherland—absolute government control
of the press. But when I think of the infamous plots which Wangenheim
was instigating at that moment, his objection to the use of a few American
shells by English battleships—if English battleships used any such shells,
which I seriously doubt—seems almost grotesque. In the early days
Wangenheim had explained to me one of Germany’s main purposes in
forcing Turkey into the conflict. He made this explanation quietly and
nonchalantly, as though it had been quite the most ordinary matter in the
world. Sitting in his office, puffing away at his big black German cigar, he
unfolded Germany’s scheme to arouse the whole fanatical Moslem world
against the Christians. Germany had planned a real “holy war” as one
means of destroying English and French influence in the world. “Turkey
herself is not the really important matter,” said Wangenheim. “Her army is a
small one, and we do not expect it to do very much. For the most part it will
act on the defensive. But the big thing is the Moslem world. If we can stir
the Mohammedans up against the English and Russians, we can force them
to make peace.”
What Wangenheim evidently meant by the “Big thing” became apparent
on November 13th, when the Sultan issued his declaration of war; this
declaration was really an appeal for a Jihad, or a “Holy War” against the
infidel. Soon afterward the Sheik-ul-Islam published his proclamation,
summoning the whole Moslem world to arise and massacre their Christian
oppressors. “Oh, Moslems!” concluded this document. “Ye who are smitten
with happiness and are on the verge of sacrificing your life and your goods
for the cause of right, and of braving perils, gather now around the Imperial
throne, obey the commands of the Almighty, who, in the Koran, promises
us bliss in this and in the next world; embrace ye the foot of the Caliph’s
throne and know ye that the state is at war with Russia, England, France,
and their Allies, and that these are the enemies of Islam. The Chief of the
believers, the Caliph, invites you all as Moslems to join in the Holy War!”
The religious leaders read this proclamation to their assembled
congregations in the mosques; all the newspapers printed it conspicuously;
it was spread broadcast in all the countries which had large Mohammedan
populations—India, China, Persia, Egypt, Algiers, Tripoli, Morocco, and
the like; in all these places it was read to the assembled multitudes and the
populace was exhorted to obey the mandate. The Ikdam, the Turkish
newspaper which had passed into German ownership, was constantly
inciting the masses. “The deeds of our enemies,” wrote this Turco-German
editor, “have brought down the wrath of God. A gleam of hope has
appeared. All Mohammedans, young and old, men, women, and children,
must fulfil their duty so that the gleam may not fade away, but give light to
us forever. How many great things can be accomplished by the arms of
vigorous men, by the aid of others, of women and children!... The time for
action has come. We shall all have to fight with all our strength, with all our
soul, with teeth and nails, with all the sinews of our bodies and of our
spirits. If we do it, the deliverance of the subjected Mohammedan kingdoms
is assured. Then, if God so wills, we shall march unashamed by the side of
our friends who send their greetings to the Crescent. Allah is our aid and the
Prophet is our support.”
The Sultan’s proclamation was an official public document, and dealt
with the proposed Holy War only in a general way, but about this same time
a secret pamphlet appeared which gave instructions to the faithful in more
specific terms. This paper was not read in the mosques; it was distributed
stealthily in all Mohammedan countries—India, Egypt, Morocco, Syria, and
many others; and it was significantly printed in Arabic, the language of the
Koran. It was a lengthy document—the English translation contains 10,000
words—full of quotations from the Koran, and its style was frenzied in its
appeal to racial and religious hatred. It described a detailed plan of
operations for the assassination and extermination of all Christians—except
those of German nationality. A few extracts will fairly portray its spirit: “O
people of the faith and O beloved Moslems, consider, even though but for a
brief moment, the present condition of the Islamic world. For if you
consider this but for a little you will weep long. You will behold a
bewildering state of affairs which will cause the tear to fall and the fire of
grief to blaze. You see the great country of India, which contains hundreds
of millions of Moslems, fallen, because of religious divisions and
weaknesses, into the grasp of the enemies of God, the infidel English. You
see forty millions of Moslems in Java shackled by the chains of captivity
and of affliction under the rule of the Dutch, although these infidels are
much fewer in number than the faithful and do not enjoy a much higher
civilization. You see Egypt, Morocco, Tunis, Algeria, and the Sudan
suffering the extremes of pain and groaning in the grasp of the enemies of
God and his apostle. You see the vast country of Siberia and Turkestan and
Khiva and Bokhara and the Caucasus and the Crimea and Kazan and
Ezferhan and Kosahastan, whose Moslem peoples believe in the unity of
God, ground under the feet of their oppressors, who are the enemies already
of our religion. You behold Persia being prepared for partition and you see
the city of the Caliphate, which for ages has unceasingly fought breast to
breast with the enemies of our religion, now become the target for
oppression and violence. Thus wherever you look you see that the enemies
of the true religion, particularly the English, the Russian, and the French,
have oppressed Islam and invaded its rights in every possible way. We
cannot enumerate the insults we have received at the hands of these nations
who desire totally to destroy Islam and drive all Mohammedans off the face
of the earth. This tyranny has passed all endurable limits; the cup of our
oppression is full to overflowing.... In brief, the Moslems work and the
infidels eat; the Moslems are hungry and suffer and the infidels gorge
themselves and live in luxury. The world of Islam sinks down and goes
backward, and the Christian world goes forward and is more and more
exalted. The Moslems are enslaved and the infidels are the great rulers. This
is all because the Moslems have abandoned the plan set forth in the Koran
and ignored the Holy War which it commands.... But the time has now
come for the Holy War, and by this the land of Islam shall be forever freed
from the power of the infidels who oppress it. This holy war has now
become a sacred duty. Know ye that the blood of infidels in the Islamic
lands may be shed with impunity—except those to whom the Moslem
power has promised security and who are allied with it. [Herein we find that
Germans and Austrians are excepted from massacre.] The killing of infidels
who rule over Islam has become a sacred duty, whether you do it secretly or
openly, as the Koran has decreed: ‘Take them and kill them whenever you
find them. Behold we have delivered them unto your hands and given you
supreme power over them.’ He who kills even one unbeliever of those who
rule over us, whether he does it secretly or openly, shall be rewarded by
God. And let every Moslem, in whatever part of the world he may be, swear
a solemn oath to kill at least three or four of the infidels who rule over him,
for they are the enemies of God and of the faith. Let every Moslem know
that his reward for doing so shall be doubled by the God who created
heaven and earth. A Moslem who does this shall be saved from the terrors
of the day of Judgment, of the resurrection of the dead. Who is the man who
can refuse such a recompense for such a small deed?... Yet the time has
come that we should rise up as the rising of one man, in one hand a sword,
in the other a gun, in his pocket balls of fire and death-dealing missiles, and
in his heart the light of the faith, and that we should lift up our voices,
saying—India for the Indian Moslems, Java for the Javanese Moslems,
Algeria for the Algerian Moslems, Morocco for the Moroccan Moslems,
Tunis for the Tunisan Moslems, Egypt for the Egyptian Moslems, Iran for
the Iranian Moslems, Turan for the Turanian Moslems, Bokhara for the
Bokharan Moslems, Caucasus for the Caucasian Moslems, and the Ottoman
Empire for the Ottoman Turks and Arabs.”
Specific instructions for carrying out this holy purpose follow. There
shall be a “heart war”—every follower of the Prophet, that is, shall
constantly nourish in his spirit a hatred of the infidel; a “speech war”—with
tongue and pen every Moslem shall spread this same hatred wherever
Mohammedans live; and a war of deed—fighting and killing the infidel
wherever he shows his head. This latter conflict, says the pamphlet, is the
“true war.” There is to be a “little holy war” and a “great holy war”; the first
describes the battle which every Mohammedan is to wage in his community
against his Christian neighbours, and the second is the great world struggle
which united Islam, in India, Arabia, Turkey, Africa, and other countries is
to wage against the infidel oppressors. “The Holy War,” says the pamphlet,
“will be of three forms. First, the individual war, which consists of the
individual personal deed. This may be carried on with cutting, killing
instruments, like the holy war which one of the faithful made against Peter
Galy, the infidel English governor, like the slaying of the English chief of
police in India, and like the killing of one of the officials arriving in Mecca
by Abi Busir (may God be pleased with him).” The document gives several
other instances of assassination which the faithful are enjoined to imitate.
Second, the believers are told to organize “bands,” and to go forth and slay
Christians. The most useful are those organized and operating in secret. “It
is hoped that the Islamic world of to-day will profit very greatly from such
secret bands.” The third method is by “organized campaigns,” that is, by
trained armies.
In all parts of this incentive to murder and assassination there are
indications that a German hand has exercised an editorial supervision. Only
those infidels are to be slain, “who rule over us”—that is, those who have
Mohammedan subjects. As Germany has no such subjects, this saving
clause was expected to protect Germans from assault. The Germans, with
their usual interest in their own well-being and their usual disregard of their
ally, evidently overlooked the fact that Austria had many Mohammedan
subjects in Bosnia and Herzegovina. Moslems are instructed that they
should form armies, “even though it may be necessary to introduce some
foreign elements”—that is, bring in German instructors and German
officers. “You must remember”—this is evidently intended as a blanket
protection to Germans everywhere—”that it is absolutely unlawful to
oppose any of the peoples of other religions between whom and the
Moslems there is a covenant or of those who have not manifested hostility
to the seat of the Caliphate or those who have entered under the protection
of the Moslems.”
Even though I had not had Wangenheim’s personal statement that the
Germans intended to arouse the Mohammedans everywhere against
England, France, and Russia, these interpolations would clearly enough
have indicated the real inspiration of this amazing document. At the time
Wangenheim discussed the matter with me, his chief idea seemed to be that
a “holy war” of this sort would be the quickest means of forcing England to
make peace. According to this point of view, it was really a great peace
offensive. At that time Wangenheim reflected the conviction, which was
prevalent in all official circles, that Germany had made a mistake in
bringing England into the conflict, and it was evidently his idea now that if
back fires could be started against England in India, Egypt, the Sudan, and
other places, the British Empire would withdraw. Even if British
Mohammedans refused to rise, Wangenheim believed that the mere threat of
such an uprising would induce England to abandon Belgium and France to
their fate. The danger of spreading such incendiary literature among a
wildly fanatical people is apparent. I was not the only neutral diplomat who
feared the most serious consequences. M. Tocheff, the Bulgarian Minister,
one of the ablest members of the diplomatic corps, was much disturbed. At
that time Bulgaria was neutral, and M. Tocheff used to tell me that his
country hoped to maintain this neutrality. Each side, he said, expected that
Bulgaria would become its ally, and it was Bulgaria’s policy to keep each
side in this expectant frame of mind. Should Germany succeed in starting a
“Holy War” and should massacres result, Bulgaria, added M. Tocheff,
would certainly join forces with the Entente.
We arranged that he should call upon Wangenheim and repeat this
statement, and that I should bring similar pressure to bear upon Enver. From
the first, however, the Holy War proved a failure. The Mohammedans of
such countries as India, Egypt, Algiers, and Morocco knew that they were
getting far better treatment than they could obtain under any other
conceivable conditions. Moreover, the simple-minded Mohammedans could
not understand why they should prosecute a holy war against Christians and
at the same time have Christian nations, such as Germany and Austria, as
their partners. This association made the whole proposition ridiculous. The
Koran, it is true, commands the slaughter of Christians, but that sacred
volume makes no exception in favour of the Germans and, in the mind of
the fanatical Mohammedan, a German rayah is as much Christian dirt as an
Englishman or a Frenchman, and his massacre is just as meritorious an act.
The fine distinctions necessitated by European diplomacy he understands
about as completely as he understands the law of gravitation or the nebular
hypothesis. The German failure to take this into account is only another
evidence of the fundamental German clumsiness and real ignorance of
racial psychology. The only tangible fact that stands out clearly is the
Kaiser’s desire to let loose 300,000,000 Mohammedans in a gigantic St.
Bartholomew massacre of Christians.
Was there then no “holy war” at all? Did Wangenheim’s “Big Thing”
really fail? Whenever I think of this burlesque Jihad a particular scene in
the American Embassy comes to my mind. On one side of the table sits
Enver, most peacefully sipping tea and eating cakes, and on the other side is
myself, engaged in the same unwarlike occupation. It is November 14th, the
day after the Sultan has declared his holy war; there have been meetings at
the mosques and other places, at which the declaration has been read and
fiery speeches made. Enver now assures me that absolutely no harm will
come to Americans; in fact, that there will be no massacres anyway. While
he is talking, one of my secretaries comes in and tells me that a little mob is
making demonstrations against certain foreign establishments. It has
assailed an Austrian shop which has unwisely kept up its sign saying that it
has “English clothes” for sale. I ask Enver what this means; he answers that
it is all a mistake; there is no intention of attacking anybody. A little while
after he leaves I am informed that the mob has attacked the Bon Marché, a
French dry-goods store, and is heading directly for the British Embassy. I at
once call Enver on the telephone; it is all right, he says, nothing will happen
to the embassy. A minute or two after, the mob immediately wheels about
and starts for Tokatlian’s, the most important restaurant in Constantinople.
The fact that this is conducted by an Armenian makes it fair game. Six men
who have poles, with hooks at the end, break all the mirrors and windows,
others take the marble tops of the tables and smash them to bits. In a few
minutes the place has been completely gutted.
This demonstration comprised the “Holy War,” so far as Constantinople
understood it. Such was the inglorious end of Germany’s attempt to arouse
300,000,000 Mohammedans against the Christian world! Only one definite
result did the Kaiser accomplish by spreading this inciting literature. It
aroused in the Mohammedan soul all that intense animosity toward the
Christian which is the fundamental fact in his strange emotional nature, and
thus started passions aflame that afterward spent themselves in the
massacres of the Armenians and other subject peoples.
CHAPTER XV

DJEMAL, A TROUBLESOME MARK ANTONY—THE FIRST GERMAN


ATTEMPT TO GET A GERMAN PEACE

I
N early November, 1914, the railroad station at Haidar Pasha was the
scene of a great demonstration. Djemal, the Minister of Marine, one of
the three men who were then most powerful in the Turkish Empire, was
leaving to take command of the Fourth Turkish Army, which had its
headquarters in Syria. All the members of the Cabinet and other influential
people in Constantinople assembled to give this departing satrap an
enthusiastic farewell. They hailed him as the “Saviour of Egypt,” and
Djemal himself, just before his train started, made this public declaration:
“I shall not return to Constantinople until I have conquered Egypt!”
The whole performance seemed to me to be somewhat bombastic.
Inevitably it called to mind the third member of another bloody triumvirate
who, nearly two thousand years before, had left his native land to become
the supreme dictator of the East. And Djemal had many characteristics in
common with Mark Antony. Like his Roman predecessor, his private life
was profligate; like Antony, he was an insatiate gambler, spending much of
his leisure over the card table at the Cercle d’Orient. Another trait which he
had in common with the great Roman orator was his enormous vanity. The
Turkish world seemed to be disintegrating in Djemal’s time, just as the
Roman Republic was dissolving in the days of Antony; Djemal believed
that he might himself become the heir of one or more of its provinces and
possibly establish a dynasty. He expected that the military expedition on
which he was now starting would make him not only the conqueror of
Turkey’s fairest province, but also one of the powerful figures of the world.
Afterward, in Syria, he ruled as independently as a medieval robber baron
—whom in other details he resembled; he became a kind of sub-sultan,
holding his own court, having his own selamlik, issuing his own orders,
dispensing freely his own kind of justice, and often disregarding the
authorities at Constantinople.
The applause with which Djemal’s associates were speeding his
departure was not entirely disinterested. The fact was that most of them
were exceedingly glad to see him go. He had been a thorn in the side of
Talaat and Enver for some time, and they were perfectly content that he
should exercise his imperious and stubborn nature against the Syrians,
Armenians, and other non-Moslem elements in the Mediterranean
provinces. Djemal was not a popular man in Constantinople. The other
members of the triumvirate, in addition to their less desirable qualities, had
certain attractive traits—Talaat, his rough virility and spontaneous good
nature, Enver, his courage and personal graciousness—but there was little
about Djemal that was pleasing. An American physician who had
specialized in the study of physiognomy had found Djemal a fascinating
subject. He told me that he had never seen a face that so combined ferocity
with great power and penetration. Enver, as his history showed, could be
cruel and bloodthirsty, but he hid his more insidious qualities under a face
that was bland, unruffled, and even agreeable. Djemal, however, did not
disguise his tendencies, for his face clearly pictured the inner soul. His eyes
were black and piercing; their sharpness, the rapidity and keenness with
which they darted from one object to another, taking in apparently
everything with a few lightning-like glances, signalized cunning,
remorselessness, and selfishness to an extreme degree. Even his laugh,
which disclosed all his white teeth, was unpleasant and animal-like. His
black hair and black beard, contrasting with his pale face, only heightened
this impression. At first Djemal’s figure seemed somewhat insignificant—
he was undersized, almost stumpy, and somewhat stoop-shouldered; as soon
as he began to move, however, it was evident that his body was full of
energy. Whenever he shook your hand, gripping you with a vise-like grasp
and looking at you with those roving, penetrating eyes, the man’s personal
force became impressive.
Yet, after a momentary meeting, I was not surprised to hear that Djemal
was a man with whom assassination and judicial murder were all part of the
day’s work. Like all the Young Turks his origin had been extremely humble.
He had joined the Committee of Union and Progress in the early days, and
his personal power, as well as his relentlessness, had rapidly made him one
of the leaders. After the murder of Nazim, Djemal had become Military
Governor of Constantinople, his chief duty in this post being to remove
from the scene the opponents of the ruling powers. This congenial task he
performed with great skill, and the reign of terror that resulted was largely
Djemal’s handiwork. Subsequently Djemal became a member of the
Cabinet, but he could not work harmoniously with his associates; he was
always a troublesome partner. In the days preceding the break with the
Entente he was popularly regarded as a Francophile. Whatever feeling
Djemal may have entertained toward the Entente, he made little attempt to
conceal his detestation of the Germans. It is said that he would swear at
them in their presence—in Turkish, of course; and he was one of the few
important Turkish officials who never came under their influence. The fact
was that Djemal represented that tendency which was rapidly gaining the
ascendancy in Turkish policy—Pan-Turkism. He despised the subject
peoples of the Ottoman country—Arabs, Greeks, Armenians, Circassians,
Jews; it was his determination to Turkify the whole empire. His personal
ambition brought him into frequent conflict with Enver and Talaat, who told
me many times that they could not control him. It was for this reason that,
as I have said, they were glad to see him go—not that they really expected
him to capture the Suez Canal and drive the English out of Egypt.
Incidentally, this appointment fairly indicated the incongruous organization
that then existed in Turkey. As Minister of Marine, Djemal’s real place was
at the Navy Department; instead of working in his official field the head of
the navy was sent to lead an army over the burning sands of Syria and
Sinai.
Yet Djemal’s expedition represented Turkey’s most spectacular attempt
to assert its military power against the Allies. As Djemal moved out of the
station, the whole Turkish populace felt that an historic moment had
arrived. Turkey in less than a century had lost the greater part of her
dominions, and nothing had more pained the national pride than the English
occupation of Egypt. All during this occupation, Turkish suzerainty had
been recognized; as soon as Turkey declared war on Great Britain, however,
the British had ended this fiction and had formally taken over this great
province. Djemal’s expedition was Turkey’s reply to this act of England.
The real purpose of the war, the Turkish people had been told, was to
restore the vanishing empire of the Osmans, and to this great undertaking
the recovery of Egypt was merely the first step. The Turks also knew that,
under English administration, Egypt had become a prosperous country and
that it would, therefore, yield great treasure to the conqueror. It is no
wonder that the huzzahs of the Turkish people followed the departing
Djemal.
About the same time Enver left to take command of Turkey’s other great
military enterprise—the attack on Russia through the Caucasus. Here also
were Turkish provinces to be “redeemed.” After the war of 1878, Turkey
had been compelled to cede to Russia certain rich territories between the
Caspian and the Black seas, inhabited chiefly by Armenians, and it was this
country which Enver now proposed to reconquer. But Enver had no ovation
on his leaving. He went away quietly and unobserved. With the departure of
these two men the war was now fairly on.
Despite these martial enterprises, other than warlike preparations were
now under way in Constantinople. At that time—in the latter part of 1914—
its external characteristics suggested nothing but war, yet now it suddenly
became the great headquarters of peace. The English fleet was constantly
threatening the Dardanelles and every day Turkish troops were passing
through the streets. Yet these activities did not chiefly engage the attention
of the German Embassy. Wangenheim was thinking of one thing and of one
thing only; this fire-eating German had suddenly become a man of peace.
For he now learned that the greatest service which a German ambassador
could render his emperor would be to end the war on terms that would save
Germany from exhaustion and even from ruin; to obtain a settlement that
would reinstate his fatherland in the society of nations.
In November, Wangenheim began discussing this subject. It was part of
Germany’s system, he told me, not only to be completely prepared for war
but also for peace. “A wise general, when he begins his campaign, always
has at hand his plans for a retreat, in case he is defeated,” said the German
Ambassador. “This principle applies just the same to a nation beginning
war. There is only one certainty about war—and that is that it must end
some time. So, when we plan war, we must consider also a campaign for
peace.”
But Wangenheim was interested then in something more tangible than
this philosophic principle. Germany had immediate reasons for desiring the
end of hostilities, and Wangenheim discussed them frankly and cynically.
He said that Germany had prepared for only a short war, because she had
expected to crush France and Russia in two brief campaigns, lasting not
longer than six months. Clearly this plan had failed and there was little
likelihood that Germany would win the war; Wangenheim told me this in so
many words. Germany, he added, would make a great mistake if she
persisted in fighting to the point of
THE BRITISH EMBASSY
This establishment and many others came under Mr. Morgenthau’s
protection when Turkey entered the war. At one time the American
Ambassador represented ten nations at the Sublime Porte.

ROBERT COLLEGE AT CONSTANTINOPLE


Founded by Americans more than fifty years ago. Turkey’s best
educational institution and the place where many of the intellectual
leaders of the Balkans have received their education.

exhaustion, for such a fight would mean the permanent loss of her colonies,
her mercantile marine, and her whole economic and commercial status. “If
we don’t get Paris in thirty days, we are beaten,” Wangenheim had told me
in August, and though his attitude changed somewhat after the battle of the
Marne, he made no attempt to conceal the fact that the great rush campaign
had collapsed, that all the Germans could now look forward to was a
tedious, exhausting war, and that all they could obtain from the existing
situation would be a drawn battle. “We have made a mistake this time,”
Wangenheim said, “in not laying in supplies for a protracted struggle; it was
an error, however, that we shall not repeat; next time we shall store up
enough copper and cotton to last for five years.”
Wangenheim had another reason for wishing an immediate peace, and it
was a reason which shed much light upon the shamelessness of German
diplomacy. The preparation which Turkey was making for the conquest of
Egypt caused this German ambassador much annoyance and anxiety. The
interest and energy which the Turks had manifested in this enterprise were
particularly giving him concern. Naturally I thought at first that
Wangenheim was worried that Turkey would lose; yet he confided to me
that his real fear was that his ally might succeed. A victorious Turkish
campaign in Egypt, Wangenheim explained, might seriously interfere with
Germany’s plans. Should Turkey conquer Egypt, naturally Turkey would
insist at the peace table on retaining this great province and would expect
Germany to support her in this claim. But Germany had no intention then of
promoting the reëstablishment of the Turkish Empire. At that time she
hoped to reach an understanding with England, the basis of which was to be
something in the nature of a division of interests in the East. Germany
desired above all to obtain Mesopotamia as an indispensable part of her
Hamburg-Bagdad scheme. In return for this, she was prepared to give her
endorsement to England’s annexation of Egypt. Thus it was Germany’s plan
at that time that she and England should divide Turkey’s two fairest
dominions. This was one of the proposals which Germany intended to bring
forth in the peace conference which Wangenheim was now scheming for,
and clearly Turkey’s conquest of Egypt would have presented complications
in the way of carrying out this plan. On the morality of Germany’s attitude
to her ally, Turkey, it is hardly necessary to comment. The whole thing was
all of a piece with Germany’s policy of “realism” in foreign relations.
Nearly all German classes, in the latter part of 1914 and the early part of
1915, were anxiously looking for peace and they turned to Constantinople
as the most promising spot where peace negotiations might most favourably
be started. The Germans took it for granted that President Wilson would be
the peacemaker; indeed, they never for a moment thought of any one else in
this capacity. The only point that remained for consideration was the best
way to approach the President. Such negotiations would most likely be
conducted through one of the American ambassadors in Europe. Obviously,
Germany had no means of access to the American ambassadors in the great
enemy capitals, and other circumstances induced the German statesmen to
turn to the American Ambassador in Turkey.
At this time a German diplomat appeared in Constantinople who has
figured much in recent history—Dr. Richard von Kühlmann, afterward
Minister for Foreign Affairs. In the last five years Dr. Von Kühlmann has
seemed to appear in that particular part of the world where important
confidential diplomatic negotiations are being conducted by the German
Empire. Prince Lichnowsky has described his activities in London in 1913
and 1914, and he figured even more conspicuously in the infamous peace
treaty of Brest-Litovsk. Soon after the war started Dr. Von Kühlmann came
to Constantinople as Conseiller of the German Embassy, succeeding Von
Mutius, who had been called to the colours. For one reason his appointment
was appropriate, for Kühlmann had been born in Constantinople, and had
spent his early life there, his father having been president of the Anatolian
railway. He therefore understood the Turks as only one can who has lived
with them for many years. Personally, he proved to be an interesting
addition to the diplomatic colony. He impressed me as not a particularly
aggressive, but a very entertaining, man; he apparently wished to become
friendly with the American Embassy and he possessed a certain attraction
for us all as he had just come from the trenches and gave us many vivid
pictures of life at the front. At that time we were all keenly interested in
modern warfare, and Kühlmann’s details of trench fighting held us
spellbound many an afternoon and evening. His other favourite topic of
conversation was Welt-Politik, and on all foreign matters he struck me as
remarkably well informed. At that time we did not regard Von Kühlmann as

You might also like