C for business programming 2nd ed Edition Molluzzo instant download
C for business programming 2nd ed Edition Molluzzo instant download
Molluzzo download
https://ebookgate.com/product/c-for-business-programming-2nd-ed-
edition-molluzzo/
https://ebookgate.com/product/programming-with-ansi-c-2nd-ed-
edition-trivedi/
https://ebookgate.com/product/programming-in-c-2nd-edition-
safari/
https://ebookgate.com/product/c-gui-programming-with-qt-4-2nd-ed-
extensively-rev-and-expanded-edition-jasmin-blanchette/
https://ebookgate.com/product/c-programming-for-arduino-1st-
edition-julien-bayle/
Programming Principles and Practices using C 2nd
Edition Bjarne Stroustrup
https://ebookgate.com/product/programming-principles-and-
practices-using-c-2nd-edition-bjarne-stroustrup/
https://ebookgate.com/product/c-programming-for-the-absolute-
beginner-3rd-edition-keith-davenport/
https://ebookgate.com/product/ai-game-engine-programming-2nd-ed-
edition-brian-schwab/
https://ebookgate.com/product/practice-made-perfect-the-
discipline-of-business-management-for-financial-advisers-1st-ed-
edition-mark-c-tibergien/
https://ebookgate.com/product/c-2013-for-c-developers-2nd-
edition-dean-c-wills/
C++ for Business
Programming
Second Edition
John C. Molluzzo
Pace University, New York
All rights reserved. No part of this book may be reproduced in any form or by any means, without
permission in writing from the publisher.
Pearson Prentice Hall® is a trademark of Pearson Education, Inc.
The author and publisher of this book have used their best efforts in preparing this book. These
efforts include the development, research, and testing of the theories and programs to determine
their effectiveness. The author and publisher make no warranty of any kind, expressed or implied,
with regard to these programs or the documentation contained in this book. The author and
publisher shall not be liable in any event for incidental or consequential damages in connection
with, or arising out of, the furnishing, performance, or use of these programs.
10 9 8 7 6 5 4 3 2 1
ISBN: 0-13-046700-6
PREFACE XV
1. INTRODUCTION TO C++ 1
Objectives 1
Why Study C++? 1
1.1 Our First C++ Program 3
1.1.1 The Program Development Cycle 3
1.1.2 Errors in the Cycle 7
1.1.3 Displaying a Two-Line Message: dem01-1.cpp 8
1.1.4 Comments 9
1.1.5 The Function main() 10
1.1.6 The Output Stream cout 11
1.1.7 The return Statement 13
1.1.8 The Preprocessor Directive #include 13
1.1.9 The using Directive 14
1.1.10 Execution of dem01-1.cpp 15
1.1.11 Keywords, Multiline Comments, and Escape Sequences 15
1.1.12 About the Exercises, Experiments, and Programming
Problems 16
1.2 Integers and Arithmetic 20
1.2.1 Identifiers 20
1.2.2 Variables 20
1.2.3 Using Integer Variables: dem01-2.cpp 22
1.2.4 Variable Declarations 23
1.2.5 Asking the User for Input: Prompts 24
1.2.6 The Input Stream cin 24
1.2.7 The Input Buffer 25
iii
iv Contents
2. REAL NUMBERS 45
Objectives 45
2.1 Real Numbers 45
2.1.1 Real-Number Variables and Constants 45
2.1.2 Input and Output of Real Numbers 47
2.1.3 Outputting Decimal Numbers 47
2.1.4 Calculating Sales Tax—dem02-1.cpp 48
2.2 Solving Problems with Real Numbers 52
2.2.1 Simulating a Cash Register—Problem 2.1 52
2.2.2 Program Design 53
2.2.3 The Program prb02-1.cpp 53
2.2.4 Discussion of prb02-1.cpp 55
2.2.5 Averaging Quiz Grades—Problem 2.2 55
2.2.6 Program Design—Mixed Types and Type Casts 55
2.2.7 The Program prb02-2.cpp 57
2.2.8 Metric Conversion—Problem 2.3 58
2.2.9 Program Design 59
2.2.10 The Program prb02-3.cpp 61
2.3 More on Arithmetic 64
2.3.1 The Value of an Expression 64
2.3.2 Multiple Assignment Statements 65
2.3.3 The Compound Assignment Operators 66
2.3.4 Increment and Decrement Operators 69
Contents v
3. ITERATION 80
Objectives 80
3.1 Relation Conditions 80
3.2 Indefinite Iteration: The while and do Statements 83
3.2.1 The while Statement 83
3.2.2 An Example of Indefinite Iteration: The char Data Type 85
3.2.3 Using cin.get() 87
3.2.4 The Program dem03-1.cpp 87
3.2.5 Embedded Assignment—Recoding dem03-1.cpp 90
3.2.6 The do-while Loop 91
3.3 Solving a Problem with Indefinite Iteration 96
3.3.1 Problem 3.1 96
3.3.2 Program Design 96
3.3.3 The Program prb03-1.cpp 98
3.3.4 More on Control-Expressions 102
3.4 Definite Iteration 105
3.4.1 The for Statement 105
3.4.2 An Example of Definite Iteration 109
3.4.3 Calculating Interest on a CD—Problem 3.2 111
3.5 Nested Loops 118
3.5.1 Nested while Loops 118
3.5.2 Nested for Loops 121
Chapter Review 126
Terminology 126
Summary 126
Review Exercises 127
5. FUNCTIONS 174
Objectives 174
5.1 The Function Concept 175
5.1.1 How Functions Work 175
5.1.2 A Function with No Arguments and No Return Value 176
5.1.3 The Function Prototype and Definition 177
5.1.4 A Function with Arguments and No Return Value 181
5.1.5 Defining and Using a Function that Has Arguments 184
5.1.6 Passing Arguments by Value 186
5.2 User-Defined Functions that Return a Value 191
5.2.1 Calculating Grades Using a Function 191
5.2.2 Calculating Grades—The Program dem05-4.cpp 192
5.2.3 Variable Attributes 194
5.2.4 Scope 195
5.2.5 Duration—Storage Class 199
5.3 Programs that Use Functions 203
5.3.1 Problem 5.1—Moving Costs 203
5.3.2 Program Design 203
5.3.3 The Program prb05-1.cpp 204
5.3.4 Problem 5.2—Calculating Simple Interest 206
5.3.5 Program Design 207
5.3.6 The Program prb05-2.cpp: 208
5.3.7 Discussion of the Program 212
Contents vii
6. ARRAYS 234
Objectives 234
6.1 Basic Concepts 234
6.1.1 Definition of an Array 235
6.1.2 Declaring an Array 236
6.1.3 Referencing and Initializing Array Elements 236
6.1.4 Accessing Array Elements by Subscript 238
6.2 Processing an Array: for Loops 242
6.2.1 Using for Loops 242
6.2.2 Searching an Array 245
6.3 Sorting an Array 250
6.3.1 Sorting 250
6.3.2 A Sort Program—dem06-4.cpp 252
6.4 Multidimensional Arrays 256
6.4.1 Declaring Multidimensional Arrays 256
6.4.2 Processing a Two-Dimensional Array 258
6.4.3 Finding Student Averages—dem06-5.cpp 259
Chapter Review 264
Terminology 264
Summary 264
Review Exercises 265
Objectives 266
7.1 Pointers 266
7.1.1 Declaring and Initializing Pointers 266
7.1.2 The Indirection Operator 270
7.1.3 Pointers and Arrays 272
viii Contents
Objectives 363
9.1 The typedef and enum Statements 364
9.1.1 The typedef Statement 364
9.1.2 The enum Statement 366
9.1.3 An Example Using typedef and enum 367
9.2 Structures 371
9.2.1 Defining a Structure 371
9.2.2 Accessing Structure Members 372
9.2.3 Initializing a Structure Variable 375
9.2.4 More Complicated Structures 375
9.2.5 Assigning One Structure Variable to Another 377
9.3 Arrays of Structures: Tables 379
9.3.1 Defining a Table Using Structures 380
9.3.2 Loading Table Values 381
9.3.3 Sorting a Table 385
9.3.4 Searching a Table 390
9.3.5 Sequential Search 392
9.3.6 Binary Search 397
9.4 Structures, Functions, and Pointers 407
9.4.1 Functions and Structures 407
9.4.2 Pointers to Structures 413
9.4.3 Structure References 418
Chapter Review 424
Terminology 424
Summary 424
Review Exercises 425
Objectives 426
10.1 Objects, Classes, and Object-Oriented Systems 427
10.1.1 Familiar Classes and Objects 428
x Contents
Objectives 476
11.1 Declaring Objects and Classes 476
11.1.1 Defining a Class 477
11.1.2 Class Methods 479
11.1.3 The Class Constructor 480
11.1.4 Methods 482
11.1.5 The Program dem11-1.cpp 482
Contents xi
Objectives 519
12.1 Using Arrays, Pointers, and Dynamic Memory Allocation 520
12.1.1 Array and Pointer Class Members 520
12.2 The Copy Constructor 528
12.2.1 The Copy Constructor: A Simple Example 528
12.2.2 A Copy Constructor For Savings_Account 533
12.3 Using const with Classes 540
12.3.1 Constant Objects and Methods 540
12.3.2 const in Pointer Declarations 543
12.3.3 Mixing Constant and Nonconstant Pointers 544
12.3.4 Constant Arguments in Functions 545
12.3.5 Constant Arguments and the Copy Constructor 547
12.3.6 Accessor Methods that Return Constant Pointers 547
12.4 Objects, Functions and Pointers 556
12.4.1 Functions that Return an Object 556
12.4.2 Passing an Object by Value 561
12.4.3 Pointers to Objects 568
12.4.4 Passing an Object by Pointer 570
12.4.5 References to Objects 574
12.4.6 Passing an Object by Reference 574
12.5 Dynamic Allocation of Objects 581
12.5.1 Using new and delete with Objects 581
xii Contents
Objectives 600
13.1 Inheritance 601
13.1.1 Examples of Inheritance and Basic Terminology 601
13.1.2 Defining Derived Classes 604
13.1.3 Constructors in a Derived Class 607
13.1.4 The Destructor in a Derived Class 609
13.1.5 The Copy Constructor in a Derived Class 612
13.2 Functions in Class Hierarchies 618
13.2.1 Inheriting a Function 618
13.2.2 Method Overriding 620
13.2.3 Using the Scope Resolution Operator 623
13.3 Polymorphism 629
13.3.1 The Class Hierarchy 629
13.3.2 Defining the Classes 630
13.3.3 Pointers in a Class Hierarchy 631
13.3.4 Virtual Methods and Polymorphism 634
13.3.5 Virtual Destructors 636
13.3.6 Putting Polymorphism to Work 641
13.4 Abstract Base Classes 649
13.4.1 Pure virtual Methods and Abstract Base Classes 649
13.4.2 The Loan Class 651
Chapter Review 661
Terminology 661
Chapter Review 661
Review Exercises 662
Objectives 664
14.1 Input/Output Streams 665
14.1.1 The Standard I/O Streams: Revisiting cin,
cout, and cerr 665
14.1.2 Text Files 666
14.1.3 User-Declared Files 667
Contents xiii
Objectives 730
15.1 friend Functions 731
15.1.1 Defining a friend Function 731
15.1.2 Inheritance and friend Functions 736
15.2 Overloading Basic Arithmetic Operators 738
15.2.1 Adding Two Objects 738
15.2.2 Adding an Object and an Integer 740
15.2.3 Operator Overloading Rules 743
15.3 Overloading Assignment and the this Pointer 745
15.3.1 Overloading Assignment 745
15.3.2 The this Pointer 747
15.3.3 Inheritance and Overloaded Operators 752
xiv Contents
xv
xvi Preface
• The book contains over 800 exercises of varying types and levels of difficulty.
These exercises are placed at the end of each section rather than at the end of
each chapter so students can immediately reinforce their new knowledge. These
exercises include exercises, experiments, and programming problems.
º Almost every section contains exercises on the syntax and semantics of C++.
Most of these are of the paper and pencil type, although some require writing
a simple program.
º The experiments, which ask the student to investigate various aspects of the
C++ language, are a unique feature of the exercise sections. The experiments
improve the student’s understanding of the finer points of C++ and help the
student avoid common errors made by beginning programmers.
º The programming problems, which range from 10-20-line programs to full-scale
projects that require the use of several user-defined functions and/or classes,
are found in most sections of the book. The chapter-illustrative programs and
programming problems emphasize the business applications of C++.
• The book conforms to the ANSI C++ standard. All illustrative programs, howev-
er, can easily be adapted to nonstandard compilers. Therefore, the book can be
used with any C++ compiler.
• Topics are introduced on a need-to-know basis to provide motivation for the stu-
dent. Therefore, the book is not encyclopedic in its coverage of C++. In some
cases, all the relevant ideas surrounding a topic are spread throughout several
sections or chapters.
• Appendix A, “Computers and Data,” and Appendix B, “Program Control,” pro-
vide supplementary material for students who have a weak background in com-
puting. Appendixes A and B contain exercises.
• The terminology and program constructs used have been updated to conform to
current practice.
• Several sections have been labeled as optional to improve the flow of the exposi-
tion and enable the reader and instructor to concentrate on the more important
concepts.
• In some chapters, notably Chapters 2 and 5, material has been rearranged to im-
prove readability.
• A section on the C++ Math Library functions has been added to Chapter 5.
• Chapter 12 in the first edition, “Friends and Operator Overloading,” has been
moved to the end of the book (Chapter 15) and has been renamed “Special Topics.”
• The section titled “Macros and Inline Functions,” has been moved from Chapter 5
to “Special Topics,” Chapter 15.
• The book now distinguishes C-style strings from objects in the string class.
Preface xvii
• To help students transition from Part I to the object-oriented concepts in Part II,
we include a transition chapter, Chapter 10, on the C++ string class. Object-
oriented concepts are introduced in this chapter so that students can begin in-
stantiating, using, and manipulating string objects without having to worry
about how to define a class.
CHAPTER OVERVIEW
Chapters 1–9 constitute Part I, “C++ Basics.” Chapter 1, “Introduction to C++,” intro-
duces the student to the basic anatomy of a C++ program. It covers the input and out-
put objects cin and cout, variables, integer data types, and arithmetic. Chapter 2,
“Real Numbers,” introduces the float and double data types, the compound assign-
ment, and increment and decrement operators.
Chapters 3 and 4 discuss the basic control structures of programming. Chapter 3,
“Iteration,” begins by covering relation conditions. Then it proceeds to discuss indefi-
nite iteration (the while and do statements), definite iteration (the for statement),
and nested loops. Chapter 4, “Decision Making,” covers the if statement, the logical
operators, nested if statements, and the switch statement.
Chapter 5 introduces the important concept of functions. Because the function is
new to most students, the concept is developed gradually—first with functions that do
not return a value, then functions having arguments, and, finally, functions that return a
value. We also include a discussion of scope and duration. An entire section is devoted
to discussing three programs that use functions. Special care is taken to show how the
program logic is modularized into functions. The chapter ends with a discussion of the
C++ Math Library functions.
Chapter 6, “Arrays,” shows how to properly define an array and reference its el-
ements. Care is taken to show how to use a for loop to process the elements of an
array. We also cover in some detail how to sort an array using the standard bubble
sort. Finally, we show how to declare and process multidimensional arrays.
Chapter 7 introduces pointers. To help the student understand this important
topic, we quickly put pointers to work by applying them to C-style strings. Illustrative
programs show how to count characters in a string, display a string in reverse, and
count words in a string. We also discuss arrays of strings and arrays of pointers.
Chapter 8, “Pointers, Arrays, and Functions,” reinforces the student’s knowledge
of strings and pointers. Call by address using pointers, call by reference, passing arrays
as function arguments, and functions that return pointers are discussed in detail. We
also cover some useful string library functions and character classification and conver-
sion functions. We also discuss the use of dynamic memory allocation using the new and
delete operators.
Chapter 9, “User-Defined Data Types and Tables,” discusses typedef, enumerat-
ed types, and structures. Special attention is given to the use of structures in defining
tables. A major application involves sorting and searching a table (an array of struc-
tures), including both sequential and binary searches. The chapter also discusses pointers
xviii Preface
to structures and using them as function arguments. This chapter can be omitted if time
is a consideration.
Chapters 10–15 comprise Part II, “Object-Oriented Programming.” Chapter 10,
“The string Class: An Introduction to Classes and Objects,” serves as a transition
from the emphasis on procedural programming of Part I to object orientation. The
chapter begins with a general discussion of object-oriented concepts. Then it illustrates
those concepts using the built-in string class. Sections discuss how to perform opera-
tions on string objects, how to manipulate string objects and make decisions with
string objects, and how to use string objects with functions. Upon completion of this
chapter, students should be comfortable with the object paradigm.
The material in Chapters 11–13 is unified through the gradual development of a
Savings Account class. As new object-oriented programming (OOP) concepts are in-
troduced, they are added to the Savings Account class. Chapter 11 introduces the read-
er to user-defined classes and objects. We discuss how to declare a class, instantiate
objects, and code methods, constructors, and destructors. The chapter ends with a thor-
ough discussion of function overloading and default method arguments.
Chapter 12, “Manipulating Objects,” is the longest chapter in the book. Some of
the topics, as outlined in the chapter introduction, can be omitted at first reading. The
chapter begins by discussing how to include array and pointer instance variables in a
class and how to use dynamic memory allocation in a constructor and destructor. Next,
the chapter discusses the copy constructor and when it is used. The many ways of using
the keyword const in C++ are then covered in detail. We also discuss functions that re-
turn objects as well as how to pass objects to functions by value, pointer, and reference.
Several of the issues relating to the dynamic allocation of objects are covered along
with the uses of static class data members and methods.
Chapter 13 covers the important concept of inheritance and related ideas. We use
one major example throughout most of the chapter to unify the material. After intro-
ducing the basic terminology of inheritance and how to construct a class hierarchy, the
chapter discusses the uses of methods in such a hierarchy and the concept of polymor-
phism. Pure virtual methods and abstract base classes complete the chapter.
Chapter 14 gives a thorough treatment of file processing in C++. The chapter be-
gins with a discussion of input/output (I/O) streams, the standard I/O class hierarchy,
and how to process simple text files. We then show how to process a file one character
at a time. Next, we discuss binary files and the random-access methods. These ideas are
then applied to the problems of processing a binary sequential file of records and to
randomly processing a binary file of records. The chapter culminates with a random-
file-access update program.
Chapter 15 covers several special topics. First we discuss the concepts of friend
functions and operator overloading. We emphasize the extensibility of the C++ opera-
tors by showing how to overload the arithmetic operators, assignment, the insertion
and extraction operators, the compound assignment operators, the relational opera-
tors, and the unary operators. We conclude the chapter with a discussion of the use of
macros and inline functions.
I thank Laura Steele and Alan Apt of Prentice Hall, who made the first edition of
this book possible. I also thank Kate Hargett and Mike Giacobbe for guiding me
through the second edition. A special thanks to Dean Susan Merritt of Pace University
Preface xix
who gave this project and me her enthusiastic support for the many years it took to
complete. Thanks also to Chin-Mei Huang for her helpful comments on an early ver-
sion of the manuscript, Anna Kristoferitsch for helping to solve some of the chapter ex-
ercises and, especially, Kenyata Millet, who spent many long hours solving the
programming problems and exercises. I also thank Esther Amiri for the work she did on
the exercises and programming problems in chapter 10. I thank Professor Gerald Wohl
of Pace University for having the courage to use the first draft of this book in his C++
courses, for catching many errors and typos, and for providing me with many helpful
comments about the book, and the many readers and reviewers who provided valuable
input to the second edition. Finally, I thank my family—my wife, Maria, and my sons,
John and Charles—for the help and love they have given me.
A note about the typefaces used in this book: In the program outputs, data that
the user inputs in response to program prompts is set in boldface to distinguish it from
output produced by the programs.
Reviewers for this edition:
Dennis D. Howard, University of Alaska Anchorage
Nitin Kale, University of Southern California
Dan Calderwood, College of the Redwoods
Safoora Fatima, Devry University
This page intentionally left blank
Part I C++ Basics
Chapter 1
Introduction to C++
OBJECTIVES
1
2 Chapter 1 Introduction to C++
specific to the hardware and operating system of the computer platform on which
it is developed. Thus, you cannot directly execute a PC assembly language pro-
gram on a Macintosh.
By contrast, high-level languages, such as COBOL, Visual Basic, and Java,
are easier to learn, maintain, and debug than assembly languages. The program
statements in such languages use English words and familiar mathematical sym-
bols to express instructions to the computer. Typically, each such instruction re-
places several equivalent assembly-language instructions. Thus, using a high-level
language is easier than using an assembly language. However, the price for this
ease of use is the loss of direct control over the computer system that you have in
an assembly language.
C++, although it is a middle-level language (and, therefore easier to learn
and use than an assembly language), contains many of the low-level capabilities
of an assembly language. Thus, C++ is sometimes called a “middle-level” lan-
guage. It is possible through C++ to attain almost as much control over the com-
puter as you can achieve with an assembly language.
• C++ is portable. Most high-level languages are portable in the sense that a pro-
gram written in a high-level language should execute, with minor modifications,
on several different computer systems. C++ is one of the most portable of all the
high-level languages. Properly written, a C++ program can run on several com-
puter systems with no modifications. Portability is important because it is now
common for a business to have several different types of computer systems (a
mainframe, minicomputers, workstations, PCs, and Macintoshes). A properly
written application in C++ should be portable to most, if not all, these systems.
Thus, portability eliminates the cost of developing the application several times
for different platforms.
• C++ is small. The C++ language does not contain many of the built-in features
present in other programming languages (such as in Visual Basic), which further
enhances its portability. For example, Visual Basic has about 150 keywords. (A
keyword is a word that has special meaning in the language.) C++, on the other
hand, has about 60 keywords. Visual Basic includes extensive capabilities to help
the programmer write programs. However, this greatly increases the complexity
of the Visual Basic language. In contrast, the designers of C++ tried to keep the
language as simple as possible by not building things into the language. Instead,
the programmer must use programmer-defined and built-in functions and classes.
This gives the C++ programmer great flexibility and allows the language to be
highly portable.
• C++ is an object-oriented extension of the C programming language. Dennis
Ritchie developed C at Bell Laboratories in 1972 to help write the UNIX oper-
ating system for the PDP-11 minicomputer. Today many mainframes and most
minicomputers, including Reduced Instruction Set Computing (RISC) work-
stations, and many Intel-based PCs and servers use the UNIX or Linux oper-
ating system. All versions of UNIX/Linux contain a version of C as their native
language. In other words, UNIX/Linux speaks C. Why is this important?
Section 1.1 Our First C++ Program 3
Step 1: Define the Problem It is very important that you understand the problem you
are trying to solve. Make sure you read the problem specifications carefully.
Know what data is to be input into the program and what form that data should
be in. Also, know what processing has to be done to that data. Finally, determine
what the expected output is supposed to be and what form the output must take.
For example, suppose you are asked to write a simple program that simu-
lates a calculator.The program is to ask the user (the person running the program)
4 Chapter 1 Introduction to C++
Step 1: Define
Step 2: Design
Step 3: Code
Step 6: Test
source
code
Figure 1.1
to enter two numbers, then the program is to output the sum of the numbers. Be-
fore you start doing anything, you have to define this problem more completely.
For example, should the program ask the user to enter the numbers? If so, how
should the program ask? What kind of numbers are to be input? Must they be
whole numbers or can they be decimal numbers? Should the numbers be input
one number per line, or can they both be input on one line? After the numbers are
input and added, how should the result be displayed? Do you want the input num-
bers output along with the sum, or do you just want to output the sum? If you want
the input numbers as well as the sum to be output, how do you want it done—in
column format or on one line?
As you can see, there are many questions to ask even in this simple problem—
and we did not ask any questions about the processing, because adding is a simple
calculation. Imagine how complex it would be to calculate a person’s income tax!
The important point here is to ensure that you solve the correct problem. Make
sure that you understand exactly what you have to do before you start the next step
in the development cycle. If you are not sure what you need to do, ask the person who
wants you to develop the program. If you are writing the program for yourself, then
you have to make all the decisions. Do not waste time solving the wrong problem.
Step 2: Design the Program There are several ways of describing program design. Two
common methods are by flowcharts and pseudocode. A flowchart is a graphic de-
scription of a program design that uses combinations of various standard flowchart
symbols. Figure 1.2 shows some standard symbols and the operations they repre-
sent.We shall use flowcharts to represent only the basic program control structures.
Pseudocode (literally, “false code”) describes program design using English.
Pseudocode avoids the syntax of a programming language and, instead, emphasizes
Section 1.1 Our First C++ Program 5
Connector
Figure 1.2
In the next step of the program development cycle, you will submit the pro-
gram code, called the source program or the source code, to the computer for
compilation.
Step 4: Compile and Link the Program The only language a given computer under-
stands is its own machine language. A machine language instruction is a binary-
coded instruction (consisting of zeros and ones) that commands the computer to
do one specific task, such as add 1 to a register. Each computer has its own ma-
chine language. The machine language for a Sun workstation is different from the
machine language of a Macintosh, which is different from the machine language
of an IBM PC, and so on. Because machine language is in binary, it is difficult to
write and find errors in machine language programs.
Because a computer understands only its own machine language, it cannot
execute high-level or middle-level language instructions directly. The computer,
using a program called a compiler, must translate middle-level and high-level lan-
guage programs into equivalent machine language programs. A compiler is a spe-
cialist. It translates only one high-level or middle-level language into a specific
machine language. A PC-based C++ compiler translates C++ into PC machine
language. The compiler cannot translate a different language (such as Java) and
cannot be used on a different type of computer (such as a Macintosh.)
A compiler has two main functions. First it checks the source program for
syntax errors. Syntax errors are errors in the grammar of the programming lan-
guage. If there are any fatal syntax errors (that is, errors so severe that the com-
piler does not understand the statement and cannot translate the statement into
machine language), the compiler will stop and notify you of the errors it found. If
the compiler finds no fatal errors, it translates each high-level language instruc-
tion into one or more machine language instructions. This machine language ver-
sion of the source program is the object program.
Although it is in machine language, the object program may not be ready to
execute. The program may contain references, called external references, to other
programs that a user may have written or that the C++ compiler provides for use
by all system users. In either case, you must use a program called a linker to
resolve these external references. The linker finds the other programs and makes
them part of your program. We call this process linking. The linker resolves ex-
ternal references and combines the object code with these other programs to pro-
duce the executable code. It is the executable code that the computer executes.
The steps necessary for you to compile and link a program depend on the
computer system and compiler on which you develop the program, and the IDE
you use. Some IDEs simply require selecting the compile and link options from
pull-down menus. Some IDEs require that you create a project in which to run
your program. Other IDEs require executing one or two statements at command
level to compile and link a program. Consult your program IDE’s manual or on-
line help for instructions on the procedure you must follow.
Step 5: Execute the Program Once you have compiled and linked the program, you
are ready to execute the program. Executing the program is usually quite simple.
In some IDEs, all you need to do is select the execute option from a menu or click
Section 1.1 Our First C++ Program 7
an icon. On other systems, you need to execute the program at command level.
Consult your program development environment user’s guide for the procedure
you must follow.
Step 6: Test and Debug the Program Even if a program executes, it does not mean that
the program is correct. Even if a program gives correct results using some data, it
does not mean that the program will give correct results using another set of data.
Make sure that you test your program under as many conditions as possible to try
to catch errors.
Errors in Step 1: An error at the problem definition stage can affect the entire
program; make sure that you understand the problem you are supposed to solve.
Errors can arise in most of the following steps because of a faulty understanding
of the problem.
Errors in Step 2: After the initial program design, you or a friend might discover
a flaw in the design. If this is the case, you have to redesign part or the entire
program.
Errors in Step 3: Errors in step 3, coding the program, can be caught by the IDE.
Many IDEs color code different syntactic elements of a program. This makes it
easier to catch obvious mistakes in your coding. Make sure that you save your
program after each correction that you make. Some coding errors, however, are
not highlighted by the IDE. Therefore, after you have entered your program in
the IDE’s text editor, read the entire program. It is also a good idea to check a
printed version of the program.
Errors in Step 4: If the compiler finds any fatal errors in your program, it will not
complete the translation of your program into machine language. You will re-
ceive a list of error messages detailing the type and location of each error the
compiler found. Then, you must go back to step 3, correct your errors, and start
the process over. Besides fatal errors, the compiler also may advise you of what it
thinks are mistakes. The compiler usually calls these warnings. Warnings are not
serious enough to stop the translation, but the compiler thinks you should be
made aware of them. If the compiler issues warnings, the compilation will take
place. However, you should try to correct the source of these warnings before you
execute the program unless you coded the source of the warning on purpose.
Statements that cause the compiler to issue warnings can cause some very subtle
errors in program output when you execute the program. In short, do not execute
your program until you have removed all syntax errors.
After a successful compile, there can be an error in the linking process. Usu-
ally, a linker error is caused by the inability of the linker to resolve an external ref-
erence. The most common cause of this error is the misspelling of the name of an
8 Chapter 1 Introduction to C++
external program. The linker cannot find the misspelled program because it does
not exist. Whatever the cause of the linker error, you must find and correct it.
Errors in Step 5: Assuming the compilation and linking are successful, you can ex-
ecute your program. Two types of errors can now occur. First, the program may
end during execution because it cannot execute a particular instruction. This is a
run-time error. When a program abnormally ends, the computer displays a mes-
sage showing the type of error that occurred. You must now locate the cause of
the error (which could be in the data processed by your program, not in the pro-
gram itself) and make the necessary changes. Many compilers have techniques
that you can use to locate run-time errors. These techniques include step-by-step
tracing of program instructions and the ability to stop the program at a predeter-
mined place to inspect the values of variables. Consult your compiler’s user’s
guide or on-line help for instructions on how to locate run-time errors.
Errors in Step 6: While testing your program with different sets of data, errors can
occur that are difficult to detect. In fact, they could go unnoticed. Although a
program executes, produces output, and ends successfully, it is not necessarily
correct. Check your output to see if it is unreasonable or if it contains obvious er-
rors. If so, you must find the cause of the error. At this point in the program de-
velopment cycle, the error is probably a logic error. The compiler checks the
program for syntax errors, but it cannot check for errors in logic. Faulty program
design causes most logic errors. If your program contains a logic error, you must
find its cause (which is sometimes very difficult), go back to step 2, redesign, re-
code, reenter, recompile, relink, and retest the program (and hope that you do not
introduce new errors along the way).
Occasionally, faulty coding causes logic errors. Faulty coding is code that is syn-
tactically correct but incorrectly translates the program design into program code. If
your program contains faulty coding, locate and correct the faulty code, and then reen-
ter, recompile, relink, and retest the program. As we work through this book, we shall
point out some common errors caused by faulty coding.
The general rule of program development is catch errors early. A mistake in step 2
might not show until step 6. If this happens, you must go back to step 2 and start the
cycle again. This wastes your time, computer time, and money. Be cautious, and work
slowly and deliberately. If you are careful at the beginning of program development,
your efforts will pay off in the end.
int main()
{
cout << "This is our first C++ program." << endl;
cout << "It works!!!" <<endl;
cout << endl;
return 0;
}
Program Output
This is our first C++ program.
It works!!!
1.1.4 Comments
The first two nonblank lines of dem01-1.cpp are comments. A comment begins with
the two characters // and continues to the end of the line. The first comment gives the
name of the program and the second gives the author of the program. A comment is
not an executable statement. That is, a comment does not result in the computer tak-
ing any action. Comments, which can appear anywhere in a C++ program, help to
describe parts of the program and are a valuable documentation tool. For exam-
ple, comments might describe what a program’s variables represent or the purpose
of a section of the program. Remember that comments are not executable state-
ments and, therefore, the C++ compiler ignores everything from // to the end of
the line.
Comment your programs to explain their code. You can follow the style that we
use in the programs in this book, although programmers frequently use other com-
menting styles. Be sure to include at least the name of the program and your name as
comments in your own programs.
The first comment shows that the name of this program is dem01-1.cpp. We use
the convention that a C++ source-code program name should be eight or fewer charac-
ters in length (the characters can be letters, digits, and the hyphen), followed by the .cpp
file-name extension. This naming convention conforms to the requirements of most
C++ compilers. (Note: Many UNIX/Linux C++ compilers require the extension .C on
the name of a C++ source-code file.)
There is a blank line separating the two comment lines in dem01-1.cpp. You can
insert blank lines anywhere in a C++ program. We shall separate the important parts
of each program by one or more blank lines to enhance the readability of our pro-
gram code.
Comments can span several lines, as shown by the following.
// This is our first C++ program. This line is a comment line.
// It is common practice to write multiple-line comments
// like this.
Before explaining the #include and using lines in dem01-1.cpp, we discuss the
remainder of the program.
10 Chapter 1 Introduction to C++
A statement in C++, which can span several lines, ends with a semicolon in much
the same way as an English sentence ends with a period. Omitting a required semi-
colon would be like omitting a period in English—you would be writing the equivalent
of a run-on sentence.
Because C++ is statement oriented, we can code the function main() of
dem01-1.cpp as follows and cause no syntax errors.
int main(){ cout << "This is our first C++ program." << endl;
cout << "It works!!!" <<endl; cout << endl; return 0;}
This code, however, is hard to read. Note 1.2 gives a good rule of thumb to use
when coding a C++ program.
It is very important to keep in mind that C++ is case sensitive. That is, when coding
C++ statements there is a difference between uppercase and lowercase letters. Coding
int Main()
is incorrect because we used an uppercase M instead of a lowercase m in the word main.
When a C++ program begins executing, it looks for a function named main(), not a
Section 1.1 Our First C++ Program 11
function named Main(). Later, we shall adopt conventions for naming various C++ pro-
gram elements. These conventions will allow the use of uppercase letters to help us rec-
ognize the type of element each name represents. Until then, use lowercase letters for
everything except what appears inside double quotes "...", where you can use whatever
combination of letters you require.
The function main() can execute any of the following:
1. A built-in C++ statement. The program dem01-1.cpp does not contain any built-
in C++ statements. Much of this book is devoted to discussing the built-in C++
statements.
2. A function. The function main() can use any function whether it is a user-
defined function (one that the programmer defines and codes) or a standard li-
brary function (a precoded function that is part of the C++ system). We shall
learn about C++ functions throughout the rest of the book.
3. Operations on C++ streams, which we explain in the next section.
4. Other operations, which we shall encounter in later chapters.
Monitor Program
cout
<<
Use the output stream cout and the insertion operator << to send data to
the output stream.
Figure 1.3
After the first cout executes, the cursor is left following the period after the word
program. Therefore, when the second cout is executed, the characters it sends to the
output stream appear beginning at the current location of the cursor, that is, immedi-
ately after the period.
To correct this problem, we use endl (end-of-line). When endl is sent to cout, it
forces the cursor to the beginning of the next line. Note that the last character in endl
is a lowercase l, NOT a 1 (the digit one).
cout << "This is our first C++ program." << endl;
cout << "It works!!!" << endl;
After the string "This is our first C++ program." is sent to cout, the state-
ment sends endl, which causes the screen cursor to move to the beginning of the next
line. Thus, more than one thing can be sent to cout in one statement by “cascading” the
<< operator. When several insertion operators are used in the same cout statement,
read the first one as “gets” or “is sent” and the subsequent ones as “followed by”.
The second of the two statements in our program displays "It works!!!" and then
sends endl to cout, which causes the cursor to move to the beginning of the next line.
It works!!!
One cout statement can display data on several lines. For example, the following
cout produces the same output as the two cout statements of dem01-1.cpp.
Section 1.1 Our First C++ Program 13
cout << "This is our first C++ program." << endl << "It works!!!" << endl;
To obtain double spacing between the displayed lines, code the following.
cout << "This is our first C++ program." << endl << endl;
cout << "It works!!!" << endl;
As we learn how to use other features of C++, we shall introduce other standard
header files. We also shall learn other preprocessor directives.
allows us to code in our programs cout (and later cin) without having to qualify
these by coding std::cout (and std::cin). The using directive basically says that
we can use all names within the std namespace (cout and cin are two such names)
without qualification.
Perhaps an analogy will help clarify the use of namespaces. Suppose I am at a
meeting of 40 people, two of which, besides me, are named John. If the committee
chairperson says “John, did you finish your report?”, there would be confusion about
which of the three Johns she is talking to. Therefore, the chairperson must qualify the
name by saying “John Molluzzo, did you finish your report?” However, when I am
home in my own “standard namespace” and my wife wants me to take out the garbage,
all she needs to say is “John, please take out the garbage.” Since I am in my own house
(my “standard namespace”), there is no need for her to qualify my name.
Note that the using directive is a requirement of the C++ standard, which was
approved in 1998. Older compilers will not recognize the using directive. If the using
directive causes errors when you compile dem01-1.cpp, you probably have an older
Section 1.1 Our First C++ Program 15
compiler that does not conform to the new standard. In that case, remove the using di-
rective and recompile your program. It will then be necessary to make the same change
to all the sample programs in the book.
TABLE 1.1
asm do if return typedef
auto double inline short typeid
bool dynamic_cast int signed typename
break else long sizeof union
case enum mutable static unsigned
catch explicit namespace static_cast using
char export new struct virtual
class extern operator switch void
const false private template volatile
const_cast float protected this wchar_t
continue for public throw while
default friend register true
delete goto reinterpret_cast try
16 Chapter 1 Introduction to C++
All three lines between the /* and */ are considered comments. This tech-
nique is convenient when you want to comment out an entire block of code for
debugging purposes. However, be careful if you use this technique—remember to
end the comment with the */. Failure to do so will cause the compiler to treat
everything from the /* to the end of the file as a comment.
Escape Sequences. Using endl, as we did in dem01-1.cpp, is the most common way
to control line spacing in C++. A second, but less common way to control line
spacing is by using the newline escape sequence. Each escape sequence begins
with the backslash character \. The escape sequence that causes the cursor to
move to the beginning of a new line on the monitor screen is \n, the newline char-
acter. Therefore, the first of the following statements displays the string "This is
our first C++ program." and then causes the cursor to move to the beginning
of a new line. The two lines produce exactly the same output as dem01-1.cpp.
cout << "This is our first C++ program.\n";
cout << "It works!!!\n";
There are many escape sequences that you can use in a string that you send to
cout. Experiments 10, 11, and 12 ask you to experiment with some escape sequences.
Table 1.2 lists the common escape sequences. To use an escape sequence in a cout
statement, the escape sequence must be contained in a quoted string.
TABLE 1.2
\a alert (bell)
\b backspace
\f form feed
\n new-line
\r carriage return
\t horizontal tab
\v vertical tab
\' single quotation mark
\" double quotation mark
\\ single back slash
\? question mark
Section 1.1 Our First C++ Program 17
and interpret the output of the program (the result of the experiment) and decide
whether the program (the experiment) worked correctly. Chemists, physicists, and bi-
ologists learn from both successful and failed experiments. You also can learn a great
deal about programming from programs that work as required and from programs
that do not work as required. In addition, the experience gained from doing the ex-
periments will help you avoid making mistakes when writing your own programs. Try
to do as many experiments as possible. The more you do, the more you will learn.
The programming problems range in difficulty from simple, straightforward
problems to problems that require considerable time to design, code, and test. Attempt
at least one programming problem in each chapter. In each programming problem, de-
sign the program, write the code, compile the program, and then test the program with
sample input data.
Exercises 1.1
1. What is wrong with the attempt at a multiline comment in main()?
// dem01-1.cpp
// John C++. Molluzzo
#include <iostream>
using namespace std;
int main()
{ // This is the body of the
function main()
cout << "This is our first C++ program." << endl;
cout << "It works!!!" << endl;
return 0;
}
Experiments 1.1
For each experiment concerning dem01-1.cpp, start with a fresh copy of dem01-1.cpp
and make the indicated changes.
1. Delete the #include <iostream> preprocessor directive from dem01-1.cpp. At-
tempt to compile and execute the resulting program. What message does your
compiler issue?
18 Chapter 1 Introduction to C++
2. As mentioned in this section, C++ is case sensitive. Replace the i in the pre-
processor directive #include by I and compile the resulting program. What mes-
sage does your compiler issue? Now replace the word cout by COUT. What
message does the compiler issue?
3. Every C++ statement must end with a semicolon. Intentionally omit the semi-
colon at the end of the first cout statement in dem01-1.cpp and compile the re-
sulting program. What message does your compiler issue?
4. A preprocessor directive must not end with a semicolon. Put a semicolon at the
end of the #include directive in dem01-1.cpp and compile the resulting pro-
gram. What message does your compiler issue?
5. The body of the function main() must be enclosed in braces {}. Omit either the
left brace 5or the right brace6 in dem01-1.cpp and compile the resulting pro-
gram. What message does your compiler issue?
6. If you are not sure if your compiler conforms to the new C++ standard, write a
program that will find out.
7. If your compiler conforms to the new C++ standard, remove the using statement
from dem01-1.cpp and compile the program. What happens?
8. If your compiler conforms to the new C++ standard, remove the using statement
from dem01-1.cpp and replace all occurrences of cout by std::cout. Recompile
the resulting program. What happens?
9. If your compiler conforms to the new C++ standard, add the .h in the #include
directive in dem01-1.cpp. Recompile the resulting program. What happens?
10. A useful escape sequence is the horizontal tab \t. It works like the tab stops on a
typewriter. Enter, compile, and execute the following program. What does the tab
escape sequence do?
// Tabs
#include <iostream>
using namespace std;
int main()
{
cout << "One\tTwo\tThree\tFour" << endl;
cout << "\tFive\tSix\tSeven" << endl;
cout << "\t\tEight\tNine" << endl;
cout << "\t\t\tTen" << endl;
return 0;
}
Based on the output, at what positions are your computer’s tabs set?
11. Another useful escape sequence is the alert \a, also called the bell or audible
tone. Enter, compile, and execute the following program. What does the alert es-
cape sequence do?
// Alert
#include <iostream>
using namespace std;
Section 1.1 Our First C++ Program 19
int main()
{
cout << "\a\a\aWake up!" << endl;
cout << "The program ran!!" << endl;
return 0;
}
12. When outputting a string with the cout statement, the double quote " indicates the
beginning or end of a character string and the backslash \ denotes the beginning of an
escape sequence. If you want the character string you are displaying to contain either
of these characters, you must use a corresponding escape sequence. Enter, compile,
and execute the following program.What do the \" and \\ escape sequences do?
// Quotes and Backslashes
#include <iostream>
using namespace std;
int main()
{
cout << "The following is enclosed in double quotes: \"Quote\""
<< endl << endl;
cout << This is a backslash: \\" << endl;
return 0;
}
Why are there two double quotes near the end of the first cout statement?
2. Write a program that has the same output as the program of Programming Prob-
lem 1, but uses just one cout statement.
3. Write a program that displays the following.
*********** * Welcome * ***********
4. Write a program that displays your first initial in block form using asterisks. For
example, the program that John writes would display the following.
*********
*
*
*
*
*****
20 Chapter 1 Introduction to C++
1.2.1 Identifiers
All programming languages, including C++, require that the programmer name vari-
ous items that a program uses. We refer to the names of these items as identifiers. An
identifier can be any name you choose as long it conforms to the rules of Note 1.5.
1.2.2 Variables
A variable is a named location in the computer’s main memory that stores a particular
type of data. Because it is a location in computer memory, a variable can assume any
one of a set of permissible values. This is why we call such a location a variable.
Section 1.2 Integers and Arithmetic 21
Alternatively, you can write all the variables on one line as follows.
int i1, i2, sum;
22 Chapter 1 Introduction to C++
Note in both cases that there is a comma after each instance of i1 and i2, and
that the declaration ends with a semicolon after the last variable name. You can declare
any number of variables of the same type by separating their names by commas and
ending the declaration by a semicolon.
A variable can be declared anywhere in a C++ program. However, a variable
must be declared before it is used. Although not required by C++, we shall adopt the
practice of placing each variable declaration at the beginning of main() on a separate
line. This improves the readability of our programs and allows us to place a comment
after a variable’s name to explain its function in the program. In later chapters, we shall
discuss when it is appropriate to declare a variable elsewhere in the program.
The value of a variable is the data stored at that location in computer memory.
Declaring a variable does not give the variable any specific value. A declaration simply
reserves storage for that variable in the computer’s memory and associates the de-
clared name with that storage. Before the program places data into a variable, the
value of the variable is meaningless to the program. In this case, we say that the vari-
able contains garbage. It is up to the programmer to make sure that the program places
meaningful data into each variable.
sum,
difference,
product,
quotient,
remainder;
// Obtain the data from the user
cout << "Input an integer followed by a return: ";
cin >> i1;
cout << "Input an integer followed by a return: ";
cin >> i2;
// Do the arithmetic
sum = i1 + i2;
difference = i1 - i2;
product = i1 * i2;
quotient = i1 / i2;
remainder = i1 % i2;
// Output the results
cout << endl;
cout << "The sum of " << i1 << " and " << i2 << " is " << sum << endl;
cout << "The difference of " << i1 << " and " << i2 << " is "
<< difference << endl;
cout << "The product of " << i1 << " and “ << i2 << " is "
<< product << endl;
cout << "The quotient of " << i1 << " and " << i2 << " is "
<< quotient << endl;
cout << "The remainder when " << i1 << " is divided by " << i2
<< " is " << remainder << endl;
return 0;
}
Program Output
Input an integer followed by a return: 15
Input an integer followed by a return: 6
The sum of 15 and 6 is 21
The difference of 15 and 6 is 9
The product of 15 and 6 is 90
The quotient of 15 and 6 is 2
The remainder when 15 is divided by 6 is 3
and i2 to store the integers input by the user. It also needs the variables sum,
difference, product, quotient, and remainder to store the results of each arith-
metic calculation. Remember that because each of these variables is an integer, each of
their values must be in the range of an integer variable. Experiment 4 addresses the
question of what happens if one of these numbers is outside the permissible range.
Program
Monitor
Keyboard
cout cin
<< >>
Use cin and the extraction operator >> to remove data from the
input stream (the keyboard.)
Figure 1.4
Other documents randomly have
different content
“It may have been that he wanted the monopoly of yourself,” said
Gaston, looking at her keenly and speaking in his quietest tones.
“Well, it’s more than you’ll ever want, then!” said Mrs. Vere, pertly;
“so you can just keep yourself out of the matter.”
“I have every intention of doing so, madam,” said Gaston, gravely. “I
know my place, and I value my peace of mind.”
Mrs. Vere flashed a quick, vindictive glance at him, as he uttered
these quiet words, and then turning to Margaret, she said:
“I want to ask you to join a little theatre-party I am giving to-
morrow evening, Miss Trevennon. There will be eight of us, and we
are going to see As You Like It, and have a little supper at my house
afterward. Now don’t say you have any other engagement.”
“Unfortunately I must,” said Margaret, conscious of the insincerity of
the qualifying term, and yet too grateful to Louis for preparing her
for this contingency to feel very contrite on account of it. “I have
already pledged myself elsewhere.”
“How tiresome!” said Mrs. Vere, darting a suspicious glance at Louis,
which he met with imperturbable gravity. “By-the-way, I called on
you while you were in Baltimore. I suppose you got my card.”
And, without waiting for an answer, she moved away, on Decourcy’s
arm, saying, as if half involuntarily:
“I detest that man.”
Decourcy, who was looking somewhat preoccupied, made no answer,
until she gave his arm a little jerk and said, with the petulance of a
child:
“What’s the matter with you? Why don’t you speak?”
“What can I say, except that I feel deeply sorry for poor Gaston, and
appropriately grateful that I do not happen to be in his place.”
He spoke in his softest tones, but Mrs. Vere knew instinctively that
her spell was, for the time being, broken. Well! it had been broken
before, she reflected, and she had always succeeded in mending it,
and she felt confident she could do so again.
Meantime, as Margaret and Louis walked away, to look for Mrs.
Gaston, the former said:
“Was it not rather odd that Mrs. Vere didn’t ask you to join her
party?”
“She did,” said Louis. “She wrote me a note, which was forwarded to
me in New York.”
“And what did you do?” asked Margaret.
“Excused myself on the score of another engagement.”
“But you didn’t——” she began, and then stopped with uplifted
eyebrows.
“I know,” he answered, smiling; “but I foresaw at least the possibility
that you would be propitious.”
“I think she’s angry with you about it.”
“Very likely. She’s been angry with me before.”
“I didn’t know, until to-night, that she was an old friend of Alan’s,”
said Margaret.
“Oh yes,” he answered, indifferently; “it’s an affair of long standing, I
hear.”
“What do you mean?” said Margaret, facing him with a sudden
surprise, and then, remembering the scene she had witnessed in the
conservatory, she averted her eyes, and was silent.
“I merely meant,” he answered, in a tone of quick regret, “that I
happened to hear Waring say that they were friends in London, last
year. Mr. and Mrs. Vere spent the season there, and your cousin
happening to be there also, naturally saw them often—all being
Americans together.”
At this point they caught sight of Mrs. Gaston, and Margaret
hastened to join her, and so the subject was very willingly dropped
by them both.
Cousin Eugenia declared and reiterated that Margaret had been a
shining success at this ball, but of that the girl thought and cared
little. But for many days to come, the recurring thoughts of that
evening brought with them certain memories that rankled, as well as
certain others that comforted and soothed.
CHAPTER XIV.
C HRISTMAS Day was fine and brilliant, and Margaret awaked early.
Her first thoughts were of home and distant friends. How well
she knew that the dear father and mother, far away in Bassett, were
thinking of her! As she rose and dressed, her heart was in full unison
with the day’s sweet lesson of peace and goodwill, and when she
knelt to say her morning prayers, she had a vague feeling that
somehow this Christmas Day was a fuller and better one than any
she had known before. She did not ask herself what was the new
element in her life that made it so; it was too indefinite to be
formulated into a tangible idea, but she felt conscious of its
presence.
General and Mrs. Gaston had a charming present for her when she
went down to breakfast—a pair of exquisite gold bracelets of the
most beautiful design and workmanship, and, as they seemed really
pleased with the little presents that she had prepared for them, they
had a very satisfactory beginning of their Christmas Day. After
breakfast, she went to her room to write a letter home, and when
that was done it was time to dress for church.
A little before eleven, as Miss Trevennon was standing in the deep
bow-window of the drawing-room, equipped for the morning service,
she heard a firm tread on the carpet behind her, and the next
moment her somewhat rusty little Prayer-book and Hymnal were
slipped from her hand, and a marvellous tortoise-shell case,
containing two beautiful little books, substituted for them. Margaret
looked up quickly, and met Louis Gaston’s smiling eyes. He had
searched New York over for the prettiest set he could find, and the
result satisfied him.
“You will use these instead, will you not?” he said. “I wanted to give
you some little thing.”
A flush of pleasure rose to Margaret’s face.
“I never saw anything half so lovely,” she said, handling them
delightedly. “To think of your taking the trouble! I suspect my
shabby little books offended your fastidious taste. I never dreamed
of your remembering me in this kind way. I wish I had a present for
you.”
“You might give me the old ones, perhaps,” he said, hesitatingly. “I
should think it a munificent return, for, as you say, they are worn
and shabby, and that comes only from much using. How often they
have been in your hands when your thoughts were away with God! I
should like to keep them as a souvenir of you. May I, if you don’t
particularly value them?”
“I should be only too glad for you to have them,” said Margaret, in a
low voice. “Only I did not think you would care for anything like that.
I asked Cousin Eugenia once what church your family belonged to,
and she said you called yourselves Unitarians, but practically you
were pagans. I couldn’t help hoping it was not really true—of you at
least.”
“It isn’t in the least true of me,” he said, frowning, and looking so
displeased that Margaret was almost sorry she had spoken. “I would
not, for anything, have you to suppose me an irreligious man, for it
is not true, and I never even called myself a Unitarian. On the
contrary, I was wishing a little while ago that I could go with you to
church, so that you and I might keep this day holy together.”
“Do,” said Margaret, earnestly. “I have seen that you do not very
often go. Go with us to-day, and make a resolve for better things in
future. You would be so wise to do it.”
“I don’t think I will go this morning,” he said; “Eugenia has not room
for me in the coupé. But will you let me take you to-night? We will
walk, perhaps, if it remains fine, and the music will be lovely.
Perhaps, if we’re lucky, they will get some good voice to sing the
Cantique de Noël.”
“I love that so dearly,” Margaret said. “I shall be delighted to go with
you.”
A little sigh rose, as she spoke. This was one of Charley Somers’
favorites; she had taken pains to see that he sang it correctly, and
his voice was trained to it beautifully.
Her reflections were cut short by the appearance of Mrs. Gaston,
who swept down the steps, elaborately arrayed in furs and velvets,
and signified her readiness to set out.
Louis helped them into the carriage, and then turned away, saying
he was going for a long walk. There was a look of gravity on his face
that Margaret found herself recalling long afterward.
The weather continued fine, and it proved quite mild enough for
Louis and Margaret to walk to church in the evening. As they took
their way along the gayly lighted streets, the young man turned
suddenly and, looking down into her face, said:
“Do you know, I found a little pressed flower in my Hymnal, when I
opened it this morning. Am I to keep it or return it to you?”
They were just under a gas-light, and Margaret, though she would
not drop her eyes under his searching gaze, felt that she looked
confused, as she said:
“No; you must give that back to me. I had forgotten it.”
It was a little flower that Charley Somers had put in there one
evening, and she had never happened to remove it.
Mr. Gaston put his hand into his pocket and took out the book. It
opened easily at the place, and he removed the flower, which was
run into a little slit, and handed it to her as they entered the church
vestibule.
“There were some initials under it,” he said.
“Oh, you can just rub those out. It doesn’t matter,” said Margaret, as
she took the flower. She was about to crush and throw it from her,
when a pang of pity for poor Charley checked her; so she opened
her own Prayer-book and hurriedly slipped it among the leaves.
The service seemed wonderfully sweet to her that night. The hymns
and anthems were triumphant and inspiring, and the sermon was
simple, earnest and comforting. Louis found his places, and used his
little book sedulously, and Margaret felt intuitively that this service
was sweet to him also. As she glanced at him occasionally, she saw
that his face looked serious and a little careworn, now that she saw
it in such perfect repose.
The sermon was ended now. The congregation had risen at its
termination, and had settled again in their seats. The wardens were
walking up the aisle to receive the alms-basins, when the organ
began to murmur a low prelude. Louis and Margaret glanced at each
other quickly. It was the Cantique de Noël.
Margaret leaned back in her seat, serene and restful, prepared for a
deep enjoyment of the pleasure before her, and at that moment a
rich, sweet voice, high up in the choir behind her began:
“Oh, holy night——”
At the first note uttered by that voice the color rushed to Miss
Trevennon’s cheeks, and she drew in her breath with a sound that
was almost a gasp.
And up on high the beautiful voice sang on:
“It is the night of the dear Saviour’s birth.”
Higher and sweeter it soared—thrilling, rich, pathetic—and how
familiar to the young girl’s ears was every modulation and inflection!
How often had that flood of melody been poured forth, for her ear
alone, in the old parlor at home!
It was Charley Somers, and she knew that he had seen her, and that
he was singing to her now, no less than then. She listened, as in a
dream, while the wistful, yearning voice sang on. And now came the
words:
“Fall on your knees! fall on your knees!”
They were somewhat indistinct, in their mingling of sweet sounds,
and, in some vague way, it seemed to Margaret that they were a
direct appeal from Charley Somers to her for mercy and pardon.
It was all so moving, and Gaston felt so touched by it himself, that it
scarcely surprised him when he glanced at Margaret, as the sweet
voice died away, to see that her eyes were full of tears. As they knelt
for the concluding prayer she brushed away the traces of these, and
when they walked down the aisle together her calmness had quite
returned. And how calm and quiet her companion looked! His
perfectly chosen clothes, the smooth neatness of his short, dark hair,
and, more than all, his self-collected bearing and thoughtful face,
made him a contrast to the rather carelessly dressed young man,
with dishevelled, curly locks, and eager, restless eyes, who stood in
the vestibule, at the foot of the gallery steps, rapidly scanning the
faces of the dispersing congregation, in complete unconsciousness of
the fact that his somewhat singular conduct and appearance were
being observed by those around him. As his restless gaze at last fell
upon Miss Trevennon, his knit brows relaxed, and he pressed
forward.
“May I come to see you to-morrow?” he said, in eager tones, which,
though low, were distinctly audible to Louis.
“Yes,” replied Margaret at once, in a somewhat tremulous voice, “at
eleven in the morning.”
Then, taking her companion’s arm, she passed on. Louis had
observed that the two did not shake hands, nor exchange any word
of greeting. This hurried question and answer was all that passed
between them. What had there been in a short, casual meeting like
that to make the girl look pale and excited, as her companion saw
by a furtive glance that she was? He could feel her hand tremble
slightly when she first laid it within his arm, but the little, almost
imperceptible flutter soon ceased, and she walked on very quiet and
still. And so they took their way along the streets in silence. She did
not seem inclined to talk, and he would not jar her by speaking.
Margaret, as she mused upon this meeting, was blaming herself for
the concession she had made, which was indeed attributable
altogether to the music.
“I have no resolution or power of resistance whatever, when I’m
under the influence of music,” she said to herself, half angrily. “It
takes away my moral accountability. I don’t believe the story of the
sirens is a fable. A beautiful voice could draw me toward itself as
truly as the pole draws the magnet. It is intense weakness. I ought
to have told him No, and ended the matter at once.”
Remembering that her companion would have reason to wonder at
her silence, Margaret roused herself with an effort and made some
comment on the service.
“It was all very beautiful,” said Louis. “I felt it very much, and I feel
very happy to have gone. That solo was exquisitely sung. The voice
does not seem to be highly cultivated, but it was thrillingly sweet.”
“It was Mr. Somers, the young man from Bassett, whose voice I
have spoken to you of. He has just come to Washington, and I knew
he would want to see me, so I named an hour when I was sure to
be free.”
When they had reached home and were going up the steps, they
found Thomas opening the door for a colored servant-man, who had
two small parcels in his hand. He took off his hat and stepped back
as they came up, and Thomas said:
“It is a parcel for Miss Trevennon.”
Margaret turned and held out her hand for it.
“Where from?” she said.
“From the Arlington, Miss,” replied the man, in evident trepidation.
“I’m very sorry, Miss, but there’s been a mistake. It was to have
been sent this morning, but it has been such a busy day that it has
been forgotten. Mr. Decourcy left particular orders, and I hope you’ll
be kind enough to excuse the delay, Miss.”
Margaret turned the parcel so as to get the light from the hall gas
upon it. As she did so, her expression changed quickly. It was
addressed to Mrs. Vere.
“There is some mistake,” she said, coldly, with a certain high turn of
the head that Louis knew. “This is not for me.”
The poor negro, who was perhaps somewhat the worse for the wine
remnants left by the Arlington’s Christmas guests, was overwhelmed
with confusion, and, quickly extending the other package, explained
that he had made a mistake between the two, and asked Miss
Trevennon rather helplessly to see if this one was not addressed to
herself.
It proved to be so; and though, under the circumstances, Margaret
would have preferred not to touch it, she was compelled to take it
and dismiss the man, which she did somewhat curtly.
She did not examine her parcel until she reached her own room, and
even then she tossed it on the bed, and removed her wraps and hat
and put them away before she untied the string which bound it.
Once she thought she would put it out of sight until to-morrow, but,
despite her disfavor toward the giver, she had a young lady’s natural
curiosity as to the gift, and so she presently took it up and untied it.
A little note fell out. It was dated Christmas morning at nine, and
ran:
“I am just leaving for Baltimore, under a pledge to spend
to-day with Amy and the children. I have been more than
disappointed—hurt at missing you, both when I called and
at the theatre last evening. I did not know you had been
present, until I heard it by accident, after we had left. It
had not at all entered into my calculations to forego the
pleasure of taking leave of you in person, and I propose to
get the better of fate by returning in a day or two for this
purpose.
“Merry Christmas, dear Daisy, and all good wishes for the
coming year! Who knows what it may have in store for
us?
“Wear my little present sometimes for the sake of yours
devotedly, A. D.”
“So much for note number one!” said Margaret. “It would be
interesting to have a glance at note number two, which I have no
doubt is equally tender and gracious.”
She took up the little leather case and opened it, revealing a
beautiful locket. In spite of herself, she could not withhold a tribute
to her cousin’s taste. The workmanship and design of this little
ornament were so effective and so uncommon that she felt sure
Alan must have gone to some trouble about it, and most likely had it
made expressly for her.
“He is kind,” she said, regretfully. “It was good of him to go back to
Baltimore, in order that Amy and the children should not be
disappointed. I almost wish I had not made this new discovery about
him; but no, no, no! It would have been dreadful to be ignorant of
the real truth of the matter.”
It occurred to her now to open the locket and, on doing so, her
cousin’s high-bred face looked out. The very sight of it made her
recoil inwardly. How well she remembered the look of these same
eyes, as they had been bent upon Mrs. Vere, with an expression she
would have liked to forget. What right had he to expect her to wear
his picture? Why should she?
He had sent another note and another present elsewhere. Was there
another picture, which some one else had been gracefully urged to
wear, for the sake of hers devotedly? It was more than probable!
“I half believe I begin to understand him,” she said to herself,
indignantly. “It is one of his sage and correct opinions that a man
should marry, but all the same a man wants his little diversions.
Under these circumstances he had better marry an amiable, easy-
going young thing, who is healthy and cheerful, who knows nothing
of the world, and who will leave him to pursue his little diversions
undisturbed. It is perfectly humiliating! I will return his locket, for
the very sight of it would always sting me.”
CHAPTER XVII.
ebookgate.com