100% found this document useful (2 votes)
22 views

Data Structures and Other Objects Using C++ 2nd edition by Michael Main ISBN 8129705826 978-8129705822 download

The document provides information on various editions of textbooks related to data structures and programming in C and C++. It includes links for downloading these textbooks and highlights the focus of the books on data types, object-oriented programming, and algorithm analysis. The fourth edition of 'Data Structures and Other Objects Using C++' emphasizes the use of the C++ Standard Template Library and offers a structured approach to understanding and implementing data types.

Uploaded by

vomorecht
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 (2 votes)
22 views

Data Structures and Other Objects Using C++ 2nd edition by Michael Main ISBN 8129705826 978-8129705822 download

The document provides information on various editions of textbooks related to data structures and programming in C and C++. It includes links for downloading these textbooks and highlights the focus of the books on data types, object-oriented programming, and algorithm analysis. The fourth edition of 'Data Structures and Other Objects Using C++' emphasizes the use of the C++ Standard Template Library and offers a structured approach to understanding and implementing data types.

Uploaded by

vomorecht
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/ 44

Data Structures and Other Objects Using C++ 2nd

edition by Michael Main ISBN 8129705826


978-8129705822 pdf download

https://ebookball.com/product/data-structures-and-other-objects-
using-c-2nd-edition-by-michael-main-
isbn-8129705826-978-8129705822-16344/

Explore and download more ebooks or textbooks


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

Data Structures And Other Objects Using C 4th Edition by


Michael Main, Walter Savitch 0132129485 9780132129480

https://ebookball.com/product/data-structures-and-other-objects-
using-c-4th-edition-by-michael-main-walter-
savitch-0132129485-9780132129480-17178/

Data Structures Using C 2nd Edition by Malik 0324782012


978-0324782011

https://ebookball.com/product/data-structures-using-c-2nd-edition-by-
malik-0324782012-978-0324782011-17222/

Data Structures and Problem Solving Using C++ 2nd edition


by MALIK ISBN 0324782012 978-0324782011

https://ebookball.com/product/data-structures-and-problem-solving-
using-c-2nd-edition-by-malik-isbn-0324782012-978-0324782011-16350/

Paediatric Radiology Rapid Reporting for FRCR Part 2B 1st


edition by Michael Paddock,Amaka Offiah 3030019659
9783030019655
https://ebookball.com/product/paediatric-radiology-rapid-reporting-
for-frcr-part-2b-1st-edition-by-michael-paddock-amaka-
offiah-3030019659-9783030019655-6052/
Principles of Data Structures Using C and C 1st Edition by
Vinu Das ISBN 8122418589 9788122418583

https://ebookball.com/product/principles-of-data-structures-using-c-
and-c-1st-edition-by-vinu-das-isbn-8122418589-9788122418583-15766/

Data Structures Algorithms and Applications in C++ With


Microsoft Compiler 2nd edition by Michael Goodrich,
Roberto Tamassia, David Mount ISBN B005FHM6X2
978-0470383278
https://ebookball.com/product/data-structures-algorithms-and-
applications-in-c-with-microsoft-compiler-2nd-edition-by-michael-
goodrich-roberto-tamassia-david-mount-
isbn-b005fhm6x2-978-0470383278-16544/

Problem Solving in Data Structures and Algorithms Using C


1st Edition by Hemant Jain ISBN 9352655915 9789352655915

https://ebookball.com/product/problem-solving-in-data-structures-and-
algorithms-using-c-1st-edition-by-hemant-jain-
isbn-9352655915-9789352655915-15768/

Problem Solving in Data Structures and Algorithms Using C


1st Edition by Hemant Jain ISBN 1540407306 9781540407306

https://ebookball.com/product/problem-solving-in-data-structures-and-
algorithms-using-c-1st-edition-by-hemant-jain-
isbn-1540407306-9781540407306-15866/

Data Structures Abstraction and Design Using Java 2nd


Edition by Elliot Koffman, Paul Wolfgang 0470128704
978-0470128701
https://ebookball.com/product/data-structures-abstraction-and-design-
using-java-2nd-edition-by-elliot-koffman-paul-
wolfgang-0470128704-978-0470128701-17228/
Preface i

DATA
STRUCTURES
&
OTHER
OBJECTS
Using C++ 4TH
EDITION

MICHAEL MAIN
Department of Computer Science
University of Colorado at Boulder

WALTER SAVITCH
Department of Computer Science
and Engineering
University of California, San Diego

Addison-Wesley

Boston Columbus Indianapolis New York San Francisco Upper Saddle River
Amsterdam Cape Town Dubai London Madrid Milan Munich Paris Montreal Toronto

Delhi Mexico City Sao Paulo Sydney Hong Kong Seoul Singapore Taipei Tokyo
ii Preface
Editor-in-Chief: Michael Hirsch Marketing Manager: Erin Davis
Editorial Assistant: Stephanie Sellinger Marketing Coordinator: Kathryn Ferranti
Managing Editor: Jeffrey Holcomb Art Director: Linda Knowles
Production Project Manager: Heather McNally Cover Designer: Elena Sidorova
Copy Editor: Sada Preisch Cover Artwork: © 2010 Stocksearch / Alamy
Proofreader: Genevieve d’Entremont Senior Manufacturing Buyer: Carol Melville

Access the latest information about all Pearson Addison-Wesley Computer Science titles from our World
Wide Web site: http://www.pearsonhighered.com/cs

The programs and applications presented in this book have been included for their instructional value. They
have been tested with care, but are not guaranteed for any particular purpose. The publisher does not offer any
warranties or representations, nor does it accept any liabilities with respect to the programs or applications.

Credits and acknowledgments borrowed from other sources and reproduced, with permission, in this textbook
appear on appropriate page within text.

UNIX® is a registered trademark in the United States and other countries, licensed exclusively through X-Open
Company, Ltd. Pez® is a registered trademark of Pez Candy, Inc.

Copyright © 2011, 2005, 2001, 1997 Pearson Education, Inc., publishing as Addison-Wesley, 501 Boylston
Street, Suite 900, Boston MA 02116. All rights reserved. Manufactured in the United States of America. This
publication is protected by Copyright, and permission should be obtained from the publisher prior to any
prohibited reproduction, storage in a retrieval system, or transmission in any form or by any means, electronic,
mechanical, photocopying, recording, or likewise. To obtain permission(s) to use material from this work,
please submit a written request to Pearson Education, Inc., Permissions Department, , 501 Boylston Street,
Suite 900, Boston MA 02116.

Many of the designations by manufacturers and seller to distinguish their products are claimed as trademarks.
Where those designations appear in this book, and the publisher was aware of a trademark claim, the
designations have been printed in initial caps or all caps.

Library of Congress Cataloging-in-Publication Data


Main, M. (Michael), 1956–
Data structures and other objects using C++ / Michael Main, Walter Savitch.-- 4th ed.
p. cm.
Includes index.
ISBN 978-0-13-212948-0 (pbk.)
1. C++ (Computer program language) 2. Data structures (Computer science) 3. Object-oriented
programming (Computer science) I. Savitch, Walter J., 1943– II. Title.

QA76.73.C153M25 2010
005.13’3—dc22
2009049328
CIP
1 2 3 4 5 6 7 8 9 10--CRS--14 13 12 11 10

ISBN 10: 0-13-212948-5


ISBN 13: 978-0-13-212948-0
Preface iii

Preface

T his book is written for a second course in computer science,


the CS 2 course at many universities. The text’s emphasis is on the
specification, design, implementation, and use of the basic data types that
normally are covered in a second-semester course. In addition, we cover a
range of important programming techniques and provide self-contained cov-
erage of abstraction techniques, object-oriented programming, big-O time
analysis of algorithms, and sorting.
We assume that the student has already had an introductory computer sci-
ence and programming class, but we do include coverage of those topics (such
as recursion and pointers) that are not always covered completely in a first
course. The text uses C++, but our coverage of C++ classes begins from
scratch, so the text may be used by students whose introduction to program-
ming was in C rather than C++. In our experience, such students need a brief
coverage of C++ input and output techniques (such as those provided in Appen-
dix F) and some coverage of C++ parameter types (which we provide in Chap-
ter 2). When C programmers are over the input/output hurdle and the parameter
hurdle (and perhaps a small “fear” hurdle), they can step readily into classes
and other object-oriented features of C++. As this indicates, there are several
pathways through the text that can be tailored to different backgrounds, includ-
ing some optional features for the student who comes to the class with a stron-
ger than usual background.

New to This Edition


The C++ Standard Template Library (STL) plays a larger role in our curricu-
lum than past editions, and we have added selected new material to support
this. For us, it’s important that our students understand both how to use the
STL classes in an application program and the possible approaches to imple- iii
iv Preface

menting these (or similar) classes. With this in mind, the primary changes that
you’ll find for this edition are:
• A new Section 2.6 that gives an early introduction to the Standard Tem-
plate Library using the pair class. We have been able to introduce students
to the STL here even before they have a full understanding of templates.
• An earlier introduction of the multiset class and STL iterators in Section
3.4. This is a good location for the material because the students have just
seen how to implement their first collection class (the bag), which is
based on the multiset.
• We continue to introduce the STL string class in Section 4.5, where it’s
appropriate for the students to implement their own string class with a
dynamic array.
• A new Section 5.6 that compares three similar STL classes: the vector, the
list, and the deque. At this point, the students have enough knowledge to
understand typical vector and list implementations.
• A first introduction to the STL algorithms appears in Section 6.3, and this
is now expanded on in Sections 11.2 (the heap algorithms) and 13.4
(expanded coverage of sorting and binary search in the STL).
• A new Section 8.4 provides typical implementation details for the STL
deque class using an interesting combination of dynamic arrays and point-
ers.
• A discussion of hash tables in the proposed TR1 expansions for the STL
is now given in Section 12.6.

Most chapters also include new programming projects, and you may also keep
an eye on our project web site, www.cs.colorado.edu/~main/dsoc.html, for new
projects as we develop them.

The Steps for Each Data Type


Overall, the fourth edition remains committed to the data types: sets, bags (or
multisets), sequential lists, ordered lists (with ordering from a “less than” opera-
tor), stacks, queues, tables, and graphs. There are also additional supplemental
data types such as a priority queue. Each of these data types is introduced fol-
lowing a consistent pattern:

Step 1: Understand the data type abstractly. At this level, a student gains an
understanding of the data type and its operations at the level of concepts and
pictures. For example, a student can visualize a stack and its operations of push-
ing and popping elements. Simple applications are understood and can be car-
ried out by hand, such as using a stack to reverse the order of letters in a word.

Step 2: Write a specification of the data type as a C++ class. In this step,
the student sees and learns how to write a specification for a C++ class that can
Preface v

implement the data type. The specification includes prototypes for the construc-
tors, public member functions, and sometimes other public features (such as an
underlying constant that determines the maximum size of a stack). The prototype
of each member function is presented along with a precondition/postcondition
contract that completely specifies the behavior of the function. At this level, it’s
important for the students to realize that the specification is not tied to any par-
ticular choice of implementation techniques. In fact, this same specification may
be used several times for several different implementations of the same data type.

Step 3: Use the data type. With the specification in place, students can write
small applications or demonstration programs to show the data type in use.
These applications are based solely on the data type’s specification, as we still
have not tied down the implementation.

Step 4: Select appropriate data structures, and proceed to design and


implement the data type. With a good abstract understanding of the data
type, we can select an appropriate data structure, such as a fixed-sized array, a
dynamic array, a linked list of nodes, or a binary tree of nodes. For many of our
data types, a first design and implementation will select a simple approach, such
as a fixed-sized array. Later, we will redesign and reimplement the same data
type with a more complicated underlying structure.
Since we are using C++ classes, an implementation of a data type will have
the selected data structures (arrays, pointers, etc.) as private member variables of
the class. With each implemented class, we stress the necessity for a clear under-
standing of the rules that relate the private member variables to an abstract notion
of the data type. We require each student to write these rules in clear English sen-
tences that we call the invariant of the abstract data type. Once the invariant is
written, students can proceed to implementing various member functions. The
invariant helps in writing correct functions because of two facts: (a) Each func-
tion (except constructors) knows that the invariant is true when the function
begins its work; and (b) each function (except the destructor) is responsible for
ensuring that the invariant is again true when the function finishes.
Step 5: Analyze the implementation. Each implementation can be analyzed
for correctness, flexibility (such as a fixed size versus dynamic size), and time
analysis of the operations (using big-O notation). Students have a particularly
strong opportunity for these analyses when the same data type has been imple-
mented in several different ways.

Where Will the Students Be at the End of the Course?


At the end of our course, students understand the data types inside out. They
know how to use the data types, they know how to implement them several
ways, and they know the practical effects of the different implementation
choices. The students can reason about efficiency with a big-O analysis and
vi Preface

argue for the correctness of their implementations by referring to the invariant


of the class.
One of the important lasting effects of the course is the specification, design,
and implementation experience. The improved ability to reason about programs
is also important. But perhaps most important of all is the exposure to classes that
are easily used in many situations. The students no longer have to write every-
thing from scratch. We tell our students that someday they will be thinking about
a problem, and they will suddenly realize that a large chunk of the work can be
done with a bag, or a stack, or a queue, or some such. And this large chunk of
work is work that they won’t have to do. Instead, they will pull out the bag or
stack or queue or some such that they wrote this semester—using it with no mod-
ifications. Or, more likely, they will use the familiar data type from a library of
standard data types, such as the C++ Standard Template Library. In fact, the
behavior of the data types in this text is a cut-down version of the Standard Tem-
plate Library, so when students take the step to the real STL, they will be on
familiar ground. And at that point of realization, knowing that a certain data type
is the exact solution he or she needs, the student becomes a real programmer.

Other Foundational Topics


Throughout the course, we also lay a foundation for other aspects of “real pro-
gramming,” with coverage of the following topics beyond the basic data struc-
tures material:

Object-oriented programming. The foundations of object-oriented program-


ming (OOP) are laid by giving students a strong understanding of C++ classes.
The important aspects of classes are covered early: the notion of a member
function, the separation into private and public members, the purpose of con-
structors, and a small exposure to operator overloading. This is enough to get
students going and excited about classes.
Further major aspects of classes are introduced when the students first use
dynamic memory (Chapter 4). At this point, the need for three additional items
is explained: the copy constructor, the overloaded assignment operator, and the
destructor. Teaching these OOP aspects with the first use of dynamic memory
has the effect of giving the students a concrete picture of dynamic memory as a
resource that can be taken and must later be returned.
Conceptually, the largest innovation of OOP is the software reuse that occurs
via inheritance. And there are certainly opportunities for introducing inheritance
right from the start of a data structures course (such as implementing a set class
as a descendant of a bag class). However, an early introduction may also result
in juggling too many new concepts at once, resulting in a weaker understanding
of the fundamental data structures. Therefore, in our own course we introduce
inheritance at the end as a vision of things to come. But the introduction to inher-
itance (Sections 14.1 and 14.2) could be covered as soon as copy constructors are
Preface vii

understood. With this in mind, some instructors may wish to cover Chapter 14
earlier, just before stacks and queues.
Another alternative is to identify students who already know the basics of
classes. These students can carry out an inheritance project (such as the ecosys-
tem of Section 14.2 or the game engine in Section 14.3) while the rest of the stu-
dents first learn about classes.

Templates. Template functions and template classes are an important part of


the proposed Standard Template Library, allowing a programmer to easily
change the type of the underlying item in a container class. Template classes
also allow the use of several different instantiations of a class in a single pro-
gram. As such, we think it’s important to learn about and use templates (Chapter
6) prior to stacks (Chapter 7), since expression evaluation is an important appli-
cation that uses two kinds of stacks.

Iterators. Iterators are another important part of the proposed Standard Tem-
plate Library, allowing a programmer to easily step through the items in a con-
tainer object (such as the elements of a set or bag). Such iterators may be
internal (implemented with member functions of the container class) or external
(implemented by a separate class that is a friend of the container class). We
introduce internal iterators with one of the first container classes (a sequential
list in Section 3.2). An internal iterator is added to the bag class when it is
needed in Chapter 6. At that point, the more complex external iterators also are
discussed, and students should be aware of the advantages of an external itera-
tor. Throughout the text, iterators provide a good opportunity for programming
projects, such as implementing an external bag iterator (Chapter 6) or using a
stack to implement an internal iterator of a binary search tree (Chapter 10).

Recursion. First-semester courses sometimes introduce students to recursion.


But many of the first-semester examples are tail recursion, where the final act of
the function is the recursive call. This may have given students a misleading
impression that recursion is nothing more than a loop. Because of this, we prefer
to avoid early use of tail recursion in a second-semester course. For example,
list traversal and other operations on linked lists can be implemented with tail
recursion, but the effect may reinforce wrong impressions about recursion (and
the tail recursive list operations may need to be unlearned when the students
work with lists of thousands of items, running into potential run-time stack
overflow).
So, in our second-semester course, we emphasize recursive solutions that use
more than tail recursion. The recursion chapter provides three examples along
these lines. Two of the examples—generating random fractals and traversing a
maze—are big hits with the students. In our class, we teach recursion (Chapter
9) just before trees (Chapter 10), since it is in recursive tree algorithms that recur-
sion becomes vital. However, instructors who desire more emphasis on recursion
can move that topic forward, even before Chapter 2.
viii Preface

In a course that has time for advanced tree projects (Chapter 11), we analyze
the recursive tree algorithms, explaining the importance of keeping the trees
balanced—both to improve worst-case performance, and to avoid potential run-
time stack overflow.

Searching and sorting. Chapters 12 and 13 provide fundamental coverage of


searching and sorting algorithms. The searching chapter reviews binary search
of an ordered array, which many students will have seen before. Hash tables
also are introduced in the search chapter. The sorting chapter reviews simple
quadratic sorting methods, but the majority of the chapter focuses on faster
algorithms: the recursive merge sort (with worst-case time of O(n log n)), Tony
Hoare’s recursive quicksort (with average-time O(n log n)), and the tree-based
heap sort (with worst-case time of O(n log n)). There is also a new introduction
to the C++ Standard Library sorting functions.

Advanced Projects
The text offers good opportunities for optional projects that can be undertaken
by a more advanced class or by students with a stronger background in a large
class. Particular advanced projects include the following:
• A polynomial class using dynamic memory (Section 4.6).
• An introduction to Standard Library iterators, culminating in an imple-
mentation of an iterator for the student’s bag class (Sections 6.3 through
6.5).
• An iterator for the binary search tree (Programming Projects in Chapter
10).
• A priority queue, implemented with a linked list (Chapter 8 projects), or
implemented using a heap (Section 11.1).
• A set class, implemented with B-trees (Section 11.3). We have made a
particular effort on this project to provide information that is sufficient for
students to implement the class without need of another text. In our
courses, we have successfully directed advanced students to do this
project as independent work.
• An inheritance project, such as the ecosystem of Section 14.2.
• An inheritance project using an abstract base class such as the game base
class in Section 14.3 (which allows easy implementation of two-player
games such as Othello or Connect Four).
• A graph class and associated graph algorithms from Chapter 15. This is
another case where advanced students may do work on their own.
Preface ix

C++ Language Features


C++ is a complex language with many advanced features that will not be
touched in a second-semester course. But we endeavor to provide complete
coverage for those features that we do touch. In the first edition of the text, we
included coverage of two features that were new to C++ at the time: the new
bool data type (Figure 2.1 on page 37) and static member constants (see
page 104). The requirements for using static member constants were changed in
the 1998 Standard, and we have incorporated this change into the text (the
constant must now be declared both inside and outside the class definition). The
other primary new feature from the 1998 Standard is the use of namespaces,
which were incorporated in the second edition. In each of these cases, these
features might not be supported in older compilers. We provide some assistance
in dealing with this (see Appendix E, “Dealing with Older Compilers”), and
some assistance in downloading and installing the GNU g++ compiler (see
Appendix K).

Flexibility of Topic Ordering


This book was written to allow instructors latitude in reordering the material to
meet the specific background of students or to add early emphasis to selected
topics. The dependencies among the chapters are shown on page xi. A line join-
ing two boxes indicates that the upper box should be covered before the lower
box.
Here are some suggested orderings of the material:

Typical course. Start with Chapters 1–10, skipping parts of Chapter 2 if the
students have a prior background in C++ classes. Most chapters can be covered
in a week, but you may want more time for Chapter 5 (linked lists), Chapter 6
(templates), Chapter 9 (recursion), or Chapter 10 (trees). Typically, we cover the
material in 13 weeks, including time for exams and extra time for linked lists
and trees. Remaining weeks can be spent on a tree project from Chapter 11, or
on binary search (Section 12.1) and sorting (Chapter 13).

Heavy OOP emphasis. If students cover sorting and searching elsewhere,


there will be time for a heavier emphasis on object-oriented programming. The
first four chapters are covered in detail, and then derived classes (Section 14.1)
are introduced. At this point, students can do an interesting OOP project, based
on the ecosystem of Section 14.2 or the games in Section 14.3. The basic data
structures are then covered (Chapters 5–8), with the queue implemented as a
derived class (Section 14.3). Finish up with recursion (Chapter 9) and trees
(Chapter 10), placing special emphasis on recursive member functions.

Accelerated course. Assign the first three chapters as independent reading in


the first week, and start with Chapter 4 (pointers). This will leave two to three
x Preface

extra weeks at the end of the term, so that students may spend more time on
searching, sorting, and the advanced topics (shaded on page xi.)
We also have taught the course with further acceleration by spending no lec-
ture time on stacks and queues (but assigning those chapters as reading).

Early recursion / early sorting. One to three weeks may be spent at the start
of class on recursive thinking. The first reading will then be Chapters 1 and 9,
perhaps supplemented by additional recursive projects.
If recursion is covered early, you may also proceed to cover binary search
(Section 12.1) and most of the sorting algorithms (Chapter 13) before introduc-
ing C++ classes.

Supplements via the Internet


The following supplemental materials for this text are available to all readers at
www.aw-bc.com/cssupport:
• Source code. All the C++ classes, functions, and programs that appear in
the book are available to readers.
• Errata. We have tried not to make mistakes, but sometimes they are
inevitable. A list of detected errors is available and updated as necessary.
You are invited to contribute any errors you find.

In addition, the following supplements are available to qualified instructors at


www.pearsonhighered.com/irc. Please contact your Addison-Wesley sales rep-
resentative, or send email to computing@aw.com, for information on how to
access them:
• PowerPoint lecture slides
• Exam questions
• Solutions to selected programming projects
• Sample assignments and lab exercises
• Suggested syllabi
Preface xi

Chapter Dependencies

At the start of the course, students should be comfortable writing functions and using
arrays in C++ or C. Those who have used only C should read Appendix F and pay
particular attention to the discussion of reference parameters in Section 2.4.

Chapter 1
Introduction

Chapters 2, 3, and 4.1–4.4


Classes
Container Classes
Pointers and Dynamic Memory Chapter 9
Recursion
Chapter 2 may be skipped by students
with a good background in C++ classes.

Chapter 5 Section 12.1


Linked Lists Binary Search
Sections 4.5–4.6
Projects:
String Class Sections 6.1–6.2
Templates Sec. 12.2–12.3
Polynomial Hash Tables
(Also requires
6.1–6.2)
Chapter 7
Sections 6.3–6.6 Stacks
More Templates
and Iterators Chapter 13
Sorting
Chapter 8 Chapter 10 (Heapsort also
Queues Trees needs Sec. 11.1)
Sections 14.1–14.2
Derived Classes
Section 11.1-2 Section 11.3 Chapter 15
Heaps B-Trees Graphs

Section 14.3
Virtual Methods Section 11.4
Detailed Tree Analysis
The shaded boxes provide
good opportunities for
advanced work.
xii Preface

Acknowledgments
We started this book while Walter was visiting Michael at the Computer Science
Department of the University of Colorado in Boulder. The work was completed
after Walter moved back to the Department of Engineering and Computer Sci-
ence at the University of California, San Diego. We are grateful to these institu-
tions for providing facilities, wonderful students, and interaction with congenial
colleagues.
Our students have been particularly helpful—nearly 5000 of our students
worked through the material, making suggestions, showing us how they learned.
We thank the reviewers and instructors who used the material in their data struc-
tures courses and provided feedback: Zachary Bergen, Cathy Bishop, Martin
Burtscher, Gina Cherry, Courtney Comstock, Stephen Davies, Robert Frohardt,
John Gillett, Mike Hendricks, Ralph Hollingsworth, Yingdan Huang, Patrick
Lynn, Ron McCarty, Shivakant Mishra, Evi Nemeth, Rick Osborne, Rachelle
Reese, and Nicholas Tran. The book was also extensively reviewed by Wolfgang
W. Bein, Bill Hankley, Michael Milligan, Paul Nagin, Jeff Parker, Andrew L.
Wright, John R. Rose, and Evan Zweifel. We thank these colleagues for their
excellent critique and their encouragement.
Thank you to Lesley McDowell and Chris Schenk, who are pleasant and
enthusiastic every day in the computer science department at the University of
Colorado. Our thanks also go to the editors and staff at Addison-Wesley. Heather
McNally’s work has encouraged us and provided us with smooth interaction on
a daily basis and eased every step of the production. Karin Dejamaer and Jessica
Hector provided friendly encouragement in Boulder, and we offer our thanks to
them. We welcome and appreciate Michael Hirsch in the role of editor, where he
has shown amazing energy, enthusiasm, and encouragement. Finally, our origi-
nal editor, Susan Hartman, has provided continual support, encouragement, and
direction—the book wouldn’t be here without you!
In addition to the work and support from those who put the book together, we
thank those who offered us daily interest and encouragement. Our deepest thanks
go to Holly Arnold, Vanessa Crittenden, Meredith Boyles, Suzanne Church, Erika
Civils, Lynne Conklin, Andrzej Ehrenfeucht, Paul Eisenbrey, Skip Ellis, John
Kennedy, Rick Lowell, George Main, Mickey Main, Jesse Nuzzi, Ben Powell,
Marga Powell, Megan Powell, Grzegorz Rozenberg, Hannah, Timothy, and
Janet.

Michael Main Walter Savitch


main@colorado.edu wsavitch@ucsd.edu
Boulder, Colorado San Diego, California
Contents xv

Contents

CHAPTER 1 THE PHASES OF SOFTWARE DEVELOPMENT


1.1 Specification, Design, Implementation 3
Design Concept: Decomposing the Problem 4
Preconditions and Postconditions 6
Using Functions Provided by Other Programmers 8
Implementation Issues for the ANSI/ISO C++ Standard 8
C++ Feature: The Standard Library and the Standard Namespace 9
Programming Tip: Use Declared Constants 11
Clarifying the Const Keyword
Part 1: Declared Constants 12
Programming Tip: Use Assert to Check a Precondition 12
Programming Tip: Use EXIT_SUCCESS in a Main Program 14
C++ Feature: Exception Handling 14
Self-Test Exercises for Section 1.1 14
1.2 Running Time Analysis 15
The Stair-Counting Problem 15
Big-O Notation 21
Time Analysis of C++ Functions 23
Worst-Case, Average-Case, and Best-Case Analyses 25
Self-Test Exercises for Section 1.2 25
1.3 Testing and Debugging 26
Choosing Test Data 26
Boundary Values 27
Fully Exercising Code 28
Debugging 28
Programming Tip: How to Debug 28
Self-Test Exercises for Section 1.3 29
Chapter Summary 30
Solutions to Self-Test Exercises 31

CHAPTER 2 ABSTRACT DATA TYPES AND C++ CLASSES


2.1 Classes and Members 34
Programming Example: The Throttle Class 34
Clarifying the Const Keyword
Part 2: Constant Member Functions 38
Using a Class 39
A Small Demonstration Program for the Throttle Class 40
Implementing Member Functions 42
Member Functions May Activate Other Members 44
Programming Tip: Style for Boolean Variables 44
Self-Test Exercises for Section 2.1 45
xvi Contents

2.2 Constructors 45
The Throttle’s Constructor 46
What Happens If You Write a Class with No Constructors? 49
Programming Tip: Always Provide Constructors 49
Revising the Throttle’s Member Functions 49
Inline Member Functions 49
Programming Tip: When to Use an Inline Member Function 50
Self-Test Exercises for Section 2.2 51
2.3 Using a Namespace, Header File, and Implementation File 51
Creating a Namespace 51
The Header File 52
Describing the Value Semantics of a Class Within the Header File 56
Programming Tip: Document the Value Semantics 57
The Implementation File 57
Using the Items in a Namespace 59
Pitfall: Never Put a Using Statement Actually in a Header File 60
Self-Test Exercises for Section 2.3 62
2.4 Classes and Parameters 63
Programming Example: The Point Class 63
Default Arguments 65
Programming Tip: A Default Constructor Can Be Provided by Using Default
Arguments 66
Parameters 67
Pitfall: Using a Wrong Argument Type for a Reference Parameter 70
Clarifying the Const Keyword
Part 3: Const Reference Parameters 72
Programming Tip: Use const Consistently 73
When the Type of a Function’s Return Value Is a Class 73
Self-Test Exercises for Section 2.4 74
2.5 Operator Overloading 74
Overloading Binary Comparison Operators 75
Overloading Binary Arithmetic Operators 76
Overloading Output and Input Operators 77
Friend Functions 80
Programming Tip: When to Use a Friend Function 81
The Point Class—Putting Things Together 82
Summary of Operator Overloading 85
Self-Test Exercises for Section 2.5 85
2.6 The Standard Template Libary and the Pair Class 86
Chapter Summary 87
Solutions to Self-Test Exercises 88
Programming Projects 90
Contents xvii

CHAPTER 3 CONTAINER CLASSES


3.1 The Bag Class 97
The Bag Class—Specification 98
C++ Feature: Typedef Statements Within a Class Definition 99
C++ Feature: The std::size_t Data Type 100
Clarifying the Const Keyword
Part 4: Static Member Constants 104
Older Compilers Do Not Support Initialization of Static Member Constants 105
The Bag Class—Documentation 105
Documenting the Value Semantics 107
The Bag Class—Demonstration Program 107
The Bag Class—Design 109
Pitfall: The value_type Must Have a Default Constructor 110
The Invariant of a Class 110
The Bag Class—Implementation 111
Pitfall: Needing to Use the Full Type Name bag::size_type 112
Programming Tip: Make Assertions Meaningful 112
C++ Feature: The Copy Function from the C++ Standard Library 116
The Bag Class—Putting the Pieces Together 117
Programming Tip: Document the Class Invariant in the Implementation File 117
The Bag Class—Testing 121
Pitfall: An Object Can Be an Argument to Its Own Member Function 121
The Bag Class—Analysis 122
Self-Test Exercises for Section 3.1 123
3.2 Programming Project: The Sequence Class 124
The Sequence Class—Specification 124
The Sequence Class—Documentation 127
The Sequence Class—Design 127
The Sequence Class—Pseudocode for the Implementation 130
Self-Test Exercises for Section 3.2 132
3.3 Interactive Test Programs 133
C++ Feature: Converting Input to Uppercase Letters 134
C++ Feature: The Switch Statement 138
Self-Test Exercises for Section 3.3 138
3.4 The STL Multiset Class and Its Iterator 139
The Multiset Template Class 139
Some Multiset Members 140
Iterators and the [...) Pattern 140
Pitfall: Do Not Access an Iterator’s Item After Reaching end( ) 142
Testing Iterators for Equality 143
Other Multiset Operations 143
Invalid Iterators 144
Clarifying the Const Keyword
Part 5: Const Iterators 144
Pitfall: Changing a Container Object Can Invalidate Its Iterators 144
Self-Test Exercises for Section 3.4 145
Chapter Summary 146
Solutions to Self-Test Exercises 146
Programming Projects 149
Random documents with unrelated
content Scribd suggests to you:
He could see that an immense avalanche was sweeping down the
mountain-side, with his house, that sheltered his daughter, directly
in the path of it.
As he approached, he heard the roar and thunder of the avalanche
as it swept everything in its path before it. He knew he was
powerless, as he could not reach the house in time, and it only
meant the certain destruction of himself if he could; and for that
reason he could do nothing but be a spectator of the tragedy which
would enact itself before his eyes in a few short minutes.
At this juncture a miracle, so it seemed to the distracted father,
occurred.
His eye chanced to fall on the Power mast on the top of his house.
He could see the iridium aerial wires which were pointing East-by-
North suddenly become red-hot; then yellow, then white-hot, at the
same time he felt that some enormous etheric disturbance had been
set up, as sparks were flying from all metallic parts of his machine.
When he looked again at the aerial on his house, he saw that a
piece of the Communico mast, which apparently had fallen at the
base of the Power mast, and which was pointing directly at the
avalanche, was streaming gigantic flames which grew longer and
longer, and gave forth shriller and shriller sounds. The flames which
streamed from the end of the Communico-mast-piece looked like a
tremendously long jet of water leaving its nozzle under pressure.
For about five hundred yards from the tip of the Communico mast it
was really only a single flame about fifteen feet in diameter. Beyond
that it spread out fan-wise. He could also see that the entire Power
mast, including the Communico mast, was glowing in a white heat,
showing that immense forces were directed upon it. By this time the
avalanche had almost come in contact with the furthest end of the
flames.
Here the unbelievable happened. No sooner did the avalanche touch
the flames, than it began turning to water. It seemed that the heat
of those flames was so intense and powerful that had the avalanche
been a block of solid ice it would not have made any marked
difference. As it was, the entire avalanche was being reduced to hot
water and steam even before it reached the main shaft of the flame.
A torrent of hot water rushing down the mountain was all that
remained of the menacing avalanche; and while the water did some
damage, it was insignificant.
For several minutes after the melting of the avalanche the flames
continued to stream from the aerial, and then faded away.
Ralph 124C 41+, in New York, four thousand miles distant, had
turned off the power of his ultra-generator.
He climbed down his glass ladder, stepped over to the Telephot, and
found that Alice had already reached her instrument.
She looked at the man smiling in the faceplate of the Telephot
almost dumb with an emotion that came very near to being
reverence.
The voice that reached him was trembling and he could see her
struggle for coherent speech.
"It's gone," she gasped; "what did you do?"
"Melted it."
"Melted it!" she echoed, "I—"
Before she could continue, the door in her room burst violently open
and in rushed a fear-stricken old man. Alice flew to his arms, crying,
"Oh father—"
Ralph 124C 41+ with discretion disconnected the Telephot.

2
TWO FACES
Feeling the need of fresh air and quiet after the strain of the last half
hour, Ralph 124C 41+ climbed the few steps leading from the
laboratory to the roof and sat down on a bench beneath the
revolving aerial.
The hum of the great city came faintly from below. Aeroflyers dotted
the sky. From time to time, trans-oceanic or trans-continental air
liners passed with a low vibration, scarcely audible.
At times a great aircraft would come close—within 500 yards
perhaps—when the passengers would crane their necks to get a
good view of his "house," if such it could be called.
Indeed, his "house," which was a round tower, 650 feet high, and
thirty in diameter, built entirely of crystal glass-bricks and
steelonium, was one of the sights of New York. A grateful city,
recognizing his genius and his benefits to humanity, had erected the
great tower for him on a plot where, centuries ago, Union Square
had been.
The top of the tower was twice as great in circumference as the
main building, and in this upper part was located the research
laboratory, famous throughout the world. An electromagnetic tube
elevator ran down the tower on one side of the building, all the
rooms being circular in shape, except for the space taken up by the
elevator.
Ralph, sitting on the roof of his tower, was oblivious to all about him.
He was unable to dismiss from his mind the lovely face of the girl
whose life he had just been the means of saving. The soft tones of
her voice were in his ears. Heretofore engrossed in his work, his
scientific mind had been oblivious to women. They had played no
part in his life. Science had been his mistress, and a laboratory his
home.
And now, in one short half hour, for him the whole world had
become a new place. Two dark eyes, a bewitching pair of lips, a
voice that had stirred the very core of his being—
Ralph shook himself. It was not for him to think of these things, he
told himself. He was but a tool, a tool to advance science, to benefit
humanity. He belonged, not to himself, but to the Government—the
Government, who fed and clothed him, and whose doctors guarded
his health with every precaution. He had to pay the penalty of his +.
To be sure, he had everything. He had but to ask and his wish was
law—if it did not interfere with his work.
There were times he grew restive under the restraint, he longed to
smoke the tobacco forbidden him by watchful doctors, and to
indulge in those little vices which vary the monotony of existence for
the ordinary individual. There were times when he most ardently
wished that he were an ordinary individual.
He was not allowed to make dangerous tests personally, thereby
endangering a life invaluable to the Government. That institution
would supply him with some criminal under sentence of death who
would be compelled to undergo the test for him. If the criminal were
killed during the experiment, nothing was lost; if he did not perish,
he would be imprisoned for life.
Being a true scientist, Ralph wanted to make his own dangerous
experiments. Not to do this took away the very spice of life for him,
and on occasion he rebelled. He would call up the Planet Governor,
the ruler of 15 billion human beings, and demand that he be relieved
of his work.
"I can't stand it," he would protest. "This constraint which I am
forced to endure maddens me, I feel that I am being hampered."
The Governor, a wise man, and a kindly one, would often call upon
him in person, and for a long time they would discuss the question,
Ralph protesting, the Governor reasoning with him.
"I am nothing but a prisoner," Ralph stormed once.
"You are a great inventor," smiled the Governor, "and a tremendous
factor in the world's advancement. You are invaluable to humanity,
and—you are irreplaceable. You belong to the world—not to
yourself."
Many times in the past few years he recalled, had the two been over
the same ground, and many times had the diplomatic Governor
convinced the scientist that in sacrifice of self and devotion to the
world's future lay his great reward.
The voice of his manservant interrupted his reverie.
"Sir," he said, "your presence in the transmission-room would be
appreciated."
"What is it?" asked the scientist, impatient at the interruption.
"Sir, the people have heard all about the Switzerland incident of an
hour ago and desire to show their appreciation."
"Well, I suppose I must submit," the inventor rather wearily
responded, and both stepped over into the round steel car of the
electromagnetic elevator. The butler pressed one of the 28 ivory
buttons and the car shot downward, with neither noise nor friction.
There were no cables or guides, the car being held and propelled by
magnetism only. At the 22nd floor the car stopped, and Ralph
stepped into the transmission-room.
No sooner had he entered than the deafening applause of hundreds
of thousands of voices greeted him, and he was forced to put his
hands to his ears to muffle the sound.
Yet, the transmission-room was entirely empty.
Every inch of the wall, however, was covered with large-sized
Telephots and loud-speaking devices.
Centuries ago, when people tendered some one an ovation, they
would all assemble in some great square or large hall. The celebrity
would have to appear in person, else there would be no ovation—
truly a clumsy means. Then, too, in those years, people at a distance
could neither see nor hear what was going on throughout the world.
Ralph's ovation was the result of the enterprise of a news "paper"
which had issued extras about his exploit, and urged its readers to
be connected with him at 5 p.m.
Naturally everyone who could spare the time had called the
Teleservice Company and asked to be connected with the inventor's
trunk-line—and this was the result.
Ralph 124C 41 + stepped into the middle of the room and bowed to
the four points of the compass, in order that all might see him
perfectly. The noise was deafening, and as it rather grew in volume
than diminished he beseechingly held up his hands. In a few
seconds the applause ceased and some one cried—"Speech!"
Ralph spoke briefly, thanking his audience for their interest, and
touching but lightly upon his rescue of the young Swiss girl, begged
his hearers to remember that in no way had he risked his life and
therefore could scarcely be called a hero.
Vociferous cries of "No, no," told him that no one shared his humble
opinion of the achievement.
It was at this juncture that Ralph's attention was caught by two
persons in the audience. There were so many thousands of faces on
each plate that nearly every countenance was blurred, due to their
constant movement. (He himself, however, was clearly seen by
them, as each one had switched on their "reversers," making it
possible to see only the object at the end of the line.)
To Ralph, the shifting, clouded appearance of his audience was a
commonplace.
This was not the first time that he had been called upon to receive
the thanks of the multitude for some unusual service he had
rendered them, or some surprising scientific feat he had successfully
accomplished. While realizing that he must of necessity yield to
public adulation, it more or less bored him.
He was not particularly interested in the crowd, either collectively or
individually, and as there were so many faces crowded into each
faceplate he made no attempt to distinguish friends from strangers.
Yet there were two faces among the numerous Telephot faceplates
that Ralph in making his brief speech, found his eyes returning to
again and again. Each occupied the whole of a respective faceplate
and while dissimilar in appearance, nevertheless were markedly alike
in expression. It was as if they were studying this great scientist,
endeavoring to fix in their minds a permanent picture of him. Ralph
sensed no animosity in their steady almost hypnotic gaze and yet
they were curiously apart from the enthusiastic throng. He felt as
though he were, to both of them, under the microscope.
One of the faces was that of a man in his early thirties. It was a
handsome face, though, to the close observer, the eyes were set just
a trifle too near together, and the mouth betrayed cunning and had
a touch of viciousness.
The other was not a Terrestrial, but a visiting Martian. It was
impossible to mistake the distinctly Martian cast of countenance. The
great black horse eyes in the long, melancholy face, the elongated
slightly pointed ears were proof enough. Martians in New York were
not sufficiently rare to excite any particular comment. Many made
that city their permanent home, although the law on the planet
Earth, as well as on Mars, which forbade the intermarriage of
Martians and Terrestrials, kept them from flocking earthwards in any
great numbers.
In the applause that followed the conclusion of Ralph's words the
incident of the two pairs of scrutinizing eyes vanished from his
thoughts. But his sub-conscious self, that marvelous mechanism
which forgets nothing, had photographed them indelibly. With the
plaudits of the crowd still ringing he bowed and left the room.
He went, via the elevator, directly to his library, and asked for the
afternoon news.
His man handed him a tray on which lay a piece of material as large
as a postage stamp, as transparent and flexible as celluloid.
"What edition is this?" he asked.
"The 5 o'clock New York News,[1] sir."
Ralph took the "News" and placed it in a metal holder which was
part of the hinged door of a small box. He closed the door and
turned on a switch on the side of the box. Immediately there
appeared on the opposite white wall of the room, a twelve-column
page of the New York News and the scientist, leaning back in his
chair, proceeded to read.
The New York News was simply a microscopic reduction of a page,
which, when enlarged by a powerful lens, became plainly visible.
Moreover, each paper had eight "pages," in separate sheets, as was
the fashion centuries ago, but eight pages literally on top of each
other. The printing process was electrolytic, no ink whatsoever being
used in the manufacture of the "newspaper." This process was
invented in 1910 by an Englishman, and improved by the American
64L 52 in 2031, who made it possible to "print" in one operation
eight different subjects, one on top of another.
These eight impressions could be made visible only by subjecting the
"paper" to different colors, the color rays bringing out the different
prints. The seven colors of the rainbow were used, while white light
was employed to show reproduced photographs, etc., in their natural
colors. With this method it was possible to "print" a "newspaper,"
fully ten times as large in volume as any newspaper of the 21st
century, on a piece of film, the size of a postage-stamp.
Each paper published an edition every 30 minutes, and if one did not
possess a projector, one could read the "paper" by inserting the
News in a holder beneath a powerful lens which one carried in one's
pocket, folded when not in use. To read the eight different pages, a
revolving color screen was placed directly underneath the lens, to
bring out the different colors necessary to read the "paper."
Ralph, 124C 41+, glancing over the head-lines of his News, saw that
considerable space was given to his latest exploit, the paper showing
actual photographs of the Swiss Alpine scene, which a
correspondent had taken as the avalanche thundered down the
mountain. The photographs had been sent by Teleradiograph
immediately after the occurrence in Switzerland, and the News had
printed them in all the natural colors twenty minutes after Ralph had
turned off the ultra-power in New York.
These photographs seemed to be the only thing that interested
Ralph, as they showed the house and the surrounding Alps. These,
with the monstrous avalanche in progression photographed and
reproduced in the natural colors, were very impressive.
Presently he revolved the color screen of his projector to green—the
technical page of the News—to him the most interesting reading in
the paper.
He soon had read all that interested him, and as there was still an
hour before dinner time he began to "write" his lecture: "On the
prolongation of animal life by π-Rays."
He attached a double leather head-band to his head. At each end of
the band was attached a round metal disc that pressed closely on
the temples. From each metal disc an insulated wire led to a small
square box, the Menograph, or mind-writer.
He then pressed a button and a low humming was heard;
simultaneously two small bulbs began to glow with a soft green
fluorescent light. Grasping a button connected with a flexible cord to
the Menograph, he leaned back in his chair.
After a few minutes' reflection he pressed the button, and at once a
wave line, traced in ink, appeared on a narrow white fabric band,
the latter resembling a telegraph recorder tape.
The band which moved rapidly, was unrolled from one reel and
rolled up on another. Whenever the inventor wished to "write" down
his thoughts, he would press the button, which started the
mechanism as well as the recording tracer.
(Below is shown the record of a Menograph, the piece of tape being
actual size.
Where the wave line breaks, a new word or sentence commences;
the three words shown are the result of the thought which expresses
itself in the words, "In olden times." ...)
The Menograph was one of Ralph 124C 41+'s earliest inventions,
and entirely superseded the pen and pencil. It was only necessary to
press the button when an idea was to be recorded and to release
the button when one reflected and did not wish the thought-words
recorded.
Instead of writing a letter, one sent the recorded Menotape, and
inasmuch as the Menolphabet was universal and could be read by
anyone—children being taught it at an early age—it was considered
that this invention of Ralph's was one of his greatest gifts to
humanity: Twenty times as much work could be done by means of
the Menograph as could be done by the old-fashioned writing, which
required considerable physical effort. Typewriters soon disappeared
after its invention. Nor was there any use for stenographers, as the
thoughts were written down direct on the tape, which was sent out
as a letter was sent centuries ago.
As was his custom in the evening he worked for some hours in the
laboratory, and retired at midnight. Before he fell asleep he attached
to his head a double leather head-band with metal temple plates,
similar to the one used in connection with the Menograph.
He then called for his man, Peter, and told him to "put on" Homer's
Odyssey for the night.
Peter went down to the library on the 15th floor, and took down
from a shelf a narrow box, labeled Odyssey, Homer. From this he
extracted a large but thin reel on which was wound a long narrow
film. This film was entirely black but for a white transparent wave-
line running through the center of it.
Peter returning to Ralph's bedroom placed the reel containing the
film in a rack and introduced the end of the film into the
Hypnobioscope. This wonderful instrument, invented by Ralph,
transmitted the impulses of the wave-line direct to the brain of the
sleeping inventor, who thus was made to "dream" the Odyssey.
It had been known for centuries that the brain could be affected
during sleep by certain processes. Thus one could be forced to
dream that a heavy object was lying on one's chest, if such an
object was placed on the sleeper's chest. Or one could be forced to
dream that one's hand was being burnt or frozen, simply by heating
or cooling the sleeper's hand.
It remained to Ralph, however, to perfect the Hypnobioscope, which
transmitted words direct to the sleeping brain, in such a manner that
everything could be remembered in detail the next morning.
This was made possible by having the impulses act directly and
steadily on the brain. In other words, it was the Menograph
reversed, with certain additions.
Thus, while in a passive state, the mind absorbed the impressions
quite readily and mechanically and a story "read" by means of the
Hypnobioscope left a much stronger impression than if the same
story had been read while conscious.
For thousands of years humanity had wasted half of its life during
sleep—the negative life. Since Ralph's invention, all this was
changed. Not one night was lost by anyone if anywhere possible,
conditions permitting. All books were read while one slept. Most of
the studying was done while one slept. Some people mastered ten
languages, during their sleep-life. Children who could not be
successfully taught in school during their hours of consciousness,
became good scholars if the lessons were repeated during their
sleep-life.
The morning "newspapers" were transmitted to the sleeping
subscribers by wire at about 5 a.m. The great newspaper offices had
hundreds of Hypnobioscopes in operation, the subscriber's wire
leading to them. The newspaper office, notified by each subscriber
what kind of news is desirable, furnished only such news.
Consequently, when the subscriber woke up for breakfast he already
knew the latest news, and could discuss it with his family, the
members of which were also connected with the newspaper
Hypnobioscope.

FOOTNOTES:
[1] At the time this was written there was no newspaper of that
name.

3
DEAD OR ALIVE?
An apologetic cough came through the entrance to the laboratory. It
was nearing one o'clock of the following day.
Several minutes later it was repeated, to the intense annoyance of
the scientist, who had left orders that he was not to be interrupted
in his work under any circumstances.
At the third "ahem!" he raised his head and stared fixedly at the
empty space between the doorjambs. The most determined optimist
could not have spelled welcome in that look.
Peter, advancing his neck around the corner until one eye met that
of his master, withdrew it hastily.
"Well, what is it?" came from the laboratory, in an irritated harsh
voice.
Peter, in the act of retreating on tiptoe, turned, and once more
cocked a solitary eye around the door-jamb. This one feature had
the beseeching look of a dog trying to convey by his expression that
not for worlds would he have got in the way of your boot.
"Beg pardon, sir, but there's a young—"
"Won't see him!"
"But, sir, it's a young lady—"
"I'm busy, get out!"
Peter gulped desperately. "The young lady from—"
At this moment Ralph pressed a button nearby, an electromagnet
acted, and a heavy plate glass door slid down from above, almost
brushing Peter's melancholy countenance, terminating the
conversation summarily.
Having secured himself against further interruption Ralph returned
to the large glass box over which he had been working, and in which
one could see, through greenish vapors, a dog, across whose heart
was strapped a flat glass box filled with a metal-like substance.
The substance in the box was Radium-K. Radium, which had been
known for centuries, had the curious property of giving out heat for
thousands of years without disintegrating and without apparently
obtaining energy from any outside source.
In 2009, Anatole M610 B9, the great French physicist, found that
Radium obtained all its energy from the ether of space and proved
that Radium was one of the few substances having a very strong
affinity for the ether. Radium, he found, attracted the ether violently
and the latter surging back and forward through the Radium became
charged electrically, presenting all the other well known phenomena.
Anatole M610 B9 compared the action of Radium on the ether with
that of a magnet acting upon a piece of iron. He proved this theory
by examining a piece of pure metallic Radium in an etherless space,
whereupon it lost all its characteristics and acted like a piece of
ordinary metal.
Radium-K, as used by Ralph, was not pure Radium, but an alloy
composed of Radium and Argonium. This alloy exhibited all the usual
phenomena of pure Radium and produced great heat, but did not
create burns on animal tissue. It could be handled freely and without
danger.
The dog lying in the glass box had been "dead" for three years. Just
three years previous, in the presence of twenty noted scientists
Ralph 124C 41+ had exhibited a live dog and had proceeded to drain
off all its blood till the dog was pronounced quite dead and its heart
had stopped beating. Thereupon he had refilled the empty blood
vessels of the animal with a weak solution of Radium-K bromide, and
the large artery through which the solution was pumped into the
body had been closed.
The flat box containing Radium-K was then strapped over the dog's
heart and it was placed in the large glass case. The latter was filled
with Permagatol, a green gas having the property of preserving
animal tissue permanently and indefinitely. The purpose of the box
containing Radium-K was to keep the temperature of the dog's body
at a fixed point.
After the case was completely filled with gas, the glass cover was
sealed in such a manner that it was impossible to open the case
without breaking the seals. The scientists had agreed to return after
a lapse of three years to witness the opening of the box.
There were several delicate instruments inside the box and these
were connected by means of wires to recording instruments on the
side, and these Ralph inspected twice each day. Throughout the
three years the "dead" dog had never stirred a muscle. His
temperature had not varied 1/100 of a degree and his respiratory
functions had shown no signs of life. To all intents and purposes the
dog was "dead."
The time was close at hand for the final stages of what Ralph
considered to be his greatest experiment. Three years ago when he
faced his fellow scientists at the end of the first stage of this work,
he electrified them by announcing that he expected to prove that
this dog, which they had all pronounced "dead," could be restored to
life, unharmed, unchanged, with no more effects upon the dog's
spirits, habits, and nature, than had the animal taken but a short
nap.
For three years this experiment of Ralph 124C 41+ had been the
subject of innumerable scientific papers, had been discussed
intermittently in the newspapers and the date of the final phase of
the great experiment was fixed in the mind of every human being on
the planet.
If the experiment succeeded it meant the prolongation of human life
over greater periods of the earth's history than had ever been
possible. It meant that premature death except through accident
would be ended.
Would he succeed? Had he attempted the impossible? Was he
challenging Nature to a combat only to be worsted?
These thoughts obtruded themselves into his consciousness as he
began the preparations for the great test of the afternoon. He
pumped out the Permagatol from the box until the green vapor had
completely disappeared. With infinite care he then forced a small
quantity of oxygen into the box. The instruments recording the
action of the respiratory organs indicated that the oxygen reaching
the dog's lungs had stimulated respiration.
This being all he could do for the present, he pressed the button
that raised the glass barrier, and summoned Peter by means of
another button.
That individual, looking a trifle more melancholy than usual,
responded at once.
"Well my boy," said Ralph good-humoredly, "the stage is all set for
the experiment that will set the whole world by the ears.—But you
don't look happy, Peter. What's troubling your dear old soul?"
Peter, whose feelings had evidently been lacerated when the door
had been lowered in his face, replied with heavy dignity.
"Beg pardon, sir, but the young lady is still waiting."
"What young lady?" asked Ralph.
"The young lady from Switzerland, sir."
"The—which?"
"The young lady from Switzerland, sir, and her father, sir. They've
been waiting half an hour."
If a bomb had exploded that instant Ralph could not have been
more astounded.
"She's here—and you didn't call me? Peter, there are times when I
am tempted to throw you out—"
"Pardon sir," replied Peter firmly, "I made bold to assume that you
might be interested in the young lady's arrival, and presumed to step
into the laboratory to so inform—"
But his master had gone, shedding his laboratory smock as he went.
Peter, gathering his dignity about him as a garment, reached the
doorway in time to see the elevator slide downwards out of sight.
And in it, Ralph, his heart thumping in a most undignified way, was
acting more like a schoolboy than a master of science. He twitched
at his tie with one hand and smoothed his hair with the other,
peering into the elevator's little mirror anxiously. Discovering a
smudge on his cheek he checked the car between floors while he
wiped away the spot with his handkerchief.
When he reached the reception room he sprang from the elevator
eagerly and hurried in. Seated by one of the windows were Alice
212B 423 and her father. Both turned as he entered, and the girl
rose to her feet and with a charming gesture held out both hands.
"We just had to come," she said prettily, and in perfect English. "You
didn't give us an opportunity to thank you yesterday, and anyhow,
we felt that telephot thanks were not nearly so nice. That is, father
thought we really ought to come in person—of course, I did, too. I
wanted to see you ever so much"—she broke off, and then, realizing
the implication of her words, went on hastily with reddened cheeks
and downcast eyes, "I mean, to—to thank you, you know."
"It was wonderful of you," he declared still holding her two hands,
and utterly unmindful of the fact that she was gently trying to
disengage them. Indeed, he was not conscious of anyone or
anything but her, until the voice of her father brought him to the
realization that there was someone else in the room.
"We need no introduction I think," said the gentleman, "but I am
James 212B 422 and I must ask you to pardon our intrusion upon a
busy scientist's time, but I felt that we should come personally to
thank you for the great service you have done us both. She is my
one daughter, sir, and I love her dearly—dearly—"
"I can quite understand that," said Ralph with an unconscious ardor
that caused Alice, who had completely recovered from her
momentary confusion, to dimple and blush delightfully.
"I'm afraid, father dear," she said, "that we are keeping a busy man
too long. Your man," she added, turning to Ralph, "said you were
engaged in a wonderful experiment, and could not be disturbed."
"Busy? Not at all," said Ralph gracelessly. "You should not have been
kept waiting one moment, and I am very indignant with Peter for not
breaking down the door. He should have known, when he saw you,
that you were not to wait."
"Oh, please, don't scold him because of me," said Alice, not,
however, at all displeased with the implied compliment.
"I didn't know yesterday that you spoke English," he said, "so I used
the language-rectifier, but I see that you speak it perfectly. That is a
great relief to me, I assure you, for I speak French very indifferently.
But tell me," he continued, "how did you get here so soon? The
afternoon transatlantic aeroliner is not due yet, and it can hardly be
twenty-four hours since you left Switzerland."
"We had the honor of being the first passengers to arrive by means
of the new Subatlantic Tube," said James 212B 422. "As you are
doubtless aware, the regular passenger service opens next week,
but being one of the consulting engineers of the new
electromagnetic tube, my daughter and I were permitted to make
the first trip westward. We made it in perfect safety, although it was
a little risky, as some small portions of the tube are not entirely
completed."
"And we were so anxious to get here as quickly as possible," broke
in Alice with a glance at Ralph.
"But you shouldn't have risked your lives, in an untested tube," he
exclaimed. And then, the scientist in him to the front: "Tell me all
about this new tube. Busy with my own work I have not followed its
progress closely enough to know all its details."
"It has been most interesting work," said James 212B 422, "and we
regard it as quite an achievement in electrical engineering. The new
tube runs in a straight line between New York and Brest, France. If
the tube were to run straight along the bottom of the ocean the
distance between the two points would be from 3600 to 3700 miles
due to the curvature of the earth. For this reason the tube was
pushed straight through the earth, thereby making the distance only
3470 miles.
"You will understand it better by examining this chart," and unfolding
a plan, he proceeded to elaborate on the finer points of the tube
construction. "The greatest trouble," he went on, "our engineers
experienced near the middle of the tube; this point is 450 miles
nearer the center of the earth and the heat became very marked. It
was necessary to install large liquid-air plants at several points in the
tube to reduce the heat, and now as you ride through no heat is
noticed.
"We boarded the spacious steel car, which resembles a thick cigar, at
Brest last night at midnight, and arrived at the New York terminal at
noon today. There was only one stop, a few hundred miles out from
Brest, because of several short-circuited electromagnets.
"There are no wheels to the tube car and it is propelled by
magnetism only. At each three hundred feet is stationed a powerful
tubular electromagnet, about thirty feet long, through which the
tube car passes. Each electromagnet exerts a tremendous pull upon
the car three hundred feet away, this being the only steel object,
and the car rushes toward the electromagnet with a tremendous
speed. When the car is only two feet away from this electromagnet,
the current is cut off automatically by the car itself, the latter
plunging through the open space of the magnet coil, only to be
influenced now by the next electromagnet, three hundred feet
distant.

"The momentum acquired by the pull of the former electromagnet


propels the car with ever-increasing speed, and by the time it has
passed through twenty-five electromagnets it has reached the speed
of three hundred miles an hour. It then continues at a steady pace
till the end of the journey.
"As the car is held suspended entirely by magnetism, there is
practically no friction whatever, as there are no wheels or rails. The
only friction is from the air, and in order that this may not heat the
car it is equipped with a double wall, the space between the inner
and outer walls being a vacuum. Consequently the temperature
inside is comfortable at all times. Once inside the car, we retired and
slept as soundly as in our swinging beds at home. There were no
shocks, no noise, no rocking—all in all the trip was so delightful, that
I must say the new tube is a decided success!"
"Fine, fine," said Ralph enthusiastically. "This new tube is going to
revolutionize intercontinental travel. I suppose it won't be long now
before we will regard our tedious twenty-four hour journeys as
things of the past. Tell me," turning to Alice who had been an
interested listener, "how did the trip impress you?"
"Oh," she exclaimed eagerly, "it was delightful! So smooth and fast!
I was so excited. Really, it was over too soon."
As she spoke Ralph watched her with keen interest. Here was a girl
who attracted him. Beneath the vivacity that so fascinated him he
sensed the strength of her character, and the depth of her mind.
"I am so glad to be in New York," she was saying. "Do you know,
this is my first visit here for ages. Why, the last time I can just barely
remember, I was such a little girl. Father has been promising me a
trip for years," with a laughingly reproachful glance at him, "but it
took an avalanche to get us started."
"I'm afraid I've been a neglectful father of late years," said her
father, "but my work has kept me tied pretty close to home. I, too,
am pleased to be here once more, and my visit promises to be
doubly interesting, for I understand that your great dog experiment
will be completed today. I am looking forward to receiving the
earliest reports of it at the hotel."
"But I can't permit you to spend your days here in a hotel,"
protested Ralph. "Of course you must both be my guests. Yes, yes,"
as they seemed about to demur, "I won't take no for an answer. I
am counting on showing you New York, and, as for my experiment,
it will give me great pleasure to have you both present in my
laboratory this afternoon at four."
He pressed a button. "Peter will show you to your rooms, and I will
send some one for your luggage."
"You are more than kind," said James. "This is quite unexpected, but
none the less delightful. As to attending the meeting in your
laboratory this afternoon, it is an honor, sir, that I appreciate deeply."
At this moment Peter stepped from the elevator and Ralph, after
giving him instructions to show his guests to their apartment, and
directions as to their bags, escorted them to the car and returned to
the laboratory.

Promptly at four, Ralph greeted a notable group of fellow scientists,


who had come from all corners of the planet to witness the
completion of the famous "Dead-Alive Dog" experiment. A host of
reporters lined the walls. Alice and her father were seated near
Ralph.
A number of the twenty scientists who had witnessed the beginning
of the experiment three years before were dubiously contemplating
the glass box, and one or two of the reporters, unawed by the
personages in the laboratory, seven of whom were "Plus" men,
seemed to find much covert amusement in the whole affair.
Finally, when all of the preparations were completed, and Ralph's
two assistants had stationed themselves beside the glass box
containing the body, the young scientist addressed the gathering.
"Ladies and gentlemen," he said, "you have come here to witness
the final phase of my dog experiment. The preliminary phases you
observed three years ago this day in this room. The seals you put in
place are intact, and you may see them for yourselves, untouched as
you left them.
"As I explained three years ago I formulated the theory that a well
preserved animal, though dead to all intents and purposes, could be
revived, or new life given to it, provided the body had not undergone
decomposition; and also provided that none of the organs had
suffered in the least.
"I found that the rare gas Permagatol would conserve animal tissue
and animal organs indefinitely; when it is used in conjunction with a
weak solution of Radium-K bromide, mixed with antiseptic salts, no
part of an animal body would undergo any change for many years.
"I also found that the body would have to be kept at a fixed
temperature and this was possible by the use of Radium-K alloy. I
am now ready to prove my theory."
He signaled to his assistants, and with their aid, the seals were
broken and the glass cover of the case removed.
A profound silence prevailed. Every eye was focussed on the dog
and many of those present found it difficult to remain seated.
Ralph coolly and deliberately freed the dog of his bandages and
attachments and placed him on an operating table in plain view of
everyone.
From then on he and his aides moved rapidly. First the dead dog's
artery was opened and the Radium-K bromide solution drained off. A
young goat was brought in and strapped on the table, and in a very
few seconds one of its arteries had been opened and connected to
the dead dog's main artery. In less than a minute the dog's body
was full of fresh warm blood and immediately efforts were made to
bring the dog back to life.
Oxygen was freely administered and the heart was artificially
pulsated by means of an electrical vibratory apparatus.
At the same time one of the assistants had trained a vacuum tube
on the dog's head and its cathode shot the powerful F-9-Rays into
the animal's brain. No sooner had these rays, which are among the
most powerful brain stimulants, been trained on the dog than he
began to show weak signs of life. One of the hind legs was drawn up
with a jerk as if in a fit. Then came a faint heave of the chest,
followed by a weak attempt to breathe.
A few minutes later the body seemed to contract and a shiver ran
through it from head to tail. A deep respiration followed, and the
animal opened its eyes as if awakening from a long sleep.
In a few minutes more the dog was lying on its paws and licking up
milk when Ralph turned to the group and said:
"Gentlemen, the experiment is concluded and I believe the condition
of the animal at this moment establishes sufficient proof of my
theory."
As the reporters eagerly dashed from the laboratory to get to the
nearest Telephot in order to communicate the news to the waiting
world the scientists gathered around Ralph and one of them, a white
haired old man considered to be the dean of the "Plus" men, voiced
the sentiment of the entire group.
"Ralph, this is one of the greatest gifts that science has brought to
humanity. For what you have done with a dog, you can do with a
human being. I only regret for myself that you had not lived and
conducted this experiment when I was a young man, that I might
have, from time to time, lived in suspended animation from century
to century, and from generation to generation as it will now be
possible for human beings to do."
The vista opened up by the results of this experiment in the minds
of the other scientists had dazed them and it was with the most
perfunctory good-byes that they left the scene of the experiment,
enveloped with their thoughts of the future.
Tired and exhausted by the nervous strain of the afternoon Ralph, a
few minutes later, lay down on his bed for a few hours' rest. But as
he closed his eyes there came to him a vivid picture of a pair of
warm dark eyes, radiating admiration, trust and something more
that aroused an emotion he had never before experienced.

4
Welcome to our website – the ideal destination for book lovers and
knowledge seekers. With a mission to inspire endlessly, we offer a
vast collection of books, ranging from classic literary works to
specialized publications, self-development books, and children's
literature. Each book is a new journey of discovery, expanding
knowledge and enriching the soul of the reade

Our website is not just a platform for buying books, but a bridge
connecting readers to the timeless values of culture and wisdom. With
an elegant, user-friendly interface and an intelligent search system,
we are committed to providing a quick and convenient shopping
experience. Additionally, our special promotions and home delivery
services ensure that you save time and fully enjoy the joy of reading.

Let us accompany you on the journey of exploring knowledge and


personal growth!

ebookball.com

You might also like