100% found this document useful (8 votes)
32 views

Where Can Buy C++ Programming D. S Ebook With Cheap Price

Programming

Uploaded by

nkwojisimoni
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 (8 votes)
32 views

Where Can Buy C++ Programming D. S Ebook With Cheap Price

Programming

Uploaded by

nkwojisimoni
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/ 62

Download the full version of the textbook now at textbookfull.

com

C++ Programming D. S

https://textbookfull.com/product/c-programming-
d-s/

Explore and download more textbook at https://textbookfull.com


Recommended digital products (PDF, EPUB, MOBI) that
you can download immediately if you are interested.

C++ Programming D. S

https://textbookfull.com/product/c-programming-d-s/

textbookfull.com

Handbook of Macroeconomics, Volume 2A-2B SET 1st Edition


John B. Taylor

https://textbookfull.com/product/handbook-of-macroeconomics-
volume-2a-2b-set-1st-edition-john-b-taylor/

textbookfull.com

C Programming From Problem Analysis to Program Design D.


S. Malik

https://textbookfull.com/product/c-programming-from-problem-analysis-
to-program-design-d-s-malik/

textbookfull.com

America's Wars on Democracy in Rwanda and the DR Congo


Justin Podur

https://textbookfull.com/product/americas-wars-on-democracy-in-rwanda-
and-the-dr-congo-justin-podur/

textbookfull.com
DevOps for Digital Leaders Reignite Business with a Modern
DevOps Enabled Software Factory 1st Edition Aruna
Ravichandran
https://textbookfull.com/product/devops-for-digital-leaders-reignite-
business-with-a-modern-devops-enabled-software-factory-1st-edition-
aruna-ravichandran/
textbookfull.com

Human Resource Information Systems: Basics, Applications,


and Future Directions 4th Edition Michael J. Kavanagh
(Editor)
https://textbookfull.com/product/human-resource-information-systems-
basics-applications-and-future-directions-4th-edition-michael-j-
kavanagh-editor/
textbookfull.com

Spatial Planning in Service Delivery: Towards Distributive


Justice in South Africa Hangwelani Hope Magidimisha

https://textbookfull.com/product/spatial-planning-in-service-delivery-
towards-distributive-justice-in-south-africa-hangwelani-hope-
magidimisha/
textbookfull.com

Brain Informatics International Conference BI 2018


Arlington TX USA December 7 9 2018 Proceedings Shouyi Wang

https://textbookfull.com/product/brain-informatics-international-
conference-bi-2018-arlington-tx-usa-december-7-9-2018-proceedings-
shouyi-wang/
textbookfull.com

Beginning Office 365 Collaboration Apps: Working in the


Microsoft Cloud Ralph Mercurio

https://textbookfull.com/product/beginning-office-365-collaboration-
apps-working-in-the-microsoft-cloud-ralph-mercurio/

textbookfull.com
PRINCIPLES OF MACROECONOMICS 5E Ben Bernanke Et Al

https://textbookfull.com/product/principles-of-macroeconomics-5e-ben-
bernanke-et-al/

textbookfull.com
Eighth Edition

C++ PROGRAMMING
Program Design Including
Data Structures

D.S. Malik
Copyright 2018 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part. WCN 02-200-202
Buy. Rent. Access.

Access student data files and other study


tools on cengagebrain.com.

For detailed instructions visit


http://solutions.cengage.com/ctdownloads/

Store your Data Files on a USB drive for maximum efficiency in


organizing and working with the files.

Macintosh users should use a program to expand WinZip or PKZip archives.


Ask your instructor or lab coordinator for assistance.

Copyright 2018 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part. WCN 02-200-202
C++ Programming:
Program Design Including Data Structures

Eighth Edition

D.S. Malik

Australia • Brazil • Japan • Korea • Mexico • Singapore • Spain • United Kingdom • United States
Copyright 2018 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part. WCN 02-200-202
C++ Programming: Program Design Including © 2018, 2015, 2013 Cengage Learning® 8
Data Structures, Eighth Edition ALL RIGHTS RESERVED. No part of this work covered by the c­ opyright
D.S. Malik herein may be reproduced or distributed in any form or by any means,
­except as permitted by U.S. copyright law, without the prior written
Senior Product Director: Kathleen McMahon ­permission of the copyright owner.
Product Team Leader: Kristin McNary
Associate Product Manager: Kate Mason For product information and technology assistance, contact us at
Associate Content Development ­Manager: Cengage Learning Customer & Sales Support, 1-800-354-9706
Alyssa Pratt
For permission to use material from this text or product,
Production Director: Patty Stephan
submit all requests online at www.cengage.com/permissions.
Senior Content Project Manager: Jennifer Further permissions questions can be emailed to
Feltri-George [email protected].
Manufacturing Planner: Julio Esperas
Art Director/Cover Design: Diana Graham Library of Congress Control Number: 2017931947
Production Service/Composition:
SPi Global
ISBN: 978-1-337-11756-2
Cover Photo: Cebas/Shutterstock.com
Cengage Learning
20 Channel Center Street
Boston, MA 02210
USA

Unless otherwise noted all items © Cengage Learning.


Unless otherwise noted, all screenshots are ©Microsoft.

Cengage Learning is a leading provider of customized learning s­ olutions


with employees residing in nearly 40 different countries and sales in more
than 125 countries around the world. Find your local representative at
www.cengage.com.

Cengage Learning products are represented in Canada by Nelson


Education, Ltd.

To learn more about Cengage Learning Solutions, visit


www.cengage.com.

Purchase any of our products at your local college store or at our preferred
online store www.cengagebrain.com.
Any fictional data related to persons or companies or URLs used throughout
this book is intended for instructional purposes only. At the time this book
was printed, any such data was fictional and not belonging to any real
persons or companies.
The programs in this book are for instructional purposes only. They have
been tested with care, but are not guaranteed for any particular intent
beyond educational purposes. The author and the publisher do not offer any
warranties or representations, nor do they accept any liabilities with respect
to the programs.

Printed in the United States of America


Print Number: 01 Print Year: 2017

Copyright 2018 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part. WCN 02-200-202
TO
My Parents

Copyright 2018 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part. WCN 02-200-202
Copyright 2018 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part. WCN 02-200-202
Brief Contents

© HunThomas/Shutterstock.com

PREFACExxxiii

1. An Overview of Computers and Programming Languages 1

2. Basic Elements of C11 27

3. Input/Output 123

4. Control Structures I (Selection) 187

5. Control Structures II (Repetition) 265

6. User-Defined Functions 347

7. User-Defined Simple Data Types, Namespaces,


and the string Type 467

8. Arrays and Strings 521

9. Records (structs)611

10. Classes and Data Abstraction 651

11. Inheritance and Composition 743

12. Pointers, Classes, Virtual Functions, Abstract Classes, and Lists 817

13. Overloading and Templates 907

14. Exception Handling 1007

15. Recursion 1051

16. Linked Lists 1085

17. Stacks and Queues 1179

18. Searching and Sorting Algorithms 1279


Copyright 2018 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part. WCN 02-200-202
vi | C++ Programming: Program Design Including Data Structures, Eighth Edition

19. Binary Trees 1361

20. Graphs 1417

21. Standard Template Library (STL) 1455

APPENDIX A   Reserved Words 1575

APPENDIX B   Operator Precedence 1577

APPENDIX C   Character Sets 1579

APPENDIX D   Operator Overloading 1583

APPENDIX E    Additional C11 Topics ONLINE

APPENDIX F    Header Files 1585

APPENDIX G    Memory Size on a System 1595

APPENDIX H   References 1597

APPENDIX I      Answers to Odd-Numbered Exercises 1599

INDEX 1647

Copyright 2018 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part. WCN 02-200-202
Table of Contents

© HunThomas/Shutterstock.com

Prefacexxxiii

AN OVERVIEW OF COMPUTERS
1 AND PROGRAMMING LANGUAGES 1
Introduction2

A Brief Overview of the History of Computers 2

Elements of a Computer System 4


Hardware4
Central Processing Unit and Main Memory 4
Input/Output Devices 5
Software5

The Language of a Computer 6

The Evolution of Programming Languages 7

Processing a C11 Program 9

Programming with the Problem


Analysis–Coding–Execution Cycle11

Programming Methodologies 20
Structured Programming 20
Object-Oriented Programming 20
ANSI/ISO Standard C11 22

Quick Review 22

Exercises 24
Copyright 2018 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part. WCN 02-200-202
viii | C++ Programming: Program Design Including Data Structures, Eighth Edition

BASIC ELEMENTS OF C11 27


2
A Quick Look at a C11 Program 28

The Basics of a C11 Program 33


Comments34
Special Symbols 35
Reserved Words (Keywords) 35
Identifiers36
Whitespaces37

Data Types 37
Simple Data Types 38
Floating-Point Data Types 40

Data Types, Variables, and Assignment Statements 42

Arithmetic Operators, Operator Precedence, and Expressions 43


Order of Precedence 45
Expressions47
Mixed Expressions 48

Type Conversion (Casting) 50

string Type 53

Variables, Assignment Statements, and Input Statements 54


Allocating Memory with Constants and Variables 54
Putting Data into Variables 57
Assignment Statement 57
Saving and Using the Value of an Expression 60
Declaring and Initializing Variables 61

Copyright 2018 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part. WCN 02-200-202
Visit https://textbookfull.com
now to explore a rich
collection of eBooks, textbook
and enjoy exciting offers!
Table of Contents | ix

Input (Read) Statement 62


Variable Initialization 65

Increment and Decrement Operators 69

Output71

Preprocessor Directives 78
namespace and Using cin and cout in a Program 79
Using the string Data Type in a Program 80

Creating a C11 Program 80

Debugging: Understanding and Fixing Syntax Errors 84

Program Style and Form 87


Syntax87
Use of Blanks 88
Use of Semicolons, Brackets, and Commas 88
Semantics88
Naming Identifiers 89
Prompt Lines 89
Documentation90
Form and Style 90

More on Assignment Statements 92

Programming Example: Convert Length 94

Programming Example: Make Change 98

Quick Review 102

Exercises104

Programming Exercises 114

Copyright 2018 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part. WCN 02-200-202
x | C++ Programming: Program Design Including Data Structures, Eighth Edition

INPUT/OUTPUT123
3
I/O Streams and Standard I/O Devices 124
cin and the Extraction Operator >> 125

Using Predefined Functions in a Program 130


cin and the get Function 133
cin and the ignore Function 134
The putback and peek Functions 136
The Dot Notation between I/O Stream
Variables and I/O Functions: A Precaution 139

Input Failure 139


The clear Function 142

Output and Formatting Output 143


setprecision Manipulator 144
fixed Manipulator 145
showpoint Manipulator 146
C1114 Digit Separator 149
setw 150

Additional Output Formatting Tools 152


setfill Manipulator 152
left and right Manipulators 154

Input/Output and the string Type 156

Debugging: Understanding Logic Errors


and Debugging with cout Statements 157

File Input/Output 160

Programming Example: Movie Tickets


Sale and Donation to Charity 164

Programming Example: Student Grade 170

Quick Review 173

Copyright 2018 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part. WCN 02-200-202
Table of Contents | xi

Exercises175

Programming Exercises 181

CONTROL STRUCTURES I (SELECTION) 187


4
Control Structures 188
SELECTION: if AND if . . . else 189
Relational Operators and Simple Data Types 189
Comparing Characters 190
One-Way Selection 191
Two-Way Selection 194
int Data Type and Logical (Boolean) Expressions 198
bool Data Type and Logical (Boolean) Expressions 198
Logical (Boolean) Operators and Logical Expressions 199
Order of Precedence 201

Relational Operators and the string Type 205


Compound (Block of) Statements 207
Multiple Selections: Nested if 207
Comparing if . . . else Statements with a Series of if Statements 210
Short-Circuit Evaluation 211
Comparing Floating-Point Numbers for Equality: A Precaution 212
Associativity of Relational Operators: A Precaution 213
Avoiding Bugs by Avoiding Partially Understood
Concepts and Techniques 215
Input Failure and the if Statement 218
Confusion between the Equality Operator (==)
and the Assignment Operator (=)221
Conditional Operator (?:)223
Program Style and Form (Revisited): Indentation 224

Using Pseudocode to Develop, Test, and Debug a Program 224

Copyright 2018 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part. WCN 02-200-202
xii | C++ Programming: Program Design Including Data Structures, Eighth Edition

switch Structures 227


Avoiding Bugs by Avoiding Partially Understood
Concepts and Techniques (Revisited) 234

Terminating a Program with the assert Function 236

Programming Example: Cable Company Billing 238

Quick Review 244

Exercises245

Programming Exercises 257

CONTROL STRUCTURES II (REPETITION) 265


5
Why Is Repetition Needed? 266

while Looping (Repetition) Structure 269


Designing while Loops 273
Case 1: Counter-Controlled while Loops 274
Case 2: Sentinel-Controlled while Loops 277
Case 3: Flag-Controlled while Loops 283
Case 4: EOF-Controlled while Loops 286
eof Function 287
More on Expressions in while Statements 292

Programming Example: Fibonacci Number 293

for Looping (Repetition) Structure 297

Programming Example: Classifying Numbers 305

do. . .while Looping (Repetition) Structure 309


Divisibility Test by 3 and 9 311
Choosing the Right Looping Structure 313

break and continue Statements 313

Nested Control Structures 315

Copyright 2018 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part. WCN 02-200-202
Table of Contents | xiii

Avoiding Bugs by Avoiding Patches 321

Debugging Loops 324

Quick Review 324

Exercises326

Programming Exercises 340

USER-DEFINED FUNCTIONS 347


6
Predefined Functions 348

User-Defined Functions 352

Value-Returning Functions 353


Syntax: Value-Returning Function 355
Syntax: Formal Parameter List 355
Function Call 355
Syntax: Actual Parameter List 356
return Statement 356
Syntax: return Statement 356
Function Prototype 360
Syntax: Function Prototype 361
Value-Returning Functions: Some Peculiarities 362
More Examples of Value-Returning Functions 364
Flow of Compilation and Execution 375

Programming Example: Largest Number 376

Void Functions 378

Value Parameters 384

Reference Variables as Parameters 386


Calculate Grade 387

Value and Reference Parameters and Memory Allocation 390

Copyright 2018 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part. WCN 02-200-202
xiv | C++ Programming: Program Design Including Data Structures, Eighth Edition

Reference Parameters and Value-Returning Functions 399

Scope of an Identifier 399

Global Variables, Named Constants, and Side Effects 403

Static and Automatic Variables 411

Debugging: Using Drivers and Stubs 413

Function Overloading: An Introduction 415

Functions with Default Parameters 417

Programming Example: Classify Numbers 420

Programming Example: Data Comparison 425

Quick Review 435

Exercises438

Programming Exercises 453

USER-DEFINED SIMPLE DATA TYPES, NAMESPACES,


7 AND THE STRING TYPE 467
Enumeration Type 468
Declaring Variables 470
Assignment470
Operations on Enumeration Types 471
Relational Operators 471
Input /Output of Enumeration Types 472
Functions and Enumeration Types 475
Declaring Variables When Defining the Enumeration Type 476
Anonymous Data Types 477
typedef Statement 477

Programming Example: The Game of Rock, Paper, and Scissors 478

Copyright 2018 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part. WCN 02-200-202
Table of Contents | xv

Namespaces487

string Type 492


Additional string Operations 496

Programming Example: Pig Latin Strings 505

Quick Review 510

Exercises512

Programming Exercises 517

ARRAYS AND STRINGS 521


8
Arrays523
Accessing Array Components 525
Processing One-Dimensional Arrays 527
Array Index Out of Bounds 531
Array Initialization during Declaration 532
Partial Initialization of Arrays during Declaration 532
Some Restrictions on Array Processing 533
Arrays as Parameters to Functions 534
Constant Arrays as Formal Parameters 535
Base Address of an Array and Array in Computer Memory 537
Functions Cannot Return a Value of the Type Array 540
Integral Data Type and Array Indices 543
Other Ways to Declare Arrays 544

Searching an Array for a Specific Item 544


Sorting547

Auto Declaration and Range-Based For Loops 551

C-Strings (Character Arrays) 552


String Comparison 555

Copyright 2018 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part. WCN 02-200-202
xvi | C++ Programming: Program Design Including Data Structures, Eighth Edition

Reading and Writing Strings 556


String Input 556
String Output 558
Specifying Input/Output Files at Execution Time 559
string Type and Input/Output Files 559

Parallel Arrays 560

Two- and Multidimensional Arrays 561


Accessing Array Components 563
Two-Dimensional Array Initialization during Declaration 564
Two-Dimensional Arrays and Enumeration Types 564
Initialization567
Print568
Input568
Sum by Row 568
Sum by Column 568
Largest Element in Each Row and Each Column 569
Passing Two-Dimensional Arrays
as Parameters to Functions 570
Arrays of Strings 573
Arrays of Strings and the string Type 573
Arrays of Strings and C-Strings (Character Arrays) 573
Another Way to Declare a Two-Dimensional Array 574
Multidimensional Arrays 575

Programming Example: Code Detection 577

Programming Example: Text Processing 583

Quick Review 590

Exercises592

Programming Exercises 604

Copyright 2018 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part. WCN 02-200-202
Table of Contents | xvii

RECORDS (STRUCTS)611
9
Records (structs)612
Accessing struct Members 614
Assignment617
Comparison (Relational Operators) 618
Input/Output618
struct Variables and Functions 619
Arrays versus structs620
Arrays in structs620
structs in Arrays 623
structs within a struct 624

Programming Example: Sales Data Analysis 628

Quick Review 642

Exercises643

Programming Exercises 648

CLASSES AND DATA ABSTRACTION 651


10
Classes652
Unified Modeling Language Class Diagrams 656
Variable (Object) Declaration 656
Accessing Class Members 657
Built-in Operations on Classes 659
Assignment Operator and Classes 659
Class Scope 660
Functions and Classes 660
Reference Parameters and Class Objects (Variables) 660
Implementation of Member Functions 661
Accessor and Mutator Functions 666
Order of public and private Members of a Class 670

Copyright 2018 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part. WCN 02-200-202
xviii | C++ Programming: Program Design Including Data Structures, Eighth Edition

Constructors671
Invoking a Constructor 673
Invoking the Default Constructor 673
Invoking a Constructor with Parameters 674
Constructors and Default Parameters 677
Classes and Constructors: A Precaution 677
In-line Initialization of Data Members and the Default Constructor 678
Arrays of Class Objects (Variables) and Constructors 679
Destructors681

Data Abstraction, Classes, and Abstract Data Types 682


A struct versus a class 684

Information Hiding 685

Executable Code 689

More Examples of Classes 691

Inline Functions 700

Static Members of a Class 701

Programming Example: Juice Machine 707

Quick Review 722

Exercises724

Programming Exercises 736

INHERITANCE AND COMPOSITION 743


11
Inheritance744
Redefining (Overriding) Member Functions of the Base Class 747
Constructors of Derived and Base Classes 754
Destructors in a Derived Class 763
Multiple Inclusions of a Header File 764
C11 Stream Classes 768

Copyright 2018 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part. WCN 02-200-202
Visit https://textbookfull.com
now to explore a rich
collection of eBooks, textbook
and enjoy exciting offers!
Table of Contents | xix

Protected Members of a Class 769


Inheritance as public, protected, or private 769
(Accessing protected Members in the Derived Class) 770

Composition (Aggregation) 773

Object-Oriented Design (OOD) and


Object-Oriented Programming (OOP) 778
Identifying Classes, Objects, and Operations 780

Programming Example: Grade Report 781

Quick Review 802

Exercises802

Programming Exercises 811

POINTERS, CLASSES, VIRTUAL FUNCTIONS,


12 ABSTRACT CLASSES, AND LISTS 817
Pointer Data Type and Pointer Variables 818
Declaring Pointer Variables 818

Address of Operator (&) 820

Dereferencing Operator (*) 821

Classes, Structs, and Pointer Variables 826

Initializing Pointer Variables 829


Initializing Pointer Variables Using nullptr 829

Dynamic Variables 830


Operator new 830
Operator delete 831

Operations on Pointer Variables 835

Dynamic Arrays 837


Arrays and Range-Based for Loops (Revisited) 840
Functions and Pointers 841
Copyright 2018 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part. WCN 02-200-202
xx | C++ Programming: Program Design Including Data Structures, Eighth Edition

Pointers and Function Return Values 842


Dynamic Two-Dimensional Arrays 842

Shallow versus Deep Copy and Pointers 845

Classes and Pointers: Some Peculiarities 847


Destructor848
Assignment Operator 849
Copy Constructor 851

Inheritance, Pointers, and Virtual Functions 858


Classes and Virtual Destructors 865

Abstract Classes and Pure Virtual Functions 866

Array-Based Lists 874

Unordered Lists 881

Ordered Lists 886

Address of Operator and Classes 887

Quick Review 889

Exercises892

Programming Exercises 903

OVERLOADING AND TEMPLATES 907


13
Why Operator Overloading Is Needed 908

Operator Overloading 909


Syntax for Operator Functions 910
Overloading an Operator: Some Restrictions 910
Pointer this 913
Friend Functions of Classes 918
Operator Functions as Member Functions and Nonmember Functions 921
Overloading Binary Operators 924

Copyright 2018 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part. WCN 02-200-202
Table of Contents | xxi

Overloading the Stream Insertion (<<) and Extraction


(>>) Operators 930
Overloading the Assignment Operator (=)935
Overloading Unary Operators 943
Operator Overloading: Member versus Nonmember 949
Classes and Pointer Member Variables (Revisited) 950
Operator Overloading: One Final Word 950

Programming Example: clockType950

Programming Example: Complex Numbers 959

Overloading the Array Index (Subscript) Operator ([]) 964

Programming Example: newString 966

Function Overloading 973

Templates973
Function Templates 973
Class Templates 975

Array-Based Lists (Revisited) 978

C1111 Random Number Generator 985

Quick Review 987

Exercises989

Programming Exercises 996

EXCEPTION HANDLING 1007


14
Handling Exceptions within a Program 1008
C11 Mechanisms of Exception Handling 1012
try/catch Block 1012
Using C11 Exception Classes 1019

Creating Your Own Exception Classes 1023


Rethrowing and Throwing an Exception 1032
Copyright 2018 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part. WCN 02-200-202
xxii | C++ Programming: Program Design Including Data Structures, Eighth Edition

Exception-Handling Techniques 1036


Terminate the Program 1036
Fix the Error and Continue 1036
Log the Error and Continue 1037

Stack Unwinding 1038

Quick Review 1041

Exercises1043

Programming Exercises 1049

RECURSION1051
15
Recursive Definitions 1052
Direct and Indirect Recursion 1054
Infinite Recursion 1054

Problem Solving Using Recursion 1055


Tower of Hanoi: Analysis 1065

Recursion or Iteration? 1065

Programming Example: Converting a


Number from Binary to Decimal 1067

Programming Example: Converting a


Number from Decimal to Binary 1071

Quick Review  1074

Exercises  1075

Programming Exercises  1080

LINKED LISTS 1085


16
Linked Lists 1086
Linked Lists: Some Properties 1087
Deletion1093
Building a Linked List 1094
Copyright 2018 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part. WCN 02-200-202
Table of Contents | xxiii

Linked List as an ADT 1099


Structure of Linked List Nodes 1100
Member Variables of the class linkedListType 1100
Linked List Iterators 1101
Print the List 1107
Length of a List 1108
Retrieve the Data of the First Node 1108
Retrieve the Data of the Last Node 1108
Begin and End 1108
Copy the List 1109
Destructor1110
Copy Constructor 1110
Overloading the Assignment Operator 1111

Unordered Linked Lists 1111


Search the List 1112
Insert the First Node 1113
Insert the Last Node 1114
Header File of the Unordered Linked List 1119

Ordered Linked Lists 1120


Search the List 1121
Insert a Node 1122
Insert First and Insert Last 1126
Delete a Node 1127
Header File of the Ordered Linked List 1128

Print a Linked List in Reverse Order


(Recursion Revisited) 1131
printListReverse1133

Doubly Linked Lists 1134


Default Constructor 1137
isEmptyList1137

Copyright 2018 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part. WCN 02-200-202
Random documents with unrelated
content Scribd suggests to you:
place of personal direction, while over all hovers the watchful eye of
the grievance committee. Meanwhile, we, the employees, look on,
watching the game.
When people are killed, when property is wrecked, we have nothing
to say. It is for the management to figure out reasons and remedies.
Of course, as individuals, we are interested and sorry when
accidents happen, but personally we do not bestir ourselves, nor do
we call upon our organizations to bestir themselves in the matter.
We simply stand pat on our rights. If a prominent railroad man is
questioned on the subject of railroad accidents, he will shrug his
shoulders and say, “Human nature.” So far as he is concerned,
railroad men are to be protected, not criticised. If you turn to the
management your errand will be equally fruitless. The
superintendent will have little to say. Generally speaking, he has no
fault to find with the men, and the men have little fault to find with
him. This seems to be a tacit understanding in the interests of
harmony. It being impossible to move without treading on
somebody’s toes, by all means let us remain motionless. As for the
public interests, they must shift for themselves. Consequently, in
place of earnest coöperation in the interests of efficiency and
improved service, there is something in the nature of a friendly
deadlock between men and management.
Nevertheless, in spite of many appearances to the contrary, the
problem of the efficient and safe running of trains is a very simple
one. Fundamentally it is not a question of rules or safety devices,
but of personal conduct and habits of thought.
In everyday life when a man fails to make a satisfactory score with a
first-class gun we do not place the blame on the weapon. If we
desire greater efficiency in marksmanship we direct our attention to
the man. But in the railroad business such commonplace logic does
not seem to apply. When a man violates an unmistakable rule or
runs a signal with disastrous results, there immediately arises on all
sides a peremptory demand for a different kind of rule or an
improved signal. Public opinion, with little understanding of the
issues at stake, has a constant tendency to blame systems and
managements. Even the Railroad Commissioners, agreeing with or
responsive to this public sentiment, almost invariably recommend
improvements along these lines. In this way for many years
attention has been concentrated upon the machinery of
management, its rules and safety appliances, and the personality of
the men has been side-tracked. The injurious effects of this policy
and the manner in which all hands have conspired to obliterate
personality from the railroad business will be evident from the
following illustration.
A short time ago, in the vicinity of Boston, an express train
telescoped an accommodation passenger train. The track in question
was protected by no less than four cautionary rules and signals. In
this way the express train received four distinct and emphatic
intimations that a train was on the block ahead of it. With the
slightest attention to the rules or to the dictates of common sense,
the protection was sufficient, yet the train ahead was telescoped as
it was pulling out of a station. Of course, in placing the responsibility,
the plain and real issue in this case was the question whether the
express train was or was not running slowly and with extreme
caution, as called for by the rules. In order to determine whether the
rules and signals were sufficient to prevent a collision, it was surely
proper and reasonable to ascertain whether, on this occasion, they
were obeyed. But the Railroad Commissioners, after an exhaustive
investigation, took a different view of the matter. Their finding or
verdict in their own words was as follows:—
“It is not necessary to determine whether the engineman did or did
not exercise proper caution; the significant fact is that the discretion
actually used led to disastrous results. Under the conditions the
signal should have been red.”
The harmfulness of this decision will at once be apparent. It cuts the
personality out of the business at points where obedience to the
rules is the vital issue. Green signals or red signals are equally
valueless if ducks and drakes can be played with the rules in regard
to them. A decision like this one is confusing and demoralizing to
conscientious railroad men, and it converts the management and
discipline of a railroad into a thing of shreds and patches.
To emphasize this point, it should be added that another collision of
a similar nature took place about the same time on the same
railroad. An express passenger train approached a fixed signal which
indicated caution. The engineman, on the lookout, but with the
caution up his sleeve, kept on his way without any reduction in
speed. A moment later he encountered a red fusee which called for
an absolute stop, but it was too late. Neither the fusee nor the
flagman frantically waving his red flag availed to arrest the
momentum of the flyer, which dashed into the rear of another
passenger train standing at a station.
Now, with all deference to the Railroad Commissioners, the
“significant facts” in these accidents are the personal conduct of the
employees and not the nature of the signals or the wording of the
rules.
Of course, taking a wider view of preventable accidents, it is always
an easy matter to divide the responsibility for them between the
men and the management. This is the usual and popular method of
treating the subject. But the idea, reasonable at times, has been
overworked, and has now degenerated into a principle that
responsibility should always be divided. Consequently, while we are
busy adjusting the division, we frequently lose sight of the real
issues, and the offenders are allowed to escape.
Fundamentally, then, it must be confessed, we railroad men are to
blame for these preventable accidents. Most of the trouble can be
directly traced to our own personal behavior, that is to say, to our
conduct and habits of thought as railroad men. This is by no means
a reflection on our character as sympathetic and reasonable human
beings. Our intentions are all right, but our training in the railroad
business has been all wrong.
But it is of little use to talk or write about personality in the abstract.
As practical men dealing with a practical topic, we must follow the
railroad man out on the road, we must watch him at his work, and
we must take notice of the common sense, the caution, and the
good judgment or otherwise, which he habitually displays in the
execution of his duties. Then, and not until then, can we expect to
become qualified to place our opinions or conclusions on record.
Now the regulations relating to the running and protection of trains
are very similar on all railroads, and therefore the following rule
taken from one of our current working time-tables may be looked
upon as thoroughly representative.
“A freight train must not leave a station to follow a passenger train
until five minutes after the departure of said passenger train.”
To any ordinary thinker this rule will appear to be plain, positive, and
for the most part necessary. Yet as a matter of fact no attention
whatever is paid to it either by enginemen, by conductors, or for
that matter by superintendents. Its violation has been the cause of
collisions and loss of life, but that does not seem to bother us, for
we continue to disregard it. Let us take another illustration.
At the point where the writer has been employed for many years,
there is a junction of four-track and two-track systems. The rule for
the handling of trains at this point is as follows:—
“All trains will approach and enter upon four-track sections under
complete control.”
There is nothing misleading or uncertain about this rule. The
instructions to enginemen are positive. The towermen at these
points understand how necessary and important this rule is. Besides,
it is the written result of the experience of the officials. Nevertheless,
it is totally and consistently ignored by enginemen. But enginemen
are not alone to blame. Conductors should at least be conversant
with the rules. The railroad officials who ride on these trains might
also very reasonably be expected to notice the persistent violation of
regulations for which they themselves are responsible. Yet even the
trains bearing the Railroad Commissioners will rush over the territory
in question as fast as the wheels can turn. The conditions and the
rules in this case are practically the same as were those at Salisbury,
England, at the time of the recent disaster in that city.
Now as it seems to me, the all-important facts in these cases do not
relate to the nature of the rules, nor even to their non-enforcement,
but to the downright neglect of railroad men to do as they are told.
For, granted observance of them, all other questions in regard to the
rules dissolve into thin air.
Unfortunately, the rules I have quoted and the interpretation put
upon them by railroad men cannot be taken as examples standing
alone, for they are merely illustrations of a principle that covers the
whole cautionary field in our railroads. In some way we have got it
into our heads that these rules are permissive, not positive. This
permissive principle means the exercise of our own judgment
according to circumstances, regardless of the rule. Acting under the
influence of this principle, the flagman protects his train to the very
letter of the rule when it is manifestly necessary, but when, in his
opinion, it is not, he takes chances. In this way he forms a habit of
using his own judgment in regard to a positive rule. Sooner or later
this means a preventable accident.
The engineman encounters a single torpedo. According to his rules,
he should bring his train to a full stop. But as he happens to have a
clear track for a mile ahead of him he keeps on. He, too, forms a
habit which has to be reckoned with some day.
Again, all trainmen understand that an express train has no business
to run past a station while accommodation trains are discharging
passengers. It is by no means an uncommon occurrence, however,
to see an express train disregard these positive instructions, on the
strength of hand motions given by trainmen on the accommodation
train to the effect that they are about to start, and that the way is
safe and clear for the flyer. Yet in this manner accidents happen, and
passengers from the accommodation are always likely to be caught
in a trap between the trains.
But the dangerous and widespread effects of the permissive principle
applied to important rules will be appreciated to the full when we
study the interpretation which railroad men in general are in the
habit of applying to the word caution.
On all railroads there are certain fixed signals for the guidance and
information of employees. When caution is called for, the light is
usually green and the semaphore horizontal. Now, as the writer
looks at it, when any signal indicates caution, it is not to be looked
upon as a permissive or conditional signal to be interpreted at will by
different enginemen. According to the rules and to common sense
when a train, at the time a cautionary signal is sighted, is running
thirty or forty miles an hour, it calls for a positive and not a
theoretical reduction in speed. The cautionary signal is not merely a
piece of information to be stowed away in the brain of the
enginemen, to be utilized when a rear end or a broken rail is
sighted.
Although for a number of years the inflexible enforcement of the
rules relating to these cautionary signals has been advocated, yet to-
day train after train will run past these semaphores and green lights
without any reduction in speed, provided the track ahead of them is
seen to be clear.
Here we tackle the very heart of the matter, for in so far as the rules
and common sense are concerned, it should not make a particle of
difference to the engineman whether the track ahead is or is not
known to be clear of trains; his instructions call for cautious running,
and by no possible interpretation or juggling with words can cautious
running, or running under control, be taken to mean running at full
speed. Yet in the way I have indicated the cancer of a very
dangerous habit has been allowed to grow into the American system
of managing trains. This wrong interpretation of the word caution by
enginemen and others has without a shadow of doubt during the
past few years cost the corporations thousands upon thousands of
dollars and multitudes of human lives. For if railroad managers labor
under the delusion that enginemen can run cautiously at full speed
when the track is clear, and avoid disaster when from unforeseen
reasons another train happens to be on the same section, they are
very much mistaken.
Practically speaking, then, the permissive principle covers the whole
field of railroad life, and is a constant menace alike to the interests
of the corporations and to those of the traveling public. As a matter
of fact, we, the employees, are bigger than the rules. According to
our way of thinking, it is not alone necessary that a rule should be
plain and sound from a general standpoint, but its downright
meaning and necessity must also be evident in each and every
particular instance. If it fails to stand this test, we consider ourselves
at liberty to use our judgment in regard to it.
Illustrations of the danger that lurks in this permissive principle can
be multiplied indefinitely. But, after all, it is only a link in the chain,
for there are other features in the personality of railroad men that
call for serious attention.
The other day, within a few miles of Boston, an express passenger
train approached a railroad crossing at grade. For some reason the
gate-tender was negligent and failed to lower the gates. By reason
of just such negligence, teams are frequently struck and lives are
lost at these crossings. On all railroads, the rules are quite plain and
unmistakable in regard to such matters. It is the duty of the
engineman to report the incident to the management. As a matter of
fact on this particular occasion the engineman failed to do so. He
failed to appreciate the fact that the safety of the public at these
crossings is altogether dependent upon the strict observance of the
rules. He had scruples and emotional objections, perhaps, to
reporting this gate-tender, and rather than do so he took all the
chances in connection therewith, chief among which is the simple
fact that on a railroad unchecked negligence can be depended upon
to breed disaster.
That railroad men in general are either indifferent to or ignorant of
the importance of the above fundamental fact will be made still
clearer by another illustration. On September 16, 1907, that is, on
the day following the disaster at West Canaan, N. H., the writer was
a witness of the violation of two most important rules by a number
of enginemen, conductors, and brakemen. A switch leading from the
west- to the east-bound main line was left open while an express
passenger train was passing inward bound. A freight train was on
the west-bound track waiting to back over. Two minutes later, with
his train only halfway in to clear the main line, the engineman on the
freight whistled in his flagman in the face of an accommodation
passenger train which had followed the express. From beginning to
end, on the permissive principle, it was a perfectly safe transaction,
for there was a mile of straight track in both directions; but the rules
for the running of the trains and for the safety of the public were
violated. The witnesses were seven or eight veteran railroad men,
who looked upon the affair as perfectly proper and justifiable under
the circumstances. It never entered the heads of these men that the
affair should be reported to the management. That some of the best
men in the service should behave in this way, as it were in the very
shadow of the accident at West Canaan, is almost inconceivable. Of
course, if these incidents stood by themselves their significance
might be comparatively trifling; but as a matter of fact they are
illustrations of a condition which is thoroughly typical of American
railroads. This condition or situation may be briefly yet correctly
outlined as follows:—
There is practically no out-on-the-road supervision on American
railroads.
Railroad managers depend upon the reports of employees for
information in regard to violations of rules. But employees do not,
and cannot be compelled to, report their associates; consequently
negligence of all kinds is practically unchecked.
Finally: unchecked negligence can be shown to be the root and
direct cause of nearly all preventable accidents, and loss of life
therefrom, on American railroads.
Here we have a conclusion worth looking into. At a glance we
perceive that negligence is the prime and fundamental fact. It is the
direct cause of the trouble. The fact that the negligence is
unchecked is important, yet secondary. It should be treated as a
separate issue, and it must stand or fall on its own merits.
But our conclusion that accidents result in almost all cases from
unchecked negligence should be supported by evidence and proof.
For examples in support of it, let us take two of the most disastrous
wrecks in the history of New England railroads.
On November 26, 1905, at Baker Bridge in Lincoln, Mass., seventeen
people were killed and thirty injured. An express passenger train was
following an accommodation train, which was somewhat late.
Cautionary signals calling for reduced speed and careful running
were passed at intervals by the express train, but, according to the
evidence, the engineman paid no attention to them; hence the
accident. Now the habitual negligence in regard to these cautionary
signals was a matter of common knowledge. In fact, attention was
called to the matter both before and after the accident by the writer.
The unchecked negligence in this particular case was therefore
directly responsible for the accident and the loss of life.
Again, on September 15, 1907, at West Canaan, N. H., twenty-five
people were killed and forty injured. The unchecked negligence in
this case is by no means so striking as in the previous example, and
yet the evidence pointing in that direction is quite as significant. A
mistake occurred in the transmission of an important train order.
This mistake was the direct cause of the accident. For various
reasons it was impossible to say by whom the mistake was made.
Now let us turn to our book of rules and take note of the following
instructions to train dispatchers and operators: “In transmitting
messages write slowly and firmly,” etc.
With all proper consideration for hard-worked and conscientious train
dispatchers, I am compelled to confess that train orders are seldom
if ever sent “slowly and firmly.” Operators will bear me out in the
statement that orders are transmitted by dispatchers as fast as the
men can handle them. That is to say, between veterans in the
business they are rattled off at the highest limit of speed. The men
concerned in the accident at West Canaan were veterans. Had the
man at West Canaan been a “plug,” that is, a green hand, in all
probability the accident would not have occurred. While, of course,
this is merely a supposition, yet the fact remains that the men would
have been transmitting slowly and firmly, and the chances for a
mistake would have been reduced to a minimum.
I thoroughly understand and appreciate the difficulties with which
the train dispatcher has to contend. I am quite aware that he is
called upon to handle trains with the utmost dispatch; nevertheless,
I insist that, in order to reduce chances of accident to a minimum,
train orders should in all cases be transmitted slowly and firmly. I
stand by the rules. The issue is between speed and safety, and in all
cases the latter should be given the right of way.
Thoughtful railroad men, who understand the situation on the
railroads at the present day, are yet very slow in suggesting
remedies. They say, “It is up to the management to enforce the
rules.” On the other hand, if a superintendent can be persuaded to
express an opinion he will retort, “It is up to the men to obey the
rules. They are plain enough and sufficient for the purpose, but we
cannot station a spy at every switch to make sure that the rules are
obeyed. We have to depend on the personality and general
intelligence of our employees.”
It will, I think, be evident from the facts and conditions that we have
been considering, that whatever secondary causes there may be for
preventable railroad accidents, the trainmen themselves hold the key
to the situation. They are at liberty to obey the rules, and thus solve
the problem in the only way in which it ever can be solved; or, they
can continue to place upon these rules a wrong interpretation, and
thus evade their manifest meaning and purpose. As matters stand
to-day between labor organizations and railroad managers, it is very
doubtful if by any practical system of supervision or discipline the
rules for the safe and efficient running of trains can in all cases and
at all times be adequately enforced. Thus the whole business
resolves itself into a personal matter with us as conscientious
railroad men. Singly and collectively, it is up to us to do the square
thing, if necessary, in spite of the management.
As the case stands to-day, we railroad men are in a class by
ourselves. We are well-paid, well-treated, well-educated, and well-
organized. In all that pertains to our material well-being we compare
more than favorably with any other class of workers in the country;
but considered as responsible individuals intrusted with the care of
railroad property and the safety of the traveling public, our records
are very unsatisfactory. The truth of this conclusion is not open to
question. We cannot escape from the statistics and the figures; and,
day by day, the evidence against us continues to accumulate.
There are many people who think that the intelligence and education
of the twentieth-century railroad man can be depended upon to
guard against the shortcomings to which I have called attention. On
the contrary, I am inclined to think that the intellectual
independence of the railroad men is in itself a danger to be guarded
against. Standing by itself, the statement that knowledge is power is
a fallacy. Knowledge is only a means. Its benefit to any one is always
an open question. In other words, the secret of power is in the
application of knowledge. Thus when we analyze a modern railroad
accident we are forced to the conclusion that many railroad men
take chances by reason of the supreme confidence which they
possess in their own cleverness and ability to deal with an
emergency, however sudden. This resourceful characteristic of
Americans is a splendid thing from a general standpoint, but in the
railroad business it has its stern limitations. Only too many of our
accidents are illustrations, not of lack of knowledge or resource, but
of the downright misapplication of these intellectual features. In
some cases we find an over-supply of self-confidence, in others a
disinclination to knuckle right down to the observance of plain and
positive instruction. In such cases a man cannot be called the
fortunate possessor of intellectual advantages, but their manifest
victim.
Railroad managers, therefore, sooner or later will come to
understand that the one thing needed in the railroad business at the
present day is to educate employees to appreciate the fact that
successful and safe railroading in the future will have to depend, not
upon the multiplication of safety devices or the reconstruction of
rules, but upon the personal effort and conduct of conscientious,
alert, and careful men.
Meanwhile, thought counts; and it is a good idea for practical
railroad men to look into and study these problems, each according
to his ability and the light that is in him.
III
THE MANAGEMENT
The problem of safety in railroad travel has been discussed, from
widely different points of view, by many conscientious investigators.
The methods of these writers in marshaling facts and drawing
conclusions are usually identical. The formula consists of a variety of
accidents, a variety of causes, and a variety of possible or proposed
remedies. For results, up to date, we have a library of information,
but not a suspicion of improvement, in the record of preventable
fatalities. Meanwhile, in the public mind there is confusion of ideas
and considerable doubt as to the practical outcome of all this
discussion. This is a natural state of affairs, for the reason that the
only factor in the situation which is constant, and about which there
is no difference of opinion, is the impotency of railroad people in
coping with the difficulties.
Now, after all that has been spoken and written on the subject of
efficient and safe railroad service, the problem remains, as at the
beginning, essentially personal, social, and ethical in its nature.
Nearly all questions in regard to it must, sooner or later, be thought
out in this direction by railroad employees and managers. We may
continue to work over and reconstruct our rules and to multiply our
safety devices until we compel trains to creep from station to
station; yet the problem will remain unsolved, the needless and
disgraceful sacrifice of life will continue, until trainmen, enginemen,
and managers put their heads together and agree to adopt a new
code of railroad morals. My meaning when I allude to railroad morals
should be clearly understood.
On nearly all railroads a given rule is obeyed at one point and
disregarded at another, on account of different sets of conditions.
This conduct leads to accidents when men who have habitually
disobeyed the regulations at points where such action is harmless
undertake to behave in the same way under conditions when a strict
observance of the rules is vitally important. Generally speaking,
managers are cognizant of this state of affairs, and thus in a
measure they are morally to blame for it; but I do not think that
they realize the extent of the evil, for the reason that any organized
out-of-door supervision is unknown, and thus the report of an
accident, that is to say, the result of these practices, is usually the
first and only information on the subject that reaches the manager’s
office. The blame for accidents that happen in this way cannot be
said to rest upon any particular class of employees or to depend
upon their intelligence or length of service. Among the culprits you
will find some of the oldest and most experienced men as well as
some of the greenest. This goes to show that the trouble is inherent
in the system, and a part of the everyday life and character of
armies of railroad men.
But in a straightforward investigation of this nature it is particularly
desirable to get hold of all the facts that can be used in any way to
throw light on the situation, and there is only one method, as yet
untried, for properly securing and emphasizing these facts. Let us
call this the confessional method. In the hands of a competent
witness it can be depended upon to furnish us with all the
information necessary for a thorough comprehension of our subject.
This confessional method has nothing to conceal. It has no axe to
grind, no interests to protect. It is born of a heartfelt appreciation of
the seriousness of the situation on our railroads. Mindful of the ever-
increasing and lamentable loss of life caused by the unstudied
indifference and negligence of employees, as well as by the
blindness of the authorities to the real issues and dangers, it
approaches and takes hold of the problem somewhat in the spirit of
the King in “Hamlet,” when in an agony of remorseful retrospection
he exclaimed, “Try what repentance can: what can it not?”
That there is an urgent call for this confessional method of supplying
the facts in this railroad business is capable of easy demonstration.
When an accident takes place on a railroad, some kind of an
explanation or reason for its occurrence is immediately called for.
Consequently there is a lining up of opposing interests. A certain
management has to be vindicated, certain employees to be
defended. In the investigation that follows, an array of facts
defensive and otherwise is brought forward in the interests of the
opposing parties; but evidence and facts that are likely to reflect on
both men and management, and perhaps on the handling of the
case or of other cases by the Board of Railroad Commissioners, are
studiously avoided. The facts that are suppressed in this way usually
contain the heart of the whole business, and are the very points in
which the public is profoundly interested. An illustration in point will
make this doubly clear.
About a year ago, in an accident near Troy, N. Y., five passengers
were killed and many were injured. A special passenger train
crashed into the rear of a regular passenger train. There is a sharp
curve in the track a short distance above the scene of the collision.
Had the special been handled carefully round this curve instead of
recklessly, the accident would not have occurred. Caution, of course,
is necessary in running round sharp curves, and the rules on all
railroads are plain and emphatic on the subject. But the authorities
who investigated this accident treated it as an isolated instance of
individual carelessness. Within a period of six months these
gentlemen are called upon to pass judgment on probably twenty
wrecks, every one of them bearing the same earmarks of
disobedience as this disaster near Troy, yet no one ever dreams of
hunting up a common cause for dozens of accidents that are exactly
similar and brought about in the same way. To be precise, this
accident at Troy was the result of a habit. At a glance we perceive
that the public is a hundred times more likely to be interested in the
uprooting of such a bad habit as running recklessly round curves
than it is in placing the responsibility or punishing the offender in
any particular instance. Yet who ever heard of a verdict that placed
the blame for an accident on a habit? The reasons for the oversight
are obvious. A dangerous habit, long continued and unchecked, is a
decided reflection on men and management, and, indeed, on the
Railroad Commissioners, whose vigilance it has escaped; and
consequently no evidence or facts in regard to these bad habits are
ever permitted to find their way into investigations. It will be
evident, therefore, that the confessional method can be profitably
employed in supplying a few missing links in our knowledge of actual
conditions and methods of operation on the railroads.

A YARD WRECK
To begin with, it will be well to take note of an estimate, made after
a careful study of the figures, that fully eighty-five per cent of the
fatalities that occur on our railroads can be directly traced to the
negligence of employees. Regardless of the accuracy of this
estimate, it certainly points to a very serious state of affairs. In
studying the nature of these accidents and the conditions under
which they take place, one cannot help being impressed with the
fact that almost every possible way in which trouble can occur on a
railroad is foreseen and provided for by some rule or safety device.
So carefully has the ground been studied and worked over, that in
every case of preventable accident it can almost be taken for
granted that an employee is to blame. That is to say, the
management of a railroad is always found to be impregnably
protected by the rules and regulations from any direct responsibility.
But, after all, this is only one side of the shield, for clearly the moral
responsibility of a railroad manager cannot be said to cease with the
printing of a batch of rules or the erection of a system of signals. It
is not only necessary that rules should be plain and sufficient in
themselves to prevent accidents, it is also equally essential that
reasonable and systematic efforts should be exerted to enforce
them. On a railroad, as elsewhere, the means employed for the
supervision of personal conduct and for the enforcement of
necessary rules are all included in the term discipline. Without some
organized and effective system of discipline no industrial
establishment of any kind can be successfully administered. On
railroads in particular, the department of discipline is intimately
related to the interests of the traveling public. Let us then examine
in a practical manner the nature and methods of the discipline that is
in force at the present day on what may be considered the most
important railroad in New England. A little personal experience will
throw the necessary light on the subject.
Some time ago, happening to notice that important regulations were
being habitually ignored by a certain class of employees, the writer
called the attention of the management to the matter. In this way,
from time to time, many cases of simple negligence, which had no
serious consequences, were reported to superintendents. Thinking it
all over, the writer finally became anxious to find out just what
disposition was made of these reports. For it must be apparent to
any thinking person that the practical value of any system of
discipline must always depend upon the efforts that are put forth
and the success that is achieved in checking and in preventing the
repetition of these instances of what may be called trouble in the
bud. The reports to which I refer were acknowledged by the
management, and there the matter ended. But as I happened to be
studying the subject at the time in a systematic manner, I was by no
means satisfied with this abrupt conclusion. So I made an
investigation on my own account, and easily discovered that
practically all other interested employees were unaware of and had
not been notified in regard to the violation of these rules because, as
the men explained, nothing had happened. That is to say, it was
necessary to hurt somebody or smash up a few carloads of freight
before any efforts could be exerted according to the rules to put a
stop to the negligence. This became very clear to me, when, upon
making further inquiries, I was informed that the men had been
disciplined to the full extent of the rules. Now my object in the
investigation was not to get at the nature or the amount of the
discipline, but simply to be able to arrive at an estimate of its value
in checking and restraining others from committing similar mistakes.
In this way I soon arrived at the conclusion that a system of
discipline that works in the dark in this way is of no practical value
whatever. It is a weakness of management, which positively
undermines the operating department and leads the way to all sorts
of disaster and loss of life. Its continued existence in practical
railroad management is a standing menace to the safety of the
traveling public. As a matter of fact, lives are still being frequently
sacrificed and much property is almost daily being destroyed as
direct tribute to this incomprehensible system of discipline.
The exact method by which this system is put into operation, and
the regulations which govern employees in regard to it, will be
understood from the following extracts from general orders on the
subject, issued by what is sometimes considered one of the best-
managed railroads in the country:—
“The System of Discipline by Record having proved beneficial both to
the road and to employees, it has been decided to extend the same
by the addition of merit marks....
“Each employee will be promptly notified of unfavorable entries
made in the record book opposite his name. He will upon request be
shown his record at any time, but will not be permitted to see the
record of another person.
“Bulletins, omitting name, date, train, and location, but containing
facts and conclusions and such comment as is applicable, will be
issued from time to time if considered necessary.”
The significance of this general order to employees should be
thoroughly understood. Practically interpreted, it means that when
an employee commits a mistake or is guilty of negligence that
endangers life and property, the affair is to be looked upon as a
secret. This interpretation is correct according to the actual
operation of the system on the railroads. Neither in the interests of
the public safety nor for any other reason can the facts in the case,
as regards date, name, location, and train, be utilized or published
for the prevention of future accidents of a similar nature. This is the
law of the road, and while it remains in force any employee can
claim the full benefit of its provisions. The practical illustration in my
own experience given above is fully explained and accounted for by
this general order. But the most astonishing feature in relation to it is
that with the records before us it should continue to be considered
and heralded as “beneficial” either to the railroads or the employees,
not to mention the public. For a full explanation of this peculiar state
of affairs we must turn to another quarter.
It is a well-known fact that the American railroad man, the trainman
and engineman in particular, has deep-rooted objections to being
“posted” in any way. We have consistently emphasized our
objections from the time, years ago, when our likes and dislikes first
began to cut a figure in the plans of the management. So to-day we
are prepared to go to almost any extreme rather than submit to any
system of discipline that will publish our mistakes and advertise us
personally by name as examples, even although such action can be
shown to be absolutely indispensable for the proper safeguarding of
life and property. With all the facts against us, we think we can be
trusted to render the best service and to live up to the rules without
the assistance of publicity in any form. We consider discipline to be a
private matter, to be settled between ourselves and the
management; and thus the workings of the system have been
arranged without any reference whatever to its effect on the
interests of the millions of people whose lives are placed in jeopardy
by its arrangements. As a matter of fact, then, the system of
discipline which I have described is the result of long-continued
pressure and consequent concessions by the management to the
demands of employees. These concessions have been granted for
the most part in the interests of harmony. What the exact nature of
this force or pressure is, which, acting on behalf of railroad
employees, has been able to influence railroad legislation and
management to the total exclusion of the public interests, calls for
the closest investigation.
A short time ago, in a report issued by the New York, New Haven
and Hartford Railroad, President Mellen stated that so far as his
system of roads was concerned, increase of pay had invariably been
followed by decreased efficiency. Mr. Mellen, of course, has the
reports and the figures to substantiate his opinion. The statement is
plain enough, although its meaning is somewhat obscure. That
decrease in efficiency has been the natural sequence and effect of
higher wages, or that men lose interest in their callings or grow
more careless in their habits with every addition to their material
prosperity, is manifestly absurd. Mr. Mellen has not informed us that
he looks upon the matter in this light, although his words may
reasonably be considered to bear some such interpretation. Be this
as it may, he certainly calls attention to a very uncomfortable
coincidence. In effect Mr. Mellen’s words may be taken as a direct
challenge to railroad men to come forward and explain a state of
affairs that has the appearance of being very much to their discredit.
The implied challenge can be immediately and concisely replied to in
this way. The efficiency of the service rendered by employees to the
New Haven road has by no means been impaired or decreased by
any consideration of wages whatsoever. Nevertheless, the power or
pressure that induced Mr. Mellen and other railroad managers to add
large sums to their pay-rolls is also responsible, by the exercise of its
influence in other directions, for the decreased efficiency. Increase of
pay and decrease of efficiency are both indications of loss of grip by
the management. Hidden away in this simple statement there is a
whole world of significance. Here are fundamental facts, from a
fearless consideration of which we shall be able to derive a logical
and clean-cut explanation of the present situation on American
railroads.
The force or influence to which I call attention is of course the
Railroad Labor Organization. But it should be clearly understood that
my conclusions in regard to these unions are not to be taken as a
reflection on their character and work while acting in legitimate
channels. The debt we railroad men owe to our organizations admits
no question. The beneficial results are before us in almost every
department of the railroad business. They have established a
fraternal feeling among us. On all sides they have aroused a spirit of
mutual helpfulness. They have also succeeded in advancing wages,
and in this way contributed to the comfort and prosperity of almost
every man in the service. Furthermore, they have been particularly
active in inciting legislation for the protection of life and limb among
workers. These facts must not be forgotten or minimized, for they
are worthy of all commendation. But in this matter of the personal
conduct and efficiency of railroad men in relation to these terrible
railroad accidents, we have first of all to consider the paramount
interests of society; and while humanity has no quarrel with the
unions while they attend to their legitimate business, it certainly can
be said to have a grievance against them that calls for prompt
attention and remedy. This grievance consists in the fact that, for a
great many years, the influence of the railroad labor organizations
has been consistently exerted, not only to raise wages and to
improve conditions, which of course is perfectly proper and
justifiable, but also to nullify discipline, to destroy personal
management and authority, and to obliterate from all schedules and
working agreements any reference to or consideration for the
paramount interests of the traveling public. It is not necessary to
quote paragraphs from these agreements, which for the most part
are secret documents. Given two angles of a triangle, it is an easy
matter to calculate the dimensions of the third. Similarly, given the
actual conduct of the men and the behavior of the management in
relation to it, we can derive very accurate conclusions in regard to
the work and power of the organizations.
Yet let no one imagine that this interference with the management in
the matter of discipline is brought about by design or is directly
intentional. On the contrary, in a very natural way, it has grown out
of a system whose main object has been to secure justice and equal
rights for every individual employee. But unfortunately, in pursuing
these personal ends and objects, the rights of the community have
been forgotten. It is easy to demonstrate that in the railroad
business this fair play to the individual frequently means a sacrifice
of the public interests. In the operating department of a railroad,
illustrations of this point meet us at every turn.
In any ordinary business establishment there is at all times a certain
amount of weeding going on for the good of the business. This is
done on the personal judgment and initiative of the manager. In this
way a high average of efficiency is attainable in all departments. But
in the railroad business no such personal action on the part of a
superintendent would be tolerated for a minute. It is surely
reasonable that among the thousands of men who enlist in the
railroad ranks there will be many who after a while will give evidence
of unfitness for the service. Regardless of the power of the
superintendent in theory, these men, if they are members of an
Order or Brotherhood, must actually hurt somebody or do
considerable damage to property, before they can be removed. That
is to say, there is no elimination of weak spots until something
happens. But this is not all. When a vacancy occurs in the service, it
is immediately advertised, and the oldest bidder in point of service
takes the position. In some of the agreements with the management
the seniority rule is said to be absolute, in others it is modified by
the clause, “with the approval of the superintendent.” But in a
business of the nature of a railroad the public interests demand that
at all points the best available man should be in charge, regardless
of his length of service or his rights as an individual. But the labor
organizations do not permit the public interests or those of the
corporation to interfere with what they consider to be the just and
inalienable rights of each and every employee. Applied to the
railroad business, the fixed principle that every man shall take his
turn is fundamentally wrong and demoralizing. It is one of the
wedges that are being used to destroy personal supervision and
management and to substitute management by machine methods.
In my opinion its tendency is in the interests of poor service. Healthy
competition in good behavior is almost obliterated, while honest
ambition and esprit de corps get very little encouragement. It has
the general effect of removing the attention of employees from the
management and concentrating it steadfastly upon the organization,
that is to say, upon the source from which increase of pay and all
other blessings are expected to flow.
Of course, I cannot expect railroad managers to agree at all points
with my estimate of their powers and functions, or of the helpless
situation in which they now find themselves. Just at present,
however, I am not interested in opinions from any quarter. The facts
that interest me, and I think the public as well, relate to what these
railroad managers have done in the past and are actually doing at
the present day, with such powers as they possess, in the interest of
safe and efficient railroad service. It may be very interesting to be
informed that a superintendent has the power promptly to discharge
an engineman for running a danger signal and placing the lives of
five hundred passengers in utmost peril, but it is much more to the
point to impress upon the public mind that the action of the official
will not amount to a snap of his finger if an organization puts down
its foot and signifies its opinion to the contrary. Illustrations of these
facts are not far to seek. Only a short time ago an engineman was
promptly discharged for disregarding a signal in a most inexcusable
manner. The case was passed up higher for the approval of the
general manager. Meanwhile the man had discovered some kind of
an excuse for his action, and a committee was appointed to look into
the matter. There being a total difference of opinion between the
management and the grievance committee, the heads of different
organizations were summoned from some western city to help
straighten out the deadlock. After a while the man was put back on
his engine, and the report passed round that the case had been
settled in this way in the interests of harmony. No wonder the
superintendent who was concerned in the matter threw up his hands
in disgust and exclaimed, “What’s the use?”
This method of interfering with the regular course of discipline may
perhaps be proper and commendable in a cigar factory or a cotton
mill, but on a railroad, where the lives of countless people are
dependent upon obedience to the rules, its effect upon the service is
absolutely fatal. But unhappily this is not the whole story, for it must
be confessed that the public frequently joins hands with the
organizations in defeating the ends and aims of discipline. After
some of the worst and most inexcusable accidents that have ever
occurred on New England railroads, petition has followed petition
into the railroad offices with the expressed object of influencing the
management to reinstate men in the service who have been
convicted of inefficiency or unpardonable carelessness. Of course a
superintendent should thoroughly investigate every case on its
merits, but the verdict of the management should be final. The
wisdom of this policy might be questioned if superintendents were
political appointees or owed their positions to “graft” or “pull.” As a
matter of fact these men are among the hardest worked, most
thoroughly capable and conscientious men in the United States. No
combination of opinion from the public, the railroad commissioners,
and the labor organizations is half as likely to be just and impartial
as the individual judgment of the superintendent on the spot. The
following significant remark by one of those gentlemen may well be
taken to heart by the public as well as by employees: “With a free
hand, we could put a stop to this killing in a week.”
The story of railroad management is now before us, and the record
of accidents all over the United States is the price that is being paid
for it. As I have described the situation, the circle of cause and effect
is now complete. Beginning with the negligence of employees, which
must be considered as the primary cause of these accidents, I next
took up the matter of discipline, whose function it is to control and
put a stop to this negligence. The system was found to be altogether
inadequate and useless. Finally, I attempted to demonstrate that the
labor organizations are responsible for the nature of this discipline,
and thus indirectly for the accidents that have resulted from its
inefficiency. Systems of discipline vary on different roads;
nevertheless these contentions are sound and universally applicable,
for the blight of interference with the management has in greater or
less degree withered every system of railroad discipline in the United
States, and exposed the traveling public to the mercy of service that
is inefficient and demoralized.
For the rest, it will be evident that the foregoing diagnosis of the
situation bears on its face unmistakable indications of the nature of
the cure. At all cost, interference with discipline must cease. This
conclusion admits no compromise. At the present day every decision
made by a superintendent is practically subject to the approval of
the Grievance Committee. But this is not all: the railroad manager is
handicapped and held up at every turn. In his dealings with the
labor problem, if by any possibility he manages to escape the fire, it
can only be by taking refuge in the frying-pan. An illustration in point
is the problem of keeping expenses within reasonable limits and at
the same time administering discipline to the very men who, backed
by powerful organizations, are continually insisting upon additions to
the pay-rolls.
But now, granting the situation and the difficulties as I have
described them, in what direction are we to look for relief? As it
seems to me, an unmistakable expression of public opinion would, in
the first place, go far in starting us all thinking and working in the
right direction. But even this will have little effect until railroad men
wake up out of the self-satisfied trance in which at present they
seem to be comfortably slumbering. Time was when our
forgetfulness of the public interests could be accounted for by our
own poverty and sufferings. But these unhappy conditions no longer
exist, for to-day we are probably as well paid and otherwise as well
provided for and equipped as any class of workers in the United
States. Nevertheless, when we are informed that in the year 1906
ten thousand people were killed and one hundred thousand injured
on American railroads, the knowledge does not seem to “give us
pause” in any way, or to ruffle our individual self-satisfaction; while
our organizations look at their surroundings silently and impassively
as the pyramids and obelisks look upon the Egyptian deserts.
But affairs have now come to such a pass on the roads that at last
we are imperatively called upon to answer questions and explain our
position. Our best friends are beginning to criticise us. They remind
us that interference with discipline is in reality an attempt to take
part in its administration, and that our unions were never intended
or organized for that purpose. For a great many years an educational
campaign has been in progress all over the country for the purpose
of reminding us of our duties and obligations to our unions. This
educational method has been extremely successful, and has brought
into being armies of laboring men thoroughly loyal and self-centred.
But the result of this system on the railroads has been so disastrous
to human life that at last we are beginning to realize that there is a
limit even to the pursuit of our individual well-being.
In paying attention, even at this late date, to the higher call of the
social conscience, we railroad men shall enter a new world with
brighter prospects and a wider horizon. The nobility of labor has
always been the proud watchword of American civilization. Let us be
watchful lest we forfeit our claim to share in this national distinction.
By recognizing our duties and responsibilities to society in our
treatment of these railroad problems, we shall finally take our place
in line with those who through sacrifice and high endeavor are
destined, in good time, to cut out their way to industrial freedom.
IV
LOYALTY
The relations, coöperative and otherwise, that exist between the men
and the management of a railroad are intimately connected with the
safety and efficiency of the service. Generally speaking, the public is
quite ignorant of the nature of these relations. The men and the
management may be working harmoniously with a constant
solicitude for the safety and well-being of the patrons of the road;
or, on the other hand, they may be intrenched in opposing camps,
mutually watchful and suspicious of each other, and more or less
forgetful of the wider and vastly more important interests of the
community at large. One way or the other, the public knows little or
nothing about the actual situation. The managers of railroads are not
in the habit of discussing such matters or of taking the public into
their confidence; our organizations of railroad men likewise pursue
the even tenor of their way. It seems to the writer that the time is
opportune for a candid discussion of this topic, with a view to the
education of public opinion, and in the general interest of travelers
by rail. A very brief preliminary survey of the situation will not be out
of place.
It is, of course, unnecessary to dwell upon the tremendous
importance of the railroads as a factor in our national life. Their
ramifications are like countless veins or arteries penetrating every
nook and corner of the continent. Backward and forward through
these arteries there passes and repasses an endless procession of
commerce and travel. In times gone by these huge systems of
national and international intercourse have, for the most part, been
directed and kept in working order by boards of management more
or less personal and irresponsible in their methods of administration.
But within a few years a great change has taken place. A new
partner, in the person of the railroad employee, has literally pushed
his way into the manager’s office. So important a factor has he now
become in the councils of a railroad corporation that hardly a move
can be made in the operating department without first consulting his
rights and wishes. Not only is the power and influence of the railroad
employee at the present day an important factor in railroad
management, but, in the opinion of competent judges, the time is
not far distant when manager and employee will meet on equal
terms and together legislate for the interests of all concerned. Now,
granting the ever-increasing power of the employee in framing the
rules and influencing the management, what is there to be said
about the division of responsibility? The question calls for the most
serious consideration of railroad men. Manifestly, it also concerns the
public interest; for, in criticising conditions on our railroads, public
opinion should be thoroughly informed concerning the situation, so
that in all fairness it may call for remedies and reform from the right
quarter.
At the present day, when an accident happens on a railroad and lives
of passengers are sacrificed by reason of the carelessness or neglect
of employees, practically the whole moral and financial responsibility
is immediately assumed by the management Heartfelt regret is at
once expressed by the highest authorities, the injured are visited by
sympathetic officials, and every conceivable kind of bill or expense is
at once acknowledged and paid. On the other hand we, the
employees, singly and collectively, ignore the whole business. We
simply stand back and let the press and the authorities figure out
reasons and remedies for themselves. We neither adopt resolutions
of sympathy nor pay out a single dollar to benefit the families of the
dead, or to alleviate the sufferings of the injured.
Considering the division of power, does this adjustment of
responsibility appeal to any fair-minded person? It has occurred to
some of us that if we or our organizations were assessed in hard
cash in proportion to our responsibility for some of these preventable
accidents, the casualty lists on our railroads would very quickly
assume microscopic proportions. An “Employees’ Liability Act” would,
of course, be looked upon as an absurdity; yet if unprejudiced
judges were to analyze a few of our accidents, they would quickly
conclude that the idea is sanely and soberly logical. They would
simply consider the matter in the light of fair and square taxation
with unmistakable and ample representation. It must not be
forgotten that the manifestation of power by railroad labor is to be
looked for not so much in the wording of schedules and agreements
as in what the managements of railroads under pressure feel
constrained to refrain from doing. The fairness and cogency of this
argument may not “be as deep as a well” nor “as wide as a church
door,” but I think, in the words of Mercutio, “’tis enough.” The
questions and considerations that arise in this way in regard to the
interests of the public, the management, and the men, are all
comprehensively included and can be profitably discussed under the
simple caption of loyalty,—on the one hand, loyalty of the men to
their employers, and, on the other, loyalty of the employers to the
men.
No sincere well-wisher of the railroad employee will question the
importance of the relation that exists, or that is supposed to exist,
on American railroads, between labor and loyalty. Volumes have
been written about loyalty in the abstract. For the most part
politicians and teachers of national morality and patriotism have
monopolized these arguments. The former would sink individualism
in the interest of the machine, the latter for the good of their
country. Granted the purity of their motives, the efforts of these
people are entirely praiseworthy; and yet the significance and
importance of loyalty in the industrial life of the nation can by no
means be said to be included in the teachings of either politician or
patriot. On American railroads, in particular, the question of the
loyalty of employees to the corporations and to the interests of the
public is vastly more important than a superficial glance at the
subject would lead one to suppose. Understanding as we do the
ever-increasing influence of the employee, the problem which we
have now to consider relates to what at the present day he is doing
with his power, and to what, with his ever-increasing importance, he
intends to do with it in the time to come. The future holds in it the
answer to these questions in terms of selfishness and abuse of
power, or in terms of loyalty to himself, the corporations, and the
public.
To attempt to give a definition of loyalty to apply to and to cover this
railroad business would simply be time and effort thrown away. It is
one thing to impress upon learned and critical readers that
individualism is in error and that loyalty is “willing and practical
devotion to a cause that is outside of the individual and larger than
he is.” It is quite another affair, and altogether more important, to
reproduce our philosophy in terms of actual conduct and behavior.
Not one railroad man in a thousand has either the time or the
mental training to study theories, and from the teachings of
professors to work out rules for his daily guidance; yet it is manifest
that the most useful and wholesome ideas can be put to little
practical utility in this railroad business until the employee is
aroused, and some practical interpretation of them brought home to
him with unmistakable sincerity and emphasis. While, therefore, it is
unnecessary to supply railroad men with a definition of loyalty, it will
be just as well to call attention to some of its most important
features.
Loyalty then, as applied to the railroad service, means the safety of
the traveling public so far as human safeguards can be depended
upon. Again, comparing the service as it actually is with what it
might be, loyalty means the elimination of numerous petty delays,
and at times serious blockades, which, at the present day, on many
railroads, are so annoying to the traveling public. This matter of
delays to passenger trains is quite an important feature, and it is
surprising how much the personality of the men and their
interpretation of loyalty to the public interest figure in the problem.
Furthermore, a stricter interpretation of loyalty by employees on any
given railroad can easily be shown to mean a positive reduction in
operating expenses to the tune of thousands upon thousands of
dollars. These additional resources placed at the disposal of the
management would mean, of course, funds wherewith to satisfy the

You might also like