C++ Programming: An Object-Oriented Approach, 1e ISE 1st Edition Behrouz A. Forouzan download
C++ Programming: An Object-Oriented Approach, 1e ISE 1st Edition Behrouz A. Forouzan download
https://ebookmass.com/product/c-programming-an-object-
oriented-approach-1e-ise-1st-edition-behrouz-a-forouzan/
https://ebookmass.com/product/foundations-of-computer-science-4th-
edition-behrouz-forouzan/
https://ebookmass.com/product/data-communications-networking-with-tcp-
ip-protocol-suite-behrouz-a-forouzan/
https://ebookmass.com/product/data-communications-and-networking-with-
tcp-ip-protocol-suite-6th-edition-behrouz-a-forouzan/
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/
https://ebookmass.com/product/an-introduction-to-programming-through-
c-abhiram-g-ranade/
https://ebookmass.com/product/c-programming-language-c-programming-
lang-_p2-2nd-edition-ebook-pdf/
https://ebookmass.com/product/learn-programming-with-c-an-easy-step-
by-step-self-practice-book-for-learning-c-1st-edition-imran/
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.
1 2 3 4 5 6 7 8 9 LWI 21 20 19
All credits appearing on page or at the end of the book are considered to be an extension of the copyright page.
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
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
2
Basics of C++ Programming 19
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
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
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
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
13
Operator Overloading 597
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
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
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
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.
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.
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:
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:
1
2 Chapter 1 Introduction to Computers and Programming Languages
CPU
Bus
ALU Registers
Control unit
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
256
15.34
Hello Data
n−1
(a) General layout
Figure 1.3 Primary memory
(photo) ©Simon Belcher/Alamy
1.1 Computer System 3
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
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.
High-level languages
Symbolic languages
Machine languages
Time
1940 1950 1960 1970 1980 1990 2000 2010
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.
Computer language
paradigms
Object-
Procedural Functional Logic
oriented
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
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);
Objects
13 17 8 10 list1
sort ( )
reverse ( )
11 17 38 14 list2
search (...)
print (...)
Shared 12 10 91 20 listn
Procedures
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.
list (6, 8)
first () rest ()
Visualization
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.
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.
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
29
Output data
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
Output largest
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.
Characters Disk
Source code
Editor
Programmer
Commands Disk
Compiled code
Compiler
Programmer Library code
Compiled code
Executable code
Linker
User
Memory
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.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.
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.
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-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-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++.
19
20 Chapter 2 Basics of C++ Programming
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.
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.
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.
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
Line 3: Function Header Line 3 of the program (without the line number) is shown below:
int main ()
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.
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:
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
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.
call
int main ( )
{
zero: success
retrun 0;
}
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).
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
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 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.
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.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.
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.
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.
ebookmasss.com