lab a and lab b computer science work.You can use visual studio 2019 first then copy paste to word doc
CSCI110 – Fundamentals of Computer Science
Homework Assignments
Winter 2022
Instructions for your lab report.
1. You need to create a cover page formatted as following:
(Notes: The cover page needs to be typed and printed)
CSCI110 – Fundamentals of Computer Science
MT SAC College
CSCI110
Lab #: __________________
Description: ______________________
______________________
______________________
Due Date: ___________________
Name: _______________________
Grade: _______________________
Notes: ______________________
CSCI110 – Fundamentals of Computer Science
Requirements for your lab reports
Your submission should include:
1. The cover page
2. The listing of the source code (See details shown below)
3. A screenshot of your program execution
The source code should be organized and presented as:
1. Prolog
a. Program Description
b. Author
c. Input variables
d. Process Flow
e. Output variables
2. A listing of source code with internal comments
Programming requirements:
1. Your program needs to be user-friendly and easy to understand.
2. You need to follow the book’s and my instructions to code your program – no deviation. If you have any questions, please let me know.
CSCI110 – Fundamentals of Computer Science
Homework Assignments
Winter 2022
Lab 1A
Requirements: Please work on p1.6 on page 26.
Test cases:
1. Please produce the report based on the book’s instructions.
1. Initial principal = 10000 (Please prompt the user for this amount)
1. Print ‘”New balance = “ for 3 years.
Due date: January 11, 2022
Submission includes 1) cover page 2) source listing 3) screen shot of program execution.
CSCI110 – Fundamentals of Computer Science
Lab 1B
Requirements:
Please work on p2.21 on page 69. You need to work on both conditions – the first time is earlier than the second time and the first time is later than the second time. There is no extra credit given for this lab.
Test cases:
1. You need to test both conditions mentioned in the requirements.
1. You need to print a user-friendly message showing the difference between these two times. Do not follow the book by simply printing “8 hours and 30 minutes”.
Due date: January 11, 2022
Submission includes 1) cover page 2) source listing 3) screen shot of program execution.
5
This page intentionally left blank
C + + f o r
E v E r y o n E
cfe2_fm_pi_xxvi.indd 1 10/28/10 5:08 PM
This page intentionally left blank
C + + f o r
E v E r y o n E
S e c o n d e d i t i o n
cay Horstmann
San Jose State University
John Wiley & Sons, Inc.
cfe2_fm_pi_xxvi.indd 3 10/28/10 5:08 PM
VICE PRESIDENT AND EXECUTIVE PUBLISHER Don Fowley
EXECUTIVE EDITOR Beth Lang Golub
EDITORIAL PROGRAM ASSISTANT Michael Berlin
PRODUCTION SERVICES MANAGER Dorothy Sinclair
SENIOR PRODUCTION EDITOR Janet Foxman
EXECUTIVE MARKETING MANAGER Christopher Ruel
MARKETING ASSISTANT Diana Smith
CREATIVE DIRECTOR Harry Nolan
SENIOR PHOTO EDITOR Lisa Gee
SENIOR DESIGNER Madelyn Lesure
EXECUTIVE MEDIA EDITOR Tom Kulesa
PRODUCTION SERVICES Cindy Johnson
COVER PHOTO © Ricardo Azoury/iStockphoto
This book was set in Stempel Garamond by Publishing Services, and printed and bound by RRD Jefferson City.
The cover was printed by RRD Jefferson City.
This book is printed on acid-free paper. ∞
Founded in 1807, John Wiley & Sons, Inc. has been a valued source of knowledge and understanding for more
than 200 years, helping people around the world meet their needs and fulfill their aspirations. Our company is
built on a foundation of principles that include responsibility to the communities we serve and where we live
and work. In 2008, we launched a Corporate Citizenship Initiative, a global effort to address the environmental,
social, economic, and ethical challenges we face in our business. Among the issues we are addressing are carbon
impact, paper specifications and procurement, ethical conduct within our business and among our vendors,
and community and charitable support. For more information, please visit our website: www.wiley.com/go/
citizenship.
Copyright © 2012, 2009 John Wiley & Sons, Inc. All rights reserved. No part of this publication may be re-
produced, stored in a retrieval system or transmitted in any form or by any means, electronic, mechanical, pho-
tocopying, recording, scanning or otherwise, except as permitted under Sections 107 or 108 of the 1976 United
States Copyright Act, without either the prior written permission of the Publisher, or authorization through
payment of the appropriate per-copy fee to the Copyright Clearance Center, Inc., 222 Rosewood Drive, Dan-
vers, MA 01923, website www.copyright.com. Requests to the Publisher for permission should be addressed to
the Permissions Department, John Wiley & Sons, Inc., 111 River Street, Hoboken, NJ 07030-5774, (201) 748-
6011, fax (201) 748-6008, website www.wiley.com/go/permissions.
Evaluation copies are provided to qualified academics and professionals for review purposes only, for use in
their courses during the next academic year. These copies are licensed and may not be sold or transferred to a
third party. Upon completion of the review period, please return the evaluation copy to Wiley. Return instruc-
tions and a free of charge return shipping label are available at www.wiley.com/go/returnlabel. Outside of the
United States, please contact your local representative.
Library of Congress Cataloging in Publication Data:
Horstmann, Cay S., 1959-
C++ for everyone / Cay S. Horstmann. — 2nd ed.
p. cm.
Includes index.
ISBN 978-0-470-92713-7 (pbk.)
1. C++ (Computer program language) I. Title.
QA76.73.C153H6685 2010
005.13’3–dc22
2010039907
ISBN 978-0-470-92713-7 (Main Book)
ISBN 978-0-470-92092-3 (Binder-Ready Version)
Printed in the United States of America
10 9 8 7 6 5 4 3 2 1
cfe2_fm_pi_xxvi.indd 4 10/28/10 5:08 PM
www.copyright.com
www.wiley.com/go/citizenship
www.wiley.com/go/citizenship
www.wiley.com/go/permissions
www.wiley.com/go/returnlabel
P r E fa C E
v
This book is an introduction to C++ and computer programming that focuses on the
essentials—and on effective learning. The book is designed to serve a wide range of
student interests and abilities and is suitable for a first course in programming for
computer scientists, engineers, and students in other disciplines. No prior program-
ming experience is required, and only a modest amount of high school algebra is
needed. Here are the key features of this book:
Guidance and worked examples help students succeed.
Beginning programmers often ask “How do I start? Now what do I do?” Of course,
an activity as complex as programming cannot be reduced to cookbook-style instruc-
tions. However, step-by-step guidance is immensely helpful for building confidence
and providing an outline for the task at hand. “Problem Solving” sections stress the
importance of design and planning. “How To” guides help students with common
programming tasks. Additional Worked Examples are available online.
Practice makes perfect.
Of course, programming students need to be able to implement nontrivial programs,
but they first need to have the confidence that they can succeed. This book contains a
substantial number of self-check questions at the end of each section. “Practice It”
pointers suggest exercises to try after each section. At the end of each chapter, you
will find a great variety of programming assignments, ranging from simple practice
problems to realistic applications.
teach computer science principles, not just c++ or object-orientation.
This book uses the C++ programming language as a vehicle for introducing com-
puter sci ence concepts. A substantial subset of the C++ language is covered, focusing
on the modern features of standard C++ that make students productive. The book
takes a traditional route, stressing control structures, procedural decomposition, and
array algorithms, before turning to the design of classes in the final chapters.
A visual approach motivates the reader and eases navigation.
Photographs present visual analogies that explain the
nature and behavior of computer concepts. Step-by-
step figures illustrate complex program operations.
Syntax boxes and example tables present a variety
of typical and special cases in a compact format. It
is easy to get the “lay of the land” by browsing the
visuals, before focusing on the textual material.
Focus on the essentials while being
technically accurate.
An encyclopedic coverage is not helpful for a begin-
ning programmer, but neither is the opposite—
reducing the material to a list of simplistic bullet points. In this book, the essentials
are presented in digestible chunks, with separate notes that go deeper into good prac-
tices or language features when the reader is ready for the additional information.
You will not find artificial over-simplifications that give an illusion of knowledge.
Visual features help the reader
with navigation.
cfe2_fm_pi_xxvi.indd 5 10/28/10 5:08 PM
vi Preface
new to This Edition
Problem Solving Strategies
This edition adds practical, step-by-step illustrations of techniques that can help stu-
dents devise and evaluate solutions to programming problems. Introduced where
they are most relevant, these strategies address barriers to success for many students.
Strategies included are:
• Algorithm Design (with pseudocode)
• First Do It By Hand (doing sample
calculations by hand)
• Flowcharts
• Test Cases
• Hand-Tracing
• Storyboards
• Reusable Functions
• Stepwise Refinement
• Adapting Algorithms
• Discover Algorithms by Manipulat-
ing Physical Objects
• Draw a Picture (pointer diagrams)
• Tracing Objects (identifying state and
behavior)
• Discovering Classes
optional Engineering Exercises
End-of-chapter exercises have been enhanced with problems from scientific and
engineering domains. Geared to students learning C++ for a technical major, the
exercises are designed to illustrate the value of programming in those fields. Addi-
tional exercises are available on the book’s companion web site.
new and reorganized Topics
All chapters were revised and enhanced to respond to user feedback and improve the
flow of topics. Loop algorithms are now introduced explicitly in Chapter 4. Debug-
ging is now introduced in a lengthy Worked Example in Chapter 5. Arrays are cov-
ered before vectors are introduced in Chapter 6, and a new section on vector algo-
rithms builds on the array algorithms presented earlier in the chapter. A new optional
section on structure types is now in Chapter 7. New example tables, photos, and
exercises appear throughout the book.
a Tour of the Book
The core material of the book is:
Chapter 1. Introduction
Chapter 2. Fundamental Data Types
Chapter 3. Decisions
Chapter 4. Loops
Chapter 5. Functions
Chapter 6. Arrays and Vectors
In a course for engineers with a need for systems and embedded programming, you
will want to cover Chapter 7 on pointers. Sections 7.1 and 7.4 are sufficient for using
pointers with polymorphism in Chapter 10.
cfe2_fm_pi_xxvi.indd 6 10/28/10 5:08 PM
Preface vii
File processing is the subject of Chapter 8. Section 8.1 can be covered sooner for
an intro duction to reading and writing text files. The remainder of the chapter gives
addi tional material for practical applications.
Chapters 9 and 10 introduce the object-oriented features of C++. Chapter 9
introduces class design and implementation. Chapter 10 covers inheritance and
polymorphism.
Four additional chapters are available on the Web. They can be used individu-
ally for a capstone chapter, or they can be combined for teaching a two-semester
course. (They can also be incorporated into a custom print version of the text; ask
your Wiley sales representative for details.)
Chapter 11. Recursion
Chapter 12. Sorting and Searching
Chapter 13. Lists, Stacks, and Queues
Chapter 14. Sets, Maps, and Priority Queues
Figure 1 shows the dependencies between the chapters.
Figure 1
Chapter Dependencies
Section 8.1
contains the core
material
Sections
7.1 and 7.4 are
required
A gentle
introduction to recursion
is optional
1. Introduction
2. Fundamental
Data Types
3. Decisions
4. Loops
5. Functions
6. Arrays
and Vectors
9. Classes 11. Recursion 12. Sorting and
Searching
8. Streams
13. Lists, Stacks,
and Queues
14. Sets, Maps,
Priority Queues
7. Pointers
10. Inheritance
Fundamentals
Online
cfe2_fm_pi_xxvi.indd 7 10/28/10 5:08 PM
viii Walkthrough
a Walkthrough of the Learning aids
The pedagogical elements in this book work together to focus on and reinforce key
concepts and fundamental principles of programming, with additional tips and detail
organized to support and deepen these fundamentals. In addition to traditional fea-
tures, such as chapter objectives and a wealth of exercises, each chapter contains ele-
ments geared to today’s visual learner.
4.3 The for Loop 143
4.4 The for Loop
It often happens that you want to execute a sequence of statements a given number of
times. You can use a while loop that is controlled by a counter, as in the following
example:
counter = 1; // Initialize the counter
while (counter <= 10) // Check the counter
{
cout << counter << endl;
counter++; // Update the counter
}
Because this loop type is so common, there is a special form for it, called the for loop
(see Syntax 4.2).
for (counter = 1; counter <= 10; counter++)
{
cout << counter << endl;
}
Some people call this loop count-controlled. In contrast,
the while loop of the preceding section can be called an
event-controlled loop because it executes until an event
occurs (for example, when the balance reaches the target).
Another commonly-used term for a count-controlled
loop is definite. You know from the outset that the loop
body will be executed a definite number of times––ten
times in our example. In contrast, you do not know how
many iterations it takes to accumulate a target balance.
Such a loop is called indefinite.
The for loop neatly groups the initialization, condi-
tion, and update expressions together. However, it is
important to realize that these expressions are not exe-
cuted together (see Figure 3).
The for loop is
used when a
value runs from a
starting point to an
ending point with a
constant increment
or decrement.
You can visualize the
for loop as an orderly
sequence of steps.
Syntax 4.2 for Statement
for (int i = 5; i <= 10; i++)
{
sum = sum + i;
}
This loop executes 6 times.
See page 147.
These three
expressions should be related.
See page 147.
This initialization
happens once
before the loop starts.
The loop is
executed while
this condition is true.
This update is
executed after
each iteration.
The variable i is
defined only in this for loop.
See page 144.
Annotations explain
required components
and point to more information
on common errors or best practices
associated with the syntax.
Throughout each chapter,
margin notes show where
new concepts are introduced
and provide an outline of key ideas.
Annotated syntax boxes
provide a quick, visual overview
of new language constructs.
Like a variable in a computer
program, a parking space has
an identifier and a contents.
Analogies to everyday objects are
used to explain the nature and behavior
of concepts such as variables, data
types, loops, and more.
cfe2_fm_pi_xxvi.indd 8 10/28/10 5:08 PM
Walkthrough ix
6.5 Problem Solving: Discovering Algorithms by Manipulating Physical Objects 277
Now how does that help us with our problem, switching the first and the second
half of the array?
Let’s put the first coin into place, by swapping it with the fifth coin. However, as
C++ programmers, we will say that we swap the coins in positions 0 and 4:
Table 3 Variable Names in C++
Variable Name Comment
can_volume1 Variable names consist of letters, numbers, and the underscore
character.
x In mathematics, you use short variable names such as x or y. This is
legal in C++, but not very common, because it can make programs
harder to understand (see Programming Tip 2.1 on page 38).
! Can_volume Caution: Variable names are case-sensitive.
This variable name is different from can_volume.
6pack Error: Variable names cannot start with a number.
can volume Error: Variable names cannot contain spaces.
double Error: You cannot use a reserved word as a variable name.
ltr/fl.oz Error: You cannot use symbols such as / or.
Step 1 Determine the inputs and outputs.
In our sample problem, we have these inputs:
• purchase price1 and fuel efficiency1, the price and fuel efficiency (in mpg) of the first car
• purchase price2 and fuel efficiency2, the price and fuel efficiency of the second car
We simply want to know which car is the better buy. That is the desired output.
H O W T O 1 . 1 Describing an Algorithm with Pseudocode
Before you are ready to write a program in C++, you need to develop an algorithm—a method
for arriving at a solution for a particular problem. Describe the algorithm in pseudocode: a
sequence of precise steps formulated in English.
For example, consider this problem: You have the choice of
buying two cars. One is more fuel efficient than the other, but also
more expensive. You know the price and fuel efficiency (in miles
per gallon, mpg) of both cars. You plan to keep the car for ten
years. Assume a price of $4 per gallon of gas and usage of 15,000
miles per year. You will pay cash for the car and not worry about
financing costs. Which car is the better deal?
WO R K E D E X A M P L E 1 . 1 Writing an Algorithm for Tiling a Floor
This Worked Example shows how to develop an algorithm for laying
tile in an alternating pattern of colors.
Memorable photos reinforce
analogies and help students
remember the concepts.
Example tables support beginners
with multiple, concrete examples.
These tables point out common
errors and present another quick
reference to the section’s topic.
Problem Solving sections teach
techniques for generating ideas and
evaluating proposed solutions, often
using pencil and paper or other
artifacts. These sections emphasize
that most of the planning and problem
solving that makes students successful
happens away from the computer.
How To guides give step-by-step
guidance for common programming
tasks, emphasizing planning and
testing. They answer the beginner’s
question, “Now what do I do?” and
integrate key concepts into a
problem-solving sequence.
Worked Examples apply
the steps in the How To to
a different example, showing
how they can be used to
plan, implement, and test
a solution to another
programming problem.
A recipe for a fruit pie may say to use any kind of fruit.
Here, “fruit” is an example of a parameter variable.
Apples and cherries are examples of arguments.
pie(fruit) pie(fruit)
Next, we swap the coins in positions 1 and 5:
cfe2_fm_pi_xxvi.indd 9 10/28/10 5:08 PM
x Walkthrough
•
Figure 3 Parameter Passing
1 Function call result1 =
side_length =
2 Initializing function parameter variable result1 =
side_length = 2
3 About to return to the caller result1 =
side_length =
volume = 8
2
4 After function call result1 = 8
double result1 = cube_volume(2);
double volume = side_length * side_length * side_length;
return volume;
double result1 = cube_volume(2);
double result1 = cube_volume(2);
The parameter variable side_length of the cube_volume function is created. 1
• The parameter variable is initialized with the value of the argument that was
passed in the call. In our case, side_length is set to 2. 2
• The function computes the expression side_length * side_length * side_length,
which has the value 8. That value is stored in the variable volume. 3
• The function returns. All of its variables are removed. The return value is trans-
ferred to the caller, that is, the function calling the cube_volume function. 4
11. Write the for loop of the invtable.cpp program as a while loop.
12. How many numbers does this loop print?
for (int n = 10; n >= 0; n–)
{
cout << n << endl;
}
13. Write a for loop that prints all even numbers between 10 and 20 (inclusive).
14. Write a for loop that computes the sum of the integers from 1 to n.
15. How would you modify the for loop of the invtable.cpp program to print all bal-
ances until the invest ment has doubled?
Practice It Now you can try these exercises at the end of the chapter: R4.2, R4.7, P4.12.
S E L F C H E C K
ch05/cube.cpp
1 #include
2
3 using namespace std;
4
5 /**
6 Computes the volume of a cube.
7 @param side_length the side length of the cube
8 @return the volume
9 */
10 double cube_volume(double side_length)
11 {
12 double volume = side_length * side_length * side_length;
13 return volume;
14 }
15
16 int main()
17 {
18 double result1 = cube_volume(2);
19 double result2 = cube_volume(10);
20 cout << "A cube with side length 2 has volume " << result1 << endl;
21 cout << "A cube with side length 10 has volume " << result2 << endl;
22
23 return 0;
24 }
Program Run
A cube with side length 2 has volume 8
A cube with side length 10 has volume 1000
Figure 3
Execution of a
for Loop
for (counter = 1; counter <= 10; counter++)
{
cout << counter << endl;
}
Initialize counter1
for (counter = 1; counter <= 10; counter++)
{
cout << counter << endl;
}
Check condition2
for (counter = 1; counter <= 10; counter++)
{
cout << counter << endl;
}
Execute loop body3
for (counter = 1; counter <= 10; counter++)
{
cout << counter << endl;
}
Update counter4
for (counter = 1; counter <= 10; counter++)
{
cout << counter << endl;
}
Check condition again5
counter = 1
counter = 1
counter = 1
counter = 2
counter = 2
Progressive figures trace code
segments to help students visualize
the program flow. Color is used
consistently to make variables and
other elements easily recognizable.
Optional engineering exercises
engage students with applications
from technical fields.
Program listings are carefully
designed for easy reading,
going well beyond simple
color coding. Functions are set
off by a subtle outline.
Self-check exercises at the
end of each section are designed
to make students think through
the new material—and can
spark discussion in lecture.
Engineering P7.20 Write a program that simulates the control
software for a “people mover” system, a set of
driverless trains that move in two concentric
circular tracks. A set of switches allows trains
to switch tracks.
In your program, the outer and inner tracks
should each be divided into ten segments.
Each track segment can contain a train that
moves either clockwise or counterclockwise.
A train moves to an adjacent segment in its track or, if that segment is occupied, to
the adjacent segment in the other track.
Define a Segment structure. Each segment has a pointer to the next and previous
segments in its track, a pointer to the next and previous seg ments in the other track,
cfe2_fm_pi_xxvi.indd 10 10/28/10 5:08 PM
Walkthrough xi
Hand-Tracing
A very useful technique for understanding whether a program
works correctly is called hand-tracing. You simulate the pro-
gram’s activity on a sheet of paper. You can use this method with
pseudocode or C++ code.
Get an index card, a cocktail napkin, or whatever sheet of
paper is within reach. Make a column for each variable. Have the
program code ready. Use a marker, such as a paper clip, to mark
the current statement. In your mind, execute statements one at a
time. Every time the value of a variable changes, cross out the old
value and write the new value below the old one.
For example, let’s trace the tax program with the data from the
program run on page 95. In lines 13 and 14, tax1 and tax2 are initial-
ized to 0.
6 int main()
7 {
8 const double RATE1 = 0.10;
9 const double RATE2 = 0.25;
10 const double RATE1_SINGLE_LIMIT = 32000;
11 const double RATE1_MARRIED_LIMIT = 64000;
12
13 double tax1 = 0;
14 double tax2 = 0;
15
In lines 18 and 22, income and marital_status are
initialized by input statements.
16 double income;
17 cout << "Please enter your income: ";
18 cin >> income;
19
20 cout << "Please enter s for single, m for married: ";
21 string marital_status;
22 cin >> marital_status;
23
Because marital_status is not “s”, we move to the
else branch of the outer if statement (line 36).
Programming Tip 3.6
Hand-tracing helps you
understand whether a
program works correctly.
marital
tax1 tax2 income status
0 0
marital
tax1 tax2 income status
0 0 80000 m
Using Undefined Variables
You must define a variable before you use it for the first time. For example, the following
sequence of statements would not be legal:
double can_volume = 12 * liter_per_ounce;
double liter_per_ounce = 0.0296;
In your program, the statements are compiled in order. When the compiler reaches the first
statement, it does not know that liter_per_ounce will be defined in the next line, and it reports
an error.
Common Error 2.1
Random Facts provide historical and
social information on computing—for
interest and to fulfill the “historical and
social context” requirements of the
ACM/IEEE curriculum guidelines.
According to legend,
the first bug was
found in the Mark II, a huge electrome-
chanical computer at Harvard Univer-
sity. It really was caused by a bug—a
moth was trapped in a relay switch.
Actually, from the note that the
operator left in the log book next to
the moth (see the photo), it appears as
if the term “bug” had already been in
active use at the time.
The First Bug
The pioneering computer scientist
Maurice Wilkes wrote, “Somehow, at
the Moore School and afterwards, one
had always assumed there would be
no particular difficulty in getting pro-
grams right. I can remember the exact
instant in time at which it dawned on
me that a great part of my future life
would be spent finding mistakes in my
own programs.”
Random Fact 4.1 The First Bug
A Sorting Algorithm
A sorting algorithm rearranges the elements of a sequence so that they are stored in sorted
order. Here is a simple sorting algorithm, called selection sort. Consider sorting the following
array values:
[0] [1] [2] [3] [4]
11 9 17 5 12
An obvious first step is to find the smallest element. In this case the smallest element is 5,
stored in values[3]. You should move the 5 to the beginning of the array. Of course, there is
already an element stored in values[0], namely 11. Therefore you cannot simply move val-
ues[3] into values[0] without moving the 11 somewhere else. You don’t yet know where the 11
should end up, but you know for certain that it should not be in values[0]. Simply get it out of
the way by swapping it with values[3]:
5 9 17 11 12
Now the first element is in the correct place. In the foregoing figure, the darker color indicates
the portion of the array that is already sorted.
Next take the minimum of the remaining entries values[1]…values[4]. That minimum
value, 9, is already in the correct place. You don’t need to do anything in this case, simply
extend the sorted area by one to the right:
5 9 17 11 12
Repeat the process. The minimum value of the unsorted region is 11, which needs to be
swapped with the first value of the unsorted region, 17:
5 9 11 17 12
Special Topic 6.2
Special Topics present optional
topics and provide additional
explanation of others.
Common Errors describe the kinds
of errors that students often make,
with an explanation of why the errors
occur, and what to do about them.
Programming Tips explain
good programming practices,
and encourage students to be
more productive with tips and
techniques such as hand-tracing.
cfe2_fm_pi_xxvi.indd 11 10/28/10 5:09 PM
xii Preface
appendices
Appendix A contains a programming style guide. Using a style guide for program-
ming assignments benefits students by directing them toward good habits and reduc-
ing gratuitous choice. The style guide is available in electronic form so that instruc-
tors can modify it to reflect their preferred style.
Appendices B and C summarize C++ reserved words and operators. Appendix D
lists character escape sequences and ASCII character code values. Appendix E docu-
ments all of the library functions and classes used in this book.
Additional appendices available from the book’s companion web site include an
expanded version of Appendix E that includes the functions and classes used in the
four optional chapters, 11–14, plus appendices that cover number systems, bit and
shift operations, and a comparison of C++ and Java.
Student and Instructor resources
The following resources for students and instructors can be obtained by visiting
www.wiley.com/college/horstmann. Two companion web sites accompany the book—
one for students, and a password-protected site for instructors only.
• Additional exercises geared to the scientific and engineering problem domains
• Worked Examples that apply the problem-solving steps in the book to other
realistic examples (identified in the book by an icon, )
• Source code for all examples in the book
• Solutions to all review and programming exercises (for instructors only)
• Lecture presentation slides (in PowerPoint format) that summarize each chapter
and include code listings and figures from the book (for instructors only)
• A test bank that focuses on skills, not just terminology (for instructors only)
• Four additional chapters on recursion, sorting and searching, and data structures
• The programming style guide in electronic form
W O R K E D E X A M P L E 2 . 1 Computing Travel Time
In this Worked Example, we develop a hand calculation to compute
the time that a robot requires to retrieve an item from rocky terrain.
Pointers in the book
describe what students
will find on the Web.
Visit the C++ for Everyone companion web sites at www.wiley.com/college/horstmann.
cfe2_fm_pi_xxvi.indd 12 10/28/10 5:09 PM
www.wiley.com/college/horstmann
www.wiley.com/college/horstmann
acknowledgments xiii
acknowledgments
Many thanks to Beth Golub, Tom Kulesa, Andre Legaspi, Elizabeth Mills, Michael
Berlin, and Lisa Gee at John Wiley & Sons, and to the team at Publishing Services for
their hard work and sup port for this book project. An especially deep acknowledg-
ment and thanks to Cindy Johnson, who, through enormous patience and attention
to detail, made this book a reality. We would also like to thank Jonathan Tolstedt,
North Dakota State University, for his high-quality solutions; Brent Seales, Univer-
sity of Kentucky, for revising and enhancing the test bank; and to Evan Gallagher,
Polytechnic Institute of New York University, for his creative PowerPoint slides.
We are very grateful to the many individuals who reviewed and/or class tested
this and the first edition of the book. We value their many valuable suggestions for
improvement. They include:
Charles D. Allison, Utah Valley State College
Fred Annexstein, University of Cincinnati
Stefano Basagni, Northeastern University
Noah D. Barnette, Virginia Tech
Susan Bickford, Tallahassee Community College
Ronald D. Bowman, University of Alabama, Huntsville
Peter Breznay, University of Wisconsin, Green Bay
Richard Cacace, Pensacola Junior College, Pensacola
Kuang-Nan Chang, Eastern Kentucky University
Joseph DeLibero, Arizona State University
Subramaniam Dharmarajan, Arizona State University
Mary Dorf, University of Michigan
Marty Dulberg, North Carolina State University
William E. Duncan, Louisiana State University
John Estell, Ohio Northern University
Waleed Farag, Indiana University of Pennsylvania
Stephen Gilbert, Orange Coast Community College
Kenneth Gitlitz, New Hampshire Technical Institute
Daniel Grigoletti, DeVry Institute of Technology, Tinley Park
Barbara Guillott, Louisiana State University
Charles Halsey, Richland College
Jon Hanrath, Illinois Institute of Technology
Neil Harrison, Utah Valley University
Jurgen Hecht, University of Ontario
Steve Hodges, Cabrillo College
Jackie Jarboe, Boise State University
Debbie Kaneko, Old Dominion University
Mir Behrad Khamesee, University of Waterloo
Sung-Sik Kwon, North Carolina Central University
cfe2_fm_pi_xxvi.indd 13 10/28/10 5:09 PM
xiv acknowledgments
Lorrie Lehman, University of North Carolina, Charlotte
Cynthia Lester, Tuskegee University
Yanjun Li, Fordham University
W. James MacLean, University of Toronto
LindaLee Massoud, Mott Community College
Charles W. Mellard, DeVry Institute of Technology, Irving
Ethan V. Munson, University of Wisconsin, Milwaukee
Philip Regalbuto, Trident Technical College
Don Retzlaff, University of North Texas
Jeff Ringenberg, University of Michigan, Ann Arbor
John P. Russo, Wentworth Institute of Technology
Kurt Schmidt, Drexel University
Brent Seales, University of Kentucky
William Shay, University of Wisconsin, Green Bay
Michele A. Starkey, Mount Saint Mary College
William Stockwell, University of Central Oklahoma
Jonathan Tolstedt, North Dakota State University
Boyd Trolinger, Butte College
Muharrem Uyar, City College of New York
Mahendra Velauthapillai, Georgetown University
Kerstin Voigt, California State University, San Bernardino
David P. Voorhees, Le Moyne College
Salih Yurttas, Texas A&M University
A special thank you to all of our class testers:
Pani Chakrapani and the students of the University of Redlands
Jim Mackowiak and the students of Long Beach City College, LAC
Suresh Muknahallipatna and the students of the University of Wyoming
Murlidharan Nair and the students of the Indiana University of South Bend
Harriette Roadman and the students of New River Community College
David Topham and the students of Ohlone College
Dennie Van Tassel and the students of Gavilan College
cfe2_fm_pi_xxvi.indd 14 10/28/10 5:09 PM
C o n T E n T S
xv
PrEfaCE v
SPECIaL fEaTurES xx
InTroDuCTIon 1
1.1 What is Programming 2
1.2 The anatomy of a Computer 3
1.3 Machine Code and Programming Languages 6
1.4 Becoming familiar with your Programming Environment 7
1.5 analyzing your first Program 11
1.6 Errors 15
1.7 Problem Solving: algorithm Design 17
funDaMEnTaL DaTa TyPES 29
2.1 variables 30
2.2 arithmetic 40
2.3 Input and output 48
2.4 Problem Solving: first Do It By Hand 52
2.5 Strings 56
DECISIonS 75
3.1 The if Statement 76
3.2 Comparing numbers and Strings 82
3.3 Multiple alternatives 90
3.4 nested Branches 94
3.5 Problem Solving: flowcharts 99
3.6 Problem Solving: Test Cases 102
3.7 Boolean variables and operators 103
3.8 application: Input validation 109
LooPS 131
4.1 The while Loop 132
4.2 Problem Solving: Hand-Tracing 139
4.3 The for Loop 142
4.4 The do Loop 148
4.5 Processing Input 150
cHAPter 1
cHAPter 2
cHAPter 3
cHAPter 4
cfe2_fm_pi_xxvi.indd 15 10/28/10 5:09 PM
xvi Contents
4.6 Problem Solving: Storyboards 154
4.7 Common Loop algorithms 157
4.8 nested Loops 165
4.9 random numbers and Simulations 168
funCTIonS 193
5.1 functions as Black Boxes 194
5.2 Implementing functions 196
5.3 Parameter Passing 199
5.4 return values 202
5.5 functions Without return values 206
5.6 Problem Solving: reusable functions 208
5.7 Problem Solving: Stepwise refinement 210
5.8 variable Scope and Global variables 218
5.9 reference Parameters 220
5.10 recursive functions (optional) 226
arrayS anD vECTorS 249
6.1 arrays 250
6.2 Common array algorithms 256
6.3 arrays and functions 265
6.4 Problem Solving: adapting algorithms 269
6.5 Problem Solving: Discovering algorithms by Manipulating
Physical objects 274
6.6 Two-Dimensional arrays 278
6.7 vectors 284
PoInTErS 307
7.1 Defining and using Pointers 308
7.2 arrays and Pointers 314
7.3 C and C++ Strings 320
7.4 Dynamic Memory allocation 325
7.5 arrays and vectors of Pointers 329
7.6 Problem Solving: Draw a Picture 332
7.7 Structures and Pointers (optional) 336
STrEaMS 351
8.1 reading and Writing Text files 352
8.2 reading Text Input 358
cHAPter 5
cHAPter 6
cHAPter 7
cHAPter 8
cfe2_fm_pi_xxvi.indd 16 10/28/10 5:09 PM
Contents xvii
Available online at www.wiley.com/college/horstmann.
8.3 Writing Text output 361
8.4 String Streams 363
8.5 Command Line arguments 365
8.6 random access and Binary files 372
CLaSSES 389
9.1 object-oriented Programming 390
9.2 Specifying the Public Interface of a Class 392
9.3 Data Members 395
9.4 Member functions 397
9.5 Constructors 403
9.6 Problem Solving: Tracing objects 407
9.7 Problem Solving: Discovering Classes 414
9.8 Separate Compilation 417
9.9 Pointers to objects 422
InHErITanCE 441
10.1 Inheritance Hierarchies 442
10.2 Implementing Derived Classes 446
10.3 overriding Member functions 451
10.4 virtual functions and Polymorphism 455
rECurSIon (WEB onLy)
11.1 Triangle numbers
11.2 Thinking recursively
11.3 recursive Helper functions
11.4 The Efficiency of recursion
11.5 Permutations
11.6 Mutual recursion
SorTInG anD SEarCHInG (WEB onLy)
12.1 Selection Sort
12.2 Profiling the Selection Sort algorithm
12.3 analyzing the Performance of the Selection Sort algorithm
12.4 Merge Sort
12.5 analyzing the Merge Sort algorithm
12.6 Searching
cHAPter 9
cHAPter 10
cHAPter 11
cHAPter 12
cfe2_fm_pi_xxvi.indd 17 10/28/10 5:09 PM
www.wiley.com/college/horstmann
xviii Contents
Available online at www.wiley.com/college/horstmann.
LISTS, STaCkS, anD QuEuES (WEB onLy)
13.1 using Linked Lists
13.2 Implementing Linked Lists
13.3 The Efficiency of List, array, and vector operations
13.4 Stacks and Queues
SETS, MaPS, anD PrIorITy QuEuES (WEB onLy)
14.1 Sets
14.2 Binary Search Trees
14.3 Maps
14.4 Priority Queues
14.5 Heaps
aPPEnDIx a C++ LanGuaGE CoDInG GuIDELInES 481
aPPEnDIx B rESErvED WorD SuMMary 489
aPPEnDIx C oPEraTor SuMMary 491
aPPEnDIx D CHaraCTEr CoDES 493
aPPEnDIx E C++ LIBrary SuMMary 495
aPPEnDIx f nuMBEr SySTEMS (WEB onLy)
aPPEnDIx G BIT anD SHIfT oPEraTIonS (WEB onLy)
aPPEnDIx H a C++ / Java CoMParISon (WEB onLy)
GLoSSary 499
InDEx 507
CrEDITS 529
cHAPter 13
cHAPter 14
APPendiceS
cfe2_fm_pi_xxvi.indd 18 10/28/10 5:09 PM
www.wiley.com/college/horstmann
Contents xix
SynTax BoxES
assignment 34
C++ Program 12
Class Definition 393
Comparisons 83
Constructor with Base-Class Initializer 451
Defining an array 251
Defining a vector 285
Derived-Class Definition 448
Dynamic Memory allocation 325
for Statement 144
function Definition 197
if Statement 78
Input Statement 48
Member function Definition 400
output Statement 13
Pointer Syntax 310
Two-Dimensional array Definition 279
variable Definition 31
while Statement 133
Working with file Streams 354
AlPHAbeticAl liSt oF
cfe2_fm_pi_xxvi.indd 19 10/28/10 5:09 PM
xx Special features
C H a P T E r
Available online at www.wiley.com/college/horstmann.
Programming
Tips
Special Topics random facts
Backup Copies 11 Escape Sequences 14 The EnIaC and the Dawn
of Computing 5
Standards organizations 7
Choose Descriptive variable
names 38
Do not use Magic numbers 39
Spaces in Expressions 46
numeric Types in C++ 38
numeric ranges and
Precisions 39
Casts 46
Combining assignment
and arithmetic 47
The Pentium floating-Point
Bug 47
International alphabets
and unicode 61
Brace Layout 79
always use Braces 80
Tabs 81
avoid Duplication in Branches 82
Compile With Zero Warnings 85
Hand-Tracing 97
Make a Schedule and
Make Time for unexpected
Problems 103
The Selection operator 81
Lexicographic ordering
of Strings 86
The switch Statement 93
Short-Circuit Evaluation
of Boolean operators 108
De Morgan’s Law 108
The Denver airport
Luggage Handling System 89
artificial Intelligence 112
use for Loops for Their
Intended Purpose only 147
Choose Loop Bounds That
Match your Task 147
Count Iterations 147
flowcharts for Loops 149
Clearing the failure State 153
The Loop-and-a-Half Problem
and the break Statement 153
redirection of Input and
output 154
The first Bug 138
Software Piracy 172
function Comments 199
Don’t Modify Parameter
variables 201
keep functions Short 216
Tracing functions 216
Stubs 217
avoid Global variables 220
Prefer return values to
reference Parameters 225
function Declarations 203
Constant references 225
The Explosive Growth of
Personal Computers 230
Common
Errors
How Tos
and
Worked Examples
1 Introduction omitting Semicolons 14
Misspelling Words 16
Describing an algorithm with
Pseudocode 20
Writing an algorithm for Tiling
a floor
2 fundamental
Data Types
using undefined variables 37
using uninitialized variables 37
unintended Integer Division 43
unbalanced Parentheses 44
forgetting Header files 45
roundoff Errors 45
Computing Travel Time
Carrying out Computations 54
Computing the Cost
of Stamps
3 Decisions a Semicolon after the
if Condition 80
Confusing = and == 85
Exact Comparison of floating-
Point numbers 86
The Dangling else Problem 98
Combining Multiple
relational operators 107
Confusing && and ||
Conditions 107
Implementing an if
Statement 87
Extracting the Middle
4 Loops Infinite Loops 136
Don’t Think “are We
There yet?” 137
off-by-one Errors 137
Writing a Loop 162
Credit Card Processing
5 functions Missing return value 203
Implementing a function 204
Matching and replacing Parts
of a String
using a Debugger
Calculating a Course Grade
Thinking recursively 229
cfe2_fm_pi_xxvi.indd 20 10/28/10 5:09 PM
www.wiley.com/college/horstmann
Special Features xxi
Available online at www.wiley.com/college/horstmann.
Programming
Tips
Special Topics Random Facts
Backup Copies 11 Escape Sequences 14 The ENIAC and the Dawn
of Computing 5
Standards Organizations 7
Choose Descriptive Variable
Names 38
Do Not Use Magic Numbers 39
Spaces in Expressions 46
Numeric Types in C++ 38
Numeric Ranges and
Precisions 39
Casts 46
Combining Assignment
and Arithmetic 47
The Pentium Floating-Point
Bug 47
International Alphabets
and Unicode 61
Brace Layout 79
Always Use Braces 80
Tabs 81
Avoid Duplication in Branches 82
Compile With Zero Warnings 85
Hand-Tracing 97
Make a Schedule and
Make Time for Unexpected
Problems 103
The Selection Operator 81
Lexicographic Ordering
of Strings 86
The switch Statement 93
Short-Circuit Evaluation
of Boolean Operators 108
De Morgan’s Law 108
The Denver Airport
Luggage Handling System 89
Artificial Intelligence 112
Use for Loops for Their
Intended Purpose Only 147
Choose Loop Bounds That
Match Your Task 147
Count Iterations 147
Flowcharts for Loops 149
Clearing the Failure State 153
The Loop-and-a-Half Problem
and the break Statement 153
Redirection of Input and
Output 154
The First Bug 138
Software Piracy 172
Function Comments 199
Don’t Modify Parameter
Variables 201
Keep Functions Short 216
Tracing Functions 216
Stubs 217
Avoid Global Variables 220
Prefer Return Values to
Reference Parameters 225
Function Declarations 203
Constant References 225
The Explosive Growth of
Personal Computers 230
Common
Errors
How Tos
and
Worked Examples
1 Introduction Omitting Semicolons 14
Misspelling Words 16
Describing an Algorithm with
Pseudocode 20
Writing an Algorithm for Tiling
a Floor
2 Fundamental
Data Types
Using Undefined Variables 37
Using Uninitialized Variables 37
Unintended Integer Division 43
Unbalanced Parentheses 44
Forgetting Header Files 45
Roundoff Errors 45
Computing Travel Time
Carrying out Computations 54
Computing the Cost
of Stamps
3 Decisions A Semicolon After the
if Condition 80
Confusing = and == 85
Exact Comparison of Floating-
Point Numbers 86
The Dangling else Problem 98
Combining Multiple
Relational Operators 107
Confusing && and ||
Conditions 107
Implementing an if
Statement 87
Extracting the Middle
4 Loops Infinite Loops 136
Don’t Think “Are We
There Yet?” 137
Off-by-One Errors 137
Writing a Loop 162
Credit Card Processing
5 Functions Missing Return Value 203
Implementing a Function 204
Matching and Replacing Parts
of a String
Using a Debugger
Calculating a Course Grade
Thinking Recursively 229
cfe2_fm_pi_xxvi.indd 21 11/9/10 9:55 AM
www.wiley.com/college/horstmann
xxii Special features
C H a P T E r
Available online at www.wiley.com/college/horstmann.
Programming
Tips
Special Topics random facts
use arrays for Sequences
of related values 255
Prefer vectors over arrays 289
Sorting with the C++ Library 263
a Sorting algorithm 263
Binary Search 264
Constant array Parameters 269
an Early Internet Worm 255
The first Programmer 290
use a Separate Definition for
Each Pointer variable 313
Program Clearly,
not Cleverly 319
Pointers and references 314
using a Pointer to Step
Through an array 318
Constant Pointers 320
Working with C Strings 323
Embedded Systems 336
Encryption algorithms 368
Databases and Privacy 377
all Data Members Should
Be Private; Most
Member functions
Should Be Public 402
const Correctness 402
Make Parallel vectors into
vectors of objects 416
Initializer Lists 405
overloading 406
Destructors and resource
Management 424
Electronic voting Machines 412
open Source and
free Software 426
use a Single Class for variation
in values, Inheritance for
variation in Behavior 450
Don’t use Type Tags 462
Calling the Base-Class
Constructor 451
virtual Self-Calls 463
The Limits of Computation 469
Common
Errors
How Tos
and
Worked Examples
6 arrays and vectors Bounds Errors 254
omitting the Column
Size of a Two-
Dimensional array
Parameter 284
Working with arrays 271
rolling the Dice
a World Population Table
7 Pointers Confusing Pointers
with the Data to
Which They Point 313
returning a Pointer to
a Local variable 319
Dangling Pointers 328
Memory Leaks 328
Working with Pointers 334
Producing a Mass Mailing
8 Streams Processing Text files 369
Looking for for
Duplicates
9 Classes forgetting a Semicolon 395
Trying to Call a Constructor 405
Implementing a Class 409
Implementing a
Bank account Class
10 Inheritance Private Inheritance 449
replicating Base-Class
Members 450
forgetting the Base-
Class name 455
Slicing an object 462
Developing an
Inheritance Hierarchy 464
Implementing an
Employee Hierarchy for
Payroll Processing
cfe2_fm_pi_xxvi.indd 22 10/28/10 5:09 PM
www.wiley.com/college/horstmann
Special Features xxiii
Available online at www.wiley.com/college/horstmann.
Programming
Tips
Special Topics Random Facts
Use Arrays for Sequences
of Related Values 255
Prefer Vectors over Arrays 289
Sorting with the C++ Library 263
A Sorting Algorithm 263
Binary Search 264
Constant Array Parameters 269
An Early Internet Worm 255
The First Programmer 290
Use a Separate Definition for
Each Pointer Variable 313
Program Clearly,
Not Cleverly 319
Pointers and References 314
Using a Pointer to Step
Through an Array 318
Constant Pointers 320
Working with C Strings 323
Embedded Systems 336
Encryption Algorithms 368
Databases and Privacy 377
All Data Members Should
Be Private; Most
Member Functions
Should Be Public 402
const Correctness 402
Make Parallel Vectors into
Vectors of Objects 416
Initializer Lists 405
Overloading 406
Destructors and Resource
Management 424
Electronic Voting Machines 412
Open Source and
Free Software 426
Use a Single Class for Variation
in Values, Inheritance for
Variation in Behavior 450
Don’t Use Type Tags 462
Calling the Base-Class
Constructor 451
Virtual Self-Calls 463
The Limits of Computation 469
Common
Errors
How Tos
and
Worked Examples
6 Arrays and Vectors Bounds Errors 254
Omitting the Column
Size of a Two-
Dimensional Array
Parameter 284
Working with Arrays 271
Rolling the Dice
A World Population Table
7 Pointers Confusing Pointers
with the Data to
Which They Point 313
Returning a Pointer to
a Local Variable 319
Dangling Pointers 328
Memory Leaks 328
Working with Pointers 334
Producing a Mass Mailing
8 Streams Processing Text Files 369
Looking for for
Duplicates
9 Classes Forgetting a Semicolon 395
Trying to Call a Constructor 405
Implementing a Class 409
Implementing a
Bank Account Class
10 Inheritance Private Inheritance 449
Replicating Base-Class
Members 450
Forgetting the Base-
Class Name 455
Slicing an Object 462
Developing an
Inheritance Hierarchy 464
Implementing an
Employee Hierarchy for
Payroll Processing
cfe2_fm_pi_xxvi.indd 23 11/9/10 9:55 AM
www.wiley.com/college/horstmann
xxiv Special features
C H a P T E r
Available online at www.wiley.com/college/horstmann.
Programming
Tips
Special Topics random facts
Library functions for Sorting
and Binary Search
The Quicksort algorithm
Defining an ordering for
Sorting objects
Cataloging your necktie
Collection
reverse Polish notation
Defining an ordering for
Container Elements
Constant Iterators
Discrete Event Simulations
Common
Errors
How Tos
and
Worked Examples
11 recursion (WEB onLy) Infinite recursion
Tracing Through recursive
functions
12 Sorting and Searching
(WEB onLy)
13 Lists, Stacks, and
Queues (WEB onLy)
14 Sets, Maps, and Priority
Queues (WEB onLy)
cfe2_fm_pi_xxvi.indd 24 10/28/10 5:09 PM
www.wiley.com/college/horstmann
Special Features xxv
Available online at www.wiley.com/college/horstmann.
Programming
Tips
Special Topics Random Facts
Library Functions for Sorting
and Binary Search
The Quicksort Algorithm
Defining an Ordering for
Sorting Objects
Cataloging Your Necktie
Collection
Reverse Polish Notation
Defining an Ordering for
Container Elements
Constant Iterators
Discrete Event Simulations
Common
Errors
How Tos
and
Worked Examples
11 Recursion (WEB ONLY) Infinite Recursion
Tracing Through Recursive
Functions
12 Sorting and Searching
(WEB ONLY)
13 Lists, Stacks, and
Queues (WEB ONLY)
14 Sets, Maps, and Priority
Queues (WEB ONLY)
cfe2_fm_pi_xxvi.indd 25 11/9/10 9:56 AM
www.wiley.com/college/horstmann
This page intentionally left blank
1C h a p t e r
1
I n t r o d u C t I o n
to learn about the architecture of
computers
to learn about machine languages and
higher-level programming languages
to become familiar with your compiler
to compile and run your first C++ program
to recognize compile-time and run-time errors
to describe an algorithm with pseudocode
to understand the activity of programming
C h a p t e r G o a l s
C h a p t e r C o n t e n t s
1.1 What Is ProgrammIng? 2
1.2 the anatomy of a ComPuter 3
Random Fact 1.1: the enIaC and the dawn of
Computing 5
1.3 maChIne Code and ProgrammIng
Languages 6
Random Fact 1.2: standards organizations 7
1.4 BeComIng famILIar WIth your
ProgrammIng envIronment 7
Programming Tip 1.1: Backup Copies 11
1.5 anaLyzIng your fIrst
Program 11
Syntax 1.1: C++ program 12
Syntax 1.2: output statement 13
Common Error 1.1: omitting semicolons 14
Special Topic 1.1: escape sequences 14
1.6 errors 15
Common Error 1.2: Misspelling Words 16
1.7 ProBLem soLvIng: aLgorIthm
desIgn 17
How To 1.1: describing an algorithm with
pseudocode 20
Worked Example 1.1: Writing an algorithm for
tiling a Floor
cfe2_ch01_p1_28.indd 1 10/25/10 1:03 PM
2
Just as you gather tools, study a project, and make a plan for
tackling it, in this chapter you will gather up the basics you
need to start learning to program. after a brief introduction
to computer hardware, software, and programming in
general, you will learn how to write and run your first
C++ program. You will also learn how to diagnose and
fix programming errors, and how to use pseudocode to
describe an algorithm—a step-by-step description of how
to solve a problem—as you plan your programs.
1.1 What Is programming?
You have probably used a computer for work or fun. Many people use computers for
everyday tasks such as electronic banking or writing a term paper. Computers are
good for such tasks. They can handle repetitive chores, such as totaling up numbers
or placing words on a page, without getting bored or exhausted.
The flexibility of a computer is quite an amazing phenomenon. The same machine
can balance your checkbook, print your term paper, and play a game. In contrast,
other machines carry out a much nar rower range of tasks; a car drives and a toaster
toasts. Computers can carry out a wide range of tasks because they execute different
programs, each of which directs the computer to work on a specific task.
The computer itself is a machine that stores data (numbers, words, pictures), inter-
acts with devices (the monitor, the sound system, the printer), and executes programs.
A computer program tells a computer, in minute detail, the sequence of steps that are
needed to fulfill a task. The physical computer and peripheral devices are collectively
called the hardware. The programs the computer executes are called the software.
Today’s computer programs are so sophisticated that it is hard to believe that they
are composed of extremely primitive operations. A typical operation may be one of
the following:
• Put a red dot at this screen position.
• Add up these two numbers.
• If this value is negative, continue the program at a certain instruction.
The computer user has the illusion of smooth interaction because a program contains
a huge number of such operations, and because the computer can execute them at
great speed.
The act of designing and implementing computer programs is called program-
ming. In this book, you will learn how to program a computer—that is, how to direct
the computer to execute tasks.
To write a computer game with motion and sound effects or a word processor
that supports fancy fonts and pictures is a complex task that requires a team of many
highly skilled programmers. Your first programming efforts will be more mundane.
The concepts and skills you learn in this book form an important foundation, and
you should not be disappointed if your first programs do not rival the sophis ticated
software that is familiar to you. Actually, you will find that there is an immense thrill
even in sim ple programming tasks. It is an amazing experience to see the computer
precisely and quickly carry out a task that would take you hours of drudgery, to
Computers execute
very basic
instructions in
rapid succession.
a computer program
is a sequence
of instructions
and decisions.
programming is the
act of designing and
implementing
computer programs.
make small changes in a program that lead to immediate improvements, and to see the
computer become an extension of your mental powers.
1. What is required to play music on a computer?
2. Why is a CD player less flexible than a computer?
3. What does a computer user need to know about programming in order to play a
video game?
Practice It Now you can try these exercises at the end of the chapter: R1.1, R1.4.
1.2 the anatomy of a Computer
To understand the programming process, you need to have a rudimentary under-
standing of the building blocks that make up a computer. We will look at a personal
computer. Larger computers have faster, larger, or more powerful components, but
they have fundamentally the same design.
At the heart of the computer lies the central processing unit (CPU) (see Figure 1).
It consists of a sin gle chip, or a small number of chips. A computer chip (integrated
circuit) is a component with a plastic or metal housing, metal connectors, and inside
wiring made principally from silicon. For a CPU chip, the inside wiring is enor-
mously complicated. For example, the Pentium chip (a popular CPU for personal
computers at the time of this writing) is composed of several million structural ele-
ments, called transistors.
The CPU performs program control and data processing. That is, the CPU locates
and executes the program instructions; it carries out arithmetic operations such as
addition, subtraction, multiplication, and division; it fetches data from external mem-
ory or devices and stores data back.
The computer stores data and programs. There are two kinds of storage. Primary
storage is made from memory chips: electronic circuits that can store data, provided
they are supplied with electric power. Secondary storage, usually a hard disk, pro-
vides less expensive storage that persists without elec tricity. A hard disk consists of
rotating platters, which are coated with a magnetic material, and read/write heads,
which can detect and change the magnetic flux on the platters (see Figure 2).
s e L f C h e C k
the central
processing unit (Cpu)
performs program
control and
data processing.
storage devices
include memory and
secondary storage.
figure 1
Central processing unit
cfe2_ch01_p1_28.indd 2 10/25/10 1:03 PM
1.2 the anatomy of a Computer 3
make small changes in a program that lead to immediate improvements, and to see the
computer become an extension of your mental powers.
1. What is required to play music on a computer?
2. Why is a CD player less flexible than a computer?
3. What does a computer user need to know about programming in order to play a
video game?
Practice It Now you can try these exercises at the end of the chapter: R1.1, R1.4.
1.2 the anatomy of a Computer
To understand the programming process, you need to have a rudimentary under-
standing of the building blocks that make up a computer. We will look at a personal
computer. Larger computers have faster, larger, or more powerful components, but
they have fundamentally the same design.
At the heart of the computer lies the central processing unit (CPU) (see Figure 1).
It consists of a sin gle chip, or a small number of chips. A computer chip (integrated
circuit) is a component with a plastic or metal housing, metal connectors, and inside
wiring made principally from silicon. For a CPU chip, the inside wiring is enor-
mously complicated. For example, the Pentium chip (a popular CPU for personal
computers at the time of this writing) is composed of several million structural ele-
ments, called transistors.
The CPU performs program control and data processing. That is, the CPU locates
and executes the program instructions; it carries out arithmetic operations such as
addition, subtraction, multiplication, and division; it fetches data from external mem-
ory or devices and stores data back.
The computer stores data and programs. There are two kinds of storage. Primary
storage is made from memory chips: electronic circuits that can store data, provided
they are supplied with electric power. Secondary storage, usually a hard disk, pro-
vides less expensive storage that persists without elec tricity. A hard disk consists of
rotating platters, which are coated with a magnetic material, and read/write heads,
which can detect and change the magnetic flux on the platters (see Figure 2).
s e L f C h e C k
the central
processing unit (Cpu)
performs program
control and
data processing.
storage devices
include memory and
secondary storage.
figure 1
Central processing unit
cfe2_ch01_p1_28.indd 3 10/25/10 1:03 PM
4 Chapter 1 Introduction
figure 2
a hard disk
Programs and data are typically stored on the hard disk and loaded into memory
when the program starts. The program then updates the data in memory and writes
the modified data back to the hard disk.
To interact with a human user, a computer requires peripheral devices. The com-
puter transmits infor mation (called output) to the user through a display screen,
speakers, and printers. The user can enter information (called input) by using a key-
board or a pointing device such as a mouse.
Some computers are self-contained units, whereas others are interconnected
through networks. Through the network cabling, the computer can read data and
programs from central storage locations or send data to other computers. For the
user of a networked computer it may not even be obvious which data reside on the
computer itself and which are transmitted through the network.
figure 3 schematic design of a personal Computer
Printer
Mouse
Keyboard
Ports
CPU
Memory
Disk
Controller
Hard disk
CD/DVD drive
Monitor
Speakers
Internet
Graphics
card
Sound
card
Network
card
cfe2_ch01_p1_28.indd 4 10/25/10 1:03 PM
1.2 the anatomy of a Computer 5
Figure 3 gives a schematic overview of the architecture of a personal computer.
Program instructions and data (such as text, numbers, audio, or video) are stored on
the hard disk, on an optical disk such as a DVD, or elsewhere on the network. When
a program is started, it is brought into memory, where the CPU can read it. The CPU
reads the program one instruction at a time. As directed by these instructions, the
CPU reads data, modifies it, and stores it. Some program instructions will cause the
CPU to place dots on the display screen or printer or to vibrate the speaker. As these
actions happen many times over and at great speed, the human user perceives images
and sound. Some program instructions read user input from the keyboard or mouse.
The program analyzes the nature of these inputs and then executes the next appropri-
ate instruction.
4. Where is a program stored when it is not currently running?
5. Which part of the computer carries out arithmetic operations, such as addition
and multiplication?
Practice It Now you can try these exercises at the end of the chapter: R1.2, R1.3.
s e L f C h e C k
the enIaC (electronic
numerical integrator
and computer) was the first usable
electronic computer. It was designed
by J. presper eckert and John Mauchly
at the university of pennsylvania and
was completed in 1946—two years
before transistors were invented. the
computer was housed in a large room
and consisted of many cabinets con-
taining about 18,000 vacuum tubes
(see Figure 2). Vacuum tubes burned
out at the rate of several tubes per day.
an attendant with a shopping cart full
of tubes constantly made the rounds
and replaced defective ones. the com-
puter was programmed by connecting
wires on panels. each wir ing configura-
tion would set up the computer for a
particular problem. to have the com-
puter work on a different problem, the
wires had to be replugged.
Work on the enIaC was supported
by the u.s. army, which was interested
in computations of ballistic tables that
would give the trajectory of a projec-
tile, depending on the wind resis tance,
initial velocity, and atmospheric con-
ditions. to compute the trajecto ries,
one must find the numerical solu-
tions of certain differential equations;
hence the name “numerical integra-
tor”. Before machines like the enIaC
were developed, humans did this kind
of work, and until the 1950s the word
“computer” referred to these people.
the enIaC was later used for peace-
ful purposes, such as the tabulation of
u.s. Census data.
figure 4 the enIaC
Random Fact 1.1 the enIaC and the dawn of Computing
cfe2_ch01_p1_28.indd 5 10/25/10 1:03 PM
6 Chapter 1 Introduction
1.3 Machine Code and programming languages
On the most basic level, computer instructions are extremely primitive. The proces-
sor executes machine instructions. A typical sequence of machine instructions is
1. Move the contents of memory location 40000 into the CPU.
2. If that value is > 100, continue with the instruction that is stored in memory
location 11280.
Actually, machine instructions are encoded as numbers so that they can be stored in
memory. On a Pen tium processor, this sequence of instruction is encoded as the
sequence of numbers
161 40000 45 100 127 11280
On a processor from a different manufacturer, the encoding would be different.
When this kind of pro cessor fetches this sequence of numbers, it decodes them and
executes the associated sequence of com mands.
How can we communicate the command sequence to the computer? The simplest
method is to place the actual numbers into the computer memory. This is, in fact,
how the very earliest computers worked. However, a long program is composed of
thousands of individual commands, and it is a tedious and error-prone affair to look
up the numeric codes for all commands and place the codes manually into memory.
As already mentioned, computers are really good at automating tedious and error-
prone activi ties. It did not take long for computer scientists to realize that the com-
puters themselves could be har nessed to help in the programming process.
Computer scientists devised high level programming
lan guages that allow programmers to describe tasks,
using a syn tax that is more closely related to the prob-
lems to be solved. In this book, we will use the C++
programming language, which was developed by Bjarne
Stroustrup in the 1980s.
Over the years, C++ has grown by the addition of
many features. A standardization process culminated
in the publi cation of the international C++ standard
in 1998. A minor update to the standard was issued in
2003, and a major revi sion is expected to come to fruition
around 2011. At this time, C++ is the most commonly
used language for develop ing system software such as
databases and operating systems. Just as importantly, C++ is increasingly used for
program ming “embedded systems”, small computers that control devices such as
automobile engines or cellular telephones.
Here is a typical statement in C++:
if (int_rate > 100) { cout << "Interest rate error"; }
This means, “If the interest rate is over 100, display an error message”. A special com-
puter program, a compiler, translates this high-level description into machine instruc-
tions for a particular processor.
High-level languages are independent of the underlying hardware. C++ instruc-
tions work equally well on an Intel Pentium and a processor in a cell phone. Of
course, the compiler-generated machine instruc tions are different, but the program-
mer who uses the compiler need not worry about these differences.
Computer programs
are stored as machine
instructions in a code
that depends on the
processor type.
Bjarne Stroustrup
C++ is a general-
purpose language
that is in widespread
use for systems
and embedded
programming.
high-level
programming
languages are
independent of
the processor.
6. Is the compiler a part of the computer hardware or software?
7. Does a person who uses a computer for office work ever run a compiler?
8. What are the most important uses for C++?
Practice It Now you can try these exercises at the end of the chapter: R1.5.
1.4 Becoming Familiar with Your
programming environment
Many students find that the tools they need as programmers are very different from
the software with which they are familiar. You should spend some time making your-
self familiar with your programming environment. Because computer systems vary
widely, this book can only give an outline of the steps you need to follow. It is a good
idea to participate in a hands-on lab, or to ask a knowledgeable friend to give you a
tour.
step 1 Start the C++ development environment.
Computer systems differ greatly in this regard. On many computers there is an inte-
grated development environment in which you can write and test your programs.
On other computers you first launch an editor, a program that functions like a word
processor, in which you can enter your C++ instructions; then open a console win-
dow and type commands to execute your program. You need to find out how to get
started with your environment.
step 2 Write a simple program.
The traditional choice for the very first program in a new programming language is a
program that dis plays a simple greeting: “Hello, World!”. Let us follow that tradi-
tion. Here is the “Hello, World!” pro gram in C++:
s e L f C h e C k
two standards orga-
nizations, the ameri-
can national standards Institute (ansI)
and the International organization for
standardization (Iso), have jointly
developed the definitive standard for
the C++ language.
Why have standards? You encoun ter
the benefits of standardization every
day. When you buy a light bulb, you
can be assured that it fits in the socket
without having to measure the socket
at home and the bulb in the store. In
fact, you may have experi enced how
painful the lack of stan dards can be if
you have ever purchased a flashlight
with nonstand ard bulbs. replacement
bulbs for such a flashlight can be dif-
ficult and expen sive to obtain.
the ansI and Iso standards organi-
zations are associations of industry
professionals who develop standards
for everything from car tires and
credit card shapes to programming
languages. having a standard for a
programming language such as C++
means that you can take a program
that you developed on one system
with one manufacturer’s compiler to a
different system and be assured that it
will continue to work.
Random Fact 1.2 standards organizations
set aside some time
to become familiar
with the programming
environment that you
will use for your
class work.
cfe2_ch01_p1_28.indd 6 10/25/10 1:03 PM
1.4 Becoming Familiar with Your programming environment 7
6. Is the compiler a part of the computer hardware or software?
7. Does a person who uses a computer for office work ever run a compiler?
8. What are the most important uses for C++?
Practice It Now you can try these exercises at the end of the chapter: R1.5.
1.4 Becoming Familiar with Your
programming environment
Many students find that the tools they need as programmers are very different from
the software with which they are familiar. You should spend some time making your-
self familiar with your programming environment. Because computer systems vary
widely, this book can only give an outline of the steps you need to follow. It is a good
idea to participate in a hands-on lab, or to ask a knowledgeable friend to give you a
tour.
step 1 Start the C++ development environment.
Computer systems differ greatly in this regard. On many computers there is an inte-
grated development environment in which you can write and test your programs.
On other computers you first launch an editor, a program that functions like a word
processor, in which you can enter your C++ instructions; then open a console win-
dow and type commands to execute your program. You need to find out how to get
started with your environment.
step 2 Write a simple program.
The traditional choice for the very first program in a new programming language is a
program that dis plays a simple greeting: “Hello, World!”. Let us follow that tradi-
tion. Here is the “Hello, World!” pro gram in C++:
s e L f C h e C k
two standards orga-
nizations, the ameri-
can national standards Institute (ansI)
and the International organization for
standardization (Iso), have jointly
developed the definitive standard for
the C++ language.
Why have standards? You encoun ter
the benefits of standardization every
day. When you buy a light bulb, you
can be assured that it fits in the socket
without having to measure the socket
at home and the bulb in the store. In
fact, you may have experi enced how
painful the lack of stan dards can be if
you have ever purchased a flashlight
with nonstand ard bulbs. replacement
bulbs for such a flashlight can be dif-
ficult and expen sive to obtain.
the ansI and Iso standards organi-
zations are associations of industry
professionals who develop standards
for everything from car tires and
credit card shapes to programming
languages. having a standard for a
programming language such as C++
means that you can take a program
that you developed on one system
with one manufacturer’s compiler to a
different system and be assured that it
will continue to work.
Random Fact 1.2 standards organizations
set aside some time
to become familiar
with the programming
environment that you
will use for your
class work.
cfe2_ch01_p1_28.indd 7 10/25/10 1:03 PM
8 Chapter 1 Introduction
#include
using namespace std;
int main()
{
cout << "Hello, World!" << endl;
return 0;
}
We will examine this program in the next section.
No matter which programming environment you use, you begin your activity by
typing the pro gram statements into an editor window.
Create a new file and call it hello.cpp, using the steps that are appropriate for your
environment. (If your environment requires that you supply a project name in addi-
tion to the file name, use the name hello for the project.) Enter the program instruc-
tions exactly as they are given above. Alternatively, locate an electronic copy in the
source files for the programs in this book and paste it into your editor.
As you write this program, pay careful attention to the various symbols, and
keep in mind that C++ is case sensitive. You must enter upper- and lowercase letters
exactly as they appear in the program listing. You cannot type MAIN or Endl. If you are
not careful, you will run into problems—see Common Error 1.2 on page 16.
step 3 Compile and run the program.
The process for building and running a C++ program depends greatly on your pro-
gramming environ ment. In some integrated development environments, you simply
push a button. In other environments, you may have to type commands. When you
run the test program, the message
Hello, World!
will appear somewhere on the screen (see Figures 5 and 6).
an editor is a program
for entering and
modifying text, such
as a C++ program.
C++ is case sensitive.
You must be careful
about distinguishing
between upper- and
lowercase letters.
the compiler
translates C++
programs into
machine code.
figure 5
running the hello
program in an
Integrated
development
environment
It is useful to know what goes on behind the scenes when your program gets built.
First, the compiler translates the C++ source code (that is, the statements that you
wrote) into machine instructions. The machine code contains only the translation of
the code that you wrote. That is not enough to actually run the program. To display a
string on a window, quite a bit of low-level activity is necessary. The implementors of
your C++ development environment provided a library that includes the definition
of cout and its functionality. A library is a collection of code that has been pro-
grammed and translated by someone else, ready for you to use in your program.
(More complicated pro grams are built from more than one machine code file and
more than one library.) A program called the linker takes your machine code and the
necessary parts from the C++ library and builds an execut able file. (Figure 7 gives an
overview of these steps.) The executable file is usually called hello.exe or hello,
depending on your computer system. You can run the executable program even after
you exit the C++ development environment.
step 4 Organize your work.
As a programmer, you write programs, try them out, and improve them. You store
your programs in files. Files have names, and the rules for legal names differ from one
system to another. Some systems allow spaces in file names; others don’t. Some dis-
tinguish between upper- and lowercase letters; others don’t. Most C++ compilers
require that C++ files end in an extension .cpp, .cxx, .cc, or .C; for example, test.cpp.
Files are stored in folders or directories. A folder can contain files as well as other
folders, which themselves can contain more files and folders (see Figure 8). This hier-
archy can be quite large, and you need not be concerned with all of its branches.
the linker combines
machine code with
library code into an
executable program.
figure 7 From source Code to executable program
CompilerEditor Linker
Executable
ProgramSource File
Library files
Machine code
cfe2_ch01_p1_28.indd 8 10/25/10 1:03 PM
1.4 Becoming Familiar with Your programming environment 9
figure 6
Compiling and
running the hello
program in a
Console Window
It is useful to know what goes on behind the scenes when your program gets built.
First, the compiler translates the C++ source code (that is, the statements that you
wrote) into machine instructions. The machine code contains only the translation of
the code that you wrote. That is not enough to actually run the program. To display a
string on a window, quite a bit of low-level activity is necessary. The implementors of
your C++ development environment provided a library that includes the definition
of cout and its functionality. A library is a collection of code that has been pro-
grammed and translated by someone else, ready for you to use in your program.
(More complicated pro grams are built from more than one machine code file and
more than one library.) A program called the linker takes your machine code and the
necessary parts from the C++ library and builds an execut able file. (Figure 7 gives an
overview of these steps.) The executable file is usually called hello.exe or hello,
depending on your computer system. You can run the executable program even after
you exit the C++ development environment.
step 4 Organize your work.
As a programmer, you write programs, try them out, and improve them. You store
your programs in files. Files have names, and the rules for legal names differ from one
system to another. Some systems allow spaces in file names; others don’t. Some dis-
tinguish between upper- and lowercase letters; others don’t. Most C++ compilers
require that C++ files end in an extension .cpp, .cxx, .cc, or .C; for example, test.cpp.
Files are stored in folders or directories. A folder can contain files as well as other
folders, which themselves can contain more files and folders (see Figure 8). This hier-
archy can be quite large, and you need not be concerned with all of its branches.
the linker combines
machine code with
library code into an
executable program.
figure 7 From source Code to executable program
CompilerEditor Linker
Executable
ProgramSource File
Library files
Machine code
cfe2_ch01_p1_28.indd 9 10/25/10 1:03 PM
10 Chapter 1 Introduction
figure 8 a Folder hierarchy
However, you should create folders for organizing your work. It is a good idea to
make a separate folder for your programming class. Inside that folder, make a sepa-
rate folder for each assignment.
Some programming environments place your programs into a default location if
you don’t specify a folder yourself. In that case, you need to find out where those files
are located.
Be sure that you understand where your files are located in the folder hierarchy.
This information is essential when you submit files for grading, and for making
backup copies.
You will spend many hours creating and improving C++ programs. It is easy to
delete a file by acci dent, and occasionally files are lost because of a computer mal-
function. To avoid the frustration of recre ating lost files, get in the habit of making
backup copies of your work on a memory stick or on another computer.
9. How are programming projects stored on a computer?
10. What do you expect to see when you load an executable file into your text
editor?
11. What do you do to protect yourself from data loss when you work on program-
ming projects?
Practice It Now you can try these exercises at the end of the chapter: R1.6.
develop a strategy
for keeping backup
copies of your work
before disaster
strikes.
s e L f C h e C k
Backup Copies
Backing up files on a memory stick is an easy and convenient stor-
age method for many people. Another increasingly popular form
of backup is Internet file storage. Here are a few pointers to keep
in mind.
• Back up often. Backing up a file takes only a few seconds, and
you will hate yourself if you have to spend many hours
recreating work that you could have saved easily. I rec ommend
that you back up your work once every thirty minutes.
• Rotate backups. Use more than one directory for backups, and rotate them. That is, first
back up onto the first directory. Then back up onto the second directory. Then use the
third, and then go back to the first. That way you always have three recent backups. If
your recent changes made matters worse, you can then go back to the older version.
• Pay attention to the backup direction. Backing up involves copying files from one place to
another. It is important that you do this right—that is, copy from your work location to
the backup location. If you do it the wrong way, you will overwrite a newer file with an
older version.
• Check your backups once in a while. Double-check that your backups are where you think
they are. There is nothing more frustrating than to find out that the backups are not there
when you need them.
• Relax, then restore. When you lose a file and need to restore it from backup, you are likely
to be in an unhappy, nervous state. Take a deep breath and think through the recovery
process before you start. It is not uncommon for an agitated computer user to wipe out the
last backup when trying to restore a damaged file.
1.5 analyzing Your First program
In this section, we will analyze the first C++ program in detail. Here again is the
source code:
ch01/hello.cpp
1 #include
2
3 using namespace std;
4
5 int main()
6 {
7 cout << "Hello, World!" << endl;
8 return 0;
9 }
The first line,
#include
tells the compiler to include a service for “stream input/output”. You will learn in
Chapter 8 what a stream is. For now, you should simply remember to add this line
into all programs that perform input or output.
programming tip 1.1
cfe2_ch01_p1_28.indd 10 10/25/10 1:03 PM
1.5 analyzing Your First program 11
Backup Copies
Backing up files on a memory stick is an easy and convenient stor-
age method for many people. Another increasingly popular form
of backup is Internet file storage. Here are a few pointers to keep
in mind.
• Back up often. Backing up a file takes only a few seconds, and
you will hate yourself if you have to spend many hours
recreating work that you could have saved easily. I rec ommend
that you back up your work once every thirty minutes.
• Rotate backups. Use more than one directory for backups, and rotate them. That is, first
back up onto the first directory. Then back up onto the second directory. Then use the
third, and then go back to the first. That way you always have three recent backups. If
your recent changes made matters worse, you can then go back to the older version.
• Pay attention to the backup direction. Backing up involves copying files from one place to
another. It is important that you do this right—that is, copy from your work location to
the backup location. If you do it the wrong way, you will overwrite a newer file with an
older version.
• Check your backups once in a while. Double-check that your backups are where you think
they are. There is nothing more frustrating than to find out that the backups are not there
when you need them.
• Relax, then restore. When you lose a file and need to restore it from backup, you are likely
to be in an unhappy, nervous state. Take a deep breath and think through the recovery
process before you start. It is not uncommon for an agitated computer user to wipe out the
last backup when trying to restore a damaged file.
1.5 analyzing Your First program
In this section, we will analyze the first C++ program in detail. Here again is the
source code:
ch01/hello.cpp
1 #include
2
3 using namespace std;
4
5 int main()
6 {
7 cout << "Hello, World!" << endl;
8 return 0;
9 }
The first line,
#include
tells the compiler to include a service for “stream input/output”. You will learn in
Chapter 8 what a stream is. For now, you should simply remember to add this line
into all programs that perform input or output.
programming tip 1.1
cfe2_ch01_p1_28.indd 11 10/25/10 1:03 PM
12 Chapter 1 Introduction
syntax 1.1 C++ program
#include
using namespace std;
int main()
{
cout << "Hello, World!" << endl;
return 0;
}
Every program includes one or
more headers for required services
such as input/output.
Every program that uses standard
services requires this directive.
Every program
has a main function.
Replace this
statement when you
write your own
programs.
The statements
of a function
are enclosed
in braces. Each statement ends in a semicolon.
See page 14.
The next line,
using namespace std;
tells the compiler to use the “standard namespace”. Namespaces are a mechanism for
avoiding naming conflicts in large programs. You need not be concerned about
namespaces. For the programs that you will be writing in this book, you will always
use the standard namespace. Simply add using namespace std; at the top of every pro-
gram that you write, just below the #include directives.
The construction
int main()
{
...
return 0;
}
defines a function called main that “returns” an “integer” (that is, a whole number
without a fractional part, called int in C++) with value 0. This value indicates that the
program finished successfully. A function is a collection of programming instruc-
tions that carry out a particular task. Every C++ program must have a main func tion.
Most C++ programs contain other functions besides main, but it will take us until
Chapter 5 to dis cuss functions and return values.
For now, it is a good idea to consider all these parts as the plumbing that is neces-
sary to write a simple program. Simply place the code that you want to execute inside
the braces of the main function. (The basic structure of a C++ program is shown in
Syntax 1.1.)
To display values on the screen, you use an entity called cout and the << operator
(sometimes called the insertion operator). For example, the statement
cout << 39 + 3;
displays the number 42.
every C++ program
contains a function
called main.
use cout and the <<
operator to display
values on the screen.
The statement
cout << "Hello";
displays the string Hello. A string is a sequence of characters. You must enclose the
contents of a string inside quotation marks so that the compiler knows you literally
mean the text "Hello" and not a function with the same name.
You can send more than one item to cout. Use a << before each one of them. For
example,
cout << "The answer is " << 6 * 7;
displays The answer is 42 (in C++, the * denotes multiplication).
The endl symbol denotes an end of line marker. When this marker is sent to cout,
the cursor is moved to the first column in the next screen row. If you don’t use an end
of line marker, then the next displayed item will simply follow the current string on
the same line. In this program we only printed one item, but in general we will want
to print multiple items, and it is a good habit to end all lines of output with an end of
line marker.
Finally, note that each statement in C++ ends in a semicolon, just as every English
sentence ends in a period.
12. How do you modify the hello.cpp program to greet you instead?
13. What is wrong with this program?
#include
using namespace std;
int main()
{
cout << Goodbye, World! << endl;
return 0;
}
14. What does the following sequence of statements print?
cout << "Hello";
cout << "World";
enclose text strings in
quotation marks.
use + to add two
numbers and * to
multiply two
numbers.
send endl to cout to
end a line of
displayed output.
end each statement
with a semicolon.
s e L f C h e C k
cfe2_ch01_p1_28.indd 12 10/25/10 1:03 PM
1.5 analyzing Your First program 13
syntax 1.2 output statement
cout << "The answer is" << 6 * 7 << endl;
Sending endl
to cout starts
a new line.
Data sent to cout
is displayed in a
console window.
You can send
strings and numbers
to cout.
Add a << symbol before
each item to be displayed.
Strings
are enclosed in
quotation marks.
* denotes
multiplication.
The statement
cout << "Hello";
displays the string Hello. A string is a sequence of characters. You must enclose the
contents of a string inside quotation marks so that the compiler knows you literally
mean the text "Hello" and not a function with the same name.
You can send more than one item to cout. Use a << before each one of them. For
example,
cout << "The answer is " << 6 * 7;
displays The answer is 42 (in C++, the * denotes multiplication).
The endl symbol denotes an end of line marker. When this marker is sent to cout,
the cursor is moved to the first column in the next screen row. If you don’t use an end
of line marker, then the next displayed item will simply follow the current string on
the same line. In this program we only printed one item, but in general we will want
to print multiple items, and it is a good habit to end all lines of output with an end of
line marker.
Finally, note that each statement in C++ ends in a semicolon, just as every English
sentence ends in a period.
12. How do you modify the hello.cpp program to greet you instead?
13. What is wrong with this program?
#include
using namespace std;
int main()
{
cout << Goodbye, World! << endl;
return 0;
}
14. What does the following sequence of statements print?
cout << "Hello";
cout << "World";
enclose text strings in
quotation marks.
use + to add two
numbers and * to
multiply two
numbers.
send endl to cout to
end a line of
displayed output.
end each statement
with a semicolon.
s e L f C h e C k
cfe2_ch01_p1_28.indd 13 10/25/10 1:03 PM
14 Chapter 1 Introduction
15. What does the following statement print?
cout << 2 * 2 << 2;
16. What does the following statement print?
cout << "Hello" << endl << endl << "World";
Practice It Now you can try these exercises at the end of the chapter: R1.7, P1.1, P1.2.
omitting semicolons
In C++ every statement must end in a semicolon. Forgetting to type a semicolon is a common
error. It confuses the compiler because the compiler uses the semicolon to find where one
statement ends and the next one starts. The compiler does not use line ends or closing braces to
recognize the ends of statements. For example, the compiler con siders
cout << "Hello, World!" << endl
return 0;
a single statement, as if you had written
cout << "Hello, World!" << endl return 0;
and then it doesn’t understand that statement, because it does not expect the word return in the
middle of an output command. The remedy is simple. Just scan every statement for a terminat-
ing semicolon, just as you would check that every English sentence ends in a period.
escape sequences
How can you display a string containing quotation marks, such as
Hello, "World"
You can’t use
cout << "Hello, "World"";
As soon as the compiler reads "Hello, ", it thinks the string is finished, and then it gets all
confused about World. Compilers have a one-track mind, and if a simple analysis of the input
doesn’t make sense to them, they just refuse to go on, and they report an error. In contrast, a
human would probably realize that the second and third quotation marks were supposed to be
part of the string.
Well, how do we then display quotation marks on the screen? The designers of C++ pro-
vided an escape hatch. Mark each quotation mark with a backslash character (), like this:
cout << "Hello, "World"""";