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

Download full Programming and Problem Solving with C 3rd Edition Edition Nell B. Dale ebook all chapters

The document promotes the 3rd edition of 'Programming and Problem Solving with C' by Nell B. Dale, highlighting its focus on making complex computer science concepts accessible to students. It outlines the book's structure, including the introduction of C++ classes and object-oriented programming, as well as new chapters on templates and exceptions. Additionally, it provides links to download the book and other related ebooks from ebookfinal.com.

Uploaded by

fellifeluxgt
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
100% found this document useful (1 vote)
4 views

Download full Programming and Problem Solving with C 3rd Edition Edition Nell B. Dale ebook all chapters

The document promotes the 3rd edition of 'Programming and Problem Solving with C' by Nell B. Dale, highlighting its focus on making complex computer science concepts accessible to students. It outlines the book's structure, including the introduction of C++ classes and object-oriented programming, as well as new chapters on templates and exceptions. Additionally, it provides links to download the book and other related ebooks from ebookfinal.com.

Uploaded by

fellifeluxgt
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 77

Visit https://ebookfinal.

com to download the full version and


explore more ebooks

Programming and Problem Solving with C 3rd


Edition Edition Nell B. Dale

_____ Click the link below to download _____


https://ebookfinal.com/download/programming-and-
problem-solving-with-c-3rd-edition-edition-nell-b-dale/

Explore and download more ebooks at ebookfinal.com


Here are some suggested products you might be interested in.
Click the link to download

Problem Solving with C The Object of Programming Fourth


Edition Walter J. Savitch

https://ebookfinal.com/download/problem-solving-with-c-the-object-of-
programming-fourth-edition-walter-j-savitch/

Introduction to Java and Software Design 1st Edition Nell


B. Dale

https://ebookfinal.com/download/introduction-to-java-and-software-
design-1st-edition-nell-b-dale/

Problem Solving with C 10th Edition Walter Savitch

https://ebookfinal.com/download/problem-solving-with-c-10th-edition-
walter-savitch/

Data Abstraction Problem Solving with C 5th Edition Frank


M. Carrano

https://ebookfinal.com/download/data-abstraction-problem-solving-
with-c-5th-edition-frank-m-carrano/
ADTs Data Structures and Problem Solving with C 2nd
Edition Larry R. Nyhoff

https://ebookfinal.com/download/adts-data-structures-and-problem-
solving-with-c-2nd-edition-larry-r-nyhoff/

Engineering Problem Solving with C United States Edition


Paperback Delores M. Etter

https://ebookfinal.com/download/engineering-problem-solving-with-c-
united-states-edition-paperback-delores-m-etter/

Geotechnical Problem Solving 1. Edition John C. Lommler

https://ebookfinal.com/download/geotechnical-problem-
solving-1-edition-john-c-lommler/

Java An Introduction to Problem Solving and Programming


7th Edition Walter Savitch

https://ebookfinal.com/download/java-an-introduction-to-problem-
solving-and-programming-7th-edition-walter-savitch/

101 Activities for Teaching Creativity and Problem Solving


1st Edition Arthur B. Vangundy

https://ebookfinal.com/download/101-activities-for-teaching-
creativity-and-problem-solving-1st-edition-arthur-b-vangundy-2/
Programming and Problem Solving with C 3rd Edition
Edition Nell B. Dale Digital Instant Download
Author(s): Nell B. Dale
ISBN(s): 9780763721039, 0763721034
Edition: 3rd Edition
File Details: PDF, 127.73 MB
Year: 2001
Language: english
h i r d Edition

Programming ond
Problem Solving with

1»^

dcifk iJ/rjad'hiPi

JONES AND BARTIj|j§,T COMPUTER SCIENCE


Digitized by the Internet Archive
in 2011

http://www.archive.org/details/programmingproblOOdale
Third Edition

Problem Solving with

Nell Dale
University of Texas, Austin

Chip Weems
University of Massachusetts, Amherst

Mark Headington
University of Wisconsin - La Crosse

JONES AND BARTLETT PUBLISHERS


Sudbury, Massachusetts
BOSTON TORONTO LONDON SINGAPORE
World Headquarters
Jones and Bartlett Publishers Jones and Bartlett Publishers Jones and Bartlett Publishers
40 Tall Pine Drive Canada International
Sudbury, MA
01776 2405 Nikanna Road Barb House, Barb Mews
978-443-5000 Mississauga, ON L5C 2W6 London W6 7PA
info@jbpub.com CANADA UK
www.jbpub.com

Copyright t 2002 by Jones and Bartlett Publishers, Inc.

Library of Congress Cataloging-in-Publication Data


Dale, Nell B.
Programming amd problem solving with C++ / Nell Dale, Chip Weems, Mark
Headington.— 3rd ed.

p. cm.
ISBN 0-7637-2103-4
1. C++ (Computer program language) I. Weems, Chip. II. Headington, Mark R. III.

Title.

QA76.73.C153 D34 2001


005.13'3-dc21 2001050447

All rights reserved. No part of the material protected by this copyright notice may be reproduced or utilized
in any form, electronic or mechanical, including photocopying, recording, or any information storage or
retrieval system, without written permission from the copyright owner.

Chief Executive Officer: Clayton Jones


Chief Operating Officer: Don W. Jones, Jr.

Executive V.P. and Publisher: Robert Holland


V.P., Managing Editor: Judith H. Hauck
V.P., Design and Production: Anne Spencer
V.P., Manufacturing and Inventory Control: Therese Brauer
Editor-in-Chief: J. Michael Stranz
Development and Product Manager: Amy Rose
Marketing Manager: Nathan Schultz
Production Assistant: Tara McCormick
Editorial Assistant: Theresa DiDonato
Cover Design: Night ft Day Design
Composition: Northeast Compositors, Inc.

Text Design: Anne Spencer


IT Manager: Nicole Healey
Printing and Binding: Courier Westford
Cover printing: John Pow Company, Inc.

This book was typeset in Quark 4.1 on a Macintosh G4. The font families used were Rotis Sans Serif Rotis
Serif and Prestige Elite. The first printing was printed on 40# Lighthouse Matte.

Printed in the United States of America


05 04 03 02 10 9 8 7 5 5 4 3 2
To you, and to all of our other students for whom it
was begun and without whom it would
never have been completed.

N.D. C.W. M.H.

To the memory of my parents, Rog and Anne, who


fostered in me a lifelong love of reading and learning.

M.H.
To quote Mephistopheles, one of the chief devils, and tempter of Faust,

...My friend, I shall be pedagogic,


And say you ought to start with Logic...
...Days will be spent to let you know
That what you once did at one blow,
Like eating and drinking so easy and free,
Can only be done with One, Two, Three.
Yet the web of thought has no such creases
And is more like a weaver's masterpieces;
One step, a thousand threads arise.
Hither and thither shoots each shuttle,
The threads flow on, unseen and subtle,
Each blow effects a thousand ties.
The philosopher comes with analysis
And proves it had to be like this;
The first was so, the second so,
And hence the third and fourth was so.
And were not the first and second here,
Then the third and fourth could never appear.
That is what all the students believe.
But they have never learned to weave.

J. W. von Goethe, Faust, Waher Kaufman trans., New York, 1963, 199.

As you study this book, do not let the logic of algorithms bind your
imagination, but rather make it your tool for weaving masterpieces of
thought.
two editions of Programming and Problem Solving with C++ have con-
first
The been among the best-seUing computer science textbooks in the United
sistently
States. Both editions, as well as the Pascal and Ada versions of the book, have
been widely accepted as model textbooks for ACM/lEEE-recommended curricula for
the CSl/ClOl course and for the Advanced Placement A exam in computer science.
Although this third edition incorporates new material, one thing has not changed:
our commitment to the student. As always, our efforts are directed toward making
the sometimes difficult concepts of computer science more accessible to all students.
This edition of Programming and Problem Solving with C++ continues to reflect
our experience that topics once considered too advanced can be taught in the first
course. For example, we address metalanguages explicitly as the formal means of
specifying programming language syntax. We introduce Big-0 notation early and
use it to compare algorithms in later chapters. We discuss modular design in terms of
abstract steps, concrete steps, functional equivalence, and functional cohesion. Pre-
conditions and postconditions are used in the context of the algorithm walk-through,
in the development of testing strategies, and as interface documentation for user-
written functions. The discussion of function interface design includes encapsulation,
control abstraction, and communication complexity. Data abstraction and abstract
data types (ADTs) are explained in conjunction with the C++ class mechanism, form-
ing a natural lead-in to object-oriented programming.
ISO/ANSI standard C++ is used throughout the book, including relevant portions
of the new C++ standard library. However, readers with pre-standard C++ compilers
are also supported. An appendix book and on the publisher's Web site)
(both in the
explains how to modify the textbook's programs to compile and run successfully
with an earlier compiler.
As in the second edifion, C++ classes are introduced in Chapter 1 1 before arrays.
This sequencing has several benefits. In their first exposure to composite types, many
students find it easier to comprehend accessing acomponent by name rather than by
position. With classes introduced in Chapter 1 1, Chapter 12 on arrays can rather eas-
ily introduce the idea of an array of class objects or an array of structs. Also, Chapter
Preface

13, which deals with the list as an ADT, can implement a list by encapsulating both the
data representation (an array) and the length variable within a class, rather than the
alternative approach of using two loosely coupled variables (an array and a separate
length variable) to represent the list. Finally, with three chapters' worth of exposure to

classes and objects, students reading Chapter 14, "Object-Oriented Software Develop-
ment," can focus on the more difficult aspects of the chapter: inheritance, composition,
and dynamic binding.

Changes in the Third Edition

The third edition incorporates the following changes:

• A new chapter covering templates and exceptions. In response to feedback from


our users and reviewers, we have added a new chapter covering the C++ tem-
plate mechanism and language facilities for exception handling. These topics
were not included in previous editions for two reasons. First, their implementa-
tions in prestandard compilers were often inconsistent and in some cases unsta-
ble. With the advent of the ISO/ANSI language standard, compilers that support
these mechanisms are now readily available. Second, we have considered these
topics to be more suitable for a second semester course than for CSl/ClOl. Many
users of the second edition agree with this viewpoint, but others have expressed
interest in seeing at least an introductory treatment of the topics. To accommo-
date the opinions of both groups, we have placed this new chapter near the end
of the book, to be considered optional material along with the chapter on recur-
sion.
• More examples of complete programs within the chapter bodies. Again in
response to requests from our users and reviewers, we have added 1 5 new com-
plete programs beginning in Chapter 2. These are not case studies (which remain,
a$ in previous editions, at the end of the chapters). Rather, they are programs
included in the main text of the chapters to demonstrate language features or
design issues that are under discussion. Although isolated code snippets continue
to be used, the new programs provide students with enhanced visual context:
Where does the loop fit into the entire function? Where are the secondary func-
tions located with respect to the main function? Where are the #include direc-
tives placed? Clearly, such information is already visible in the case studies, but
the intent is to increase the students' exposure to the "geographic" layout of pro-
grams without the overhead of problem-solving discussions as found in the case
studies. To this end, we have ensured that every chapter after Chapter has at 1

least one complete program in the main text, with several chapters having three
or four such programs.

C++ and Object-Oriented Programming

Some educators reject the C family of languages (C, C++, Java) as too permissive and
too conducive to writing cryptic, unreadable programs. Our experience does not support
this view, provided that the use of language features is modeled appropriately. The fact

that the C family permits a terse, compact programming style cannot be labeled simply
Preface |

as "good" or "bad." Almost any programming language can be used to write in a style
that is too terse and clever to be easily understood. The C family may indeed be used in
this manner more often than are other languages, but we have found that with careful
instruction in software engineering and a programming style that is straightforward,
disciplined, and free of intricate language features, students can learn to use C++ to
produce clear, readable code.
It must be emphasized that although we use C++ as a vehicle for teaching computer
science concepts, the book is not a language manual and does not attempt to cover all

of C++. Certain language features— operator overloading, default arguments, run-time


type information, and mechanisms for advanced forms of inheritance, to name a few-
are omitted in an effon not to overwhelm the beginning student with too much too fast.

There are diverse opinions about when to introduce the topic of object-oriented
programming (OOP). Some educators advocate an immersion in OOP from the very
beginning, whereas others (for whom this book is intended) favor a more heterogeneous
approach in which both functional decomposition and object-oriented design are pre-
sented as design tools. The chapter organization of Programming and Problem Solving
with C++ reflects a transitional approach to OOP. Although we provide an early preview
of object-oriented design in Chapter 4, we delay a focused discussion until Chapter 14
after the students have acquired a firm grounding in algorithm design, control abstrac-
tion, and data abstraction with classes.

Synopsis

Chapter 1 is designed to create a comforiable rapport between students and the subject.
The basics of hardware and software are presented, issues in computer ethics are raised,
and problem-solving techniques are introduced and reinforced in a Problem-Solving
Case Study.
Chapter 2, instead of overwhelming the student right away with the various
numeric types available in C++, concentrates on two types only: char and string. (For
the latter, we use the ISO/ANSI string class provided by the standard library.) With
fewer data types to keep track of, students can focus on overall program structure and
get an eariier stan on creating and running a simple program. Chapter 3 then begins
with a discussion of the C++ numeric types and proceeds with material on arithmetic
expressions, function calls, and output. Unlike many books that detail all of the C++
data types and all of the C++ operators at once, these two chapters focus only on the
int, float, char, and string types and the basic arithmetic operators. Details of the
other data types and the more elaborateC++ operators are postponed until Chapter 10.
The functional decomposition and object-oriented design methodologies are a major
focus of Chapter 4, and the discussion is written with a healthy degree of formalism.
This early in the book, the treatment of object-oriented design is more superficial than
that of functional decomposition. However, students gain the perspective that there are
two-not one-design methodologies in widespread use and that each serves a specific
purpose. Chapter 4 also covers input and The eariy introduction of files permits
file I/O.

the assignment of programming problems that require the use of sample data files.
Students learn to recognize functions in Chapters and 2, and they learn to use
1

standard library funcnons in Chapter 3. Chapter 4 reinforces the basic concepts of func-
viii I Preface

tion calls, argument passing, and function libraries. Chapter 4 also relates functions to
the implementation of modular designs and begins the discussion of interface design
that is essential to writing proper functions.
Chapter 5 begins with Boolean data, but its main purpose is to introduce the con-
cept of flow of control. Selection, using If-Then and If-Then-Else structures, is used to
demonstrate the distinction between physical ordering of statements and logical order-
ing. We also develop the concept of nested control structures. Chapter 5 concludes with
a lengthy Testing and Debugging section that expands on the modular design discussion
by introducing preconditions and postconditions. The algorithm walk-through and code
walk-through are introduced as means of preventing errors, and the execution trace is
used to find errors that made it into the code. We also cover data validation and testing
strategies extensively in this section.
Chapter 6 is devoted to loop control strategies and looping operations using the
syntax of the While statement. Rather than introducing multiple syntactical structures,
our approach is to teach the concepts of looping using only the While statement. How-
ever, because many instructors have told us that they prefer to show students the syntax
for all of C++'s looping statements at once, the discussion of For and Do-While state-
ments in Chapter 9 can be covered optionally after Chapter 6.

By Chapter 7, the students are already comfortable with breaking problems into
modules and using and they are receptive to the idea of writing their
library functions,
own functions. Chapter 7 focuses on passing arguments by value and covers flow of
control in function calls, arguments and parameters, local variables, and interface
design. The last topic includes preconditions and postconditions in the interface docu-
mentation, control abstraction, encapsulation, and physical versus conceptual hiding of
an implementation. Chapter 8 expands the discussion to include reference parameters,
scope and lifetime, stubs and drivers, and more on interface design, including side
effects.

Chapter 9 covers the remaining "ice cream and cake" control structures in C++
(Switch, Do-While, and For), along with the Break and Continue statements. Chapter 9
forms a natural ending point for the first quarter of a two-quarter introductory course
sequence.
Chapter 10 begins a transition between the control structures orientation of the first

half of the book and the abstract data type orientation of the second half. examine We
the built-in simple data types in terms of the set of values represented by each type and
the allowable operations on those values. We introduce more C++ operators and discuss
at length the problems of floating-point representation and precision. User-defined sim-
ple types, user-written header files, and type coercion are among the other topics cov-
ered in this chapter.
We begin Chapter 1 1 with a discussion of simple versus structured data types. We
introduce the record (struct in C++) as a heterogeneous data structure, describe the
syntax for accessing its components, and demonstrate how to combine record types into

a hierarchical record structure. From this base, we proceed to the concept of data
abstraction and give a precise definition to the notion of an ADT, emphasizing the sepa-
ration of specification from implementation.The C++ class mechanism is introduced as
a programming language representation of an ADT. The concepts of encapsulation,
information hiding, and public and private class members are stressed. We describe the
1

Preface |

separate compilation of program files, and students learn the technique of placing a
class's declaration and implementation two separate files: the specification (.h) file
into
and the implementation file.

In Chapter 12, the array is introduced as a homogeneous data structure whose com-
ponents are accessed by position rather than by name. One-dimensional arrays are
examined in depth, including arrays of structs and arrays of class objects. Material on
multidimensional arrays completes the discussion.
Chapter 13 integrates the material from Chapters 11 and 12 by defining the list as
an ADT. Because we have already introduced classes and arrays, we can clearly distin-
guish between arrays and lists from the beginning. The array is a built-in, fixed-size
data structure. The list is a user-defined, variable-size structure represented in this
chapter as a length variable and an array of items, bound together in a class object.
The elements in the list are those elements in the array from position through posi-
tion length - 1. In this chapter, we design C++ classes for unsorted and soried list
ADTs, and we code the list algorithms as class member functions. We use Big-0 nota-
tion to compare the various searching and sorting algorithms developed for these
ADTs, Finally, we examine C strings in order to give students some insight into how a
higher-level abstraction (a string as a list of characters) might be implemented in terms
of a lower-level abstraction (a null-terminated char array).
Chapter 14 extends the concepts of data abstraction and C++ classes to an explo-
ration of object-oriented software development. Object-oriented design, introduced
briefly in Chapter 4, is revisited in greater depth. Students learn to distinguish between
inheritance and composition relationships during the design phase, and C++"s derived
classes are used to implement inheritance. This chapter also introduces C++ virtual
functions, which support polymorphism in the form of run-time binding of operations
to objects.
Chapter 15 examines pointer and reference types. We present pointers as a way of
making programs more efficient and of allowing the run-time allocation of program
data. The coverage of dynamic data structures continues in Chapter 16, in which we
present linked lists, linked-list algorithms, and alternative representations of linked lists.
Chapter 17 introduces C++ templates and exception handling, and Chapter 18 con-
cludes the text with coverage of recursion. There is no consensus as to the best place to
introduce these subjects. We believe that it is better to wait until at least the second
semester to cover them. However, we have included this material for those instructors
who have requested it. Both chapters have been designed so that they can be assigned
for reading along with eariier chapters. Below we suggest prerequisite reading for the
topics in Chapters 17 and 18.

Section(s) Topic Prerequisite

17.1 Template functions Chapter 10


17.2 Template classes Chapter 13
17.3 Exceptions Chapter 1

18.1-18.3 Recursion with simple variables Chapter 8


18.4 Recursion with arrays Chapter 12
18.5 Recursion with pointer variables Chapter 16
I
Preface

Additional Features

Web Links Special Web icons found in tiie prompt students


Special Sections (see below)
to visit the text's companion Web site located at www.problemsolvingcpp.jbpub.coin
for additional information about selected topics. These Web Links give students instant
access to real-world applications of material presented in the text. The Web Links are
updated on a regular basis to ensure that students receive the most recent information
available on the Internet.

Special Sections Five kinds of features are set off from the main text. Theoretical
Foundations sections present material related to the fundamental theory- behind various
branches of computer science. Software Engineering Tips discuss methods of making
programs more reliable, robust, or efficient. Matters of Style address stylistic issues in
the coding of programs. Background Information sections explore side issues that
enhance the student's general knowledge of computer science. May We Introduce
sections contain biographies of computing pioneers such as Blaise Pascal, Ada Lovelace,
and Grace Murray Hopper. Web Links appear in most of these Special Sections
prompting students to visit the companion Web site for expanded material.

Goals Each chapter begins with a list of learning objectives for the student. These
goals are reinforced and tested in the end-of-chapter exercises.

Problem-Solving Case Studies Problem solving is best demonstrated through case


studies. In each case study, we present a problem and use problem-solving techniques
to develop a manual solution. Next, we expand the solution to an algorithm, using
functional decomposition, object-oriented design, or both; then we code the algorithm
in C++. We show sample test data and output and follow up with a discussion of what
is involved in thoroughly testing the program.

Testing and Debugging Following the case studies in each chapter, this section
considers in depth the implications of the chapter material with regard to thorough
testing of programs. The section concludes with a list of testing and debugging hints.

Quick Checks At the end of each chapter are questions that test the student's recall of
major points associated with the chapter goals. Upon reading each question, the student
immediately should know the answer, which he or she can then verify by glancing at
the answers at the end of the section. The page number on which the concept is

discussed appears at the end of each question so that the student can review the
material in the event of an incorrect response.

Exam Preparation Exercises These questions help the student prepare for tests. The
questions usually have objective answers and are designed to be answerable with a few
minutes of work. Answers to selected questions are given in the back of the book, and
the remaining questions are answered in the Instructor's Guide.
Preface I

Programming Warm-up Exercises This section provides the student with experience in
writingC++ code fragments. The student can practice the syntactic constructs in each
chapter without the burden of writing a complete program. Solutions to selected
questions from each chapter appear in the back of the book; the remaining solutions
may be found in the Instructor's Guide.

Programming Problems These exercises, drawn from a wide range of disciplines,


require the student to design solutions and write complete programs.

Case Study FoUow-Up Much of modern programming practice involves reading and
modifying existing code. These exercises give the student an opportunity to strengthen
this critical skill by answering questions about the case study code or by making
changes to it.

Supplements

Instructor's Guide and Test Bank The Instructor's Guide features chapter-by-chapter
teaching notes, answers to the balance of the exercises, and a compilation of exam
questions with answers. The Instructor's Guide, included on the Instructor's TookKit CD-
ROM, is available to adopters on request from Jones and Bartlett.

Instructor's ToolKit CD-ROM Available to adopters upon request from the publisher is

a powerful teaching tool entitled "Instructor's ToolKit." This CD-ROM contains an


electronic version of the Instructor's Guide, a computerized test bank, PowerPoint
lecture presentations, and the complete programs from the text (see below).

Programs The programs contain the source code for all of the complete programs that
are found within the textbook. They are available on the Instructor's ToolKit CD-ROM
and also as a freedownload for instructors and students from the publisher's Web site
www.problemsolvingcpp.jbpub.com. The programs from all the case studies, plus
complete programs that appear in the chapter bodies, are included. Fragments or
snippets of program code are not included nor are the solutions to the chapter-ending
"Programming Problems." The program files can be viewed or edited using any standard
text editor, but in order to compile and run the programs, a C++ compiler must be used.
The publisher offers compilers bundled with this text at a substantial discount.

Companion Web Site This Web site (www.problemsolvingcpp.jbpub.com) features


integrated Web Links from the textbook, the complete programs from the text, and
Appendix D entitled "Using this Book with a Prestandard Version of C++," which describes
the changes needed to allow the programs in the textbook to run successfully with a
prestandard compiler. The Web site also includes the C++ syntax templates in one location.

A Laboratory Course in C++, Third Edition Written by Nell Dale, this lab manual
follows the organization of the third edition of the text. The lab manual is designed to
xii I Preface

allow the instructor maximum flexibility and may be used in both open and closed
laboratory settings. Each chapter contains three types of activities: Prelab, Inlab and
Postlab. Each lesson is broken into exercises that thoroughly demonstrate the concepts
covered in the chapter. The programs, program shells (partial programs), and data files

thataccompany the lab manual can be found on the Web site for this book,
www. problemsolvingcpp jbpub com. .
.

Student Lecture Notebook Designed from the PowerPoint presentations developed for
this text, the Student Lecture Notebook is an invaluable tool for learning. The notebook
is designed to encourage students to focus their energies on listening to the lecture as
they fill in additional details. The skeletal outline concept helps students organize their
notes and readily recognize the important concepts in each chapter.

Acknowledgments

We would like to thank the many individuals who have helped us in the preparation of
this third edition. We are indebted to the members of the faculties of the Computer Sci-
ence Departments at the University of Texas at Austin, the University of Massachusetts
at Amherst, and the University of Wisconsin-La Crosse.
We extend special thanks to Jeff Brumfield for developing the syntax template
metalanguage and allowing us to use it in the text.
For their many helpful suggestions, we thank the lecturers, teaching assistants, con-
sultants, and student proctors who run the courses for which this book was written, and
the students themselves.
We are grateful to the following people who took the time to offer their comments
on potential changes for this edition: Trudee Bremer, Illinois Central College; Mira Carl-
son, Northeastern Illinois University; Kevin Daimi, University of Detroit, Mercy; Bruce
Elenbogen, University of Michigan, Dearborn; Sandria Kerr, Winston-Salem State; Ali-
cia Kime, Fairmont State College; Shahadat Kowuser, University of Texas, Pan America;
Bruce Maxim, University of Michigan, Dearborn; William McQuain, Virginia Tech;
Xiannong Meng, University of Texas, Pan America; William Minervini, Broward Uni-
versity; Janet Remen, Washtenaw Community College; Viviana Sandor, Oakland Uni-
versity; Mehdi Setareh, Virginia Tech; Katy Snyder, University of Detroit, Mercy; Tom
Steiner, University of Michigan, Dearborn; John Weaver, West Chester University;
Charles Welty, University of Southern Maine; Cheer-Sun Yang, West Chester University.
We also thank Mike and Sigrid Wile along with the many people at Jones and
Bartlett who J. Michael Stranz and Anne Spencer. Our
contributed so much, especially
special thanks go to Amy Rose, our Development and Product Manager, whose skills

and genial nature turn hard work into pleasure.


Anyone who has ever written a book-or someone who has-can appre-
is related to
ciate the amount of time involved in such a To our families-all the Dale clan
project.
and the extended Dale family (too numerous to name); to Lisa, Charlie, and Abby; to
Anne, Brady, and Kari-thanks for your tremendous support and indulgence.

N. D.
C. W.
M. H.
f

^^mmmmmi^

Preface v

Overview of Programming and Problem Solving 1

1.1 Overview of Programming 2

What Is Programming? 2

How Do We Write a Program? 3

1.2 What Is a Programming Language? 9


1.3 What Is a Computer? 15
1.4 Ethics and Responsibilities in the Computing Profession 24
Software Piracy 24
Privacy of Data 25
Use of Computer Resources 26
Software Engineering 27
1.5 Problem-Solving Techniques 27
Ask Questions 28
Look for Things That Are Familiar 28
Solve by Analogy 28
Means-Ends Analysis 29
Divide and Conquer 30
I
Contents

The Building-Block Approach 30


Merging Solutions 31

Mental Blocks: The Fear of Starting 32


Algorithmic Problem Solving 33
Problem-Solving Case Study: An Algorithm for an Employee
Paycheck 33
Summary 37
Quick Check 38
Answers 39
Exam Preparation Exercises 39
Programming Warm-Up Exercises 41

Case Study Follow-Up 41

C++ Syntax and Semantics, and the Program Development


8 Process 43
2.1 The Elements of C++ Programs 44
C++ Program Structure 44
Syntax and Semantics 46
Syntax Templates 49
Naming Program Elements: Identifiers 52
Data and Data Types 53
Naming Elements: Declarations 56
Taking Action: Executable Statements 61

Beyond Minimalism: Adding Comments to a Program 66


2.2 Program Construction 67
Blocks (Compound Statements) 69
The C++ Preprocessor 71

An Introduction to Namespaces 73
2.3 More About Output 74
Creating Blank Lines 74 I
Inserting Blanks Within a Line 75
2.4 Program Entry, Correction, and Execution 76
Entering a Program 76
Compiling and Running a Program 77
Finishing Up 78
Problem-Solving Case Study: Contest Letter 79
3 5 8 1

Contents | xv

Testing and Debugging 83


Summary 84
Quick Check 85
Answers 87
Exam Preparation Exercises 88
Programming Warm-Up Exercises 90
Programming Problems 92
Case Study Follow-Up 94

Numeric Types, Expressions, and Output 95


3 3.1 Overview of C++ Data Types 96
3.2 Numeric Data Types 97
Integral Types 97
Floating-Point Types 98
3.3 Declarations for Numeric Types 99
Named Constant Declarations 99
Variable Declarations 100
3.4 Simple Arithmetic Expressions 101

Arithmetic Operators 101

Increment and Decrement Operators 104


3.5 Compound Arithmetic Expressions 105
Precedence Rules 105
Type Coercion and Type Casting 106
3.6 Function Calls and Library Functions 111

Value-Returning Functions 1 1

Library Functions 1 1

Void Functions 114


3.7 Formatting the Output 115
Integers and Strings 1 1

Floating-Point Numbers 1 1

3.8 Additional string Operations 122


The length and size Functions 122
The find Function 124
The substr Function 125
Problem-Solving Case Study: Painting Traffic Cones 1 28
xvi I
Contents

Testing and Debugging 132


Summary 133
Quick Check 133
Answers 135
Exam Preparation Exercises 136
Programming Warm-Up Exercises 140
Programming Problems 143
Case Study Follow-Up 145

Program Input and the Software Design Process 147


4 4.1 Getting Data into Programs 148
Input Streams and the Extraction Operator (») 149
The Reading Marker and the Newline Character 1 52
Reading Character Data with the get Function 1 53
Skipping Characters with the ignore Function 156
Reading String Data 1 57
4.2 Interactive Input/Output 158
4.3 Noninteractive Input/Output 160
4.4 File Input and Output 161

Files 161

Using Files 162


An Example Program Using Files 1 65
Run-Time Input of File Names 1 67
4.5 Input Failure 168
4.6 Software Design Methodologies 170
4.7 What Are Objects? 171

4.8 Object-Oriented Design 173


4.9 Functional Decomposition 174
Modules 176
Implementing the Design 177
A Perspective on Design 181

Problem-Solving Case Study: Stretching a Canvas 183


Testing and Debugging 189
Testing and Debugging Hints 191
Contents | xvii

Summary 191

Quick Check 192


Answers 193
Exam Preparation Exercises 193
Programming Warm-Up Exercises 196
Programming Problems 198
Case Study Follow-Up 199

Conditions, Logical Expressions, and Selection


5 Control Structures 201
5.1 Flow of Control 202
Selection 203
5.2 Conditions and Logical Expressions 204
The bool Data Type 204
Logical Expressions 205
Precedence of Operators 214
Relational Operators with Floating-Point Types 216
5.3 The If Statement 217
The If-Then-Else Form 217
Blocks (Compound Statements) 220
The If- Then Form 222
A Common Mistake 224
5.4 Nested If Statements 224
The Dangling else 228
5.5 Testing the State of an I/O Stream 229
Problem-Solving Case Study: Warning Notices 231
Testing and Debugging 236
Testing in the Problem-Solving Phase: The Algorithm
Walk-Through 236
Testing in the Implementation Phase 239
The Test Plan 244
Tests Performed Automatically During Compilation and Execution
246
Testing and Debugging Hints 247
xviii I
Contents

Summary 249
Quick Check 249
Answers 250
Exam Preparation Exercises 250
Programming Warm-Up Exercises 254
Programming Problems 256
Case Study Follow-Up 259

Looping 261
6 6.1 The While Statement 262
6.2 Phases of Loop Execution 264
6.3 Loops Using the While Statement 265
Count-Controlled Loops 265
Event-Controlled Loops 267
Looping Subtasks 273
6.4 How to Design Loops 276
Designing the Flow of Control 277
Designing the Process Within the Loop 278
The Loop Exit 279
6.5 Nested Logic 280
Designing Nested Loops 284
Problem-Solving Case Study: Average Income by Gender 291

Testing and Debugging 297


Loop-Testing Strategy 297
Test Plans Involving Loops 297
Testing and Debugging Hints 299
Summary 300
Quick Check 301
Answers 301

Exam Preparation Exercises 302


Programming Warm-Up Exercises 305
Programming Problems 305
Case Study Follow-Up 308
Contents

Functions 309
7 7.1 Functional Decomposition with Void Functions 310
When to Use Functions 311

Writing Modules as Void Functions 311

7.2 An Overview of User-Defined Functions 315


Flow of Control in Function Calls 316
Function Parameters 316
7.3 Syntax and Semantics of Void Functions 319
Function Call (Invocation) 319
Function Declarations and Definitions 320
Local Variables 322
The Return Statement 324
Header Files 325
7.4 Parameters 326
Value Parameters 327
Reference Parameters 328
An Analogy 331
Matching Arguments with Parameters 332
7.5 Designing Functions 335
Writing Assertions as Program Comments 337
Documenting the Direction of Data Flow 339
Problem-Solving Case Study: Comparison of
Furniture-Store Sales 343
Testing and Debugging 352
The assert Library Function 353
Testing and Debugging Hints 354
Summary 355
Quick Check 356
Answers 357
Exam Preparation Exercises 357
Programming Warm-Up Exercises 363
Programming Problems 365
Case Study Follow-Up 369
XX I
Contents

Scope, Lifetime, and More on Functions 371


8 8.1 Scope of Identifiers 372
Scope Rules 374
Variable Declarations and Definitions 378
Namespaces 379
8.2 Lifetime of a Variable 382
Initializations in Declarations 382
8.3 Interface Design 384
Side Effects 384
Global Constants 387
8.4 Value-Returning Functions 389
Boolean Functions 394
Interface Design and Side Effects 398
When to Use Value-Returning Functions 399
Problem-Solving Case Study: Reformat Dates 401
Problem-Solving Case Study: Starship Weight
and Balance 412
Testing and Debugging 423
Stubs and Drivers 423
Testing and Debugging Hints 425
Summary 426
Quick Check 427
Answers 428
Exam Preparation Exercises 428
Programming Warm-Up Exercises 432
Programming Problems 433
Case Study Follow-Up 435

Additional Control Structures 437


3 9.1 The Switch Statement 438
9.2 The Do-While Statement 443
9.3 The For Statement 446
9.4 The Break and Continue Statements 450
9.5 Guidelines for Choosing a Looping Statement 453
Problem-Solving Case Study: Monthly Rainfall Averages 454
Contents I xxi

Testing and Debugging 459


Testing and Debugging Hints 460
Summary 460
Quick Check 461
Answers 461
Exam Preparation Exercises 462
Programming Warm-Up Exercises 463
Programming Problems 465
Case Study Follow-Up 467

Simple Data Types: Built-in and User-Defined 469


10.1 Built-in Simple Types 470
Integral Types 472
Floating-Point Types 475
10.2 Additional C++ Operators 476
Assignment Operators and Assignment Expressions 478
Increment and Decrement Operators 479
Bitwise Operators 480
The Cast Operation 480
The sizeof Operator 481
The ? : Operator 481
Operator Precedence 482
10.3 Working with Character Data 484
Character Sets 485
C++ char Constants 487
Programming Techniques 488
10.4 More on Floating-Point Numbers 495
Representation of Floating-Point Numbers 495
Arithmetic with Floating-Point Numbers 498
Implementation of Floating-Point Numbers in the Computer 499
10.5 User-Defined Simple Types 505
The Typedef Statement 506
Enumeration Types 506
Named and Anonymous Data Types 513
User-Written Header Files 514
xxii I Contents

10.6 More on Type Coercion 515


Type Coercion in Arithmetic and Relational Expressions 516
Type Coercion Assignments, Argument Passing, and Return of
in a
Function Value 517
Problem-Solving Case Study: Finding the Area Under
a Curve 519
Problem-Solving Case Study: Rock, Paper, Scissors 527
Testing and Debugging 536
Floating-Point Data 536
Coping with Input Errors 536
Testing and Debugging Flints 537
Summary 539
Quick Check 539
Answers 540
Exam Preparation Exercises 540
Programming Warm-Up Exercises 543
Programming Problems 544
Case Study Follow-Up 545

Structured Types, Data Abstraction, and Classes 547


11 11.1 Simple Versus Structured Data Types 548
11.2 Records (C++ Structs) 549
Accessing Individual Components 551

Aggregate Operations on Structs 553


A/lore About Struct Declarations 554
Hierarchical Records 555
11.3 Unions 557
11.4 Data Abstraction 559
11.5 Abstract Data Types 561

11.6 C++ Classes 564


Classes, Class Objects, and Class Members 568
Built-in Operations on Class Objects 569
Class Scope 571
Information Hiding 571

11.7 Specification and Implementation Files 573


The Specification File 573
Contents | xxiii

The Implementation File 575


Compiling and Linking a Multifile Program 580
11.8 Guaranteed Initialization with Class Constructors 582
Invoking a Constructor 584
Revised Specification and Implementation Files
for TimeType 585
Guidelines for Using Class Constructors 588
Problem-Solving Case Study: Manipulating Dates 590
Problem-Solving Case Study: Birthday Calls 602
Testing and Debugging 610
Testing and Debugging Hints 614
Summary 615
Quick Check 615
Answers 617
Exam Preparation Exercises 619
Programming Warm-Up Exercises 622
Programming Problems 624
Case Study Follow-Up 628

Arrays 631
12 12.1 One-Dimensional Arrays 632
Declaring Arrays 634
Accessing Individual Components 635
Out-of-Bounds Array Indexes 638
Initializing Arrays in Declarations 638
(Lack of) Aggregate Array Operations 639
Examples of Declaring and Accessing Arrays 640
Passing Arrays as Arguments 645
Assertions About Arrays 648
LJsing Typedef with Arrays 648
12.2 Arrays of Records and Class Objects 649
Arrays of Records 649
Arrays of Class Objects 651
12.3 Special Kinds of Array Processing 652
Subarray Processing 652
Indexes with Semantic Content 652
Contents

12.4 Two-Dimensional Arrays 653


12.5 Processing Two-Dimensional Arrays 656
Sum the Rows 657
Sum the Columns 659
Initialize the Array 660
Print the Array 661
12.6 Passing Two-Dimensional Arrays as Arguments 662
12.7 Another Way of Defining Two-Dimensional Arrays 664
12.8 Multidimensional Arrays 666
Problem-Solving Case Study: Comparison of Two Lists 669
Problem-Solving Case Study: City Council Election 675
Testing and Debugging 685
One-Dimensional Arrays 685
Complex Structures 686
Multidimensional Arrays 687
Testing and Debugging Hints 688
Summary 689
Quick Check 689
Answers 691

Exam Preparation Exercises 692


Programming Warm-Up Exercises 698
Programming Problems 701

Case Study Follow-Up 705

Array-Based Lists 707


13 1 3.1 The List as an Abstract Data Type 708
13.2 Unsorted Lists 713
Basic Operations 713
Insertion and Deletion 716
Sequential Search 718
Sorting 721
13.3 Sorted Lists 724
Basic Operations 726
Insertion 727
Sequential Search 730
Binary Search 730
Deletion 736
Contents I
xxv

13.4 Understanding Character Strings 739


Initializing C Strings 742
C String Input and Output 743
C String Library Routines 746
String Class or C Strings? 747
Problem-Solving Case Study: Exam Attendance 748
Testing and Debugging 755
Testing and Debugging Hints 756
Summary 757
Quick Check 757
Answers 758
Exam Preparation Exercises 758
Programming Warm-Up Exercises 761

Programming Problems 762


Case Study Follow-Up 763

Object-Oriented Software Development 765


14 14.1 Object-Oriented Programming 766
14.2 Objects 768
14.3 Inheritance 769
Deriving One Class from Another 770
Specification of the ExtTime Class 774
Implementation of the ExtTime Class 776
Avoiding Multiple Inclusion of Header Files 780
14.4 Composition 781

Design of a TimeCard Class 782


Implementation of the TimeCard Class 783
14.5 Dynamic Binding and Virtual Functions 785
The Slicing Problem 787
Virtual Functions 788
14.6 Object-Oriented Design 790
Step 1 : Identify the Objects and Operations 790
Step 2: Determine the Relationships Among Objects 792
Step 3: Design the Driver 792
14.7 Implementing the Design 793
Problem-Solving Case Study: Time Card Lookup 794
xxvi I
Contents

Testing and Debugging 814


Testing and Debugging Hints 81 5

Summary 816
Quick Check 816
Answers 818
Exam Preparation Exercises 819
Programming Warm-Up Exercises 822
Programming Problems 823
Case Study Follow-Up 824

Pointers, Dynamic Data, and Reference Types 825


IS 15.1 Pointers 826
Pointer Variables 826
Pointer Expressions 831
15.2 Dynamic Data 836
1 5.3 Reference Types 842
15.4 Classes and Dynamic Data 846
Class Destructors 851
Shallow Versus Deep Copying 852
Class Copy-Constructors 854
Problem-Solving Case Study: Personnel Records 857
Problem-Solving Case Study: Dynamic Arrays 872
Testing and Debugging 882
Testing and Debugging Hints 884
Summary 885
Quick Check 886
Answers 887
Exam Preparation Exercises 888
Programming Warm-Up Exercises 892
Programming Problems 893
Case Study Follow-Up 894

Linked Structures 897


16 16.1 Sequential Versus Linked Structures 898
16.2 Array Representation of a Linked List 900
Contents | xxvii

16.3 Dynamic Data Representation of a Linked List 902


Algorithms on Dynamic Linl<ed Lists 908
Pointer Expressions 926
Classes and Dynamic Linked Lists 927
16.4 Choice of Data Representation 929
Problem-Solving Case Study: Simulated Playing Cards 930
Problem-Solving Case Study: Solitaire Simulation 938
Testing and Debugging 956
Testing and Debugging Hints 956
Summary 956
Quick Check 957
Answers 957
Exam Preparation Exercises 957
Programming Warm-Up Exercises 960
Programming Problems 961
Case Study Follow-Up 962

Templates and Exceptions 963


17 17.1 Template Functions 964
Function Overloading 964
Defining a Function Template 967
Instantiating a Function Template 968
Enhancing the Print Template 969
User-Defined Specializations 970
Organization of Program Code 971
17.2 Template Classes 974
Instantiating a Class Template 976
Organization of Program Code 978
A Caution 981
17.3 Exceptions 982
The throw Statement 983
The try- catch Statement 985
Nonlocal Exception Handlers 988
Re-Throwing an Exception 991
Standard Exceptions 992
Back to the Division-by-Zero Problem 995
xxviii I
Contents

Problem-Solving Case Study: The SortedList Class Revisited 996


Testing and Debugging 1007
Testing and Debugging Hints 1007
Summary 1008
Quick Check 1009
Answers 1010
Exam Preparation Exercises 1011

Programming Warm-Up Exercises 1012


Programming Problems 1014
Case Study Follow-Up 1014

Recursion 1017
18 18.1 What Is Recursion? 1018
18.2 Recursive Algorithms with Simple Variables 1022
18.3 Towers of Hanoi 1025
18.4 Recursive Algorithms with Structured Variables 1030
18.5 Recursion Using Pointer Variables 1032
Printing a Dynamic Linked List in Reverse Order 1032
Copying a Dynamic Linked List 1035
18.6 Recursion or Iteration? 1040
Problem-Solving Case Study: Converting Decimal Integers to
Binary Integers 1041

Problem-Solving Case Study: Minimum Value in an


Integer Array 1044
Testing and Debugging 1046
Testing and Debugging Hints 1046
Summary 1047
Quick Check 1047
Answers 1048
Exam Preparation Exercises 1048
Programming Warm-Up Exercises 1050
Programming Problems 1052
Case Study Follow-Up 1053

Appendix A Reserved Words 1055


Appendix B Operator Precedence 1055
Contents | XXIX

Appendix C A Selection of Standard Library Routines 1057


Appendix D Using This Book with a Prestandard Version of C++ 1 066
Appendix E Character Sets 1071

Appendix F Program Style, Formatting, and Documentation 1073


Glossary 1081

Answers to Selected Exercises 1091

Index 1125
Overview of
Programming and
Problem Solving
To understand what a computer program is.

To be able to list the basic stages involved in writ-


ing a computer program.

To understand what an algorithm is.

To learn what a high-level programming language


is.

To be able to describe what a compiler is and what


it does.

To understand the compilation and execution pro-


cesses.

To learn the history of the C++ programming language.

To learn what the major components of a computer are


and how they work together.

To be able to distinguish between hardware and soft-


ware.

To learn about some of the basic ethical issues con-


fronting computing professionals.

To be able to choose an appropriate problem-solving


method for developing an algorithmic solution to a

problem.

nm«<t<ana«anaa«iaamH«|niia«i

I
Chapter 1 : Overview of Programming and Problem Solving

Overview of Programming
1.1
In the box in the margin is a definition of computer. What a brief definition for some-
thing that has, in just a few decades, changed the way of Hfe in industrialized societies!
Computers touch all areas of our lives: paying bills,

^m-put-erilonv^toirir^ driving cars, using the telephone, shopping. In fact, it

that computes; specif, a programmable electronic device would be easier to list those areas of our lives that are
that can store, retrieve, and process data* not affected by computers.*
— •—'^ —'^— « —-— i^ J5 5a(j ^]^a^ a device that does so much good is

so often maligned and feared. How many times have


you heard someone say, "I'm sorry, our computer fouled things up" or "I just don't
understand computers; they're too complicated for me"? The very fact that you are
reading this book, however, means that you are ready to set aside prejudice and learn
about computers. But be forewarned: This book is not just about computers in the
abstract. This is a text to teach you how to program computers.

What Is Programming?

Much of human behavior and thought is characterized by logical sequences. Since


infancy, you have been learning how to act, how to do things. And you have learned to
expect certain behavior from other people.
A lot of what you do every day you do automatically. Fortunately, it is not neces-
sary for you to consciously think of every step involved in a process as simple as turn-
ing a page by hand:

1. Lift hand.

2. Move hand to right side of book.

3. Grasp top right comer of page.


4. Move hand from right to left until page is posifioned so that you can read what is

on the other side.

5. Let go of page.

Think how many neurons must fire and how many muscles must respond, all in a cer-
tain order or sequence, to move your arm and hand. Yet you do it unconsciously.
Much of what you do unconsciously you once had to learn. Watch how a baby con-
centrates on putting one foot before the other while learning to walk. Then watch a

group of three-year-olds playing tag.


On a broader scale, mathematics never could have been developed without logical
sequences of steps for solving problems and proving theorems. Mass production never
would have worked without operafions taking place in a certain order. Our whole civi-
lization is based on the order of things and actions.

*By permission. From Merriam-Webster's Collegiate Dictionary: Tenth Edition. ® 1994 by Merriam-Webster
Inc.
1.1 Overview of Programming |

We create order, both consciously and


unconsciously, through a process we call Programming Planning or scheduling the performance
programming. This book is concerned with of a task or an event.

the programming of one of our tools, the Computer A programmable device that can store,
computer. retrieve, and process data.
Just as a concert program lists the order A sequence
Computer program of instructions to be
in which the players perform pieces, a com- performed by a computer.
puter program lists the sequence of steps the
Computer programming The process of planning a
computer performs. From now on, when we a computer to follow.
sequence of steps for
use the words programming and program, we
mean computer programming and computer
program.
The computer allows us to do tasks more efficiently, quickly, and accurately than
we could by hand-if we could do them by hand at all. In order to use this powerful
tool, we must specify what we want done and the order in which we want it done. We
do this through programming.

How Do We Write a Program?

A computer is not intelligent. It cannot analyze a problem and come up with a solution.
A human (the programmer) must analyze the problem, develop a sequence of instruc-
tions for solving the problem, and then communicate it to the computer. What's the
advantage of using a computer if it Once we have written the
can't solve problems?
solution as a sequence of instructions for the computer, the computer can repeat the
solution very quickly and consistently, again and again. The computer frees people from
repetitive and boring tasks.
To write a sequence of instructions for a computer to follow, we must go through a
two-phase process: problem solving and implementation (see Figure 1-1).

Problem-Solving Phase

1. Analysis and specification. Understand (define) the problem and what the solution
must do.
2. General solution (algorithm). Develop a logical sequence of steps that solves the
problem.
3. Verify. Follow the steps exactly to see if the solution really does solve the prob-
lem.

Implementation Phase

1. Concrete solution (program). Translate the algorithm into a programming lan-


guage.
2. Test. Have the computer follow the instructions. Then manually check the results.
If youfind errors, analyze the program and the algorithm to determine the source
of the errors, and then make corrections.
I Chapter 1: Overview of Programming and Problem Solving

PROBLEM-SOLVING PHASE IMPLEMENTATION PHASE

r
Analysis
and
specification

General solution Concrete solution


(algorithm) (program)

i
Verify
Test

Maintenance phase
Vs.

Figure 1-1 Programming Process

Once a program has been written, it enters a third phase: maintenance.

Maintenance Phase

1. Use. Use the program.


2. Maintain. Modify the program to meet changing requirements or to correct any
errors that show up in using it.

The programmer begins the programming process


'

' '' ""


'

by analyzing the problem and developing a general


Algorithm A step-by-step procedure for solving a prob- solution called an algorithm. Understanding and ana-
lem in a finite amount of time. lyzing a problem take up much more time than Figure
'
"' i iiii
.i
1-1 implies. They are the heart of the programming
process.
If our definitions of a computer program and an algorithm look similar, it is

because all programs are algorithms. A program is simply an algorithm that has been
written for a computer.
An algorithm is a verbal or written description of a logical sequence of actions. We
use algorithms every day. Recipes, instructions, and directions are all examples of algo-
rithms that are not programs.
1.1 Overview of Programming I

When you start your car, you follow a step-by-step procedure. The algorithm might
look something like this:

1. Insert the key.

2. Make sure the transmission is in Park (or Neutral).

3. Depress the gas pedal.

4. Turn the key to the start position.

5. If the engine starts within six seconds, release the key to the ignition position.

6. If the engine doesn't start in six seconds, release the key and gas pedal, wait ten seconds, and repeat Steps 3 through

6, but not more than five times.

7. If the car doesn't start, call the garage.

Without the phrase "but not more than five times" in Step 6, you could be trying to
start the car forever. Why? Because if something is wrong with the car, repeating Steps

3 through 6 over and over again will not start it. This kind of never-ending situation is

called an infinite loop. If we leave the phrase "but not more than five times" out of Step

6, the procedure does not fit our definition of an algorithm. An algorithm must termi-
amount of time for all possible conditions.
nate in a finite
Suppose a programmer needs an algorithm to determine an employee's weekly
wages. The algorithm reflects what would be done by hand:

\t.

1. Look up the employee's pay rate.

2. Determine the number of hours worked during the week.

3. If the number of hours worked is less than or equal to 40, multiply the number of hours by the pay rate to calculate
regular wages.

4. If the number of hours worked is greater than 40, multiply 40 by the pay rate to calculate regular wages, and then
multiply the difference between the number of hours worked and 40 by 1- times the pay rate to calculate overtime

wages.

5. Add the regular wages to the overtime wages (if any) to determine total wages for the week.
6 I
Chapter 1 : Overview of Programming and Problem Solving

The steps the computer follows are often the same steps you would use to do the calcu-
lations by hand.
After developing a general solution, the programmer tests the algorithm, walking
through each step mentally or manually. If the algorithm doesn't work, the programmer
repeats the problem-solving process, analyzing the problem again and coming up with
another algorithm. Often the second algorithm is just a variation of the first. When the
programmer is satisfied with the algorithm, he or she
a«eg^-ir.-^.^^^^.^^.^....:^c->irr««^w.>,a«»^-«^ ttanslatcs it into a programming language. We use

Programming language A set of rules, symbols, and the C++ programming language in this book,
special words used to construct computer program. A programming language is a simplified form of
— '-""- "-" -'-
'
— —-— — ——~— —
'^-'^
a

- " ^
j

English (with math symbols) that adheres to a strict

set of grammatical rules. English is far too compli-


cated a language for today's computers to follow. Programming languages, because they
limit vocabulary and grammar, are much simpler.
Although a programming language is simple in form, it is not always easy to use.
Try giving someone directions to the nearest airport using a vocabulary of no more than
45 words, and you'll begin to see the problem. Programming forces you to write very
simple, exact instructions.
Translating an algorithm into a programming language is called coding the algorithm.
The product of that translation-the program-is tested by running (executing) it on the
computer. If the program fails to produce the desired results, the programmer must debug
it— that is, determine what is wrong and then modify the program, or even the algorithm,
to fix it. The combination of coding and testing an algorithm is called implementation.
There is no single way to implement an algorithm. For example, an algorithm can
be translated into more than one programming language. Each translation produces a
different implementation. Even when two people translate an algorithm into the same
programming language, they are likely to come up with different implementations (see
Figure 1-2). Why? Because every programming language allows the programmer some
flexibility in how an algorithm is translated. Given this flexibility, people adopt their
own styles in writing programs, just as they do in writing short stories or essays. Once
you have some programming experience, you develop a style of your own. Throughout
this book, we offer tips on good programming style.
Some people try to speed up the programming process by going directly from the
problem definition to coding the program (see Figure 1-3). A shortcut here is very
tempting and at first seems to save a lot of time. However, for many reasons that will

become obvious to you as you read this book, this kind of shortcut actually takes more
time and Developing a general solution before you write a program helps you
effort.

manage the problem, keep your thoughts straight, and avoid mistakes. If you don't take
the time at the beginning to think out and polish your algorithm, you'll spend a lot of
extra time debugging and revising your program. So think first and code later! The
sooner you start coding, the longer it takes to write a program that works.
Once a program has been put into use, it is often necessary to modify it. Modifica-
tion may involve fixing an error that is discovered during the use of the program or
changing the program in response to changes in the user's requirements. Each time the
program is modified, it is necessary to repeat the problem-solving and implementation
phases for those aspects of the program that change. This phase of the programming
1.1 Overview of Programming |
7

Nell's C++ Program

Algorithm Nell's Java Program

Nell's Ada Program

a. Algorithm translated into different languages

Nell's C++ Program

Algorithm Chip's C++ Program

Mark's C++ Program

b. Algorithm translated by different people

Figure 1-2 Differences in Implementation

PROBLEM-SOLVING PHASE

Algorithm

Shortcut?

^ Program

IMPLEMENTATION PHASE

Figure 1-3 Programming Shortcut?


I Chapter 1 : Overview of Programming and Problem Solving

processis known as maintenance and actually accounts for the majority of the effort

expended on most programs. For example, a program that is implemented in a few


months may need to be maintained over a period of many years. Thus, it is a cost-effec-
tive investment of time to develop the initial problem solution and program implemen-
tation carefully. Together, the problem-solving, implementation, and maintenance
phases constitute the program's life cycle.

implementing
In addition to solving the problem,
"**' ~"
'

the and maintaining the program,


algorithm,
Documentation The written text and comments that
documentation is an important part of the program-
make a program easier for others to understand, use, and
ming process. Documentation includes written expla-
modify.
I
nations of the problem being solved and the
Information Any knowledge that can be communicated
organization of the solution, comments embedded
Data Information in a form a computer can use. within the program and user manuals that
itself,

describe how to use the program. Most programs are


worked on by many different people over a long
period of time. Each of those people must be able to read and understand your code.
After you write a program, you must give the computer the information or data
necessary to solve the problem. Information is any knowledge that can be communi-
cated, including abstract ideas and concepts such as "the earth is round." Data is infor-
mation in a form the computer can use-for example, the numbers and letters making
up the formulas that relate the earth's radius to its volume and surface area. But data is
not restricted to numbers and letters. These days, computers also process data that rep-
resents sound (to be played through speakers), graphic images (to be displayed on a
computer screen or printer), video (to be played on a VCR), and so forih.

Thenretiral Fnunriatinns
(ic-. Binary Representation of Data

In a computer, data is represented electronically by pulses of electricity. Electric circuits, in

their simplest form, are either on or off. Usually a circuit that is on is represented by the num-
ber 1 ; a circuit that is off is represented by the number 0. Any kind of data can be represented

by combinations of enough Is and Os. We simply have to choose which combination repre-
sents each piece of data we are using. For example, we could arbitrarily choose the pattern
11010001 10 to represent the name C++.
Data represented by Is and Os is in binary form. The binary (base-2) number system uses
only Is and Os to represent numbers. (The decimal [base-10] number system uses the digits

through 9.) The word bit (short for binary digit) often is used to refer to a single 1 or 0. The

pattern 1 1010001 10 thus has 10 bits. A binary number with 10 bits can represent 2^° (1024)
different patterns. A byte is a group of 8 bits; it can represent 2^ (256) patterns. Inside the
computer, each character (such as the letter A, the letter g, or a question mark) is usually rep-

resented by a byte. Four bits, or half of a byte, is called a nibble or nybble-a name that origi-

nally was proposed with tongue in cheek but now is standard terminology. Groups of 16, 32,

(continued) ^
Exploring the Variety of Random
Documents with Different Content
It would seem, however, that Providence was keeping its eye on the
Acacias. For the very next morning brought a solution of the
difficulty. The marquis wrote from Yorkshire to suggest that during
the following week, if convenient to himself, Mr. Lascelles should
come to Barne Moor, as previously arranged, to paint the fair
Priscilla.
It appeared that in the stress of circumstance both Jim and his
mother had forgotten the Yorkshire marquis and the fair Priscilla.
“And it means a cool five hundred, too,” said Jim, with a little
pardonable exultation. “The terms are already arranged, thanks to
that old sportsman who is the oddest mixture of a human being I
have ever met.”
And then Jim gave a groan, for he remembered that it was upon the
strength of this important commission he had made up his mind to
take the plunge with the Goose Girl. The next moment he was
cursing himself because his upper lip was so flabby.
“You will never be the least use in this world, James Lascelles, my
son,” was the burden of his reflections, “if you can’t learn to take a
facer or two. Every time they knock you down you have got to come
up smiling, or you will certainly never be a Velasquez.”
Mrs. Lascelles was overjoyed by the providential letter from
Yorkshire. She blessed the marquis and all his acres. She insisted
that Jim should write by the next post to announce his intention of
coming to Barne Moor on the following Monday. And, in order that
there should be no possible doubt about the matter, she put on her
hat, although it was raining hard, and sallied forth to the stationer’s
shop at the corner of Chestnut Road and invested one of her few
remaining sixpences in Bradshaw’s Guide.
CHAPTER XXXII
BARNE MOOR

ABOUT tea-time on the following Monday Jim Lascelles found


himself at Barne Moor. The house was a bleak upstanding place in
the north of Yorkshire. It was in a fold of the moors, and, although
its size was impressive, it was architecturally hideous.
Jim had been very unhappy all the way up from London. The change
of locale, however, raised his spirits a little. The contemplation of the
five hundred pounds and a period of definite employment did
something to help him also. And hardly had he set foot in the house
than a great surprise was in store for him.
Almost the first person he saw was the Goose Girl. She had been out
with the guns, and was now consuming tea and hot buttered cakes.
It was nearly six weeks since they had parted in Wales. In that
period each had changed. With his artist’s eye Jim could not help
noticing that she was still the elemental creature of the Devonshire
lanes. Her candor and simplicity were not less than they were, but
somewhere in her was a kind of reserved inclosure, an expanse of
deep feeling hidden away, which only those who held her secret
would ever be able to discover.
Perhaps Jim Lascelles was glad to notice it. It did honor to the slow-
witted immobile creature, and it did honor to him. Yes, she was true
blue. There was nothing in her words and very little in the manner of
her greeting to suggest that a creature so primitive as herself had
this reserved space in her. She was just as she always was, and yet
at her first words of greeting Jim knew that she was much more.
“Why, it’s Jim!” she exclaimed in just the old way; and putting her
cake in her saucer, she said, “I can’t shake hands with you, Jim,
because my fingers are all over butter.”
Jim hardly knew whether to rejoice at her presence or to be
dismayed by it.
“Why, Goose Girl,” said he, “whoever could have thought of seeing
you here?”
“Aunt Caroline is here,” said she, “and Miss Burden, and Lord
Cheriton too.”
“How strange that we should meet again like this!” said Jim, rather
lamely.
Yet it was scarcely so strange as Jim thought it was. Aunt Caroline,
in spite of her years and her increasingly difficult temper, still had
certain houses open to her, and Barne Moor was one of them. Her
store of energy was by no means exhausted; she liked still to keep
in the world, to know what was doing; and she liked her rubber. It
would not, perhaps, be strictly true to say that she was welcome at
Barne Moor, but when Wales began to bore her she resolutely turned
her face in that direction, because she knew that at that time
Yorkshire would contain a choice collection of her friends and her
enemies, and would be infinitely more diverting than Pen-y-Gros
Castle or London itself in the absence of Parliament.
At Barne Moor Jim of course was a nobody, and was treated as such.
His hostess, who was of the strain of the former Whig oligarchy, like
so many to be found under that ample roof, was not so much
exclusive as she was indifferent to those outside the circle. She was
a ponderous, neutral kind of woman, who bullied her husband and
had very definite views about religion. From the first Jim Lascelles
did not find her in the last easy to get on with. It must be confessed
that he did not try to get on with her particularly.
Still, during the time Jim spent at Barne Moor things did not go
amiss. The Goose Girl was still the child of nature she had always
been. The old woman of Hill Street was reasonably civil; quite as
civil, in fact, as Jim expected her to be. Miss Burden, in a curiously
delicate manner, showed that she understood the tragedy. As for
Cheriton, who was an old friend of the house, and for some reason
high in the esteem of everybody, he extended the same genial
kindness to him that he had always done.
The only other of Jim’s acquaintances among the score or so people
that were gathered under the hospitable roof of Barne Moor was
George Betterton. No announcement had yet been made upon the
subject, but it was common knowledge that “an arrangement” was
likely to be forthcoming with a daughter of the house.
Jim Lascelles supposed that “the old sportsman” knew his own
business best, but he rather hoped that “it wouldn’t come off.” In
Jim’s opinion “George was a genuine fellow,” and Jim personally had
not the least admiration for the fair Priscilla. For one thing he had to
paint her to order; and that of course did not tell in her favor with
the temperament of genius.
She had not the least sense of pose. She was just a wooden sort of
Englishwoman, as neutral as her mother, who clipped her g’s and
powdered her nose, with dull red hair and pale green eyes, who took
very little interest in anything or anybody. But she shot well and rode
well, and went to church twice on Sunday.
She sat half a dozen times, and the rising artist did what he could
with her. Jim’s special talent lay in his color and his sense of values.
He used the dark oak of the gloomy old library for his background,
and he painted Priscilla’s hair a warm and glowing Titian color, with a
striking and distinguished pallor for the face; and for the eyes a
shade of blue which was extremely daring but successful. The
picture in its style and its distinction was absurdly unlike Priscilla
herself; yet somehow it was sufficiently like her to pass muster with
those who cared more for Priscilla than they did for her counterfeit
presentment.
About the fifth day of Jim’s sojourn Cheriton announced that the
picture of Priscilla was going to turn out very fine. He exhorted
Kendal publicly to send it to the next Royal Academy, and
complimented him upon having had the foresight and good sense to
obtain the man of the future to do the work. The bullet-headed
Yorkshireman was pleased, of course, since every bullet-headed
Yorkshireman likes to be complimented on his foresight and good
sense by an acknowledged expert.
“I wonder if he would paint my wife,” said Mr. Crosby of the Foreign
Office.
“You can ask him, my dear fellow,” said the expert.
“Would he want a stiff figure?” said Mr. Crosby, who had a very
practical mind.
“It would cost you a cool thousand, I dare say,” said Cheriton, before
Kendal could announce that it had cost him five hundred.
“Stiff, ain’t it, for an unknown man?” said Mr. Crosby.
“He is going to be the man, my dear fellow,” said Cheriton. “What do
you say, Caroline? You have seen some of his work.”
“I agree with you, Cheriton,” said the flattered Caroline, who knew
as much about pictures as Ponto did. “He has painted two of my
nieces, and in my opinion they are excellent likenesses.”
“Have you two nieces, Caroline?” said the Marquis. “That is
interesting. When are we to have the opportunity of seeing the other
one?”
“Next season—perhaps.”
As yet there had been no formal announcement of Cheriton’s
engagement, but it was known to many. It is true that those who
were best acquainted with him maintained an attitude of incredulity.
So many times in the past had there been talk of entertaining at
Cheriton House. Yet there was a consensus of opinion that he really
meant to settle down at last; and while all disinterested people could
not fail to admire his taste, the critical were a little inclined to doubt
his wisdom. Still, there was no doubt about the beauty and the
docility of his choice, and in her quaint way she had unmistakably
the bel air. She was a good honest girl, a Wargrave, and the old
woman of Hill Street could well afford to do something in the matter.
Still, the knowing ones “could not see it at all”; those who were not
so knowing thought that “Cheriton might have done worse.”
All the same, Miss Perry was famous and she was popular. Her
simplicity was something that was growing very rare; she was
unaffectedly good to everybody, and everybody could not help being
grateful to her for her goodness, because it sprang straight from the
heart. No matter whether people were important or unimportant, it
made no difference to her. Great beauty and an absolute friendliness
which is extended to all, which keeps the same gracious smile for
the odd man about the stables that it has for the wearer of the
Garter, will go far towards the conquest of the world.
Miss Perry had conquered her world. All agreed that Cheriton had
done well. Yet the creature was not in the least happy. So much
practice, however, had the Wargraves had in the course of the
centuries in dissembling their unhappiness and in offering their
heads to the block, that only four persons were able to suspect that
a brave, smiling, and bountiful exterior concealed a broken heart.
Jim Lascelles was one. He knew for certain. Miss Burden was
another. Caroline Crewkerne was no believer in broken hearts. For
one thing, she had never had a heart of any sort to break. But she
had seen those great damp splotches on the correspondence with
her father, she had noticed that the creature’s appetite was not what
it was; and there were half a dozen other symptoms that enabled
her to put two and two together. As for the fourth person, it was
Cheriton himself. He was a man of immense practical sagacity. The
Lascelles affair was perfectly familiar to him in all its bearings. He
himself was primarily responsible for it. And none knew better than
did he that youth will be served.
During Jim’s stay at Barne Moor, Cheriton went out of his way to
show him consideration. He behaved like a habitually courteous and
broad-minded man of the world, who, so to speak, knew the whole
alphabet of life, and if necessary could repeat it backwards.
“You have no right to be here, my dear fellow,” he said tacitly to Jim
Lascelles; “but since my Yorkshire friend, Kendal, has blundered, as
one’s Yorkshire friends generally do, and you find yourself in the
wrong galley, behave just as you would under ordinary
circumstances, and, if you have the courage, take up the parable
more or less where you left it. After all, you were brought up
together, and I am only an interloper, and an old one at that.”
It was bold and it was generous of Cheriton to take this course. But
the young fellow Lascelles had behaved so well that he was bound
to respect him. And he had a genuine liking for him too. Therefore
he raised no objection to their spending long hours upon the moors
with only one another for company, while he gossiped and shot
birds, and fribbled and idled away his time indoors among more
mature persons.
Still, it was trying Jim Lascelles somewhat highly. The test was a
severer one than perhaps Cheriton knew. For Jim was confident that
he had only to speak the word for the Goose Girl to marry him by
special license at Barne Moor parish church. Once, indeed, they
found themselves in it, since the Goose Girl was by way of being a
connoisseur in churches; and they had a pleasant and instructive
conversation with the vicar.
However, all’s well that ends well, as Shakespeare informs us. Jim
Lascelles did not obtain a special license, but returned to his mother
like a good son and, shall we say, a man of honor. For it would have
been such a fatally easy and natural thing to marry the Goose Girl at
Barne Moor parish church. If you came to think about it, why should
she be offered for sacrifice? Dickie, of course, would be able to go to
Sandhurst, and Milly would be able to go to the boarding school; but
all the same, it was desperately hard on the Goose Girl.
CHAPTER XXXIII
EVERYTHING FOR THE BEST IN THE BEST OF
ALL POSSIBLE WORLDS

JIM LASCELLES returned to Balham exactly nine days after he had


left that friendly but uninspired suburb. He had worked hard during
his absence in Yorkshire; the picture of the fair Priscilla had made
excellent progress, and there was a check for five hundred pounds in
prospect on completion. Further, by the interest and undoubted
talent for commerce of his friend Lord Cheriton, Mr. Crosby of the
Foreign Office had been induced to rise to seven hundred and fifty
pounds for the portrait of Mrs. Crosby and her children.
So far as the things of this world were concerned, Jim really
returned to his mother in high feather. The progress he was making
in his profession he felt was out of all proportion to his talent. But it
is a great thing to have a friend at court. So much is done in that
way. It is not always the best picture, or the best oratorio, or the
best play, or the best novel that makes the most guineas in the
market-square. It is one thing to create a masterpiece, and it is
another to translate it into pounds, shillings, and pence. There can
be no doubt that Jim Lascelles had made amazing strides in his art;
but all the same, he was a lucky fellow to have a man like Cheriton
to go round with a bell to call the attention of the picture-buying
public to the quality of his work.
Jim Lascelles would have been less than human had he not been
immensely grateful to Cheriton. And yet he would not have been
human either had he not hated him very sorely. After all, what is the
use of material prosperity if the man who confers it upon you robs
you of the only girl in the world you feel you will ever be able to
marry? Certainly he would now have the means to buy his mother a
new frock or so in order to deprive her of her favorite excuse for not
looking older. But life, even with professional success, was going to
be a hollow business.
However, Jim Lascelles contrived in this crisis to behave with a
discretion that was very creditable to his character. He had gone
down to the depths of late, and, as is often the case with such
divers in deep seas, he had brought up a few pearls. One of these
was resolution. He finished the picture of Priscilla out of hand and
drew his check; and although the season was November, he paid
several visits to Eaton Square and did his best for Mrs. Crosby and
her youthful family. And ever and anon he took his courage in his
hands and spent an hour in further devotion to the masterpiece that
was to make him famous.
It was not until early in January that Jim Lascelles made the
announcement to his patron that the portrait of Miss Perry was
complete. Thereupon quite a number of people interested in art
found their way to the Acacias. They were by no means unanimous
in their opinion regarding its intrinsic merit, but they all agreed that
it was bound to prove one of the sensations of the year.
“An extraordinarily clever fake,” said a critic of the fine arts privately.
“Mr. Lascelles,” said a dealer, “I should like you to give me an option
on all the work you produce during the next five years. I feel sure I
could sell it.”
“We have a new Gainsborough here,” said a third person, who spoke
in an unofficial capacity, “and that is all there is to be said about it.”
About the end of the month Cheriton himself appeared, duly armed
with expert opinion, to see for himself. He was accompanied by Miss
Burden and his fiancée, who was looking thin and unhappy. It was a
beautiful day for the time of year; and in regard to his appearance,
the happy wooer was as fastidious as usual. Never had he seemed
more faultless in his attire or more scrupulously paternal in his
demeanor. He looked long at the masterpiece, and he looked
particularly.
“Lascelles, my good fellow,” said he, “I am forced to arrive at one
conclusion. If you were to paint a thousand pictures, this is
something you will never surpass.”
“Why do you think so?” said Jim.
“Because, my dear fellow, there is growth in it. You began it a callow
stripling; you have finished it, shall I say, a strong man in the
plenitude of his power. I have watched you and the picture grow
together from month to month. It is given to no man to do that sort
of thing twice.”
Jim Lascelles, however, was a robust young fellow—at least, it was
his ideal to be so. He was apt to be on his guard against high-flown
sentiment, yet he knew that Cheriton had spoken the truth.
“You are right,” he said simply. “That canvas has got all I have or all
I ever shall have. I am older now than when I began it, and I hope
I’m wiser.”
“Not wiser really, my dear fellow; we never get wiser. But you have
found yourself. A great career lies before you.”
“You may be right,” said Jim, “or you may not be right, but either
way it doesn’t matter.”
Cheriton inspected the young fellow with the greatest coolness and
impartiality. There was no mistaking that the words were tragic.
Cheriton’s penetration declared them to be so. He took some little
time for reflection, and then he slowly drew a check out of his
pocket-book with an air that was really unfathomable.
“There must be no misunderstanding, Lascelles,” said he, with an air
that was brisk and businesslike. “There is every reason to believe
that the picture of Miss Perry will prove a valuable property. But at
the same time, I hold your promise that I may purchase it on my
own terms. Is not that the case?”
“It is, Lord Cheriton,” said Jim, with indifference.
“I hope the bargain I drove with you may not prove too hard,” said
Cheriton, with an enigmatic smile that Jim Lascelles took not the
least pains to fathom. “But if I may say so, your conduct in allowing
me to drive such a bargain was curiously injudicious. For everybody
tells me that your picture is magnificent.”
“I don’t think it matters,” said Jim, who was looking tired. “Although
one is glad you like it, of course.”
“It must always be pleasant to the artist to have his work admired.
My own comment upon your work is this. I hope, my dear fellow,
you will be able to forgive its extravagance.”
As he spoke he gave the check to Jim Lascelles. The painter,
however, paid no heed to it at first. His instinct was to crush it in his
hands and fling it away, so repugnant was the piece of paper to the
touch. Now that the time had come to part with the sole remaining
solace he possessed, he felt unable to yield it.
This, however, was a weakness he must not indulge. He looked at
the paper perfunctorily, and then he gave a little exclamation. The
check was made out in his favor for ten thousand pounds.
“I don’t understand,” said Jim. “Is there not some mistake?”
“You must constrain your modesty a little, that is all,” said Cheriton.
“People tell me it will be worth every penny of this sum to the next
generation. It is pleasant sometimes to anticipate the verdict of
posterity.”
Jim Lascelles did not know how to act or what to say. In his
judgment this was the most Quixotic proceeding he had ever
encountered.
“Really, Lord Cheriton,” he said, “I don’t feel that there are sufficient
grounds upon which I can accept such a sum as this.”
“A bargain is a bargain,” said Cheriton. “I hold your promise that I
am to purchase the picture on my own terms.”
In the flood tide of his bewilderment Jim Lascelles had perforce to
remain silent.
“Don’t forget, my dear Lascelles, that the highest pleasure that is
given to any man is to adopt the role of Mæcenas. And are you
aware that the Red House at Widdiford is in the market, and that six
thousand pounds will purchase it?”
Jim flinched a little. A deep flush overspread his face. This was
sacred ground, upon which it behoved the outside world to tread
warily.
“I hope you don’t mean that the Red House at Widdiford means
nothing to you?”
Jim was not proof against the assault.
“I’m not sure that it does,” he said miserably.
“I wouldn’t be too sure about that if I were you.”
Jim began to look decidedly fierce. In spite of the check for ten
thousand pounds, which he viewed as somewhat in the nature of a
mockery, he showed no disposition to be baited.
“Perhaps it would be wise, Lord Cheriton, not to pursue the subject.”
Cheriton laughed outright at the solemnity of the young fellow’s
manner.
“On the contrary,” said he, “one feels that the subject of the Red
House at Widdiford should be discussed at length. Miss Perry and I
have been over to look at the old place before completing the
purchase.”
“Ah! that is interesting,” said Jim, who was more bewildered than
ever.
“It seems that, in addition to its other lures, the Red House at
Widdiford has peaches in season.”
“Of course it has,” said Jim, who was beginning to feel that Cheriton
was making a rather long excursion in the realms of bad taste.
“Well, my dear fellow, I put it to you—what is the use of having
peaches in season if one has not the appetite to eat them?”
“What, indeed!” said Jim.
“And again, my dear fellow—what, pray, is the use of giving Buszard
a contract for the large size when cream buns lose their savor?”
Jim made no reply, but merely looked miserable.
“Let me tell you in confidence, Lascelles,” said his patron, in a
becomingly low tone, “that even the circus has begun to pall. And as
for Joseph Wright of Derby, the question of his permanent merit is
beginning to appear almost a matter of indifference. Do you feel
competent to give advice in regard to what ought to be done?”
“I am afraid I don’t, Lord Cheriton,” said Jim, rather feebly.
“That is disappointing, for in the past you have shown such a
surprising fertility of ideas and resources. The problem is so serious.
Can one conceive a world in which cream buns have no savor,
circuses no glamor, and in which the Joseph Wrights of Derby are
allowed to ruffle it unquestioned among their betters? Frankly, the
feat is beyond me, Lascelles. And then, too, my dear fellow, the
news that Muffin is to have a new mauve from London to wear in
the spring has excited hardly any enthusiasm.”
“Indeed?” said Jim.
“That is so, I assure you. And to my mind, that is not the least
sinister symptom. I have conferred with the wise woman of Hill
Street, and during my sojourn in the west country also with the
presiding genius of Slocum Magna. And after some discussion of the
pros and cons of the situation, for mon père and ma tante do not
appear to see eye to eye in all things, we are at last in agreement
that something ought to be done to restore the savor to the best
confectionery, and also to insure that no upstart shall occupy without
question the same kind of fauteuil as Rembrandt and Velasquez. The
result of our deliberations is, my dear fellow, that we have come to
the conclusion that you are the man to help us.”
“I!” said Jim, impotently.
“Have you any objection to undertaking such a scheme of
philanthropy?”
“If I could do anything to add to Miss Perry’s happiness,” said Jim, “I
should be just about the proudest chap in the world.”
“Well, it seems, my dear fellow, that you can do so. At least, that is
the opinion that has been arrived at by the experts who have
communed over her case.”
Jim’s heart beat painfully.
“Tell me what I can do,” he said rather hoarsely, “for the best, the
truest-hearted, the most absolutely genuine girl in the world.”
“You can marry her.”
“Marry her?” said Jim, weakly.
“Yes, in the afternoon of April the First, at Saint Sepulchre’s Church.”
“But——” said Jim.
“The oracle of Hill Street thinks the First of June is preferable,
because there will be more people in town, and the presents are
likely to be more numerous. But personally I agree with Mrs.
Lascelles and mon père that April is as good a time as any other for
visiting the Prado.”
“But——” said Jim.
“I forget the inn I stayed at when I was last at Madrid. It was ‘El’
Something, and for some obscure reason it had no aspirate. But one
Ford is the authority for Spain, although, to be sure, a certain
Borrow wrote a famous work upon the subject. By the way, we must
not overlook one important argument in favor of June.”
“What is it?” said Jim, mechanically.
“It is hardly right to expect a new mauve to make its début on the
First of April. Yet there seems no help for it. No ceremony could
possibly be considered complete without it.”
“Am I to understand——?” said Jim, who stopped with ridiculous
abruptness right in the middle of his question.
“By the way, my dear fellow, I have taken the liberty of suggesting
to your accomplished mother that it might help her literary career if
she moved a little nearer to the center. A little flat in Knightsbridge
might be a judicious investment. As you may be aware, publishers as
a race are highly susceptible, and an address in Knightsbridge might
favorably impress them.”
“Do you think so?” said Jim, who did not know in the least what he
was saying.
But there is really no reason to persist in this history. In spite of
scruples, which were as much due to pride as to generosity, Jim
Lascelles married the Goose Girl at Saint Sepulchre’s Church on the
First of April. On that significant occasion the presiding genius of Hill
Street displayed an amount of Christian feeling which, in the opinion
of a contemporary, was without parallel in his experience.
The entire family of Slocum Magna, including Milly, whose pigtail was
the color of a yellow chrysanthemum, and was tied with a ribbon,
came up to London and stayed a whole week at Morley’s Hotel.
Among other things, they all went one day to see the Exhibition, and
found there wasn’t one. Papa dined twice in Hill Street, and met
dukes and people; and he brought back the report that Aunt
Caroline was less worldly than he had feared she was. He gave his
daughter away on the glorious First; and Muffin wore her new
mauve on that occasion. In the opinion of all qualified persons it was
quite as successful as the peerless original. Polly, who took after her
papa, and had more intellect than all the rest of the family put
together, Dickie and Doggo included, looked charmingly proper in a
“costume” more reticent than Muffin’s. Her young man assisted the
Dean of Dunstable, the uncle of the bride, in performing the
ceremony.
Jim Lascelles and the Goose Girl spent a month in the land of
Cervantes and Velasquez. They are living now at the Red House at
Widdiford. Jim is quite likely to be elected to an Associateship of the
Royal Academy before long. At least, he is getting very good prices
for his work, and his “Miss Perry” has been esteemed a rare triumph
for British art. His “Naiad” also, purchased by the Chantrey Bequest,
has been generally and justly admired.
The accomplished mother of the rising artist took the disinterested
advice of a well-wisher, and a fortnight after her son’s brilliant
marriage—the Morning Mirror described it as such—she left “P.P.C.”
cards on the Miss Champneys at the Chestnuts, and moved “nearer
to the center.” It may have been coincidence, or it may have been
cause and effect, but within a fortnight of her installation at No. 5,
Beaufort Mansions, W., “The Fair Immortal” was accepted on a
royalty by an eminent firm of publishers, and made its appearance in
the course of the summer. It won such unanimous approval from the
Press and the public, that it can now be purchased for sixpence of
any self-respecting bookseller in the United Kingdom; its fortunate
authoress has signed contracts for work for the next three years and
has been elected a member of three of the best ladies’ clubs in the
metropolis.
Muffin’s season at Hill Street was an even greater triumph than her
sister’s—but thereby hangs a tale for a wet afternoon. Aunt Caroline,
in spite of her advanced years, is worth “a good many dead ones” at
present, and in the opinion of her oldest friend her manner has more
amenity. Perhaps it is that the influence of youth has been a good
one in her life. It is right to think so since there is no reason to
believe that she has altered her opinion of the clergy.
Polly has not yet married her parson, but she is certain to do so.
Serious people, however, “make haste slowly,” as the wise Italians
say. It is well that they should. Charley has found his way to
Sandhurst all right, and feels himself to be a field-marshal already.
Dickie has lately been presented to a living worth eleven hundred a
year—a really preposterous emolument, considering the widespread
depression in things ecclesiastical. However, in justice to Dickie, it
should be stated that he was always quietly confident that
something would come of his left-arm bowling. And so it ought if
you break both ways.
Milly has been two terms already at her Brighton boarding school. In
the opinion of her mistresses she is the best inside right at hockey
on the South Coast. If she is not chosen to play against Wales in the
forthcoming international match she will be much disappointed.
Entertaining at Cheriton House is still to seek. The thing threatens to
become a national scandal. Comparisons, highly unfavorable to the
present peer, are being constantly drawn by convinced free-fooders
and the praisers of past times. The noble earl, however, is fully
occupied at present in steering a course between the Scylla of Hill
Street on the one hand, and the Charybdis of No. 5, Beaufort
Mansions on the other. The presiding genius of the former locality,
however, defines a coxcomb as a person who never means anything.
Still, it doesn’t do to be too sure in these days.
As an instance of the need for honest doubt, George Betterton did
not lead the fair Priscilla to the altar after all. The world understood
that a religious difference was the rock which sundered them.
Whether George had too little religion and Priscilla had too much, is
one of those things that has never been elucidated clearly. But,
beyond all shade of controversy, they were never brought to the
question. Priscilla made quite a good marriage, all the same. As for
George—well, what really happened to him is a story for one of
those typical English afternoons in which it is really not fit for a dog
to be out. People say that George is much improved lately.
In conclusion, we feel bound to record our opinion that it is gravely
to be doubted whether Jim Lascelles will make as great a painter as
Velasquez. Considering his youth, his attainments, and his temper,
we were among those who predicted a high destiny for the young
fellow, but that was before “the wicket rolled out so plumb.”
Authorities upon the subject are not slow to inform us, however, that
it is better to marry the girl you want to, and to live at the Red
House at Widdiford, and be a county magistrate, and to have a
couple of expensive sons in the Services, and to have your girls
dressed by Redfern and presented at Court, than to appear on a
pedestal by public subscription in front of the National Gallery three
centuries after you have ceased to take an interest in the verdict of
posterity.
Quot homines tot sententiæ. These wiseacres may be right, or they
may not be right. It is only the Caroline Crewkernes who are
infallible.
THE END
GOOD FICTION
ANONYMOUS
SAPPHO IN BOSTON
A dainty and brilliant novel by a writer of long
experience. Scene, Boston and England. Period, to-
day. Illustrated. $1.50.

JOHN LUTHER LONG’S


FELICE
Mr. Long has never written a more charming story than
this tale of Italian life in Philadelphia. Illustrated in
colors. $1.50.

THOMAS L. MASSON’S
THE VON BLUMERS
A sparkling picture of American life in the suburbs of
New York, full of insight and penetrating,
unostentatious humor. Illustrated by Bayard Jones,
$1.50.

ROBERT HAVEN SCHAUFFLER’S


WHERE SPEECH ENDS
A novel of the orchestra which takes the reader into
complete comradeship with the men who interpret
the world’s greatest music in the world’s greatest
way. $1.50

CONSTANCE SMEDLEY’S
THE DAUGHTER
A vigorous, likeable novel of the modern suffragette
movement in England. Has an extremely interesting
plot, and moves rapidly from the start. 12mo. $1.50

CONFLICT
An unusually strong and fascinating story of English life
in some of its most up-to-date phases. Depicts a
modern business woman in a modern environment.
$1.50

ALICE McALILLY’S
THE LARKINS WEDDING
“An apotheosis of good humor and neighborly
kindness.”—The Outlook. 24 illustrations. $1.00.

EDEN PHILLPOTTS’S
THE VIRGIN IN JUDGMENT
Mr. Phillpotts never wrote a finer, sounder novel of
Dartmoor than this. It has characters that will live
long. 12mo. $1.50.
J. C. SNAITH’S
WILLIAM JORDAN, JUNIOR
“The most moving and fascinating piece of work the
author of ‘Broke of Covenden’ has yet given us.”—
Contemporary Review (London). $1.50.

JOHN TREVENA’S
FURZE THE CRUEL
“It is always difficult to define what constitutes
greatness in any form of art, but when greatness
exists it is easy to discern. This is a great book—
almost a masterpiece.”—London Academy. $1.50.

ELIZABETH ROBINS’S
THE MILLS OF THE GODS
One of Miss Robin’s most finished and brilliant stories.
Its flavor is almost medieval in quality, although the
period is to-day. A superb artistic story of
Continental life. 12mo. $1.50.

ANNULET ANDREWS’S
THE WIFE OF NARCISSUS
“A stroke of genius.”—Hartford Courant.
“Instinct with spring-like romance.”—Chicago Record-
Herald. 12 mo. $1.50.
ELEANOR TALBOT KINKEAD’S
THE INVISIBLE BOND
“Rises to fine heights and is inspired by fine ideals.”—
New York Tribune.
“A gripping, brainy story, revealing an artist in literature
of decided promise.”—Boston Herald. Illustrated.
$1.50.

The COURAGE of BLACKBURN BLAIR


“The characterization is markedly good, various men
and women standing out like clear portraits. Best of
all, perhaps, the whole exhales a subtle aroma of
delicate romance and passion.”—Chicago Record-
Herald. 12mo. $1.50.

MOFFAT, YARD & COMPANY


NEW YORK
TRANSCRIBER’S NOTES:
Obvious typographical errors have been corrected.
Inconsistencies in hyphenation have been
standardized.
Archaic or variant spelling has been retained.
*** END OF THE PROJECT GUTENBERG EBOOK ARAMINTA ***

Updated editions will replace the previous one—the old editions will
be renamed.

Creating the works from print editions not protected by U.S.


copyright law means that no one owns a United States copyright in
these works, so the Foundation (and you!) can copy and distribute it
in the United States without permission and without paying
copyright royalties. Special rules, set forth in the General Terms of
Use part of this license, apply to copying and distributing Project
Gutenberg™ electronic works to protect the PROJECT GUTENBERG™
concept and trademark. Project Gutenberg is a registered trademark,
and may not be used if you charge for an eBook, except by following
the terms of the trademark license, including paying royalties for use
of the Project Gutenberg trademark. If you do not charge anything
for copies of this eBook, complying with the trademark license is
very easy. You may use this eBook for nearly any purpose such as
creation of derivative works, reports, performances and research.
Project Gutenberg eBooks may be modified and printed and given
away—you may do practically ANYTHING in the United States with
eBooks not protected by U.S. copyright law. Redistribution is subject
to the trademark license, especially commercial redistribution.

START: FULL LICENSE


THE FULL PROJECT GUTENBERG LICENSE
PLEASE READ THIS BEFORE YOU DISTRIBUTE OR USE THIS WORK

To protect the Project Gutenberg™ mission of promoting the free


distribution of electronic works, by using or distributing this work (or
any other work associated in any way with the phrase “Project
Gutenberg”), you agree to comply with all the terms of the Full
Project Gutenberg™ License available with this file or online at
www.gutenberg.org/license.

Section 1. General Terms of Use and


Redistributing Project Gutenberg™
electronic works
1.A. By reading or using any part of this Project Gutenberg™
electronic work, you indicate that you have read, understand, agree
to and accept all the terms of this license and intellectual property
(trademark/copyright) agreement. If you do not agree to abide by all
the terms of this agreement, you must cease using and return or
destroy all copies of Project Gutenberg™ electronic works in your
possession. If you paid a fee for obtaining a copy of or access to a
Project Gutenberg™ electronic work and you do not agree to be
bound by the terms of this agreement, you may obtain a refund
from the person or entity to whom you paid the fee as set forth in
paragraph 1.E.8.

1.B. “Project Gutenberg” is a registered trademark. It may only be


used on or associated in any way with an electronic work by people
who agree to be bound by the terms of this agreement. There are a
few things that you can do with most Project Gutenberg™ electronic
works even without complying with the full terms of this agreement.
See paragraph 1.C below. There are a lot of things you can do with
Project Gutenberg™ electronic works if you follow the terms of this
agreement and help preserve free future access to Project
Gutenberg™ electronic works. See paragraph 1.E below.
1.C. The Project Gutenberg Literary Archive Foundation (“the
Foundation” or PGLAF), owns a compilation copyright in the
collection of Project Gutenberg™ electronic works. Nearly all the
individual works in the collection are in the public domain in the
United States. If an individual work is unprotected by copyright law
in the United States and you are located in the United States, we do
not claim a right to prevent you from copying, distributing,
performing, displaying or creating derivative works based on the
work as long as all references to Project Gutenberg are removed. Of
course, we hope that you will support the Project Gutenberg™
mission of promoting free access to electronic works by freely
sharing Project Gutenberg™ works in compliance with the terms of
this agreement for keeping the Project Gutenberg™ name associated
with the work. You can easily comply with the terms of this
agreement by keeping this work in the same format with its attached
full Project Gutenberg™ License when you share it without charge
with others.

1.D. The copyright laws of the place where you are located also
govern what you can do with this work. Copyright laws in most
countries are in a constant state of change. If you are outside the
United States, check the laws of your country in addition to the
terms of this agreement before downloading, copying, displaying,
performing, distributing or creating derivative works based on this
work or any other Project Gutenberg™ work. The Foundation makes
no representations concerning the copyright status of any work in
any country other than the United States.

1.E. Unless you have removed all references to Project Gutenberg:

1.E.1. The following sentence, with active links to, or other


immediate access to, the full Project Gutenberg™ License must
appear prominently whenever any copy of a Project Gutenberg™
work (any work on which the phrase “Project Gutenberg” appears,
or with which the phrase “Project Gutenberg” is associated) is
accessed, displayed, performed, viewed, copied or distributed:
This eBook is for the use of anyone anywhere in the United
States and most other parts of the world at no cost and with
almost no restrictions whatsoever. You may copy it, give it away
or re-use it under the terms of the Project Gutenberg License
included with this eBook or online at www.gutenberg.org. If you
are not located in the United States, you will have to check the
laws of the country where you are located before using this
eBook.

1.E.2. If an individual Project Gutenberg™ electronic work is derived


from texts not protected by U.S. copyright law (does not contain a
notice indicating that it is posted with permission of the copyright
holder), the work can be copied and distributed to anyone in the
United States without paying any fees or charges. If you are
redistributing or providing access to a work with the phrase “Project
Gutenberg” associated with or appearing on the work, you must
comply either with the requirements of paragraphs 1.E.1 through
1.E.7 or obtain permission for the use of the work and the Project
Gutenberg™ trademark as set forth in paragraphs 1.E.8 or 1.E.9.

1.E.3. If an individual Project Gutenberg™ electronic work is posted


with the permission of the copyright holder, your use and distribution
must comply with both paragraphs 1.E.1 through 1.E.7 and any
additional terms imposed by the copyright holder. Additional terms
will be linked to the Project Gutenberg™ License for all works posted
with the permission of the copyright holder found at the beginning
of this work.

1.E.4. Do not unlink or detach or remove the full Project


Gutenberg™ License terms from this work, or any files containing a
part of this work or any other work associated with Project
Gutenberg™.

1.E.5. Do not copy, display, perform, distribute or redistribute this


electronic work, or any part of this electronic work, without
prominently displaying the sentence set forth in paragraph 1.E.1
with active links or immediate access to the full terms of the Project
Gutenberg™ License.

1.E.6. You may convert to and distribute this work in any binary,
compressed, marked up, nonproprietary or proprietary form,
including any word processing or hypertext form. However, if you
provide access to or distribute copies of a Project Gutenberg™ work
in a format other than “Plain Vanilla ASCII” or other format used in
the official version posted on the official Project Gutenberg™ website
(www.gutenberg.org), you must, at no additional cost, fee or
expense to the user, provide a copy, a means of exporting a copy, or
a means of obtaining a copy upon request, of the work in its original
“Plain Vanilla ASCII” or other form. Any alternate format must
include the full Project Gutenberg™ License as specified in
paragraph 1.E.1.

1.E.7. Do not charge a fee for access to, viewing, displaying,


performing, copying or distributing any Project Gutenberg™ works
unless you comply with paragraph 1.E.8 or 1.E.9.

1.E.8. You may charge a reasonable fee for copies of or providing


access to or distributing Project Gutenberg™ electronic works
provided that:

• You pay a royalty fee of 20% of the gross profits you derive
from the use of Project Gutenberg™ works calculated using the
method you already use to calculate your applicable taxes. The
fee is owed to the owner of the Project Gutenberg™ trademark,
but he has agreed to donate royalties under this paragraph to
the Project Gutenberg Literary Archive Foundation. Royalty
payments must be paid within 60 days following each date on
which you prepare (or are legally required to prepare) your
periodic tax returns. Royalty payments should be clearly marked
as such and sent to the Project Gutenberg Literary Archive
Foundation at the address specified in Section 4, “Information
about donations to the Project Gutenberg Literary Archive
Foundation.”

• You provide a full refund of any money paid by a user who


notifies you in writing (or by e-mail) within 30 days of receipt
that s/he does not agree to the terms of the full Project
Gutenberg™ License. You must require such a user to return or
destroy all copies of the works possessed in a physical medium
and discontinue all use of and all access to other copies of
Project Gutenberg™ works.

• You provide, in accordance with paragraph 1.F.3, a full refund of


any money paid for a work or a replacement copy, if a defect in
the electronic work is discovered and reported to you within 90
days of receipt of the work.

• You comply with all other terms of this agreement for free
distribution of Project Gutenberg™ works.

1.E.9. If you wish to charge a fee or distribute a Project Gutenberg™


electronic work or group of works on different terms than are set
forth in this agreement, you must obtain permission in writing from
the Project Gutenberg Literary Archive Foundation, the manager of
the Project Gutenberg™ trademark. Contact the Foundation as set
forth in Section 3 below.

1.F.

1.F.1. Project Gutenberg volunteers and employees expend


considerable effort to identify, do copyright research on, transcribe
and proofread works not protected by U.S. copyright law in creating
the Project Gutenberg™ collection. Despite these efforts, Project
Gutenberg™ electronic works, and the medium on which they may
be stored, may contain “Defects,” such as, but not limited to,
incomplete, inaccurate or corrupt data, transcription errors, a
copyright or other intellectual property infringement, a defective or
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!

ebookfinal.com

You might also like