0% found this document useful (0 votes)
63 views

Programming and Problem Solving with C 3rd Edition Edition Nell B. Dale 2024 scribd download

Dale

Uploaded by

laquabordor2
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
63 views

Programming and Problem Solving with C 3rd Edition Edition Nell B. Dale 2024 scribd download

Dale

Uploaded by

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

Visit https://ebookfinal.

com to download the full version and


explore more ebook

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 ebook at ebookfinal.com


Here are some recommended products that might interest you.
You can download now and explore!

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/

ebookfinal.com

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/

ebookfinal.com

Problem Solving with C 10th Edition Walter Savitch

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

ebookfinal.com

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/

ebookfinal.com
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/

ebookfinal.com

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/

ebookfinal.com

Geotechnical Problem Solving 1. Edition John C. Lommler

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

ebookfinal.com

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/

ebookfinal.com

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/

ebookfinal.com
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
[email protected] 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
soon in funeral swathes we also at an end shall be; and they
anointed with the fragrant myrrh shall lie of odour ill. How is it they
adorn’d with gold lie unadorn’d and void of form? Therefore, my
brethren well belov’d, musing on our brief life, let us of Christ entreat
for rest for him who hence hath gone, and for great mercy for our
souls.
Verse. O Lord, deliver my soul from unrighteous lips.
Farewell, vain life; farewell, all friends, acquaintances, and
children too; for in a way I go where never have I trod. But come,
remembering my love for you, follow ye me, and give ye to the grave
this clay of mine, and pray ye Christ with tears, who hath to judge my
humble soul, that he may snatch me from the quenchless fire.
Glory. Both now. Theotokion.
O gate impassable, in mystery seal’d, God-bearing Virgin bless’d;
accept our prayers, and offer them thy Son and God, that he,
through thee, may save our souls.
Stichera idiomela, tone iii.
Lo, brethren mine belov’d, amid you all I silent lie, bereft of
speech; the mouth is listless, still the tongue, impeded are the lips,
the hands are tied, the feet together bound, the countenance is
chang’d, the eyes are dimm’d and see not them that wail, the
hearing takes not in the cry of them that mourn, the nose the fragrant
incense smelleth not; but in nowise true love becometh dead.
Therefore I you beseech, all mine acquaintances and friends,
Remember me before the Lord, that I in day of doom may mercy find
before that fearful judgment-seat.
Verse. I have lifted up mine eyes to the hills, whence cometh my
help.
All human things are vanity which last not after death: riches abide
not, nor doth glory stay; for when death cometh these all disappear.
Then let us cry to the immortal Christ, O rest him who is gone away
from us where is the dwelling-place of all that joy.
Verse. The Lord shall keep thy goings-out and thy comings-in from
henceforth and for evermore.
O men, why do we vainly we ourselves disquiet? the course we
run is quick and hard: life is as smoke: soon vapour, dust, and ashes
we shall be; and as a flower shall fade. Therefore let us to the
immortal Christ exclaim, Rest him remov’d from us where is the
dwelling-place of all that joy.
Glory. Both now. Theotokion.
God-bearing Virgin, we, we tempest-tost upon life’s sea, thee as
salvation’s haven have. Therefore pray God, who seedlessly from
thee incarnate was, and man became unspeakably, to save our
souls.
Stichera, tone iv.
Where is the predilection of the world? where their imaginings who
fade? where is the silver and the gold? where servants’ multitude
and noise? All dust, all ashes, all a shade. But, come ye, let us say
to the immortal King, O Lord, him, who hath been remov’d from us,
of thine eternal blessings worthy count, him resting in thine ageless
happiness.
Verse. I was glad when they said unto me, Let us go into the
house of the Lord.
Death as a robber came, like as a thief he came, and laid me low;
he came, and me declar’d as one existing not; he came, and, being
earth, I lie as being not. We verily are a dream, O men, a phantom
verily. But, come ye, let us cry to the immortal King, O Lord,
vouchsafe thine everlasting blessings unto him remov’d from us, him
resting in the life that grows not old.
Glory. Both now. Theotokion.
O only pure and spotless Virgin, who without seed didst bring forth
God, pray that our souls be sav’d.
Stichera, tone v.
I remember’d what the prophet said, I am earth and I am dust; and
again I meditated in the graves, and saw the naked bones, and said,
Who now is king, or, warrior, who; or, who is rich, or, who is poor; or,
who the just, or, he that sinn’d? But, with the just, thy servant rest, O
Lord.
Verse. Our feet have stood in thy courts, O Jerusalem.
Thou, Christ, hast said that he in thee believing shall not death
behold: but, as I out of light in light am light, so shall ye also in my
glory be enlightened in me; for I, that am true God, have come to
save them that revere me in true right-belief, me, one Lord God, in
dual nature of deity and flesh, but one in essence. Therefore, thy
faithful servant, who thus confesseth thee, rest in thy countenance’s
light among the Saints, as lover of mankind.
Glory. Both now. Theotokion.
We thee beseech, as Mother of God, O blessed one, Pray thou for
us, that we be sav’d.
Stichera, tone vi.
To me thy life-effecting bidding was substance and origin; for,
willing me to form a living one from nature that unseen is and is
seen, my body thou didst make of earth, and, by thy breathing life-
creating and divine, me gavest soul. Therefore, O Christ, thy servant
rest in tract of them that living are, and in the dwellings of the just.
Verse. Unto thee have I lifted up mine eyes, O thou that dwellest in
heaven.
That which thy hands did frame thou with thine image honour’d
hast, O Word; for, in material form inscribing livingly a mental
essence’s similitude, of this me also thou hast made participant,
placing me on the earth to be, of mine own power, creation’s lord.
Therefore, thy servant, Saviour, rest in tract of them that living are,
and in the dwellings of the just.
Glory. Both now. Theotokion.
God-bearing Virgin, we have understood the God made flesh from
thee, whom do thou pray to save our souls.
Stichera, tone vii.
After thine image and resemblance in the beginning making man,
in paradise thou him didst place to be of thy creation lord; but, by the
devil’s enviousness beguil’d, he ate the fruit, transgressing thy
commands. Therefore again to earth, whence he was taken, thou
hast doom’d him to return, O Lord, and beg for rest.
Verse. How amiable are thy tabernacles, O Lord of hosts.
Death looseth every grief befalling Adam’s nature; for corrupt we
have become, partaking of the food. Then let us learn, form’d out of
earth, we dust and ashes shall become, like as we were before.
Therefore let us with wailing voice our Maker pray pardon and mercy
to bestow on him removed hence.
Glory. Both now. Theotokion.
Thee, O God-bearing one, we faithful have as an unbroken wall
and trust. Therefore, cease not, O Queen, to pray for them thy
servants that in faith have slept, that in the judgment there may
pardon be for them, when he thy Son and God shall sit; for thou dost
nature know, that it with every sin is now commix’d: so may we bless
thee all.
Stichera, tone viii.
I weep and I lament when I reflect on death, and see the
comeliness, according to God’s image, that was shap’d for us lying
in the graves disfigur’d, and bereft of glory and of form. O wonder!
what is this mystery concerning us? how to corruption have we been
assign’d? how unto death conjoin’d? Verily by God’s command, as it
is written, who giveth the departed rest.
Bearing an image incorrupt, and having an immortal soul received
by breath divine, and so become compound, as it is written, why do
we fade away? and why did we God’s bidding overstep? O wonder!
why did we leave the food of life, and eat the fruit that bringeth bitter
death? why, by guile, have we been robb’d of life divine? As for the
rest, let us exclaim to Christ, Him whom thou hast removed hence
place in thy courts.
Glory. Both now. Theotokion.
God-bearing Virgin, thy protection is a spiritual healing place; for
thereunto betaking us, we are set free from ailments of the soul.
Stichera, tone viii. Idiomela.
To them that prodigally live unmeasur’d torment is, gnashing of
teeth, and wailing unconsol’d, gloom unillum’d, and darkness most
profound, the never dying worm, and unavailing tears, and, without
mercy, doom. Therefore let us, before the end, lift up our voice, and
say, O Master Christ, him who thou chosen hast give rest with thine
elect.
Similar.
The trumpet shall give sound, and, as from sleep, the dead shall
rise, desiring to obtain the heavenly life, they who have put their trust
in thee, the Maker and the Lord. Then, O condemn thy servant not;
for thou, immortal one, for our sake mortal didst become. Therefore
let us, before the end, lift up our voice, and say, O Master Christ, him
whom thou chosen hast, give rest with thine elect.
Behold, the elements, the heaven and earth shall be transform’d,
and all creation shall with incorruption clothed be. Corruption shall be
done away, and darkness at thine advent fly; for thou with glory art to
come again, as it is written, to render unto each as he hath done. O
Master Christ, him whom thou chosen hast, give rest with thine elect.
Glory, tone vi.
O come ye all and see a strange and fearful sight made manifest
to all, the image now beheld, and vex yourselves no more with
transient things. To-day divided from the body is a soul, and is
translated to th’ eternal world; for in a way it goeth wherein never yet
it went, and to the Judge who no respect of persons hath, where
stand the Angels’ hosts. My brethren, fearful is that judgment-seat,
where naked all of us shall stand, and some be crown’d and some
be sham’d. Then let us to th’ immortal King exclaim, When thou shalt
try the secrets of mankind, O spare thy servant whom thou hast
receiv’d, Lord, Lover of mankind.
Both now. Theotokion.
Through her entreaties who to thee gave birth, O Christ, and those
of thy Forerunner, and of apostles, prophets, hierarchs, venerables,
and just, and of all Saints, unto thy sleeping servant give thou rest.
Then, It is a good thing to give thanks unto the Lord.... The whole.
Trisagion. After Our Father....
Our Saviour, rest thy servant with the just, and place him in thy
courts, as it is written, as being good despising his iniquities, both
willing ones and those unwilling, and all those done in knowledge
and in ignorance, O lover of mankind.
In thy resting-place, O Lord, where all thy Saints repose, O rest thy
servant’s soul; for thou alone art lover of mankind.
O holy Mother of describeless Light, revering thee with angels’
songs, we magnify thee piously.
The deacon saith,
Have mercy upon us, O God, according to thy great mercy, we
pray thee, hear and have mercy. Vide page 139.
After the exclamation of the prayer the kiss is given, while the
choir singeth the stichera, tone ii.
Come, brethren, let us give the last kiss....
And the rest, as hath previously been written in the order for
laymen.
Then, Glory, tone vi. Me, lying voiceless....
Both now. The theotokion.
And giving forth to the grave the priests sing the irmi of the great
canon, that is to say,
A help and protection.... And the rest.
Trisagion. After Our Father.... In thy resting-place, O Lord.... O only
pure and spotless Virgin....
Then, Have mercy upon us, O God.... and the rest as customarily.
O God of spirits....
And the remains are buried.
And the full dismissal is made.
Chapter XIX.
THE OFFICE OF THE BURIAL OF A BABE.

After the priest hath given the blessing, the singers sing,
Whoso dwelleth under the defence of the Most High....[48]
And after this, Alleluia, in tone viii.
Verse. Blessed is he whom thou hast chosen....
Verse. And his remembrance is to generation and generation.
Trisagion. And after Our Father.... For thine is the kingdom.
Then, Thou who man-lovingly in depth of wisdom....
Glory.
Our Maker, and our Author, and our God.
Both now.
We have thee as a fortress and a haven....
Then psalm l.
And after this the requiem canon over a departed babe is begun.
Ode i. Tone viii.
Crossing the sea as on dry land....
Refrain. Rest thou the babe, O Lord.
O Word of God, who in the flesh didst poor become, and, without
change, wast pleas’d a babe to be; we pray thee place in Abraham’s
bosom the babe thou hast receiv’d.
Thou wast beheld a babe who ere all ages art, and, as the blessed
one, thy kingdom promis’d hast to babes: O number thou therein the
present babe.
Glory.
The undefiled babe, O Saviour Christ, whom thou received hast
ere earthly pleasures’ trial, vouchsafe eternal blessedness, as lover
of mankind.
Both now.
Thou who unspeakably didst bear him who the Father’s Wisdom is
and Word; heal thou my soul’s sore wound, and my heart’s pain
appease.
Ode iii. Irmos.
O Lord, creator of the vault of heaven and builder of the church;
thou me hast stablish’d in thy love, thou ending of desire, the
faithful’s confirmation, sole lover of mankind.
Refrain. Rest thou the babe, O Lord.
O thou most perfect Word, who didst appear a perfect babe, thou
hast removed to thyself a babe imperfect in its growth, whom do thou
rest with all the just who have been welcome unto thee, sole lover of
mankind.
Him taken hence, not tasting of the pleasures of the world, of
supermundane blessings make participant we pray, O thou
Compassionate One, even the uncorrupted babe, whom thou hast
chang’d by thy divine command.
Glory.
Of heavenly dwellings, and of shining lot, and of the sacred choir
of Saints, O Lord, make the pure babe participant, even him, whom,
Saviour, as thou wast well-pleas’d, thou hast remov’d.
Both now.
Bereft of all, to thy sole shelter, most pure Queen, I fly, O aid thou
me; for I unto much sinful riches cleave, but with a poverty of virtues
am altogether fill’d.
Then the irmos. And after the irmos the priest saith this ectenia.
Again and again in peace let us pray to the Lord.
Choir. Lord, have mercy.
Furthermore let us pray for the repose of the happy babe, name,
and that to him may be vouchsafed, according to thine undeceiving
promise, thy heavenly kingdom.
Choir. Lord, have mercy, thrice.
That the Lord our God may place his soul where all the just
repose.
Choir. Lord, have mercy, thrice.
The mercy of God, the kingdom of heaven, and repose among the
Saints, for him and for ourselves let us ask of Christ, our immortal
King and God.
Choir. Vouchsafe, O Lord.
Priest. Let us pray to the Lord.
Choir. Lord, have mercy.
Priest.
O Lord Jesus Christ our God, who hast promised to bestow the
kingdom of heaven upon them that are born again of water and of
the spirit and in a blameless life are translated onto thee, and hast
said, Suffer the children to come unto me, for of such is the kingdom
of heaven; we humbly beseech thee to grant, according to thine
undeceiving promise, the inheritance of thy kingdom unto thy
servant, the blameless babe, name, now removed from us; and
count us worthy to continue and end an unblamable and christian
life, and to be stablished in heavenly abiding-places with all thy
Saints.
And he exclaimeth,
For thou art the resurrection, the life, and the repose of all thy
servants, and of thy servant, the babe, name, now removed from us,
O Christ our God, and to thee we ascribe glory, with thine
unbeginning Father, and with thy most holy, and good, and life-
creating Spirit, now and ever, and to ages of ages.
Choir. Amen.
Then troparion.
Verily everything is vain, and life a shadow is, a dream; for vainly
every earth-born one disquieteth himself, as saith the scripture.
When we have gain’d the world, then dwell we in the grave, where
kings and beggars, elders and babes together are. Therefore, Christ
God, as lover of mankind, rest the departed babe.
Ode iv. Irmos.
I have heard, O Lord, the mystery of thy dispensation....
Refrain. Rest thou the babe, O Lord.
We wail not for the babes, but rather for ourselves do we lament,
we, who have always sinn’d, that we may be delivered from
gehenna.
Thou, Master, hast depriv’d the babe of the delights of earth: do
thou, as righteous judge, vouchsafe him heavenly blessings.
Glory.
He hath declared thee a citizen of paradise, O truly happy babe,
he who hath taken thee from earth and ranged thee among the
choirs of Saints.
Both now. Theotokion.
All we that are illuminated, O all-pure, own thee God-bearing,
thou, O Ever-virgin; for thou the Sun of righteousness hast borne.
Ode v. Irmos.
Why hast thou rejected me....
Refrain. Rest thou the babe, O Lord.
By thy just dooming, ere he waxed perfectly in growth, thou hast,
as new grown herb, cut down the babe whom thou hast taken, Lord;
but, leading him, O Word, to hill divine of everlasting blessings, plant
him there.
As a young branch the sword of death hath come and cut thee off,
thou who of worldly sweets no trial hast sustain’d, thou happy one!
but, lo, to thee the gates of heaven Christ open’d hath, counting thee
with th’ elect, as being loving-kind.
Glory.
Concerning me, lament ye not; for I in nowise have begun for
weeping to be meet; but rather weep ye alway for yourselves, ye
who have sinn’d, O kinsfolk and O friends, the dead babe cries, so
that of torment ye have no essay.
Both now.
I am despairing of myself when on the number of my deeds I
muse; but when in mind I bear thee, Mother of God, who above mind
didst bear the Lord, I am refresh’d with hope; for we have thee a sole
defence.
Ode vi. Irmos.
I will pour forth a prayer before the Lord, and to him will I tell my
grief; for my soul is full of evils, and my life draweth nigh unto hades,
and I pray as Jonas, O God, raise me out of corruption.
Refrain. Rest thou the babe, O Lord.
Thou was laid in a manger as a babe, and wast plac’d in an
elder’s arms, who generatest babes in the womb; and ere this one
attain’d perfect growth, thou hast bidden him to thee. Then we with
thanksgiving extol thee.
Thou didst say to the apostles, O Word, Let the children come
unto me; for my kingdom is for them that are such in wiseness. Then
count the babe remov’d to thee of thy light worthy.
Glory.
Thou of earth’s blessings hast depriv’d thy babe, that thou of
heaven’s might’st make him sharer, who hath not overstepp’d thy bid
divine. O Good One, we extol thy judgments’ depth unmeasur’d.
Both now. Theotokion.
We have thee, Maiden, as a sheltering wall, for souls a full
salvation, and in afflictions ample room; and in thy light we aye
rejoice, and in this save us now, O Queen, from passions and from
dangers.
Then the irmos. And after the irmos the priest saith the previously
written ectenia and the prayer. Page 139.
Then the condakion, tone viii.
Rest with the Saints, O Christ, thy servant’s soul, where is no pain
nor grief, nor sighing, but life that endeth not.
Icos.
Thyself alone immortal art, who madest and didst fashion man; for
out of earth we mortals fashion’d were, and unto that same earth
shall go, as thou who madest me hast given command, and sayest
unto me, Earth thou art, and unto earth shalt thou return. And thither
all we mortals go, making the funeral wail, even the song, the
Alleluia.
And these following icosi.
More sympathetic than a mother there is none, and than a father
more compassionate none; for vexed are their inward parts when
they the babes accompany hence: great is the sting which for the
children’s sake their hearts receive, and still the more when these
sweet-spoken are, and they their words remember with the song, the
Alleluia.
For oft beside the grave they smite their breasts, and say, O thou
my son and sweetest child! hearest thou not thy mother what she
saith? lo, ’tis the womb that thee hath borne: why dost thou speak
not as thou wert wont to speak to us? But so thou silent art, even to
say with us the Alleluia.
O God, O God, who callest me, be now the comfort of my house,
for great the wailing is befalling them; for they all have regard to me,
even they who have me as a sole-begotten one. But thou who wast
of Virgin Mother born, refresh the bowels of my mother, and bedew
my father’s heart, even with this, the Alleluia.
Then the condakion, tone viii.
Rest with the Saints....
Ode vii. Irmos.
The hebrew children in the furnace.
Refrain. Rest thou the babe, O Lord.
Write in the book of them that saved be, as lover of mankind
compassionate, thy babe, that he rejoicing may exclaim to thy
might’s glory, Thou art bless’d.
By, O thou Word, thy countenance’s light, illuminate thy babe, who
now to thee in faith, at an untimely age, is gone, and sings to thee,
Thou blessed art, O Lord, O God.
Glory.
Affliction’s cause thy going hence now seemeth unto them that
thee have lov’d, but unto thee procuracy in truth of gladness and of
joy; for thou, O babe, inheritest eternal life.
Both now. Theotokion.
Behold my grief, O Virgin, which th’ abundance of mine ills doth
bring on me, and ere my going hence give me refreshment by thy
mother prayers to make God merciful to me.
Ode viii. Irmos.
The furnace seven times more....
Refrain. Rest thou the babe, O Lord.
In Abraham’s bosom, in tabernacles of repose, where is their joy
who ever festal keep, in places of refreshment where living water is,
may Christ thee place, yea, he who for our sake became a child,
even ours who unto him cry ceaselessly, O priests, extol him, and, O
people, set him up for aye.
A constant cause of grief to us, yea, and for tears, thine ever
thought on parting is in truth become; for ere the tasting in this life of
things that give delight thou hast left earth, yea, and thy parents’
breasts. But Abraham’s bosom hath received thee, as babe, and
unparticipant of every stain.
Glory.
Why mourn ye me, a babe, that hence is gone? lying he cries
invisibly: for I am wont not to be mourn’d; for destin’d is the joy of all
the just for babes: to them that works perform not there meetness is
for tears. But those the song upraise to Christ, O priests, extol him,
and, O people, set him up for aye.
Both now. Theotokion.
To mine assistance, O God-bearing one, arise, attend unto my
prayer, and me deliver from the dreadful doom, the grave essay, the
darkness, and the fire, the gnashing of the teeth, the contumely of
demons, and from every need, thou hope of them that have no hope,
thou, the despairing’s life.
Ode ix. Irmos.
Be thou in dread concerning this, O heaven, and let earth’s limits
be amaz’d: for God hath shewn himself in flesh to men, and wider
than the heavens thy womb becomes. Therefore the principals of
Angels and of men thee magnify, God-bearing one.
Refrain. Rest thou the babe, O Lord.
Christ, who unchang’d becam’st a babe, and willingly didst bear
the cross, and the maternal pain didst see of her that gave thee birth;
assuage the grief and bitter pain of faithful parents of a babe
deceas’d, that we thy might may glorify.
Master, thou King of all, who from on high didst send and take the
happy babe as a pure bird to heavenly nest, thou hast from diverse
snares preserv’d his soul, and join’d it with the righteous souls thy
kingdom’s sweets that taste.
Glory.
To babes that nothing have perform’d, O Word of God, thou hast
vouchsaf’d a heavenly dwelling-place; for so thou art well-pleas’d, O
blessed one, with these to count up thy creation; and, taking now the
babe to thee, do thou thyself alleviate the parents’ pain, as all-
compassionate and lover of mankind.
Both now. Theotokion.
The heart’s eyes turn I ever unto thee, who hast maternal prayer
with him who birth receiv’d from thee; for I entreat thee, O All-pure,
Quell thou the passions of my soul, rouse me betimes to penitence,
O maid, and with thy light enlighten me.
Then the little ectenia.
And the exapostilarion.
Now am I at rest, and much forgiveness have receiv’d; for I have
passed from corruption, and am translated unto life: glory to thee, O
Lord.
And the people the same.
Verse. Man is as grass, his day is as a flower of the field.
Verse. For his spirit goeth forth through him, and he shall not be.
Verse. And the mercy of the Lord shall endure to ages.
And to each verse the exapostilarion.
Then, Glory. Both now.
Now have I chosen the maiden Mother of God; for Christ,
redeemer of all, was born of her: glory to thee, O Lord.
And straightway the priest exclaimeth,
For holy art thou, O our God, and thou restest on the Saints, and
to thee we ascribe glory, to the Father, and to the Son, and to the
Holy Ghost, now and ever, and to ages of ages.
Choir. Amen. And they sing, Holy God....
Prokimenon, tone vi.
Blessed is the way in which thou goest to-day, O soul....
Verse. Return, O my soul, unto thy rest.
The epistle to the Corinthians, section clxii.
Brethren, all flesh is not the same.... ending, a quickening spirit.[49]
Verse. Blessed is he whom thou hast chosen and received, O
Lord.
Verse. His soul shall dwell in good things.
The gospel from John, section xxi.
The Lord spake unto the Jews that came unto him, I am the bread
of life.... ending, at the last day.[50]
And straightway the last kiss is given, while the singers sing these
stichera. Tone viii.
Like, O most glorious wonder!
Who would not weep, my child, because of thy lamented taking
from this life; for thou, a babe unwax’d in growth, from the maternal
arms, like to a bird, hast quickly flown, and unto all things’ Maker
hast betaken thee. O child! who would not weep, beholding faded thy
clear face, which erewhile beauteous as a lily was? Who would not
sigh, my child, and would not cry with wailing because of thy much
comeliness, and for the charm of thine estate? for as a ship that
leaves no track thou quickly from the eyes art gone. Come, ye, my
friends, kinsfolk, and neighbours, and, along with me, let us him kiss
whom send we to the grave.
Death is the freeing of the babes; for unparticipants of ills of life
they are declar’d, and unto rest attain, and they in Abraham’s bosom
with heavenly joys are glad, and now along with holy babes in choirs
divine rejoice, and festal high in faith they keep; for from corruption,
through the love of sin, they, being pure, translated are.
Glory. Tone vi.
On Adam pain befell of old in Eden through the tasting of the tree,
when bane the serpent spued; for thereby death hath come on the
omnigenous man who ate. But the Lord came, subdued the serpent,
and repose bestow’d on us. Then let us cry to him, O Saviour, spare,
and rest with thine elect him whom thou hast receiv’d.
Both now. Theotokion.
Thou that alleviation art for those in grief, deliverance of the weak,
God-bearing Virgin, save the city and the folk, thou that for those at
enmity art peace, for tempest-tost a calm, the faithful’s sole defence.
Then, Trisagion. O most holy Trinity.... Our Father.... For thine is
the Kingdom....
Then the troparion, With the spirits of the righteous.... Page 138.
And he commemorateth according to custom, saying the
previously written ectenia, and the prayer. Page 139.
Then the deacon. Wisdom.
Choir. The more honourable than the Cherubim.... Glory. Both
now. Lord, have mercy, thrice. Bless.
And the priest maketh this dismissal.
Thou that didst arise from the dead, and hast dominion over quick
and dead, Christ our true God, through the prayers of thy most pure
Mother, and of all thy Saints, place the soul of the babe, name,
removed from us, in holy tabernacles, and number it with the just, as
being good and the lover of mankind.
Choir. Amen.
And after the dismissal the priest saith,
Thy remembrance is everlasting, O thou deservedly blessed and
ever remembered babe, name.
And the choir singeth thrice, Everlasting remembrance.
After this the priest saith this prayer,
the deacon having said, Let us pray to the Lord,
and the singers, Lord, have mercy.
O Lord, who guardest babes in the life that now is, and in the world
to come preparest for them the amplitude of Abraham’s bosom, and,
for their purity, bright angelic places where the souls of the righteous
are established; do thou thyself, O Lord Christ, accept in peace the
soul of thy servant, the babe, name. For thou hast said, Suffer the
children to come unto me, for of such is the kingdom of heaven. For
to thee is due all glory, honour, and worship, with the Father, and
with the Holy Ghost, now and ever, and to ages of ages. Amen.
And, taking up the body, they go to the grave, preceded by the
priests and deacons and all the clergy, singing, Holy God....
And, the remains having been laid in the grave, the presiding
priest, taking a shovel, scattereth earth in the grave, saying,
The earth is the Lord’s, and the fulness thereof, the world and all
they that dwell therein.
And they depart giving thanks unto God.
End of the burial of a babe.
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