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

C++ Programming: An Object-Oriented Approach, 1e ISE 1st Edition Behrouz A. Forouzan download

The document provides information about the book 'C++ Programming: An Object-Oriented Approach' by Behrouz A. Forouzan and Richard F. Gilberg, including its publication details and a brief table of contents. It also includes links to download the book and other related resources from ebookmass.com. The book covers various topics in C++ programming, including basics, functions, classes, and data structures.

Uploaded by

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

C++ Programming: An Object-Oriented Approach, 1e ISE 1st Edition Behrouz A. Forouzan download

The document provides information about the book 'C++ Programming: An Object-Oriented Approach' by Behrouz A. Forouzan and Richard F. Gilberg, including its publication details and a brief table of contents. It also includes links to download the book and other related resources from ebookmass.com. The book covers various topics in C++ programming, including basics, functions, classes, and data structures.

Uploaded by

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

Visit https://ebookmass.

com to download the full version and


browse more ebooks or textbooks

C++ Programming: An Object-Oriented Approach, 1e


ISE 1st Edition Behrouz A. Forouzan

_____ Press the link below to begin your download _____

https://ebookmass.com/product/c-programming-an-object-
oriented-approach-1e-ise-1st-edition-behrouz-a-forouzan/

Access ebookmass.com now to download high-quality


ebooks or textbooks
We have selected some products that you may be interested in
Click the link to download now or visit ebookmass.com
for more options!.

Foundations of Computer Science 4th Edition Behrouz


Forouzan

https://ebookmass.com/product/foundations-of-computer-science-4th-
edition-behrouz-forouzan/

Data communications & networking with TCP/IP protocol


suite Behrouz A. Forouzan

https://ebookmass.com/product/data-communications-networking-with-tcp-
ip-protocol-suite-behrouz-a-forouzan/

Data Communications and Networking with TCP/IP Protocol


Suite 6th Edition Behrouz A. Forouzan

https://ebookmass.com/product/data-communications-and-networking-with-
tcp-ip-protocol-suite-6th-edition-behrouz-a-forouzan/

Object Oriented Programming_hard_man_v1.pdf Amany Fawzy


Elgamal

https://ebookmass.com/product/object-oriented-
programming_hard_man_v1-pdf-amany-fawzy-elgamal/
Design patterns: elements of reusable object-oriented
software Gamma

https://ebookmass.com/product/design-patterns-elements-of-reusable-
object-oriented-software-gamma/

An Introduction to Programming through C++ Abhiram G.


Ranade

https://ebookmass.com/product/an-introduction-to-programming-through-
c-abhiram-g-ranade/

C Programming Language: C PROGRAMMING LANG _p2 2nd


Edition, (Ebook PDF)

https://ebookmass.com/product/c-programming-language-c-programming-
lang-_p2-2nd-edition-ebook-pdf/

Learn Programming with C: An Easy Step-by-Step Self-


Practice Book for Learning C 1st Edition Imran

https://ebookmass.com/product/learn-programming-with-c-an-easy-step-
by-step-self-practice-book-for-learning-c-1st-edition-imran/

Principles of Economics: A Streamlined Approach, 4e ISE


4th/ISE Edition Robert H. Frank

https://ebookmass.com/product/principles-of-economics-a-streamlined-
approach-4e-ise-4th-ise-edition-robert-h-frank/
C++ Programming:
An Object-Oriented Approach

Behrouz A. Forouzan
Richard F. Gilberg
C++ PROGRAMMING: AN OBJECT-ORIENTED APPROACH

Published by McGraw-Hill Education, 2 Penn Plaza, New York, NY 10121. Copyright © 2020 by McGraw-Hill Education. All rights
reserved. Printed in the United States of America. No part of this publication may be reproduced or distributed in any form or by any
means, or stored in a database or retrieval system, without the prior written consent of McGraw-Hill Education, including, but not
limited to, in any network or other electronic storage or transmission, or broadcast for distance learning.

Some ancillaries, including electronic and print components, may not be available to customers outside the United States.

This book is printed on acid-free paper.

1 2 3 4 5 6 7 8 9 LWI 21 20 19

ISBN 978-0-07-352338-5 (bound edition)


MHID 0-07-352338-0 (bound edition)
ISBN 978-1-259-57145-9 (loose-leaf edition)
MHID 1-259-57145-9 (loose-leaf edition)

Executive Portfolio Manager: Suzy Bainbridge


Product Developer: Heather Ervolino
Marketing Manager: Shannon O’Donnell
Content Project Managers: Jane Mohr and Sandra Schnee
Buyer: Laura Fuller
Designer: Egzon Shaqiri
Content Licensing Specialist: Shawntel Schmitt
Cover Image: ©McGraw-Hill Education
Compositor: MPS Limited

All credits appearing on page or at the end of the book are considered to be an extension of the copyright page.

Library of Congress Cataloging-in-Publication Data

Forouzan, Behrouz A., author. | Gilberg, Richard F., author.


C++ programming : an object-oriented approach / Behrouz A. Forouzan, Richard F. Gilberg.
First edition. | New York, NY : McGraw-Hill Education, [2020] |
Includes index.
 LCCN 2018030975| ISBN 9780073523385 (bound edition : acid-free paper) |
ISBN 0073523380 (bound edition : acid-free paper) | ISBN 9781259571459 (loose-leaf edition) |
ISBN 1259571459 (loose-leaf edition)
LCSH: Object-oriented programming (Computer science) | C++ (Computer program language)
LCC QA76.64 .F684 2019 | DDC 005.1/17—dc23
LC record available at https://lccn.loc.gov/2018030975

The Internet addresses listed in the text were accurate at the time of publication. The inclusion of a website does not indicate an endorse-
ment by the authors or McGraw-Hill Education, and McGraw-Hill Education does not guarantee the accuracy of the information presented
at these sites.

mheducation.com/highered
To my wife, Faezeh
Behrouz A. Forouzan

To my wife, Evelyn
Richard F. Gilberg
This page intentionally left blank
Brief Table of Contents

Preface xv
Chapter 1 Introduction to Computers and Programming Languages 1
Chapter 2 Basics of C++ Programming 19
Chapter 3 Expressions and Statements 59
Chapter 4 Selection112
Chapter 5 Repetition158
Chapter 6 Functions208
Chapter 7 User-Defined Types: Classes 273
Chapter 8 Arrays338
Chapter 9 References, Pointers, and Memory Management  380
Chapter 10 Strings443
Chapter 11 Relationships among Classes 496
Chapter 12 Polymorphism and Other Issues  553
Chapter 13 Operator Overloading 597
Chapter 14 Exception Handling 657
Chapter 15 Generic Programming: Templates 693
Chapter 16 Input/Output Streams 716
Chapter 17 Recursion776
Chapter 18 Introduction to Data Structures 813
Chapter 19 Standard Template Library (STL) 852
Chapter 20 Design Patterns Available online

v
Appendixes A-R  Available online

Appendix A Unicode
Appendix B Positional Numbering System

Appendix C C++ Expressions and Operators

Appendix D Bitwise Operations

Appendix E Bit Fields

Appendix F Preprocessing

Appendix G Namespaces

Appendix H Ratios

Appendix I Time

Appendix J Lambda Expressions

Appendix K Regular Expressions

Appendix L Smart Pointers

Appendix M Random Number Generation

Appendix N References

Appendix O Move versus Copy

Appendix P A Brief Review of C++ 11

Appendix Q Unified Modeling Language (UML)

Appendix R Bitset

CheckPoints  Available online

True/False Questions  Available online

Review Questions  Available online

Glossary  Available online

Index 915
Contents

Preface xv
What Is the C++ Language? xv
Why This Book? xv
Appendicesxvi
Instructor Resources xvii
Acknowledgmentsxvii

1
Introduction to Computers and Programming Languages 1

1.1 Computer System 1


1.2 Computer Languages 5
1.3 Language Paradigms 7
1.4 Program Design 10
1.5 Program Development 13
1.6 Testing15
Key Terms 16
Summary17
Problems17

2
Basics of C++ Programming 19

2.1 C++ Programs 19


2.2 Variable, Value, and Constant 26
2.3 Components of a C++ Program 32
2.4 Data Types 36
Key Terms 52
Summary52
Problems52
Programming Projects 57

vii
viii Contents

3
Expressions and Statements 59

3.1 Expressions59
3.2 Type Conversion  71
3.3 Order of Evaluation 76
3.4 Overflow and Underflow 81
3.5 Formatting Data 85
3.6 Statements93
3.7 Program Design  98
Key Terms 105
Summary105
Problems106
Programs110

4
Selection 112

4.1 Simple Selection 112


4.2 Complex Decisions 126
4.3 Decisions on Specific Values 134
4.4 Conditional Expressions 142
4.5 Program Design  144
Key Terms 152
Summary153
Problems153
Programs156

5
Repetition 158

5.1 Introduction158
5.2 The while Statement 161
5.3 The for Statement 175
5.4 The do-while Statement  180
5.5 More About Loops 184
5.6 Other Related Statements  188
5.7 Program Design  191
Key Terms 203
Summary203
Problems204
Programs206
Contents ix

6
Functions 208

6.1 Introduction208
6.2 Library Functions  213
6.3 User-Defined Functions 224
6.4 Data Exchange 233
6.5 More About Parameters 244
6.6 Scope and Lifetime  248
6.7 Program Design  256
Key Terms 265
Summary265
Problems266
Programs269

7
User-Defined Types: Classes 273

7.1 Introduction273
7.2 Classes275
7.3 Constructors and Destructors 283
7.4 Instance Members 294
7.5 Static Members 302
7.6 Object-Oriented Programming 311
7.7 Designing Classes 320
Key Terms 332
Summary332
Problems333
Programs335

8
Arrays 338

8.1 One-Dimensional Arrays 338


8.2 More on Arrays 349
8.3 Multidimensional Arrays 363
8.4 Program Design  369
Key Terms 376
Summary376
Problems376
Programs378
x Contents

9
References, Pointers, and Memory Management  380

9.1 References380
9.2 Pointers391
9.3 Arrays and Pointers 405
9.4 Memory Management 414
9.5 Program Design 425
Key Terms 437
Summary437
Problems437
Programs442

10
Strings 443

10.1 C Strings 443


10.2 The C++ String Class 460
10.3 Program Design 484
Key Terms 492
Summary492
Problems493
Programs494

11
Relationships among Classes 496

11.1 Inheritance496
11.2 Association519
11.3 Dependency528
11.4 Program Design 532
Key Terms 546
Summary546
Problems547
Programs550

12
Polymorphism and Other Issues  553

12.1 Polymorphism553
12.2 Other Issues 567
Contents xi

Key Terms 594


Summary594
Problems594
Programs596

13
Operator Overloading 597

13.1 Three Roles of an Object 597


13.2 Overloading Principles 602
13.3 Overloading as a Member 605
13.4 Overloading as a Nonmember  621
13.5 Type Conversion 625
13.6 Designing Classes 626
Key Terms 652
Summary653
Problems653
Programs654

14
Exception Handling 657

14.1 Introduction657
14.2 Exceptions in Classes 675
14.3 Standard Exception Classes 682
Key Terms 688
Summary688
Problems689
Programs692

15
Generic Programming: Templates 693

15.1 Function Template 693


15.2 Class Template 703
Key Terms 713
Summary713
Problems714
Programs715
xii Contents

16
Input/Output Streams 716

16.1 Introduction716
16.2 Console Streams 720
16.3 File Streams 729
16.4 String Streams 751
16.5 Formatting Data 755
16.6 Program Design 766
Key Terms 773
Summary773
Problems774
Programs774

17
Recursion 776

17.1 Introduction776
17.2 Recursive Sort and Search 792
17.3 Program Design 803
Key Terms 808
Summary808
Problems809
Programs811

18
Introduction to Data Structures 813

18.1 Introduction813
18.2 Singly Linked List 815
18.3 Stacks and Queues 825
18.4 Binary Search Trees 841
Key Terms 849
Summary850
Problems850
Programs851
Contents xiii

19
Standard Template Library (STL) 852

19.1 Introduction  852


19.2 Iterators853
19.3 Sequence Containers 856
19.4 Container Adapters 877
19.5 Associative Containers 884
19.6 Using Functions  894
19.7 Algorithms899
Key Terms 910
Summary910
Problems911
Programs911

20
Design Patterns Online

20.1 Introduction
20.2 Creational Patterns
20.3 Structural Patterns
20.4 Behavioral Patterns
Key Terms
Summary
Problems
Programs

Online Appendices
Appendix A Unicode
Appendix B Positional Numbering System
Appendix C C++ Expressions and Operators
Appendix D Bitwise Operations
Appendix E Bit Fields
Appendix F Preprocessing
xiv Contents

Appendix G Namespaces
Appendix H Ratios
Appendix I Time
Appendix J Lambda Expressions
Appendix K Regular Expressions
Appendix L Smart Pointers
Appendix M Random Number Generation
Appendix N References
Appendix O Move versus Copy
Appendix P A Brief Review of C++ 11
Appendix Q Unified Modeling Language (UML)
Appendix R Bitset

CheckPoints Available online

True/False Questions Available online

Review Questions Available online

Glossary Available online

Index 915
Preface

This book complements a course designed to teach object-oriented programming using the syntax
of the C++ language. It will also prepare students for advanced concepts such as data structure
and design patterns. Students who have completed this course will be ready to take on any other
object-oriented language course, a data-structure course, or a course about design patterns.

What Is the C++ Language?


C++ is a progressive programming language derived from its predecessors, the C language
and the B language. The C++ language expands the idea of a struct to a class in which dif-
ferent objects can be created from one single definition of a class with different values for
each data element.
Furthermore, the C++ language explores the idea of object-oriented languages that
simulate real life. In real life, we define a type and then we have objects of that type. In the
C++ language, we define a class and then we create objects from that class. C++ also in-
cludes the idea of inheritance. In inheritance, we can create a class and then extend the defi-
nition to create other classes, just as in real life where the idea of an animal can be extended
to create the idea of a horse, a cow, a dog, and so on.
Perhaps the most interesting addition to C++ is the idea of polymorphism. Polymor-
phism gives us the ability to write several versions of an action with the same name to be
used by different objects. This practice is found in real life when we use the verb open. We
can say that we open a business, open a can, open a door, and so on. Although the word open
is used in all cases, it elicits different actions on different objects.
The most recent additions to C++ include the Standard Template Library (STL), a
collection of predefined complex objects and actions that can be applied to those objects, as
well as design patterns to make problem solving more efficient and coherent.

Why This Book?


The book has five distinctive goals as discussed below.

Teach Computer Programming


The book can be used as the first course in computer programming using the C++ language
as the vehicle. Chapters 1 to 6 are designed for this purpose. They discuss computer systems
and languages. They also discuss the basics of the C++ syntax and program controls, such
as decisions and repetitions. Chapters 1 to 6 are essential to learning programming using the
C++ language.

Teach the Syntax of the C++ Language


Chapters 7 to 12 are essential in the study of object-oriented programming. Although Chap-
ters 8 and 9 are not directly related to the object-oriented features of C++, we believe that
these two chapters can be taught after students understand the basics of object-oriented pro-
gramming, which are discussed in Chapter 7.
xv
xvi Preface

Present New Features of C++


Chapters 13 to 17 discuss other topics normally taught in a first or second course in program-
ming. They can be taught in any order.

Discuss Data Structure and Introduce the STL Library


Chapters 18 and 19 are an introduction to data structures. They prepare students for a course
in data structures.

Introduce Design Patterns


Chapter 20 (which can be found online) gives simple and alternative solutions to some
typical problems in object-oriented programming that would be more difficult to solve if
patterns were not used. Chapter 20 gives students an insight to object-oriented programming
through a set of standard solutions to specific problems. Although design patterns are nor-
mally taught in computer graphics courses, we have applied them to nongraphic problems
for students who have no graphical programming experience.

Course Outline
The twenty chapters of the book are outlined in the following figure.

Chapter 1

Chapter 6

Chapter 7 Chapter 8
Chapter 10 Chapter 9
Chapter 11
Chapter 12

Chapter 13
Legend:
Chapter 17 Basic C++ language
Object-oriented concepts
Chapter 18 Can be taught in anywhere after chapter 7
Chapter 19 Can be taught if time allows (second course)
Data structures (optional)
Chapter 20 Design patterns (optional)

Appendices
Appendices can be found online and are divided into six categories.

References
Appendices A to E are designed to be used as references for students. Students may need to
consult these appendices when studying chapters in the book.

Language Knowledge
Appendices F and G give students information about how C++ prepares a source code for
compilation and how it handles names in different sections.
Preface xvii

Advanced Topics
Appendixes H to O discuss some advanced topics that were added to C++. They can be
taught in the class, or students can use them as a source of additional information.

Brief Review of C++ 11


Appendix P gives a brief review of C++ 11 topics that were not discussed in the appendices
that discussed advanced topics.

Brief Review of UML


We have used UML diagrams in the text. Appendix Q provides general insight into UML as
a tool for designing object-oriented projects.

Bitset
The concept of bitset becomes more popular when C++ is used in network programming.
We have included this topic in Appendix R.

Instructor Resources
Accompanying this text are several additional resources which can be found online at www
.mhhe.com/forouzan1e. These include CheckPoint questions that help instructors gauge stu-
dent understanding after reading each section of a chapter. True/false and review questions
are also available to further test student’s knowledge. Complete solutions to the CheckPoint
features, true/false questions, review questions, and problems are provided as well. Lastly,
Lecture PPTs, text image files, and sample programs are provided as well.

Acknowledgments
We would like to express our gratitude to the reviewers of this text. Their insight and sug-
gestions over the last few years greatly influenced this first edition. In alphabetical order, the
reviewers are as follows:

Vicki H. Allan, Utah State University


Kanad Biswas, Institute of Technology, Delhi
Gary Dickerson, Union College
Max I. Formitchev, Maximus Energy
Cynthia C. Fry, Baylor University
Barbara Guillott, Q&A Analyst, CGI, Lafayette, LA
Jon Hanrath, Illinois Institute of Technology
David Keathly, University of North Texas
Robert Kramer, Youngstown State University
Kami Makki, Lamar University
Christopher J. Mallery, Principal Software Engineering Lead for Microsoft
Michael L. Mick, Purdue University, Calumet
Amar Raheja, California State Polytechnic University, Pomona
Brendan Sheehan, University of Nevada–Reno

At McGraw-Hill, we would like to thank the following editorial and production staff:
Thomas Scaife, Senior Portfolio Manager; Suzy Bainbridge, Executive Portfolio Manager;
Heather Ervolino, Product Developer; Shannon O’Donnell, Marketing Manager; Patrick
Diller, Business Project Manager; and Jane Mohr, Content Project Manager.
This page intentionally left blank
1 Introduction to Computers
and Programming Languages
In this chapter, we describe the components of a computer system and discuss the general
ideas behind computer languages. The overview provided in this chapter will help prepare
you for future chapters. You can skip the chapter in the first reading and return to it when
you have a better understanding of programming.

Objectives
After you have read and studied this chapter, you should be able to:

• Discuss the two major components of a computer: hardware and software.


• Describe the six parts of hardware: CPU, primary memory, secondary storage, input system,
output system, and communication system.
• Describe the two major categories of software: system software and application software.
• Describe the evolution of computer languages from machine languages, to assembly
languages, and to high-level languages.
• Discuss four different paradigms of computer languages: procedural, object-oriented,
functional, and logic.
• Describe the two steps of program design: understand the problem and develop a solution.
• Describe the multistep procedure that transforms a program written in the C++ language to
an executable program.

1.1 COMPUTER SYSTEM


A computer system is made of two major components: hardware and software. The com-
puter hardware is the physical equipment. The software is the collection of programs
(instructions) that allow the hardware to do its job.

1.1.1 Computer Hardware


The hardware of a computer system consists of six parts: a central processing unit (CPU),
main memory, secondary storage, the input system, the output system, and the communica-
tion system. These components are connected together by what is called a bus. Figure 1.1
shows these six components and their connection.

Central Processing Unit (CPU)


The central processing unit (CPU) consists of the arithmetic-logical unit (ALU), the con-
trol unit, and a set of registers to hold data temporarily while being processed. The control
unit is the traffic cop of the system; it coordinates all the operations of the system. The ALU

1
2 Chapter 1  Introduction to Computers and Programming Languages

CPU

Bus

Main Secondary Input Output Communication


memory storage system system system

Figure 1.1 Basic hardware components

ALU Registers
Control unit

Central processing unit (CPU)

Figure 1.2 Central processing unit


(photo) ©leungchopan/Getty Images

executes instructions such as arithmetic calculations and comparisons among data. Figure 1.2
shows the general idea behind a central processing unit.

Primary Memory
Primary memory is where programs and data are stored temporarily during processing.
The contents of primary memory are lost when we turn off the computer. Figure 1.3 shows
primary memory in more detail. Each storage location in memory has an address, much like
a street address, that is used to reference the memory’s contents. The addresses in Figure
1.3(a) are shown on the left as numbers ranging from zero to (n – 1), where n is the size of
memory. In Figure 1.3(b) the address is shown symbolically as x.

0
1 Address Contents
Operating
system
x 256

(b) Address and contents


Program

256
15.34
Hello Data

n−1
(a) General layout
Figure 1.3 Primary memory
(photo) ©Simon Belcher/Alamy
1.1  Computer System 3

Figure 1.4 Some secondary storage devices


©Shutterstock/PaulPaladin; ©David Arky/Getty Images; ©McGraw-Hill Education

Figure 1.5 Some input systems


©JG Photography/Alamy; ©Keith Eng 2007

Generally, each address refers to a fixed amount of memory. In personal computers,


the amount of storage accessed is usually one, two, or four bytes. In large computers, it can
be many bytes. When more than one byte is accessed at a time, word rather than byte is usu-
ally used for the memory size.
In general, primary memory is used for three purposes: to store the operating system,
to store the program, and to store data. The type of data stored is dependent on the applica-
tion. In Figure 1.3, we demonstrate three different types of data: an integer (256), a real
number (15.34), and a string (Hello).

Secondary Storage
Programs and data are stored permanently in secondary storage. When we turn off the
computer, our programs and data remain in the secondary storage ready for the next time
we need them. Examples of secondary storage include hard disks, CDs and DVDs, and flash
drives (Figure 1.4).

Input System
The input system is usually a keyboard where programs and data are entered into the com-
puter. Examples of other input devices include a mouse, a pen or stylus, a touch screen, or
an audio input unit (Figure 1.5).

Output System
The output system is usually a monitor or a printer where the output is displayed or printed.
If the output is displayed on the monitor, we say we have a soft copy. If it is printed on the
printer, we say we have a hard copy (Figure 1.6).

Communication System
We can create a network of computers by connecting several computers. Communication
devices are installed on a computer system for this purpose. Figure 1.7 shows some of these
devices.
4 Chapter 1  Introduction to Computers and Programming Languages

Figure 1.6 Some output systems


©Roy Wylam/Alamy; ©Stephen VanHorn/Alamy

Figure 1.7 Some communication devices


©Ingram Publishing; ©somnuek saelim/123RF

1.1.2 Computer Software


Computer software is divided into two broad categories: system software and application
software. This is true regardless of the hardware system architecture. System software man-
ages the computer resources. Application software, on the other hand, is directly responsible
for helping users solve their problems.

System Software
System software consists of programs that manage the hardware resources of a computer
and perform required information processing. These programs are divided into three groups:
the operating system, system support, and system development.
Operating System The operating system provides services such as a user interface, file and
database access, and interfaces to communication systems. The primary purpose of this soft-
ware is to operate the system in an efficient manner while allowing users access to the
system.

System Support System support provides system utilities and other operating services. Ex-
amples of system utilities are sort programs and disk format programs. Operating services
consist of programs that provide performance statistics for the operational staff and security
monitors to protect the system and data.

System Development System development software includes the language translators that
convert programs into machine language for execution, debugging tools to assure that the
programs are error-free, and computer-assisted software engineering (CASE) systems that
are beyond the scope of this book.
1.2  Computer Languages 5

Application Software
Application software is broken into two categories: general-purpose software and
application-specific software.
General-Purpose Software General-purpose software is purchased from a software devel-
oper and can be used for more than one application. Examples of general-purpose software
include word processors, database management systems, and computer-aided design sys-
tems. These programs are called general purpose because they can solve a variety of user
computing problems.

Application-Specific Software Application-specific software can be used only for its in-
tended purpose. A general ledger system used by accountants and a material requirements
planning system used by engineers are examples of application-specific software. They can
be used only for the task they were designed for; they cannot be used for other generalized
tasks.

1.2 COMPUTER LANGUAGES


To write a program for a computer, we must use a computer language. Over the years,
computer languages have evolved from machine to symbolic to high-level languages and
beyond. A time line for computer languages is seen in Figure 1.8.

1.2.1 Machine Languages


In the earliest days of computers, the only programming languages available were machine
languages. While each computer still has its own machine language, which is made of
streams of 0s and 1s, we no longer program in machine language.

The only language understood by a computer is its machine language.

1.2.2 Symbolic Languages


It became obvious that not many programs would be written if programmers continued to
work in machine language. In the early 1950s, Grace Hopper, a mathematician and a mem-
ber of the United States Navy, developed the concept of a special computer program for
converting programs into machine language (see Figure 1.9).
Her work led to the use of programming languages, which simply mirrored the ma-
chine languages using symbols, or mnemonics, to represent the various machine language
instructions. Because they used symbols, these languages were known as symbolic lan-
guages. A special program called an assembler is used to translate symbolic code into ma-
chine language. Because symbolic languages have to be assembled into machine language,
they soon became known as assembly languages. This name is still used today for symbolic
languages that closely represent the machine language of their computer.

High-level languages
Symbolic languages
Machine languages
Time
1940 1950 1960 1970 1980 1990 2000 2010

Figure 1.8 Computer language evolution


6 Chapter 1  Introduction to Computers and Programming Languages

Figure 1.9 Grace Hopper


©Cynthia Johnson/Getty Images

Symbolic language uses mnemonic symbols to


represent machine language instructions.

1.2.3 High-Level Languages


Although symbolic languages greatly improved programming efficiency, they still required
programmers to concentrate on the hardware they were using. Working with symbolic lan-
guages was also very tedious because each machine instruction had to be individually coded.
The desire to improve programmer efficiency and to change the focus from the computer to
the problem being solved led to the development of high-level languages.
High-level languages are portable to many different computers, which allows the pro-
grammer to concentrate on the application problem at hand rather than the intricacies of the
computer. High-level languages are designed to relieve the programmer from the details of
the assembly language. However, high-level languages share one thing with symbolic lan-
guages: They must be converted to machine language. This process is called compilation.
The first widely used high-level language, FORTRAN (Formula Translation), was
created by John Backus and an IBM team in 1957. Following soon after FORTRAN was
COBOL (Common Business-Oriented Language). Admiral Grace Hopper was again a key
figure, this time in the development of the COBOL business language.
1.3  Language Paradigms 7

Over the years, several other languages—most notably BASIC, Pascal, Ada, C, C++,
and Java—were developed. Today, one of the popular high-level languages for system soft-
ware and new application code is C++, which we discuss in this book.

1.3 LANGUAGE PARADIGMS


Computer languages can be categorized according to the approach they use in solving a prob-
lem. A paradigm is a model or a framework for describing how a program handles data. Al-
though there are several taxonomies for dividing current languages into a set of paradigms, we
discuss only four: procedural, object-oriented, functional, and logic, as shown in Figure 1.10.
The figure also shows which language belongs to which paradigm according to our taxonomy.
Note that the C++ language can be used both as a procedural and an object-oriented
paradigm, as we will see in future chapters.

1.3.1 Procedural Paradigm


In a procedural (also called imperative) paradigm, a program is a set of commands. The
execution of each command changes the state of the memory related to that problem. For
example, assume we want to find the sum of any two values. We reserve three memory
locations and call them a, b, and sum. The combination of these three memory locations
comprises a state in this case. Figure 1.11 shows how a procedural paradigm uses four com-
mands to change the state of memory four times. Note that the memory locations in gray
show the original state, wherein the locations are reserved for the program.
To get the value of the first number, a, into memory, we use an input command (input
a). After execution of this command, the computer waits for us to enter a number on the
keyboard. We entered 6. When we press the enter key on the keyboard, the number 6 is
stored in the first memory location and the state of memory is changed. After the second
command, again the state of the memory is changed and now both 6 and 8 are stored in
memory. The third command changes the memory state by adding the values of a and b
and storing the result in sum. Although the last command (output sum) does not look like it
is changing the memory state, it is considered a change because the value of sum is output.
The way we have written the code in Figure 1.11 is very inefficient for two reasons.
First, it contains some commands that can be repeated in the same program or other pro-
grams. Second, if the set of data to be handled is large, we need to handle them one by one.
To remove these two inefficiencies, the procedural paradigm allows packaging commands
and data items.

Computer language
paradigms

Object-
Procedural Functional Logic
oriented

FORTRAN Smalltalk LISP Prolog


COBOL C++ Scheme
BASIC Visual Basic
Ada C#
Pascal Java
C
C++

Figure 1.10 Language paradigms


8 Chapter 1  Introduction to Computers and Programming Languages

a
b
sum
a 6 6
input a b
sum
input b
a 6
sum = a + b 8
b 8
output sum sum
a 6
Program b 8
sum 14
a 6
b 8 14
14
sum 14
States

Figure 1.11 An example of a procedural paradigm

a. If we are writing code for different programs, we can package the code and create
what is called a procedure (or function). A procedure can be written once and then
copied in different programs. The standard procedures can be stored in the language
library and be used instead of rewritten.
b. If we are handling a large set of data items (for example, hundred or thousands of
numbers), we need to store them in a package (called different names such as array
or record) and input them all together, process them all together, and output them
all at the same time. The operation at the background is still done one data item at a
time, but the program can see the data items as packages.
The following shows how a procedural paradigm uses three lines of code to sort a list of
numbers of any size. Of course, we must have already written the procedures and already
packaged data items into a list.

input (list);
sort (list);
output (list);

1.3.2 Object-Oriented Paradigm


In the procedural paradigm, the often-used procedures can be created and saved. We then
apply a subset of these procedures to the corresponding data packages to solve our particular
problem. One thing that is obvious in this paradigm is that there is no explicit relationship
between the set of procedures and the set of data packages. When we want to solve a prob-
lem, we need to choose our data package and then go and find the appropriate procedure(s)
to be applied to it.
The object-oriented paradigm goes further and defines that the set of procedures that
can be applied to a particular type of data package needs to be packaged with the data. The
whole is referred to as an object. In other words, an object is a package containing all pos-
sible operations that can be applied to a particular type of data structure.
This is the same concept we find in some physical objects in our daily life. For exam-
ple, let us think about a dish-washing machine as an object. The minimum operations we ex-
pect from a dishwasher are washing, rinsing, and drying. All of these operations are included
1.3  Language Paradigms 9

Objects

13 17 8 10 list1
sort ( )
reverse ( )
11 17 38 14 list2
search (...)

print (...)
Shared 12 10 91 20 listn
Procedures

Figure 1.12 An example of an object-oriented paradigm

in any typical dish-washing machine. However, each time we load the machine with a dif-
ferent set of dishes (same as a different set of data). We need to be careful, however, not to
load the machine with a load it is not designed for (not to wash clothes, for example, in the
dish-washing machine).
In the real world, all the hardware necessary for an operation is included in an object;
in the object-oriented programming world, each object holds only data, but the code that
defines the procedures is shared. Figure 1.12 shows the relationship between the procedures
and data in the object-oriented paradigm.

1.3.3 Functional Paradigm


In the functional paradigm, a program is a mathematical function. In this context, a func-
tion is a black box that maps a list of inputs to a list of outputs. For example, adding num-
bers can be considered as a function in which the input is a list of numbers to be added and
the output is a list with only one item, the sum. In other words, the functional paradigm is
concerned with the result of a mathematical function. In this paradigm, we are not using
commands and we are not following the memory state. The idea is that we have some primi-
tive functions, such as add, subtract, multiply, divide. We also have some primitive func-
tions that create a list or extract the first element or the rest of the elements from a list. We
can write a program or a new function by combining these primitive functions. Figure 1.13
shows how we add two numbers using the functional paradigm. The code is symbolic, but
each language in this paradigm has its own definition for a function. Note also that in our
code, we distinguish between a number and a list. We have a number as 8, but a list with one

list (6, 8)

first () rest ()

sum (first (6, 8), first (rest (6, 8))) (8)


6 first ()
Code 8
sum ()
14

Visualization

Figure 1.13 An example of a functional paradigm


10 Chapter 1  Introduction to Computers and Programming Languages

Parent (Fay, Tara)


Parent (Tara, Willie) 1. Parent (Willie, Tara)? No
Parent (Tara, Benji) 2. Parent (Fay, Benji)? No
Facts 3. Parent (Tara, Benji)? Yes
4. Grandparent (Tara,Willi)? No
Grandparent (X, Y) 5. Grandparent (Fay, Benji)? Yes
Parent (X, Z) AND Parent (Z, Y) 6. Grandparent (Fay, Willi)? Yes
Queries
Rule

Figure 1.14 An example of a logic paradigm

element is (8). The function first gets a number, but the function rest gets a list. To get
the second number in the list, we first use the function rest to get the list (8) and then use
the function first to get 8.

1.3.4 Logic Paradigm


The logic paradigm uses a set of facts and a set of rules to answer queries. It is based on
formal logic as defined by Greek mathematicians. We first give the program the facts and
rules before asking queries. Figure 1.14 shows a simplified and symbolic version of a logic
paradigm. A fact such as Parent (Fay, Tara) is read as “Fay is the parent of Tara.”

1.3.5 Paradigms in C++ Language


Our discussion of four paradigms might lead you to wonder where the C++ language stands.
C++ is an extension to the C language and is based on the procedural paradigm. However,
the existence of classes and objects allows the language to be used as an object-oriented lan-
guage. In this book we use C++ mostly as a procedural paradigm in early chapters (except
for input/output that are done using objects). However, we use the language as an object-
oriented paradigm after the introductory chapters.

1.4 PROGRAM DESIGN


Program design is a two-step process that requires understanding the problem and then de-
veloping a solution. When we are given the assignment to develop a program, we are given
a program requirements statement and the design of any program interfaces. In other words,
we are told what the program needs to do. Our job is to determine how to take the inputs we
are given and convert them to the outputs that have been specified. To understand how this
process works, let’s look at a simple problem.

Find the largest number in a list of numbers.

How do we go about doing this?

1.4.1 Understand the Problem


The first step in program design is to understand the problem. We begin by reading the
requirements statement carefully. When we fully understand it, we review our understand-
ing with the user. Often this involves asking questions to confirm our understanding. For
example, after reading our simple requirements statement, we should ask several clarifying
questions.
1.4  Program Design 11

What type of numbers are we dealing with (with fractions or without fractions)?
Are the numbers arranged in any special sequence, such as lowest to highest?
How many numbers can we expect?

If we don’t clarify the problem—that is, if we make assumptions about the input or
the output—we may supply the wrong answer. To answer our questions, we need to process
integers arranged in any sequence. There is no limit as to the number of integers.
As this example shows, even the simplest problem statements may require clarifica-
tion. Imagine how many questions must be asked for a program that contains hundreds or
thousands of detailed statements.

1.4.2 Develop the Solution


Once we fully understand the problem and have clarified any questions we may have, we
develop a solution in the form of an algorithm. An algorithm is a set of logical steps neces-
sary to solve a problem. Algorithms have two important characteristics: first, they are inde-
pendent of the computer system. This means that they can be used to implement a manual
system in an office as well as a program in a computer. Second, an algorithm accepts data as
input and processes the data into an output.
To write the algorithm for our problem, we use an intuitive approach, calling not only
on the problem statement but also our knowledge and experience. We start with a small set
of five numbers: Once we have developed a solution for five numbers, we extend it to any
number of integers.

13  7  19  29  23

We begin with a simple assumption: The algorithm processes the numbers one at a
time. We name the algorithm FindLargest. Every algorithm has a name to identify it.
FindLargest looks at each number in turn without knowing the values of the others. As it
processes each number, it compares it to the largest number known to that point and deter-
mines if the new number is larger. It then looks at the next number to see if it is larger, and
then the next number and the next number until all of the numbers have been processed.
Figure 1.15 shows the steps in determining the largest among five integers.
The algorithm requires that we keep track of two values, the current number and the
largest number found. We determine the largest number using the following steps.
∙∙ Step 1: We input the first number, 13. Since largest has no value, we set it to the
value of the first number.
∙∙ Step 2: We input the second number, 7. Since 7 is less than 13, the value of largest
does not need to be changed.
∙∙ Step 3: We input the third number 19. When we compare 19 to the value of largest, 13,
we see that 19 is larger. We therefore set largest to 19.
∙∙ Step 4: We input the fourth number, 29. When we compare 29 to the value of largest,
19, we see that 29 is larger. We set largest to 29.
∙∙ Step 5: We input the fifth number, 23. Because it is smaller than 29, largest does not
need to be changed. Because there is no more input, we are done and we have deter-
mined that the largest value is 29.
∙∙ Step 6: We output the value of largest, which is 29.
12 Chapter 1  Introduction to Computers and Programming Languages

Input data
13 07 19 29 23

Step 1 13 first number 13 largest

Step 2 07 second number 13 largest

Step 3 19 third number 19 largest

Step 4 29 fourth number 29 largest

Step 5 23 fifth number 29 largest

29
Output data

Figure 1.15 Find the largest among five integers

Algorithm Generalization
The algorithm shown in Figure 1.15 does not quite solve our original problem definition
because it only handles five numbers. To make it work for all number series, we need to re-
place steps 2 through 5 to process an undetermined number of values. This requires that we
generalize the statements so that they are the same. We can do this with a minor rephrasing
of the statements as shown below.

If the current number is greater than largest, set largest to the current number.

We then include the rephrased statement in a repeat statement that executes the steps
until all numbers are processed. The resulting algorithm is shown in Figure 1.16.
It is important to realize that the design is done before we write the program. In this
respect, it is like the architect’s blueprint. No one would start to build a house without
a detailed set of plans, yet one of the most common errors of both experienced and new

The find largest algorithm

Input first number

Set largest to first number

While there are more numbers, repeat


Input next number

If next number greater than largest.


set largest to current number

Output largest

Figure 1.16 Algorithm to find largest among n numbers


1.5  Program Development 13

programmers alike is to start coding a program before the design is complete and fully
documented.
This rush to start is partially because programmers think they fully understand the
problem and partially because they are excited about getting on with a new problem to solve.
In the first case, they find that they did not fully understand the problem. By taking the time
to design the program, they raise more questions that must be answered and therefore gain a
better understanding of the problem.
The second reason programmers code before completing the design is just human na-
ture. Programming is a tremendously exciting task. To see your design begin to take shape,
to see your program creation working for the first time, brings a form of personal satisfaction
that is a natural high.

Unified Modeling Language (UML)


The Unified Modeling Language (UML) is a standard tool for designing, specifying, and
documenting many aspects of a computing system. For example, it can be used to design
large complex systems, programs, and objects within a program. It can also be used to show
the relationship between objects in an object-oriented language such as C++. We discuss
UML in future chapters when we learn to design programs.

1.5 PROGRAM DEVELOPMENT


Figure 1.17 shows the general procedure for turning a program written in any language into
machine language. The procedure for a C++ program is a little bit more involved. The pro-
cess is presented in a straightforward, linear fashion, but we need to recognize that these steps are
repeated many times during the development process to correct errors and make improvements
to the code.

Characters Disk
Source code
Editor
Programmer
Commands Disk
Compiled code
Compiler
Programmer Library code
Compiled code

Executable code
Linker

Commands Executable code


Disk
Loader
User
Executable code
Output data
Input data

User
Memory

Figure 1.17 Writing, editing, and executing a program


14 Chapter 1  Introduction to Computers and Programming Languages

It is the job of the programmer to write the program and then to turn it into an execut-
able file. There are four steps in this process:
a. Write and edit the program.
b. Compile the program.
c. Link the program with the required library modules (normally done automatically).
d. Execute the program. From our point of view, executing the program is one step.
From the computer point of view, however, it is two substeps: load the program and
run the program.

1.5.1 Write and Edit Programs


The software used to write programs is known as a text editor. A text editor helps us
enter, change, and store character data. Depending on the editor on our system, we could
use it for writing letters, creating reports, or writing programs. The big difference be-
tween the other forms of text processing and writing programs is that programs are ori-
ented around lines of code, while most text processing is oriented around characters and
paragraphs.
The text editor could be a generalized word processor, but it is more often a special
editor provided by the company that supplies the compiler. Some of the features we look for
in an editor are search commands that are used to locate and replace statements, copy-and-
paste commands that can be used to copy or move statements from one part of a program
to another, formatting commands that use colors to display key parts of the program, and
automatic formatting that aligns and indents parts of the program.
After we complete a program, we save our file to disk. This file then becomes the input
to the compiler; it is known as a source file.

1.5.2 Compile Programs


The information in a source file stored on disk must be translated into machine language so
the computer can understand it. This is the job of the compiler.

1.5.3 Link Programs


As we will see later in the text, a program is made up of many functions. Some of these
functions are written by us and are part of our source program. However, there are other
functions, such as input/output processes and mathematical library functions, that exist else-
where and must be attached to our program. The linker assembles the system functions and
ours into the executable file.

1.5.4 Execute Program


Once the program has been linked, it is ready for execution. To execute a program we use
an operating system command, such as run, to load the program into main memory and
execute it. Getting the program into memory is the function of an operating system program
known as the loader. It locates the executable program and reads it into memory. When
everything is ready, control is given to the program and it begins execution.
In a typical program execution, the program reads data for processing, either from the
user or from a file. After the program processes the data, it prepares the output. Data output
can be written to the user’s monitor or to a file. When the program is finished, it tells the
operating system, which removes the program from memory.
1.6  
Testing 15

1.6 TESTING
After we write the program, we must test it. Program testing can be a very tedious and
time-consuming part of program development. As the programmer, we are responsible for
completely testing it. We must make sure that every instruction and every possible situation
have been tested.

1.6.1 Designing Test Data


Test data should be developed throughout the design and development of a program. As we
design the program, we create test cases to verify the design. These test cases then become
part of the test data after we write the program.
In addition, as we design the program, we ask ourself what situations, especially
unusual situations, we need to test, and then we make a note of them. For example, in
FindLargest, what if only one number is input? Similarly, what if the data were in se-
quence or all the same? When we design the program, we review it with an eye toward
test cases and make additional notes of the cases needed. Finally, while we code the pro-
gram, we make more notes of test cases.
When it comes time to construct the test cases, we review our notes and organize
them into logical sets. Except for very simple student programs, one set of test data never
completely validates a program. For large-scale development projects, 20, 30, or even more
test cases may need to be run to validate a program. All of these test cases become what is
known as a test plan.

One set of test data never completely validates a program.

Finally, as we test the program, we discover more test cases. Again, we write them down
and incorporate them into the test plan. When the program is finished and in production, we
still need the test plan for modifications to the program. Testing of modifications is known as
regression testing and should start with the test plan developed when we wrote the program.
How do we know when our program is completely tested? In reality, there is no way
to know for sure, but there are a few things we can do to help the odds. While some of
these concepts will not be clear until we get to later chapters, we include them here for
completeness.
a. Verify that every line of code has been executed at least once. Fortunately, there are
programming tools on the market today that help us do this.
b. Verify that every conditional statement in the program has executed both the true and
false branches, even if one of them is null.
c. For every condition that has a range, make sure the tests include the first and last
items in the range, as well as items before the first and after the last. The most
common mistakes in range tests occur at the extremes of the range.
d. If error conditions are being checked, make sure all error logic is tested. This may
require a temporary modification to the program to force the errors; for instance, an
input/output error usually cannot be created—it must be simulated.

1.6.2 Program Errors


There are three general classifications of errors: specification errors, code errors, and logic
errors.
16 Chapter 1  Introduction to Computers and Programming Languages

Specification Errors
Specification errors occur when the problem definition is either incorrectly stated or misin-
terpreted. Specification errors should be caught when we review our design with analysts
and users.

Code Errors
Code errors usually generate a compiler error message. These errors are the easiest to
correct. Some code errors generate what is known as a warning message, which usually
means that the compiler has made an assumption about the code and needs to have it
verified. It may be right, or it may be wrong. Even though the program may run with a
warning message, the code should be changed so that all warning messages are elimi-
nated.

Logic Errors
The most difficult errors to find and correct are logic errors. Examples of logic errors are
division by zero or forgetting to store the first number in largest in FindLargest. They
can be corrected only by thorough testing. And remember, before we run a test case, we
should know what the correct answer is. Don’t assume that the computer’s answer is correct;
if there’s a logic error, the answer will be wrong.

K e y T e r m s

algorithm loader
application software logic errors
application-specific software logic paradigm
arithmetic-logical unit (ALU) machine language
assembler object-oriented paradigm
assembly language operating system
central processing unit (CPU) output system
code errors primary memory
compiler procedural paradigm
computer hardware procedure
computer language program design
computer software program errors
computer system program testing
data item regression testing
executable file secondary storage
executable program software
function source file
functional paradigm specification errors
general-purpose software symbolic language
hardware system development software
high-level language system software
imperative paradigm system support software
linker text editor
input system Unified Modeling Language (UML)
Problems 17

S u m m a r y

Computer systems are made up of two major components: hardware (CPU, memory, second-
ary storage, output system, and communication system) and software (system software and
application software).
Computer languages are used to develop software. The computers themselves run in ma-
chine language. Over the years programming languages have progressed through symbolic
languages to the many high-level languages used today.
Language paradigms (procedural, object-oriented, functional, logic) describe the ap-
proach used to solve problems on the computer. C++ is based on the procedural and object-
oriented paradigms.
Program design is a two-step process that requires understanding the problem and then
developing a solution.
Algorithms have two important characteristics; they are independent of the computer
system and they accept data as input and process data into an output.
Program development turns the program design into a computer system in four steps:
write the program, compile it, link it, and execute it.
Testing a program requires that every instruction and every possible situation is vali-
dated.

P r o b l e m s

PR-1. Show the state of the memory for the following example of a procedural paradigm
(see Figure 1.11).
input a
input b
input c
sum = a + b + c
output sum

PR-2. Show the state of the memory for the following example of a procedural
paradigm (see Figure 1.11). Assume that values of length and width are 12 and 8,
respectively, and represent the sides of a rectangle.
input length
input width
area = length × width
parameter = 2 × (length + width)

PR-3. Imagine we need to create a bank account object using an object-oriented


paradigm. Show the data and list of procedures you think need to be encapsulated
with the data (see Figure 1.12).
PR-4. In a functional paradigm, show the result of the following function (see Figure 1.13).
first (rest (rest (a, b, c)))

PR-5. In a functional paradigm, show the result of the following function, assuming that
the list (...) makes a list of given elements (see Figure 1.13).
list (first (rest (a, b)), first (a, b))
18 Chapter 1  Introduction to Computers and Programming Languages

PR-6. Based on Figure 1.14, what is the result of the following queries?
Parent (Benji, Tara)?
GrandParent (Fay, Willi)?

PR-7. Based on Figure 1.14, what is the result of the following queries?
Parent (Fay, Tara)?
GrandParent (Tara, Willi)?

PR-8. Show the value of sum after the following algorithm is executed.
sum = 0
sum = sum + 10
sum = sum × 10
sum = sum − 10

PR-9. Show the value of x after the following algorithm is executed.


x=5
x=x+1
x = x − 10

PR-10. Show the value of x, y, and z after the following algorithm is executed.
x=2
y=5
x=x+1
y = y − 10
z=8
z=x+y
x=y+z
y=x+y+z

PR-11. Design an algorithm that converts a value in centimeters to a value in inches using
the following formula:
1 inch = 2.54 centimeters

PR-12. Design an algorithm that converts a value in inches to a value in centimeters using
the following formula:
1 centimeter = 0.3937 inch

PR-13. Design an algorithm that converts a temperature value in Fahrenheit (F) to a value
in Celsius (C) using the following formula:
C = (F − 32) × (100/180)

PR-14. Design an algorithm to find the sales tax and the total sale value of a transaction
made of two soft drinks (1 dollar each), three bottles of milk (2 dollars each), and
one can of coffee (3 dollars). The tax is 9 percent.
PR-15. Design an algorithm that finds the smallest among a list of numbers.
PR-16. Design an algorithm that finds the sum of a list of numbers.
PR-17. Design an algorithm that finds the product of a list of numbers.
PR-18. Design an algorithm that adds numbers from 1 to 100.
2 Basics of C++ Programming

This chapter sets the foundation of computer programming in C++. Each C++ pro-
gram involves input, output, and assignment. First, we discuss how these activities can
be achieved using two objects and an operator. Next, we introduce the fundamental data
types in C++. Fundamental data types are primitive built-in data types that can be used
without being declared. We then discuss variables, values, and constants and how they can
be used in a program. Finally, we discuss two components of a program, namely, tokens
and comments.

Objectives
After you have read and studied this chapter, you should be able to:

• Discuss variables, values, and constants and how they are used in C++ programs.
• Discuss the general components of a C++ program that is made of tokens and comments.
• Discuss the fundamental data types in C++ and their size.
• Show how we can use integer data types in programs.
• Show how we can use character data types in programs.
• Show how we can use Boolean data types in programs.
• Show how we can use floating-point data types in programs.
• Discuss the void data type and discuss its use.
• Introduce C++ strings and briefly discuss their use.
• Introduce and discuss some simple programs in C++.

2.1 C++ PROGRAMS


Every C++ program is made of several sections, and each section is made of several parts.
Each section or part must follow the rules defined in the C++ language, just as documents
written in one of the natural languages follow the rules of that language.
Before we formally delve into the structure of a C++ program and explore some of the
pertinent rules, we study some sample programs.

2.1.1 First Program


Program 2.1 shows a simple example of a C++ program and will help us gain a basic under-
standing of C++ programs.

19
20 Chapter 2  Basics of C++ Programming

Program 2.1 The first simple program

1 #include <iostream>
2
3 int main ()
4 {
5 std :: cout << "This is a simple program in C++ ";
6 std :: cout << "to show the main structure." << std :: endl;
7 std :: cout << "We learn more about the language ";
8 std :: cout << "in this chapter and the rest of the book.";
9 return 0;
10 }
Run:
This is a simple program in C++ to show the main structure.
We learn more about the language in this chapter and in the rest of the book.

Box and Background Coloring


We have shown the program in a table made of two columns and several rows with some
boxes and some colored or shaded backgrounds. These decorations are just for demonstra-
tion in this book. They are not part of the C++ language. Other books may use other decora-
tions to make the components of a program more visible.

Box and background coloring are not part of a C++ program;


they are used in this book to show different sections of a program.

Separation of Code and Result


We have divided the program into two sections vertically. The top section, in two columns,
shows the code that we have written. The bottom section shows the result of the program
when it runs. Note that the first line of the second section (Run:) is not part of the program or
its results after running. It is added by us to show that this section is the result of running the
program. If we run the program more than once, you will see multiple sections each starting
with (Run:). The results of the program are normally shown on the screen of the computer
on which we compile and run the program, but we show them at the bottom of each program
inside a shaded area for quick reference.

We separate the code from the results of the program for demonstration;
the results of the program are normally shown on the screen.

Case Sensitivity
Every C++ program is case-sensitive. We must use the terms exactly as defined in the
language. If we change the case of a letter in a term that is part of the language, we get a
compilation error. In other words, we cannot use the word Include or IOSTREAM instead
of include or iostream in line 1 of the program. We cannot use the word Main instead of
main in line 3. This is also true with terms like std, cout, endl, and return.

C++ language is case-sensitive. The term that names an entity


must be used as it is defined without changing the case of its letters.
2.1  C++ Programs 21

Program Lines
Although it is not necessary to do so, we divide our programs into lines to show the different
sections and to increase readability. When we discuss the program, we use line numbers for
ease of reference. Line numbers are not part of the program and should not be included in
the program when we create the source code. Note that we also add blank lines to separate
different sections of the program (for example, line 2 in Program 2.1).

Line numbers are not part of the program and should not be included in
the source code. They are used in this book for reference to each line.

Indention
In Program 2.1, we have indented lines in the function body. Although it is not necessary
to do so we believe it improves the readability of the program. We always indent lines that
belong to an enclosing entity. Lines 5 to 9 belong to the function body, and we have indented
them to show that they are inside the two braces.

Line indention improves the readability of a program


and we strongly recommend it.

Program Analysis
We briefly analyze the program line by line (except for line 2, which is blank to increase
readability to indicate the separation of the two sections).
Line 1: Preprocessor Directive A preprocessor directive is a command to the compiler to take
some action before it compiles the program. Line 1 of the program (without the line number)
is a preprocessor directive as shown below:

#include <iostream>

A C++ program needs some predefined lines of code that are not written by us.
These lines of code are very complex and sometimes access the hardware of the computer,
which means they depend on the type of computer we are using. The C++ designers cre-
ated these lines of code and included them in files referred to as header files. We do not
have to write these lines; we can simply copy the contents of these files into our code.
To copy them, we need to know the name of the file, iostream, which stands for input/
output stream in this case. To tell the complier that we need to include the contents of
this file, we need to have an include line as shown above. The include line starts with
the # symbol. When a line in a program starts with this symbol, it is an indication to the
compiler that something needs to be done before the program can be compiled. Before
the compiler starts compiling our code, it runs another program, called preprocessor, that
checks all preprocessor commands (the include directive is one of them). The compiler
does what is needed in the command (such as including the contents of the header file) and
then removes the preprocessor directive. After all preprocessor directives have been taken
care of and are removed, the program is ready for compilation. Note that each preprocess-
ing command needs to be in a single line by itself with the first nonblank, character, the
symbol # (pound sign). In the include directive, the name of the file must be enclosed in
two pointed brackets such as <filename> after the term include. We discuss preprocess-
ing in more details in Appendix F.
22 Chapter 2  Basics of C++ Programming

Note that no semicolon should be put after any include directive.


The compiler may generate an error if it finds one.

Line 3: Function Header Line 3 of the program (without the line number) is shown below:

int main ()

A C++ program is normally made of a number of functions. A function, as we will


see in future chapters, is a section that groups a number of lines of code. A C++ program
consists of one or more functions, but it must contain one function named main. The execu-
tion of a C++ program starts with the main function and terminates when the main function
is terminated.

Execution of each C++ program starts with the main function, which
means that each program must have one function named main.

Each function has a header and a body. The header defines the name of the function
and what goes into the function (inside the parentheses) and what type of information comes
out of the function, mentioned before the name int in this case. Line 3 is the header of the
main function. It shows that the name of the function is main; nothing will be passed to the
function (parentheses are empty); an integer value will be returned from the function (int is
C++ for an integer) and given to the operating system.
Lines 4 and 10: Opening and Closing Braces Lines 4 and 10 are a combination of an opening
and a closing brace (curly brackets) that need to go together to enclose the whole body of
the function. It is a compilation error to have one without the other. The following shows
these lines.

{

}

Every function definition in C++ needs a body enclosed between an opening and a closing
brace.

It is a major error to have an opening brace without a closing


one or a closing brace without an opening one.

Line 5: The First Line of Body Let us now discuss the contents of the body, line by line, start-
ing with line 5 that is shown below:

std :: cout << "This is a simple program in C++ ";

Most of the lines in the body of a function are commands that tell the computer what
to do. As we see in a natural language, a command (an imperative sentence) is made of a
verb, a direct object, an indirect object (target or recipient), and a terminator (normally a
period). This is what we see in a command line in a function although in a different order. In
2.1  C++ Programs 23

Target Verb Object Terminator


std :: cout << "This is a simple program in C++" ;

Monitor write on the message end

Figure 2.1 Analysis of line 5

this case. the target object (cout, which is the monitor) comes first, the verb (write) comes
next, and what to write (direct object, a string) comes last. The command is terminated with
a semicolon (instead of a period). With this explanation, line 5 of Program 2.1 says that
the computer should write the object string (This is a simple program in C++) on the
monitor and move to the next command. Note that the two quotation marks are part of the
language syntax; they are not written on the screen. Figure 2.1 shows a graphical analysis
of line 5.
We will see that each object in C++ (as an object-oriented language) has a name. The
monitor connected to our computer also has a name in C++. It is called std :: cout. Note that
the name in this case is made of two parts, std and cout, separated by a colon. Just like
people in real life are recognized by two identifiers, last name and first name, an object in
C++ also has a last name and a first name. The monitor’s last name is std (abbreviation
for standard); its first name is cout (abbreviation for console out). The last name defines
the group (family) to which the object belongs; the first name defines the actual name of
the object in the group. In summary, line 5 tells the computer to write the given message
on the screen.

Line 6: The Second Line of Body Line 6 of the program is as shown below:

std :: cout << "to show the main structure. " << std :: endl;

This line is very similar to line 5 with some exceptions. First, the message is different,
“to show the main structure.” Second, after the message is written, the verb (<<) is repeated.
Third, no new message is defined, but the program writes a predefined object called std ::
endl. This is a different object, an object that when sent to the monitor adds a new line at the
end of the previous message, which causes the output to move to the next line. This object,
endl, is an abbreviation of (end line). The next output will be printed on the next line. Figure
2.2 shows that the destination is the same (mentioned only once) but the verb and the object
are repeated. In the first section, the object is a string object; in the second it is endl (note that
the last character is a lowercase L, not a one).
Lines 7 and 8 Lines 7 and 8 are similar to lines 5 and 6, but there is no endl object because
line 8 is the last line of text and there is no need for the endl object.

Destination Verb Object Verb Object Terminator


std :: cout << "to show the main structure." << std :: endl ;

monitor write message write line feed end

Figure 2.2 Analysis of line 6


24 Chapter 2  Basics of C++ Programming

call
int main ( )
{

C++ Runner nonzero: failure

zero: success
retrun 0;
}
Program

Figure 2.3 Relationship between the runner and our program

Line 9 The last line in the body of the function is different from other lines:

return 0;

This line is still a command, but there is no explicit target object. The target object is
implicit here. It is an entity in the C++ system that is called the runner. Figure 2.3 shows
the situation.
The runner starts the main function running from the first command in the body; the
runner expects the function to return a value that shows if the program has been successful
or not. The returned value defines the success or failure. If the program reaches the last line
in the function and returns 0, it means success. Figure 2.3 shows a simple version of the
program as started and stopped by the runner.

Program Output
The result of the execution of the commands whose target object is cout is shown on the
monitor connected to the computer on which we are running the program. In this case, we
have two lines of text to be shown on the monitor. Figure 2.4 shows the monitor (console)
window where our program output is displayed (the details are platform dependent).

2.1.2 Second Program


In this section we write another program in C++ similar to the first one, but with some
modification and addition. Although many puritans believe that every object in the pro-
gram should be coded with both a last name and a first name, such as std :: cout or std
:: endl, most programmers believe that we do not need to mention the last name of each
object individually. They believe we should give the group (last) name at the top of the pro-
gram and then use only the first name. We discuss this issue in more detail in Appendix G,
namespaces. Program 2.2 shows our second program.

C:\.
This simple C++ program shows the main structure.
We will learn more about the C++ language in this chapter and in the rest of the book.

Figure 2.4 The console (cout object) where the output is shown.
2.1  C++ Programs 25

Program 2.2 The second simple program

1 /***************************************************************
2 * This program shows how we can print a square of asterisks. *
3 ***************************************************************/
4 #include <iostream>
5 using namespace std;
6 int main ()
7
8 {
9 // Printing a square of asterisks
10 cout << "******" << endl;
11 cout << "******" << endl;
12 cout << "******" << endl;
13 cout << "******" << endl;
14 cout << "******" << endl;
15 cout << "******";
16 return 0;
17 }
Run:
******
******
******
******
******
******

Analysis
We briefly analyze the lines in Program 2.2 that are different from the corresponding lines
in the first program.
Lines 1 to 3: Block Comment Lines 1 to 3 in the second program are different from the first
program. They are what we call a block comment. A block comment is one or more lines
that are considered comments for the user or reviewer of the code and are totally ignored
by the compiler (block comments are erased before the program is compiled). The format
is shown below:

/* Text to be ignored
Text to be ignored
Text to be ignored */

The comment has a starting section and ending section. The starting section is made
of two characters (/*), and the ending section is made of the same two characters but in
the reverse order (*/). Everything in between is considered a comment and is ignored.
Note that we can have any character between the starting section and the ending sec-
tion (including * and /) but not in combination to create a starting section or an ending
26 Chapter 2  Basics of C++ Programming

section. Inside the program we use colored text for the whole comment. Note that in lines
1 to 3, we have used some asterisks as text to create a frame for our comment, but this is
a personal choice.

Line 5 This line is also new in this program, as shown below:

using namespace std;

Line 5 tells the compiler that when it cannot see the last name of an object, insert std:: in
front of it to make the name complete. In other words, it tells the compiler that some names
that we use in the program belong to the namespace std. With this single line, we can use
the cout and endl objects without qualifying them with the std namespace.

Line 9 This line is also a comment, but a line comment (instead of a block comment). This
type of comment starts with two slashes and continues with text as a comment (up to the end
of the line). The whole line is ignored by the compiler.

// Printing a square of asterisks

This type of comment can span only a single line. If we need two lines of comments, we
must start another line comment or use a block comment.
Lines 10 to 15 These lines do the same thing as similar ones in the first program, but we can
use cout and endl without (std ::). Each line prints a line of six asterisks on the monitor to
create a square of asterisks. In Program 2.2 we have used a yellow background to highlight
the body of the function here. This is not needed; it is only used for readability.

2.2 VARIABLE, VALUE, AND CONSTANT


Before we can write more programs, we need to understand three concepts: variables, val-
ues, and constants.

2.2.1 Variables
Programs written in the C++ language receive input data, manipulate them, and create out-
put data. Since the input and output data may change, we must be able to store the input
data, store the intermediate data, and store the output data in memory. For this reason, C++,
like most programming languages, uses the concept of variables. A variable in computer
language parlance is a memory chunk that needs to have a name and a type. It is called a
variable because its contents may change during the execution of the program. It’s purpose
is to store and retrieve data. It must have a type because we use different data types for
different purposes.

A variable is a memory location, with a name and a type, that stores


different values in each moment of a program’s execution.

Before we use a variable, we must define it. We must tell the compiler that we want to
use a memory location with the given name and the given type. The name is used to refer to
the variable; the type is used to tell what type of data is stored in the variable.
Other documents randomly have
different content
it made a mighty bound within his bosom. ‘Tell me,’ he cried, ‘by
your soul—say, for my mind misgives me—tell me, art thou not the
wife of Rhyman Khan?’
She could not reply—she burned—her mouth became parched and
her eyes swam.
‘Speak,’ he cried, ‘for the sake of Alla!’ But no reply came;
confusion was evident on her countenance; as he held her from him,
suddenly her head drooped, and her form relaxed within his grasp;
had he not supported her she would have fallen; for the sense of
sudden detection had overpowered her already too excited feelings,
and she had fainted.
‘Holy Prophet! what is to be done?—she is insensible,’ exclaimed
Kasim aloud; he was heard by Sozun, who entered.
‘Tell me, by your soul, if she is the Khan’s wife?’ he cried in
agitation not to be repressed.
‘What matter if she is, Patél? she loves you, your destiny is bright;
shall I retire?’
‘It is as I thought then. Holy Alla! I bless thee that this was spared
me! See, she is recovering; yonder is water—take her hence
speedily, her secret will die with me; assure her of this, and tell her
the Khan is my friend and benefactor.’ And so saying, he opened a
small door and disappeared.
‘He is gone,’ said Sozun, as her lady recovered and looked wildly
around her: it was enough. They did not wait more than a few
minutes; then Kummoo returned to her distasteful home, filled with
rage and shame, and burning for revenge.
CHAPTER XXXVIII.

Months had passed, and Herbert Compton remained in the lonely


fastness to which he had been doomed. He had no hope of release—
none of escape. As he looked forth over the vast plain beneath his
feet, he could see the interminable forests spread out before him,
through which he well knew there was no path, or, if any, one known
to the inhabitants only of the hills—intricate, and utterly unattainable
by himself. The Fort itself occupied a round knoll on the very verge
of the range, and jutted out, a bold promontory, into the plain,
forming evidently one of the extreme angles of the chain of
mountains upon which he was; its sides were dizzy precipices of five
thousand feet almost perpendicular to the bottom, where they
rested amidst forests, the waving even of which could not be seen
from the top. Looking eastward was the plain of Coimbatoor,
stretching away to a dim horizon, where, at the distance of a
hundred miles, were seen the rocky ranges of the Barah Mahal hills,
broken at first, but gradually appearing to unite and form a
continuous chain away to the left, till, increasing in height in the
immense circle, they joined the huge mass on part of which stood
his prison.
Through this the Bhowanee, the Baraudee, and several other
streams which escaped from the mountains, wound their silent
course, glistening in the bright sun like silver threads, away to the
broader Cavery, a faint glimmer of which might now and then be
seen, as the early rays of the morning sun shone upon the plain.
Away to the south and west the mountains recommenced with the
triangular peak of Dindigul, which could sometimes be seen, and
continued, range over range, of every form, of every hue with which
a brilliant sun, acting upon a dry, a damp, or a hot atmosphere,
could clothe them—hues of sombre grey, of violet, of brilliant purple,
till in the nearer range of the Animallee hills they assumed more
positive colours and forms.
To the west lay the broad valley, filled with wood, the only road to
the sea; and thence Herbert’s sad thoughts often wandered in vivid
remembrance of the past, to the land where those most dear to him
on earth mourned him as dead. He could not think that they could
retain any hope that he lived; years had fled since they had heard of
him, and he was become to them as one in the grave; one for whom
—when any trivial incident, a word, a look, a tone, recalls the dead
to present association—regrets, mingled with hopes for the future,
are the spontaneous expressions of undying affections, and a tear is
silently dropped, the overflow of some heart which clings to the
memory of the dead with fondness which even time does not impair.
To the north and west Herbert looked across the tremendous
chasm through which the military road now winds its gradual and
easy ascent up to Coonoor, upon the verdant and sunny hills
beyond. It was clothed with wood here and there, as though planted
with the most consummate taste, occupying now the side, now the
gorge of a tiny valley, through which a small stream leaped from
rock to rock, till, joining some larger one, it dashed down the
precipitous sides of the chasm, into the foaming stream of the
Baraudee, the roar of which sometimes reached his ear. At times he
could distinguish noble herds of elk browsing upon the smooth,
verdant sides of the declivities, and would watch their motions for
hours with curious interest; or huge herds of buffalos, tended by a
few herdsmen, who appeared to be the only inhabitants of those
lovely regions, where the cool climate of his beloved country was
joined to the brightness and radiance of an eastern sun.
But though he lived amidst the most exquisite scenery that it is
possible to conceive, it was but a poor compensation for liberty;
true, under the rigour of a burning climate, captivity would have
been more difficult and painful of endurance than here, where he
might almost fancy himself in his own land; and could he have
enjoyed the happiness of wandering about as he listed over those
beauteous hills, through the valleys and beside their bounding
streams, it would have sufficed to him to have thus dreamed away
his existence. Poor Herbert! his guards might have set him free; for
escape from those mountains, through untrodden and pestilential
jungles, into a country where death would await him if he were
discovered, was guarantee enough that he would have remained;
but they were answerable for him with their lives, and every
kindness consistent with his safety was shown him; and though their
food was coarse barley bread, rice, and the flesh of elk or wild hog,
or jungle game,—yet his health and strength seemed to increase,
and he had never felt greater vigour.
There were often changes in the little garrison: new comers
brought such spices and condiments as were needed, and among
them at last arrived one who spoke a few words of Hindostanee.
That he should be able to speak intelligibly with any one was a
subject of inexpressible delight to Herbert; but soon a new hope
sprung up in his heart, which though slowly admitted, yet was, or
might be, practicable—escape. Without a guide it was a useless risk
of life to attempt it; with one who knew the country and the roads,
either to the coast or to Madras, it was a matter, he thought, of
difficult but not impossible attainment. Long he watched his
opportunity to converse with his friend, for the man, he thought,
was civil and obliging beyond his fellows; but he was evidently afraid
to speak before them, lest he should at once be suspected and
dismissed; but the time came at length.
Herbert, as was his wont, lay upon the green sward on the highest
point of the Fort, basking in the warm sun, watching the shadows
which chased each other over the beauteous and many-hued plain—
now sailing over what appeared endless forests—now dimming the
sparkle of the Bhowanee for a moment, which again glittered
brightly as the shade passed away: again they appeared to creep up
the face of some precipitous hill, or hang among its woods, while the
sunlight toyed with the green slopes and mossy banks. Sometimes
he speculated idly upon the scene below, and tried to make out the
forms of villages among the groves which everywhere appeared
amidst the cultivated parts. All was quite still, and not even a leaf
rustled to disturb the silence; only the drowsy hum of a bee was
heard now and then, as one flew by to its nest under a precipice,
laden with sweets. Suddenly, as he listened, he thought he heard
the roll of musketry: it was very faint, but it came to a soldier’s ear
with distinctness enough to be heard. He started to his feet, and
listened with painful eagerness, while his eye travelled in the
direction of the sound. His whole action was so sudden, and his
attitude so wrapt, that his attendant, who had been basking beside
him, was thrown completely off his guard.
‘What dost thou hear, Sahib?’ he said eagerly in Hindostanee.
‘What dost thou see?’
‘Hush!’ cried Herbert; ‘listen! there was a gun, and then musketry;
hark—a gun again! What can that mean?’
‘Alla knows!’ said the man; ‘but it is even so. Look! was that
smoke? By Alla, it is; at Coimbatoor too—thou canst see the
minarets of the mosque gleaming brightly.’
‘Thou speakest well in thy new tongue,’ said Herbert. ‘Why hast
thou not spoken to me before?’
‘I dared not: even now do not, for the sake of your faith and mine,
venture by word or sign to speak to me before the others, or it may
cost me my life.’
‘I will be discreet, and risk nothing; where are they?’
‘Some are hunting, some are at the house. Enough—listen!’ The
sound came again. ‘Dost thou not see the smoke?’ inquired he.
‘No, I see none,’ said Herbert, straining his eyes.
‘The Sultaun must be there, and they are firing,’ said the man. ‘It
is wonderful that sound should come thus far.’
For some time they continued to hear it; for Ahmed, Herbert’s
acquaintance, called his associates, and they all listened and
speculated, but could come to no conclusion; and then the wind
arose, and they heard no more. But they were evidently perplexed,
and continued to speak of it during the evening. At last one went
out, and returned with an expression of wonder upon his
countenance: he spoke to his companions, and some got up and
followed him. Soon these sent for the rest, and they took Herbert
with them.
It was quite dark. Near them a few objects were distinguishable
when the eye became accustomed to the darkness, but overhead
the sky was quite overcast and black; and though there was no
wind, yet the cold air of night was chill and piercing at that height.
They advanced to the place where they had been in the morning; it
was within a stone’s throw of the brink of the precipice, which
descended full four thousand feet before it met even any of the
projecting buttresses which appeared to support the mighty fabric.
With difficulty they could see to the edge; beyond that all was black
—a vast void, into the depths of which the eye strove to penetrate,
as the mind into illimitable space and eternity, and felt as if it were
thrust back and checked for its presumption by the awful profundity.
It seemed to Herbert as though the ground they trod had no
support, and was sinking into the gloomy abyss. There seemed to be
no horizon, no sky. Instinctively the group closed together, and
seemingly awe-stricken spoke hardly above their breath.
‘We saw it awhile ago,’ said one to another of those who had just
arrived with Herbert.
‘What did ye see?’
‘Lights,—sparks in that black darkness. Look carefully, ye may see
them again.’
‘There! there!’ cried several. ‘Look! what can they be?
Herbert saw where they pointed; in the direction where he had
heard the firing in the morning, and in the middle of the void before
him, for an instant or two were several bright flashes; he rubbed his
eyes, which ached from gazing, and from the effect even of those
transient flashes. Again he looked and listened; there was no sound
except the sigh of the night breeze in a tree near him; but again
there were flashes in the same place. And now, while they gazed, a
light arose, soared in a little circle into the air, and descended.
Another and another. Herbert knew what they were, and his heart
bounded within him with a quickness of pulsation it had not known
for years. If they should be his countrymen!
His guards turned to one another, and spoke rapidly among
themselves with eager gestures. At last Ahmed addressed him.
‘They bid me ask you,’ he said, ‘what this is; you Europeans know
all things. Hath the sky such lights?’
‘No, it is a siege,’ said Herbert, ‘and the lights are shells and
cannon. Is the Sultaun at war?’
‘I know not, but will ask.’ And Herbert heard the word Feringhee in
the answer. He was sure that his countrymen were near, and his
heart yearned to them.
‘There have been rumours of war,’ said Ahmed, ‘and we heard that
the English were in the Barah Mahal; but they cannot have got so
far, for the Sultaun had marched in person with the whole of the
army.’
Herbert thought otherwise. He could imagine nothing but victory
for the arms he had once borne, and for the cause in which he
would gladly have died. After watching long they withdrew from the
spot chilled and wearied, and all lay down to rest. But Herbert could
not sleep; his thoughts were too engrossing for sleep. Escape was
now possible, and long he deliberated whether it was not practicable
alone. On the south, east, and north sides of the Droog were huge
precipices, as we have already mentioned; the only access to it was
from the west, by which he had come. Even were he to escape from
the fort, could he venture to descend any of the passes to the plain?
Narrow paths, which at the bottom branched out into endless
ramification, led he knew not whither through dense forests that
extended for miles and miles, the abode of pestilence and of wild
beasts innumerable. The thought was appalling; and the more he
weighed the risk in his mind, the less chance did there appear of
success. Could it be that Ahmed would assist him? the obstacle of
language had been broken through; and no sooner did his busy
thoughts suggest the idea, than his mind clung to it. Ahmed was
poor, he could not refuse money, and he would offer him anything
he chose to demand—thousands, for liberty! He waited till his watch
came, and when all were asleep and breathing heavily, he called him
by name in a loud whisper.
‘Ahmed! Ahmed!’
He was dozing even on his watch, and did not hear at first.
Herbert was in agony lest the others should awake.
Ahmed answered at last. ‘What dost thou require?’ he said.
‘Come here, I would speak to thee secretly.’ He arose and crossed
the hut; it was a good sign. He seated himself close to Herbert;
perhaps he had too been thinking of the escape.
‘Ahmed,’ said the young man, ‘thou hast been kind to me: I love
thee, for thou hast spoken to me: thou art my friend. Wilt thou then
aid me?’
‘They say you English are deceitful and faithless,’ replied the man.
‘They wrong us—by thy head, they wrong us. Our enemies alone
say so; we are faithful even to death. Wilt thou trust one, and that
one me?’
The man moved, but spoke not.
‘Wilt thou aid me?’ continued Herbert, for he perceived he was
listened to. ‘Behold, I trust thee in thus speaking to thee, and am
utterly in thy power; if it is thy will, thou canst denounce me to thine
associates even now. See how I trust thee—thou wilt not betray me.
For years I have languished in captivity. I have a father, mother,
brethren, sisters—one other, too, even dearer than they. They think
me dead, and the old have long mourned with bitter grief, even the
grief of parents for a firstborn and beloved. Hast thou no heart for
this to plead for me within thee?’
Again the man writhed, but spoke not.
‘Hast thou no tenderness, that I may appeal to it? Hast thou no
father—mother—wife—who, if thou wert dead, would mourn for
thee, but who, living, rejoice for thee?’
‘I have all,’ was the reply.
‘I have not the last,’ said Herbert sadly, ‘that was a pang spared
me. Yet there is one who in blighted hope, and crushed and
withered affection, mourns me as long since numbered with the
dead. Thou canst restore peace where there is sorrow, hope where
there is despair.’
‘I cannot aid thee, Sahib.’
‘Thou canst! thou canst! My countrymen are yonder; I feel that
they are,—they must be victorious, else they had not penetrated so
far. Guide me to them, and thou wilt earn my gratitude, and with it a
competence for life. Thou knowest the passes; to me the attempt
unaided would be death.’
‘It would indeed: alone I would not attempt them for a kingdom,
even with my knowledge; but I feel for thee, Feringhee; thy looks
are gentle, thy speech is soft; thou art not as I have been told the
English are: I will believe thou art to be trusted.’
‘Oh believe it, believe it, Ahmed! my life will be in thy hands; thou
canst guide me to liberty or to death; I am ready to trust thee. Can I
say more?’
‘Enough, Sahib; I rely upon thee. I swear by Alla and the Prophet
to guide thee safely to Coimbatoor—if it be true that thy countrymen
are there: further than that, if they are not there, I should but lead
thee into death and fall a sacrifice myself. But listen, I risk much; my
parents live—they love me: I have too a wife and a child—they are
dependent upon me. If we are detected, the vengeance of the
Sultaun will fall on them, and that is fearful. Thou seest I have an
equal risk with thyself;—now wilt thou trust me?’
‘Thou hast, brave fellow! and I estimate thy generosity as that of a
brother; but we have spoken of no reward.’
‘Nor will I,’ said the man; ‘you are noble; your words—your
appearance, even in those rags, is noble. I trust to you.’
‘Gallant fellow! thy confidence shall be well repaid. If I live, thou
shalt know no poverty, but wealth to the end of thy life, and
honourable service, if thou choosest it. But enough—when shall we
make the attempt?’
‘The relief is expected to-morrow, or the day after; the men will
bring us news, and upon that we will arrange all.’
By evening the next day the expected relief came. The news was
true: the English besieged Coimbatoor, but with indifferent success;
it was said that the Sultaun was out, and victorious even to the
gates of Madras; the men were exulting over the discomfiture of the
English.
‘Darest thou now attempt it?’ asked Ahmed that evening; ‘the
news of thy people is bad.’
‘I will, should I perish in the attempt.’
‘Then I will lead thee out to-morrow, on pretence of taking thee
with me to hunt. I have already said thou shouldst have recreation,
and they have agreed to allow it. Enough now; but gird up thy loins
tightly and be ready, for we shall have far to go, and to tarry by the
way is death.’
The morrow dawned,—a cloudy and damp day; the mighty mists
lay still in the hollows and ravines, obscuring everything. Ahmed was
in despair. ‘Through those clouds,’ he said, ‘we can never penetrate,
but should be lost among the precipices.’ Long before noon,
however, the wind arose, and stirring the vast volumes of cloud from
their repose, caused them to boil up from the abysses around them,
and gradually to melt into air.
‘Come!’ said Ahmed to Herbert, whose heart bounded, and his eye
sparkled, as he heard the summons,—‘Come, the men are about to
return; we will see them a little way, and then turn on ourselves.
Come! they are departing.’
He obeyed eagerly, and soon the Fort was left behind; and the
narrow neck which connects the place to the main body of the chain
—an awful precipice on each hand—was passed in safety. Soon they
plunged deeper and deeper into the woods by a narrow path,
descending till they reached one branch of the Baraudee, which,
foaming and dashing amidst rocks, brawled on its way to the plain.
Here they divided; the party ascending the green slope before them,
and Herbert and his companion turning up the stream, apparently in
search of game.
‘Lie down! lie down!’ cried Ahmed; ‘Shookur Alla! they are gone,
and there is yet day enough for us. Ere evening we must be on the
edge of the range, and the morrow will see us far below it. Canst
thou bear fatigue?’
‘Any: look at me—I am stronger than thou art.’
The man regarded him earnestly, and read full well in the clear
eye and open brow, ruddy cheek, and firmly knit frame, a defiance
of danger. ‘I fear not for thee,’ he said; ‘Alla Akbar! the victory will be
ours.’
A while they lay concealed among the long fern, and then rising
up, Ahmed looked carefully around him; the party was long out of
sight, and they proceeded with light hearts and buoyant steps.
Ahmed had not overrated his knowledge of the mountains; he led
Herbert along the edge of the stream for a while, and as they went
along Herbert pulled wild flowers,—the flowers of his own England.
Woodbine and wild rose, archis and wild hyacinth, and the graceful
cyclamen, and fern and violets; and the more familiar buttercup and
wild anemone. ‘They know not that such a paradise exists in this
land,’ he said, ‘and these shall be my tokens; even as the spies
brought grapes and figs to the children of Israel in the desert.’
Hardly now he heeded the lovely scenery that was around him
everywhere, among which the round top of his old prison occupied a
conspicuous place, clothed with wood to its very summit; and its
precipitous sides rising out of the huge chasm that now lay between
him and it, at the bottom of which roared the Baraudee, leaping
from ledge to ledge in foam, in an endless succession of cataracts.
Now and then they would catch glimpses of the blue plain beyond
which melted into the horizon; and the deep and gloomy ravine on
their right hand presented an endless variety of views, of such
exquisite beauty, that Herbert would often stop breathless to
contemplate in admiration of their loveliness, for which his
companion appeared to have no eyes.
They had now travelled for some hours, and the road had been a
toilsome one, owing to the constantly recurring deep valleys which
broke into the ravine we have mentioned.
It was now evening; the sun was sinking into the west amidst
clouds of glory, and the huge shadows of the mountains were fast
creeping over the plain. The precipices of Hulleekul-droog shone like
gold under the red light, which, resting upon the vast forests and
hanging woods, caused them to glow with a thousand rich tints; and
wherever a small oozing of water spread itself down a naked rock, it
glittered so that the eye could hardly behold it.
‘Art thou fatigued, Sahib?’ asked Ahmed; ‘thou hast borne this
well, and like a man. By Alla! I had thought thy race were as soft as
women.’
‘No! I can endure yet a good hour,’ said Herbert gaily.
‘’Tis well! then we will push on. Why hast thou burthened thyself
with those flowers? fling them away—thou wilt be the lighter.’
‘Not so, my friend; these are the flowers of my own land, and I
take them to my comrades; thou dost not know—thou canst not feel
how dearly such things are prized in a distant land—bringing with
them, as they do, remembrances of past time, and of those who
shared it. On with thee! behold I follow.’
Hardly a mile further, on the very summit of the mountain, ere it
declined into the plain, they reached a rock, beside which was a tiny
footpath, hardly perceptible. ‘This is our resting place for the night,’
said Ahmed; ‘many a time have I slept here, with a load of tobacco
on my shoulders for the mountaineers, who are a curious people.’
‘Ay, indeed!’
‘Yes, I will tell thee all about them: but lay thyself down beneath
this rock, and it will shelter thee from the cold wind. I will get some
sticks, and we will have a fire; I should like a smoke, too, after this
travel.’ And so saying, he disencumbered himself of his arms, and
turned off to a short distance.
Herbert lay for a while looking out on the glorious prospect, in a
sense of the most delicious security and enjoyment. What exquisite
visions were floating before his eyes, as, shutting them, he allowed
the ideas to crowd into his soul!—visions of home, of love, of Amy,
of his parents! Suddenly, however, there was a loud roar, the crash
of which seemed to paralyse his heart: it was followed by a scream
so shrill and piercing, that he never forgot it to his dying day. Hastily
snatching up the sword which lay before him, he drew it, and
hurried to the spot from whence it had proceeded—but his brave
guide was gone for ever!
CHAPTER XXXIX.

There are few on earth, who in the chequered track of their


earthly pilgrimage—often cheered by the glowing beams of a sunny
mind, often obscured by despondency, often hurried on by
impatience and querulousness, and yearning with vain desire to
penetrate the veil of the hidden future—who do not recall to
memory some crisis when the happiness they sought has been
apparently within their reach—when the hand, stretched forth to
grasp the cup, has been dashed down by a rude but irresistible
force, which taught them in that moment how vain was their power,
how little their strivings to attain their end, when compared with the
Providence which held it in disposal. Providence, fate, destiny,
chance—call it what we will—there is an overruling power, visible in
the meanest events of our lives, which, if we follow it up to its
source in our own hearts, cannot fail to impress us with awe—with a
feeling of littleness, often mortifying, and hard for proud minds to
bear,—a feeling that there is a power guiding, and often suddenly
and rudely checking us, in the midst of a career which we have
marked out for good—certainly for gratification—but which may not
be accordant with the purposes of our being. Happy is the possessor
of that temperament who, even in the midst of disappointment—
when a murmur at misfortune, blighted hope, prolonged sickness, or
blasted ambition rises to his lips—can say, ‘It is for my good—it is
the hand of Providence—I bow to its correction in humility.’
But it was difficult for Herbert Compton to be reasonable under so
bitter a disappointment; wild with excitement, he roamed hither and
thither without fear, for in that moment he had no thought of
danger. The poor fellow who had perilled his all for him—the safety
of his parents, of his wife—who had so trusted him as to commit
without hesitation his future destiny into his hands—whose last act
was one of careful kindness and solicitude—was gone for ever! The
happiness, the exquisite enjoyment of a meeting with his
countrymen, which he had tasted in anticipation, had been dashed
from his hand in one moment!
How often, while there was light, did he awake the echoes of the
mountains with the name of Ahmed! He roamed everywhere, tried
to track the animal who had carried off his poor friend by the trail of
his body through the fern, and succeeded for a short distance, but
lost it again irretrievably. He returned to the spot where they had
first stopped; the whole was a hideous dream, which in vain he tried
to shut out from his thoughts. Vain indeed was the effort! the tiger’s
roar and Ahmed’s piercing scream rang in his ears, and often he
would start, as he thought they were repeated, during the fearful
hours which ensued. As the night closed, the wind arose, and with it
clouds came up out of the west, filled with cold driving rain; the
ledge he was under afforded but slight protection, and yet it
sheltered him enough to allow of a smouldering fire, which after
many efforts he kindled.
The storm increased; dark masses of clouds hurried past,
apparently close to his head, and the blast groaned and whistled
through the ravines and around the peaks and precipices. Of the
mountains he could see nothing, for the same black darkness which
had surrounded Hulleekul-droog the night before, now enveloped
him; there was only the little light of the fire, as the leaves and dead
fern blazed up at times under the effect of an eddy of wind, and
then utter darkness fell again. Hour after hour passed in deliberation
as to his future conduct. Dare he attempt the passage of those
fearful jungles alone? Encounter wild beasts, thread trackless
forests, where there was no path, and which were filled with rank
grass and reeds, thorny rattans, matted creepers, dank and noisome
swamps, the abode of deadly pestilence? For the time he was free;
but even if he gained the plain, did not a more terrible captivity
await him perhaps in a hot and parching dungeon, where the fresh
air and the beauteous face of nature would never be felt or seen?
But he was not to be daunted; he thought he knew the direction,—
his countrymen were before him, and the path was distinct enough,
he supposed, for him to track it: this idea consoled him, and he fell
asleep for a while, till the morning broke.
He awakened only to endure fresh disappointment; he was
surrounded by dense mists, which, though sometimes they would
partially clear away, filled the space before him so completely that he
could see nought but a thick boiling mass, fearfully agitated by the
wind, now rising up as though to overwhelm him, now sinking and
displaying for an instant the bluff top of Hulleekul-droog or a part of
its precipitous sides, or at an immeasurable and giddy depth the
bottom of the chasm, with the Baraudee roaring and flashing among
the darkness.
He was in despair, but he was calmer; even the utter hopelessness
of attempting to proceed down a precipitous mountain-side into a
trackless forest, enveloped in cloud, caused a revulsion of feeling,
and a sense that there was an unseen but sensibly-felt protection
afforded him—that the very obstacles in his path probably preserved
him from following it on to destruction.
There was no other course left but to return—perhaps to captivity,
for suspicion might be aroused against him,—to a life of wearisome
endurance, but still with beautiful nature for a companion, in whose
ever-varying and glorious features there was ever something new to
contemplate and to adore.
Ahmed’s sword, shield, and matchlock lay on the ground: he took
them with him, vowing they should never part from him; the latter
was useless for defence, for the charge was wet, and the powder-
horn and bullet-pouches had been around the waist of the dead. The
flowers he had gathered too lay beside them: they were faded now
—fitting types of his withered hope; that day he was to have
rejoiced over them with his countrymen! Alas! when would such an
event now come; the future was a dreary blank before him, where
so lately all had been bright and sunny; and with a sad heart, but
with feelings subdued from the excitement of the past evening, he
began to retrace his steps. This was no easy task, for the rain, which
had cleared away for an hour or so after daylight, now began again
to pour in torrents, and he was chilled to the heart. But the very
difficulties before him caused him to summon all his energies to
meet them, and he strove manfully and conquered. His worst
suffering was faintness for want of food; for the cakes they had
brought with them Ahmed had tied in a handkerchief about his back,
which he had not removed.
As the night set in gloomily and dark, Herbert Compton, well nigh
exhausted by hunger, fatigue, and cold, toiled up the steep and
rugged path which led to the Fort from the stream below; and
though often missing the way, which in the darkness caused by the
thick wood over his head was almost undiscernible, he at last
crossed the narrow neck already mentioned, and soon after saw the
welcome lights of the garrison huts twinkling among the trees above
him. This lent him fresh energy, and in a few minutes he arrived
before them. Hungry, wet and cold, he did not consider for a
moment the probable issue of his reception, and entered that
habitation where he had used to reside.
There was a group sitting smoking around a blazing fire, who
started to their feet suddenly, as he thus unceremoniously presented
himself; and after gazing earnestly at him for a moment, all
simultaneously dashed towards him and seized him. Herbert did not
struggle in their hands, nor could he answer the rapid and almost
unintelligible inquiries for their missing companion which were
poured forth in a torrent. In a few moments too they saw Ahmed’s
sword and shield, and their dark frowns and menacing looks were
bent upon him, and the hand of more than one stole to the weapon
by his side as if to inflict summary revenge on him who they might
well suppose had destroyed their absent friend. Gradually, however,
Herbert’s calm and sorrowful manner impressed them with a sense
of his innocence; and as they became more reasonable in their
behaviour, he described as well as he was able, and mostly by signs,
the event which had happened, and pointed in the direction of the
place.
Sorrow was on all their faces, and many wept, for Ahmed had
been a favourite among them; and while one of them set
refreshment before the weary Herbert, the rest conversed in groups
upon the subject. Although he could understand but little of what
passed, he could see that it was their intention to put his innocence
to the proof, by conducting them to the spot where the event had
happened. He was right: they allowed him to rest that night without
molestation, but by daylight he was awakened, and he found the
majority of the little garrison, twelve or fourteen men, equipped for
the expedition, each with his match lighted; after a hasty meal they
proceeded.
The morning was clear and fine, and the air fresh and bracing: the
errand upon which he was going was a sad one to Herbert, and yet
there was a melancholy satisfaction in finding perhaps the body of
the unfortunate Ahmed, and at any rate the cheering excitement of
vigorous exercise, in a rapid walk over the beautiful hills. There were
no traces of the storm of the day before, except an increased
freshness and odour of the wild flowers: here and there vast masses
of white vapour were hanging softly upon the precipices of the
droog, or resting in the abysses at its foot. Herbert proceeded at a
rapid pace before the rest.
There was evidently much surprise excited among them at the
direction which he took, and many significant glances were
exchanged from time to time; nor were these the less decided when
they arrived at the rock and little footpath: several appeared at once
to conclude that escape had been Ahmed’s object, and they pointed
significantly to the plain and to the path which led to it. Here was
the place, however, and having explained as well as he could their
arrival, and Ahmed’s intention of lighting a fire, Herbert led them to
the long fern whither he had gone for materials for the purpose.
They were all armed, and every man blew his match, and looked
carefully as he proceeded; it was evident now that they believed
him. The chief among them was in advance; he was a capital shot,
and Herbert had often seen him hit the smallest marks when they
practised for their amusement at the Fort. The trail of the body was
quickly found, and these expert hunters at once traced it, where
Herbert could see no mark, much further than he had any idea the
tiger would have gone. Here and there, too, a bit of rag fluttered
upon a thorny bush, which was a plain indication that they were
right.
At last, as they proceeded more and more carefully, a crow
suddenly arose from among some tall fern with a hoarse and
startling croak, and, hovering over the spot, aroused many others;
some vultures and kites, too, flew up and wheeled around,
screaming discordantly; and a jackal skulked off into a near thicket,
evidently disturbed from his repast.
‘He is there!’ said the leader of the party in a low tone; and a
hasty colloquy took place among them for a moment: all seemed
brave fellows, and again they advanced without hesitation.
They had scarcely gone many steps when some torn apparel met
their eye, and a few steps further, lying amongst the fern, were the
mangled remains of their poor comrade; his features were all gone,
but the powder-horn and bullet-pouches were around his waist, and
to his back was fastened the handkerchief, which still contained the
cakes he had tied up in it. With a passionate burst of grief most of
them darted to the spot, and looked on the sad spectacle—most sad
to Herbert, who, overcome by bitter thoughts, gave full vent to
emotions he did not seek to repress.
But they were not long inactive; a search for the tiger seemed
determined on, and they proceeded in a body round and round the
place. They had not gone far, however, when they heard a growl, a
low harsh growl, which made the blood run cold in Herbert’s veins;
they stood for a moment, and it was repeated. It appeared close to
them, and one fired in the direction. It was enough: with a roar
which rent the air, the noble brute bounded forth from his lair of
fern, his yellow-streaked sides shining in the bright sun: for an
instant he regarded them with glaring eyes,—then turned and fled.
There was a precipice a little beyond: he stopped at the edge and
looked over; it was evidently too high to leap, and as he hesitated
on the brink one man fired;—the shot was well aimed. The tiger
turned again, roared most fearfully, but immediately after staggered
to the edge of the cliff; his hind quarters appeared paralysed and fell
over, but he still held on by his claws, though they slipped every
moment. The leader saw his opportunity, raised his gun and fired.
Herbert heard the ball crash into the skull—saw the grim head quiver
for a moment, the paws relax their hold, and the whole frame slip.
All darted forward and looked over: it was a fearfully giddy place;
the blue depth was filled with boiling mist—the tiger’s body was
descending rapidly, turning over and over; at last it hit a projection
and bounded away, till the mist appeared to rise and hide it from
their view.
‘Enough!’ cried the leader, ‘let us depart.’
They returned to the dead; it was impossible to remove the
remains, they were so mutilated; but they hastily dug a shallow
place with their broad hunting-knives and laid them in it, covering
the spot with thorns and large heavy stones. Then all lay down on
the brow of the mountain and rested for a while; and Herbert was
glad when they set out on their return homewards, for the spot was
filled with too many bitter regrets for the dead, and for the untoward
accident that once more had thrown him back into captivity, which
now appeared endless; for as they passed the rock and pathway,
they pointed to it and to the plain, and shook their heads—some
laughing, others with frowns and threatening gestures, which told
him plainly that to attempt to escape would be death. Henceforth his
life became a blank.

It was not long after Philip Dalton and his wife reached India with
their companion young Hayward, that the aggressions of Tippoo
Sultaun upon the Rajah of Travancore, and his known detention of
prisoners since the peace of 1784, together with many insults upon
the frontiers for which no satisfaction was ever obtained, determined
Lord Cornwallis to declare war against him; and once this had been
done in a formal manner, every nerve was strained by the
Government of India to meet the exigency in a decisive and efficient
manner.
It is foreign to our tale to describe every event of the war, which
has already been so much more efficiently done in the histories of
the period; besides we have a pleasant licence in such matters,
without which it would be impossible for us to conduct our readers
to any satisfactory conclusion of our history. We shall therefore only
state that, availing himself of the undefended state of the passes,
and while the Sultaun was occupied with his fruitless negotiations
with the French, Lord Cornwallis ascended into Mysore, and, ere he
could be opposed by any force, had advanced considerably towards
the strong fort of Bangalore. There were partial engagements for
some days between the Mysore cavalry, led often by the Sultaun in
person, and the English; but they were attended by no decisive
result, and did not operate in any way to check the invasion.
Bangalore fell: the siege and the heroic defence of its brave
governor are themes which are still sung in the country, and will
never pass from the memory of its inhabitants while there remains
one of its itinerant bards, who, with two brass wires stretched
between two gourds at each end of a stick, perambulate the towns
and villages for a scanty and hard-earned subsistence.
The Sultaun retreated upon his capital, and to capture that was
the object of the campaign; but ere the army could advance, it was
thought necessary to reduce some small forts in the neighbourhood,
and to throw into them garrisons of such Hindoo inhabitants of the
country, who had welcomed the English invasion and already
assisted it against the Sultaun, as would keep them from the
occupation of the Sultaun’s troops.
From his interest with the higher ranks of the army, and his talent
and efficiency, Philip Dalton had, in the opening of the campaign,
been appointed to the general staff of the army, while Charles
Hayward remained with his regiment; they continued, however,
together, both inhabiting the same tent, and as their history was
known to many, they were objects of peculiar interest. Indeed poor
Herbert’s fate was one in which the sympathies of all were
powerfully excited, and many were the sincere aspirations that the
issue of the war might restore him and others, both English and
native, to sorrowing and despairing relatives.
The reduction of the small forts we have alluded to was a service
of no great difficulty; and when the army lay encamped near
Balapoor—one of them—while arrangements were being made for its
occupation, it was common for the officers to examine such places
or objects of interest as the neighbourhood of their camp afforded.
Pre-eminent among these was the famous rock whence prisoners
used to be flung, and of which mention has already been made as
connected with Herbert Compton.
No one, whether European or native, could approach this spot
without feelings of horror; for the lonely rock stood alone in the
plain; and the fearful use to which it had been devoted, both by
Hyder and Tippoo, was fresh in the memory of all. A few in the force
had seen and examined it, and Philip Dalton and Charles rode thither
accompanied by a few mounted orderlies on the very first
opportunity of leisure.
A silent feeling of sickening apprehension grew upon them as they
approached it, and a thought would force itself upon Philip, despite
of his hopes and prayers to the contrary, that Herbert’s fate might
have been the dreadful one experienced by the hundreds whose
whitened bones and skulls lay around the foot of the rock; but he
did not mention this to his companion, and they rode on in silence.
At length they reached the rock, and, leaving their horses below,
ascended to the top, where still stood, though somewhat
dilapidated, the small hut or house we have once mentioned. But
this did not attract their notice at first; the fatal brink, which had
witnessed the frantic death-struggles of so many, was the spot to
which they were led by the orderlies, who had a hundred marvellous
tales to tell of events that happened there, and of the tremendous
strength of those whose business it was to hurl the victims from the
precipice. They looked over, too, and saw the bones and skulls
scattered at the bottom, and shreds of white calico and red cloth
fluttering among the bushes—the sad evidence of the fate of brave
soldiers who had perished there. There was nothing there to induce
them to remain, and Philip and his young friend turned away
sickened from the spot.
‘And this is the place where the unfortunate persons were
confined,’ said an orderly, who, pushing open a rude and half-broken
door, ushered them into a mean and dilapidated apartment.
‘Good God! it is covered with the names of poor fellows who have
died here,’ exclaimed Philip; ‘what if his should be here? we must not
leave an inch unexamined, Charles.’
‘Why, do you think he was ever here?’ asked the young man in an
agitated tone.
‘God forbid! but it is our duty to look; we may possibly gain a
clue.’
And they fell to examining the walls with careful scrutiny. It was a
painful task; there were many names; the hands which had written
them were now dry bones bleaching without, or had long ago
mouldered into dust; many were the humble prayers written there,
and obscene words and curses mingled with them in strange
combination. Many a direction, too, for parents and wives and
children of those who were dead, in case others might visit the spot,
and bear them to the far west.
‘Heavens!’ exclaimed young Hayward suddenly; ‘Come here, Philip!
quick!’
Dalton darted across the apartment, and Charles pointed to a
small writing scratched in the plaster with a pin or nail; it was plain
even to his swimming eyes and sickened heart.

‘Herbert Compton.
‘May 24, 17—. Many have been thrown from this abode of death; I
have waited my turn; it will come to-morrow; it will deliver me from
a life of misery and—’

There was no more—a stone flung against the wall had hit the
rest and obliterated it.
Philip sank down and groaned aloud. That there should be such
an end to his hopes, which this proved to have had foundation, was
hard indeed to bear. Awhile Charles strove to comfort him, but both
their hearts were sick, and they were poor comforters one to
another.
‘There may be further trace of him,’ said Philip; ‘let us look
around.’
They did so. For a while they found nothing, but at length a joyful
cry again broke forth from Charles. ‘God be praised!’ he said, ‘come
here and read, Philip.’
The writing on the wall was rough and misshapen, but they were
characters of blessed hope to both; the words were these:—
‘Captin Comtin was taking awey from this horible pleace verry ill,
on the day of—
‘John Simpson.’
‘God be praised for this!’ exclaimed Philip, as he fell on his knees
and blessed Him aloud; ‘there is yet hope, for assuredly he did not
perish here, Charles.’
CHAPTER XL.

‘These are too precious to remain here, Charles,’ said Philip; ‘we
must remove them.’ It was easily done: with their pen-knives they
carefully cut round the plaster of each inscription, and then
separated it from the wall without difficulty; they were precious
relics, and the young men long gazed on them, with that depth of
feeling which such memorials were well calculated to excite. ‘Ah!
Philip, if we could only trace him further,’ said Charles.
‘We thought not of this when we came hither,’ he replied, ‘and we
should be thankful; it is just possible that some one in the town may
have heard tidings of him if he were really ill, and we will go thither
and inquire.’
They did not tarry on the rock for an instant; their horses awaited
them at the bottom, and the distance between the rock and the
small town being quickly traversed, they arrived in the bazaar. Philip
directly made for the Chouree, where the former Kotwal and others
sat engaged in their functions of superintending the market, and
directing the issues of grain and forage to the followers of the British
army.
They were received courteously by the functionary, who was all
civility to his late conquerors: Philip at once opened the cause of his
visit, and expressed his anxiety for intelligence, however vague, of
his lost friend.
The Kotwal racked his brains, or appeared to do so; he could
remember nothing about the rock or its victims, being fearful lest he
should compromise himself by some unlucky remark or confession.
‘So many had perished there,’ he said; ‘it was the Sultaun’s order,
and in Balapoor they never knew anything about them.’
‘But was no one ever brought here?’ asked Philip.
‘Really he could not remember, so many went and came; how
could he, the Kotwal, who saw a thousand new faces every day,
retain a recollection of any? Prisoners too in hundreds passed by—
sometimes remaining there for a day, but he never saw them; he
had no curiosity, he had other business; he was in fact the Kotwal,
upon whom rested all the affairs of the town.’
Philip was in despair. ‘Can you get me no information?’ he said; ‘I
do not speak the native language, and to me inquiry is useless.’
‘Of course, if my lord wished it,’ he would make every inquiry; and
in truth he began in earnest with those about him; none, however,
could remember anything but vague descriptions of prisoners
passing and repassing; and Philip, after a long and patient
investigation which led to no result, was about to depart,
disappointed and vexed, when a man entered who had been absent
on some message; he was one of the labourers, or scouts of the
village, and the Kotwal immediately said to Philip, ‘If any one can
give you the information you seek, it is this man, for it was his
business to attend upon the Sultaun’s people who came hither with
prisoners.’
He was immediately questioned, and gave ready answers; he
perfectly remembered a Feringhee who was brought ill, and long
remained at the Fakeer’s Tukea,[54] beyond the town, lying upon the
Chubootra;[55] they were told he was an officer, and an order came
to him from the Sultaun himself, brought by Jaffar Sahib Jemadar.

54. Lit. Pillow, the abode of a Fakeer.

55. Elevated seat or terrace.

‘Surely, surely!’ cried the Kotwal, whose memory appeared


wonderfully refreshed; ‘’tis strange I should have forgotten him,
seeing that he was often fed from my house; women you know,
Sahib, have tender hearts, even for those of a different faith, and we
knew nothing of the brave English then.’
‘Canst thou guide me to this Fakeer?’ said Philip to the man, who
could speak indifferent Hindostanee.
‘Certainly,’ he replied; ‘’tis but a short distance.’ And so saying he
took up his long staff. Philip rose to depart.
‘I will accompany you, sir,’ said the Kotwal; ‘the old Sein[56] is very
curious in his behaviour to strangers, and may not be civil; besides
he hath been ill of late.’

56. Respectful appellation of a Mahomedan Fakeer.

‘I thank you,’ returned Philip, ‘but I would prefer going alone. I


have no doubt the old man will be reasonable, even to a Feringhee.
Salaam!’
Guided by the scout, who ran before their horses, they were
quickly at the garden we have before mentioned. It had been
respected by all; the little mosque was as purely clean, the space
around it as neatly swept as ever: the flowers bloomed around the
tiny fountain, and the noble trees overshadowed all as closely as
when, sick and exhausted, Herbert Compton lay beneath their
shade, and blessed God that he had found such a refuge and such a
friend as the old Fakeer.
The venerable old man sat in his usual spot under the tamarind-
tree; before him was his Koran, which he read in a monotonous
tone; his face was very thin, and he looked weak and attenuated by
sickness.
‘Salaam, Baba!’ said Philip advancing, ‘we are English officers, who
would speak to thee.’
‘Salaam Aliekoom!’ returned the old man benignantly, ‘ye are
welcome; the turn of destiny hath allowed us to say that to those
whom we have called kafirs; but ye are welcome to the old Fakeer—
all are welcome who come in peace and good will. What seek ye?’
‘Father,’ said Philip, much touched by the benevolence of his tone
and appearance, ‘thou art no bigot, and wilt aid us if thou canst. I
seek a lost friend, as dear to me as a brother; I know not if it be the
same, but I have heard that one of my race was tended by thee,
and remained ill with thee for long; it may be he; didst thou know
his name?’
‘Holy Alla!’ cried the old man eagerly, ‘art thou aught to him who
loved me as a son?’
‘Alas! I know not his name, father.’
‘His name! it was—’ and he fell to musing, his forefinger between
his teeth. ‘I cannot remember it now,’ he said, ‘though it is daily on
my lips. Ka— Ka—’
‘Compton?’ said Philip.
‘The same! the same!’ cried the old man; ‘the same—Compton—
Captain Compton; the name is music to me, Sahib; I loved that
youth, for he was gentle, and often told me of your cool and
beautiful land in the distant west, where the sun goes down in glory;
and he taught me to love the race I heard reviled and persecuted.’
‘Alla will reward thee!’ said Philip; ‘but canst thou tell me anything
respecting his fate?’
‘Alas! nothing; for a month he was with me, ill, very ill—we
thought he would die; but the prayers of the old Fakeer were heard,
and the medicines of his hand were blessed; and once more he
spoke with reason and grew calm, and the fever left him; then,
when his strength returned, an order from the Sultaun arrived, and
it was a bold bad man that brought it, and he was taken away from
me, and never since that have I gained any tidings of him. May his
destiny have been good! my prayers have been night and day for
him to that being who is your God and mine.’
Philip was much touched, and poured out his thanks to the old
man most sincerely and with a full heart. ‘Alas! I fear all trace of him
is lost,’ he said.
‘Say not so, my son; I dread—but I hope. The Sultaun is not
always cruel—he is just; his death was never intended—his life was
too valuable for that; he is most likely at Seringapatam, whither ye
are proceeding they say—I would not despair. And now listen: Alla
hath sent thee hither, thou who wast his friend; he gave me a letter,
a packet which he wrote here in secret; I would ere this have
delivered it in thy camp, but I am grown very feeble and infirm of
late, the effect of illness, and I could not walk so far, wilt thou
receive it? to me it has been a memorial of the young man, and I
have looked on it often, and remembered his beautiful features, and
his gratitude when I risked this my little possession, which to me is a
paradise, in taking it from him.’
Eagerly, most eagerly Philip implored to see it, and the Fakeer
rising attempted to walk to his humble residence, but with difficulty.
Philip and Charles flew to his aid, and leaning on them, as he
glanced from one to the other with evident pleasure, the old man
reached the door. ‘Remain here,’ he said, ‘the dwelling is low—ye are
better here. I will return to you.’ He did so in a few minutes, bearing
the packet.
Philip took it with a delight he had no words to express, and was
well nigh overpowered by his emotion as the familiar handwriting
met his eye. ‘There can be no doubt,’ he said, ‘that it was he—I
would swear to his handwriting among a thousand.’
‘Do not open it here,’ said the Fakeer; ‘but sit and speak to me of
him and his parents, and his beloved, for I heard all,’ continued the
old man with a sigh, ‘and pitied his sad fate.’
Philip told him all, and they talked for hours over the lost one; he
told him how he had gone to England and married his sister; how
the youth beside them was her brother of whom he had heard; and
then the old man blessed the youth. ‘Thou wilt not be the worse that
I have done so,’ he said; while a tear filled his eye—rested there for
a while—then welling over, trickled down his furrowed cheek and
was lost in his white beard.
Long, long they talked together, and the day was fast declining ere
they left him, promising to return whenever they could; they took
away the precious packet with them, to pore over its contents
together in Philip’s tent.
They opened it with eager anxiety; it was addressed ‘To any
English officer.’ There were a few lines from Herbert, informing
whomsoever should receive it that he was alive, and imploring him
to forward it to the Government; and a few more descriptive of his
captivity, of his escape from the rock, and his uncertainty for the
future.
There were letters too to be forwarded, one to his father, one to
Amy; another for Philip himself, which he opened impatiently. It was
short—he said he dared not write much. He described his various
trials and sufferings, and the kindness of the old Fakeer, without
whose aid he must have perished: he besought him not to despair of
finding him alive, even though years should intervene between that
time and when the letter should reach him.
‘Nor will I despair, dear Herbert,’ cried Philip; ‘never, never! The
hand of Providence is clearly discernible through all this chain of
events; it will lead us, Charles, to the close. Yet we must be secret:
these letters must not be delivered, nor must our present success be
known in England till we can confirm the glad tidings, or for ever
despair.’
There was not a day while the army remained there that the
friends did not visit the old Fakeer. They could not prevail on him to
accept money; but there were articles which were of use to him—
cloth, and blankets, and other trivial things, which he received
gladly. They left him with sorrow, and with little hope that they
should ever renew their intercourse with him. Yet they met again.
The progress of the army was slow; for the forage, except in a few
places, had been destroyed, and the draught and carriage bullocks
died by hundreds. The Nizam’s force, too, had joined the British
army, and it presented a most gorgeous Eastern display, far more
imposing than any Philip had yet seen. Men of all nations of the
East, and tribes of India, the courtly Persian, the reckless Afghan,
the wild Beloche, the sturdy Pathan, the more slender and
effeminate Dukhanee, the chivalrous Rajpoot and hardy Mahrattas,
all were mingled in a wild confusion—men hardly belonging to any
corps, and clustered round every leader’s standard, apparently as
fancy, or caprice, or hope of plunder dictated. The force was utterly
inefficient, however, for the purposes of the war, for the leader had
no control over it, nor could he supply it with food; and his fidelity to
the English cause, if not the Nizam’s also, was questionable.
At every day’s march the distress of the army increased. Men were
upon the lowest rations; the cavalry were almost inefficient from the
starvation and weakness of their horses, and the active and irregular
Welcome to our website – the perfect destination for book lovers and
knowledge seekers. We believe that every book holds a new world,
offering opportunities for learning, discovery, and personal growth.
That’s why we are dedicated to bringing you a diverse collection of
books, ranging from classic literature and specialized publications to
self-development guides and children's books.

More than just a book-buying platform, we strive to be a bridge


connecting you with timeless cultural and intellectual values. With an
elegant, user-friendly interface and a smart search system, you can
quickly find the books that best suit your interests. Additionally,
our special promotions and home delivery services help you save time
and fully enjoy the joy of reading.

Join us on a journey of knowledge exploration, passion nurturing, and


personal growth every day!

ebookmasss.com

You might also like