Professional Documents
Culture Documents
Preface xv
vii
viii Contents
CHAPTER 10 Characters, C-Strings, and More About the string Class 547
10.1 Character Testing 547
10.2 Character Case Conversion 551
10.3 C-Strings 554
10.4 Library Functions for Working with C-Strings 558
10.5 C-String/Numeric Conversion Functions 569
10.6 Focus on Software Engineering: Writing Your Own
C-String-Handling Functions 575
10.7 More About the C++ string Class 581
10.8 Focus on Problem Solving and Program Design: A Case Study 590
Welcome to Starting Out with C++: From Control Structures through Objects, 8th edition.
This book is intended for use in a two-semester C++ programming sequence, or an acceler-
ated one-semester course. Students new to programming, as well as those with prior course
work in other languages, will find this text beneficial. The fundamentals of programming
are covered for the novice, while the details, pitfalls, and nuances of the C++ language are
explored in-depth for both the beginner and more experienced student. The book is written
with clear, easy-to-understand language, and it covers all the necessary topics for an intro-
ductory programming course. This text is rich in example programs that are concise, practi-
cal, and real-world oriented, ensuring that the student not only learns how to implement the
features and constructs of C++, but why and when to use them.
xv
xvi Preface
● The range-based for loop is introduced in Chapter 7. This new looping mechanism
automatically iterates over each element of an array, vector, or other collection,
without the need of a counter variable or a subscript.
● Chapter 7 shows how a vector can be initialized with an initialization list.
● The nullptr key word is introduced as the standard way of representing a null
pointer.
● Smart pointers are introduced in Chapter 9, with an example of dynamic memory
allocation using unique_ptr.
● Chapter 10 discusses the new, overloaded to_string functions for converting numeric
values to string objects.
● The string class’s new back() and front() member functions are included in
Chapter 10’s overview of the string class.
● Strongly typed enums are discussed in Chapter 11.
● Chapter 13 shows how to use the smart pointer unique_ptr to dynamically allocate
an object.
● Chapter 15 discusses the override key word and demonstrates how it can help prevent
subtle overriding errors. The final key word is discussed as a way of preventing a virtual
member function from being overridden.
In addition to the C++11 topics, the following general improvements were made:
● Several new programming problems have been added to the text, and many of the
existing programming problems have been modified to make them unique from previ-
ous editions.
● The discussion of early, historic computers in Chapter 1 is expanded.
● The discussion of literal values in Chapter 2 is improved.
● The introduction of the char data type in Chapter 2 is reorganized to use character
literals in variable assignments before using ASCII values in variable assignments.
● The discussion of random numbers in Chapter 3 is expanded and improved, with the
addition of a new In the Spotlight section.
● A new Focus on Object-Oriented Programming section has been added to Chapter 13,
showing how to write a class that simulates dice.
● A new Focus on Object-Oriented Programming section has been added to Chapter 14,
showing an object-oriented program that simulates the game of Cho-Han. The program
uses objects for the dealer, two players, and a pair of dice.
Figure P-1
Chapter 1
Introduction
Chapters 2–7
Basic Language
Elements
*A few subtopics in
Chapter 12 require
Chapter 10 Chapters 9 and 11.
Characters, Strings, Chapter 11
and the string Class Structures
Chapter 13
Introduction to
Classes
Chapter 14
More About Classes
Chapter 15
Inheritance and
Polymorphism
Chapter 16
Exceptions,
Templates, and STL
Chapter 17
Linked Lists
Chapter 18 Chapter 19
Stacks and Queues Recursion
Chapter 20
Binary Trees
xviii Preface
Chapter 1 covers fundamental hardware, software, and programming concepts. You may
choose to skip this chapter if the class has already mastered those topics. Chapters 2 through
7 cover basic C++ syntax, data types, expressions, selection structures, repetition structures,
functions, and arrays. Each of these chapters builds on the previous chapter and should be
covered in the order presented.
After Chapter 7 has been covered, you may proceed to Chapter 8, or jump to either Chapter
9 or Chapter 12. (If you jump to Chapter 12 at this point, you will need to postpone sections
12.7, 12.8, and 12.10 until Chapters 9 and 11 have been covered.)
After Chapter 9 has been covered, either of Chapters 10 or 11 may be covered. After Chap-
ter 11, you may cover Chapters 13 through 17 in sequence. Next you can proceed to either
Chapter 18 or Chapter 19. Finally, Chapter 20 may be covered.
This text’s approach starts with a firm foundation in structured, procedural programming
before delving fully into object-oriented programming and advanced data structures.
Chapter 6: Functions
In this chapter the student learns how and why to modularize programs, using both void
and value returning functions. Argument passing is covered, with emphasis on when argu-
ments should be passed by value versus when they need to be passed by reference. Scope of
variables is covered, and sections are provided on local versus global variables and on static
local variables. Overloaded functions are also introduced and demonstrated.
Chapter 7: Arrays
In this chapter the student learns to create and work with single and multidimensional
arrays. Many examples of array processing are provided including examples illustrating
how to find the sum, average, highest, and lowest values in an array and how to sum the
rows, columns, and all elements of a two-dimensional array. Programming techniques using
parallel arrays are also demonstrated, and the student is shown how to use a data file as
an input source to populate an array. STL vectors are introduced and compared to arrays.
Chapter 9: Pointers
This chapter explains how to use pointers. Pointers are compared to and contrasted with
reference variables. Other topics include pointer arithmetic, initialization of pointers, rela-
tional comparison of pointers, pointers and arrays, pointers and functions, dynamic mem-
ory allocation, and more.
Chapter 10: Characters, C-strings, and More About the string Class
This chapter discusses various ways to process text at a detailed level. Library functions for
testing and manipulating characters are introduced. C-strings are discussed, and the tech-
nique of storing C-strings in char arrays is covered. An extensive discussion of the string
class methods is also given.
denominator (GCD), performing a binary search, and sorting (QuickSort). The classic Tow-
ers of Hanoi example is also presented. For students who need more challenge, there is a
section on exhaustive algorithms.
Appendix F: Namespaces
This appendix explains namespaces and their purpose. Examples showing how to define a
namespace and access its members are given.
Warnings Warnings are notes that caution the student about certain C++
features, programming techniques, or practices that can lead to
malfunctioning programs or lost data.
Case Studies Case studies that simulate real-world applications appear in
many chapters throughout the text. These case studies are de-
signed to highlight the major topics of the chapter in which they
appear.
Review Questions Each chapter presents a thorough and diverse set of review
and Exercises questions, such as fill-in-the-blank and short answer, that check
the student’s mastery of the basic material presented in the chap-
ter. These are followed by exercises requiring problem solving
and analysis, such as the Algorithm Workbench, Predict the Out-
put, and Find the Errors sections. Answers to the odd-numbered
review questions and review exercises can be downloaded from
the book’s Companion Web site at www.pearsonhighered.com/
gaddis.
Programming Each chapter offers a pool of programming exercises designed
Challenges to solidify the student’s knowledge of the topics currently being
studied. In most cases the assignments present real-world prob-
lems to be solved. When applicable, these exercises include input
validation rules.
Group Projects There are several group programming projects throughout the
text, intended to be constructed by a team of students. One
student might build the program’s user interface, while another
student writes the mathematical code, and another designs and
implements a class the program uses. This process is similar to
the way many professional programs are written and encourages
team work within the classroom.
Software Available for download from the book’s Companion Web site at
Development www.pearsonhighered.com/gaddis. This is an ongoing project
Project: that instructors can optionally assign to teams of students. It
Serendipity systematically develops a “real-world” software package: a
Booksellers point-of-sale program for the fictitious Serendipity Booksellers
organization. The Serendipity assignment for each chapter adds
more functionality to the software, using constructs and tech-
niques covered in that chapter. When complete, the program will
act as a cash register, manage an inventory database, and produce
a variety of reports.
C++ Quick For easy access, a quick reference guide to the C++ language is
Reference Guide printed on the last two pages of Appendix C in the book.
Supplements
Student Online Resources
Many student resources are available for this book from the publisher. The following items
are available on the Gaddis Series Companion Web site at www.pearsonhighered.com/gaddis:
● The source code for each example program in the book
● Access to the book’s companion VideoNotes
● A full set of appendices, including answers to the Checkpoint questions and answers
to the odd-numbered review questions
● A collection of valuable Case Studies
● The complete Serendipity Booksellers Project
Instructor Resources
The following supplements are available to qualified instructors only:
• Answers to all Review Questions in the text
• Solutions for all Programming Challenges in the text
• PowerPoint presentation slides for every chapter
• Computerized test bank
Preface xxv
Acknowledgments
There have been many helping hands in the development and publication of this text. We
would like to thank the following faculty reviewers for their helpful suggestions and expertise.
I would like to thank my family for their love and support in all of my many projects. I
am extremely fortunate to have Matt Goldstein as my editor. I am also fortunate to have
Kathryn Ferranti as marketing coordinator. She does a great job getting my books out to
the academic community. I had a great production team led by Marilyn Lloyd and Kayla
Smith-Tarbox. Thanks to you all!
MyProgrammingLab ™
1 and Programming
TOPICS
1.1 Why Program? 1.4 What Is a Program Made of?
1.2 Computer Systems: Hardware 1.5 Input, Processing, and Output
and Software 1.6 The Programming Process
1.3 Programs and Programming 1.7 Procedural and Object-Oriented
Languages Programming
Think about some of the different ways that people use computers. In school, students use
computers for tasks such as writing papers, searching for articles, sending e-mail, and partici-
pating in online classes. At work, people use computers to analyze data, make presentations,
conduct business transactions, communicate with customers and coworkers, control machines
in manufacturing facilities, and do many other things. At home, people use computers for
tasks such as paying bills, shopping online, social networking, and playing computer games.
And don’t forget that smart phones, iPods®, car navigation systems, and many other devices
are computers as well. The uses of computers are almost limitless in our everyday lives.
Computers can do such a wide variety of things because they can be programmed. This
means that computers are not designed to do just one job, but any job that their programs
tell them to do. A program is a set of instructions that a computer follows to perform a
task. For example, Figure 1-1 shows screens using Microsoft Word and PowerPoint, two
commonly used programs.
Programs are commonly referred to as software. Software is essential to a computer because
without software, a computer can do nothing. All of the software that we use to make our
computers useful is created by individuals known as programmers or software developers.
A programmer, or software developer, is a person with the training and skills necessary
to design, create, and test computer programs. Computer programming is an exciting and
rewarding career. Today, you will find programmers working in business, medicine, govern-
ment, law enforcement, agriculture, academics, entertainment, and almost every other field.
1
2 Chapter 1 Introduction to Computers and Programming
Computer programming is both an art and a science. It is an art because every aspect of
a program should be carefully designed. Listed below are a few of the things that must be
designed for any real-world computer program:
• The logical flow of the instructions
• The mathematical procedures
• The appearance of the screens
• The way information is presented to the user
• The program’s “user-friendliness”
• Manuals and other forms of written documentation
There is also a scientific, or engineering, side to programming. Because programs rarely
work right the first time they are written, a lot of testing, correction, and redesigning is
required. This demands patience and persistence from the programmer. Writing software
demands discipline as well. Programmers must learn special languages like C++ because
computers do not understand English or other human languages. Languages such as C++
have strict rules that must be carefully followed.
Both the artistic and scientific nature of programming make writing computer software like
designing a car: Both cars and programs should be functional, efficient, powerful, easy to
use, and pleasing to look at.
CONCEPT: All computer systems consist of similar hardware devices and software
components. This section provides an overview of standard computer
hardware and software organization.
1.2 Computer Systems: Hardware and Software 3
Hardware
Hardware refers to the physical components that a computer is made of. A computer, as
we generally think of it, is not an individual device, but a system of devices. Like the instru-
ments in a symphony orchestra, each device plays its own part. A typical computer system
consists of the following major components:
• The central processing unit (CPU)
• Main memory
• Secondary storage devices
• Input devices
• Output devices
The organization of a computer system is depicted in Figure 1-2.
Figure 1-2
Central Processing
Unit
Output
Devices
Input
Devices
Main Memory
(RAM)
Secondary
Storage Devices
The CPU
When a computer is performing the tasks that a program tells it to do, we say that the
computer is running or executing the program. The central processing unit, or CPU, is the
part of a computer that actually runs programs. The CPU is the most important component
in a computer because without it, the computer could not run software.
In the earliest computers, CPUs were huge devices made of electrical and mechanical compo-
nents such as vacuum tubes and switches. Figure 1-3 shows such a device. The two women in
4 Chapter 1 Introduction to Computers and Programming
Figure 1-3
the photo are working with the historic ENIAC computer. The ENIAC, considered by many
to be the world’s first programmable electronic computer, was built in 1945 to calculate
artillery ballistic tables for the U.S. Army. This machine, which was primarily one big CPU,
was 8 feet tall, 100 feet long, and weighed 30 tons.
Today, CPUs are small chips known as microprocessors. Figure 1-4 shows a photo of a lab tech-
nician holding a modern-day microprocessor. In addition to being much smaller than the old
electro-mechanical CPUs in early computers, microprocessors are also much more powerful.
Figure 1-4
Another random document with
no related content on Scribd:
DANCE ON STILTS AT THE GIRLS’ UNYAGO, NIUCHI
I see increasing reason to believe that the view formed some time
back as to the origin of the Makonde bush is the correct one. I have
no doubt that it is not a natural product, but the result of human
occupation. Those parts of the high country where man—as a very
slight amount of practice enables the eye to perceive at once—has not
yet penetrated with axe and hoe, are still occupied by a splendid
timber forest quite able to sustain a comparison with our mixed
forests in Germany. But wherever man has once built his hut or tilled
his field, this horrible bush springs up. Every phase of this process
may be seen in the course of a couple of hours’ walk along the main
road. From the bush to right or left, one hears the sound of the axe—
not from one spot only, but from several directions at once. A few
steps further on, we can see what is taking place. The brush has been
cut down and piled up in heaps to the height of a yard or more,
between which the trunks of the large trees stand up like the last
pillars of a magnificent ruined building. These, too, present a
melancholy spectacle: the destructive Makonde have ringed them—
cut a broad strip of bark all round to ensure their dying off—and also
piled up pyramids of brush round them. Father and son, mother and
son-in-law, are chopping away perseveringly in the background—too
busy, almost, to look round at the white stranger, who usually excites
so much interest. If you pass by the same place a week later, the piles
of brushwood have disappeared and a thick layer of ashes has taken
the place of the green forest. The large trees stretch their
smouldering trunks and branches in dumb accusation to heaven—if
they have not already fallen and been more or less reduced to ashes,
perhaps only showing as a white stripe on the dark ground.
This work of destruction is carried out by the Makonde alike on the
virgin forest and on the bush which has sprung up on sites already
cultivated and deserted. In the second case they are saved the trouble
of burning the large trees, these being entirely absent in the
secondary bush.
After burning this piece of forest ground and loosening it with the
hoe, the native sows his corn and plants his vegetables. All over the
country, he goes in for bed-culture, which requires, and, in fact,
receives, the most careful attention. Weeds are nowhere tolerated in
the south of German East Africa. The crops may fail on the plains,
where droughts are frequent, but never on the plateau with its
abundant rains and heavy dews. Its fortunate inhabitants even have
the satisfaction of seeing the proud Wayao and Wamakua working
for them as labourers, driven by hunger to serve where they were
accustomed to rule.
But the light, sandy soil is soon exhausted, and would yield no
harvest the second year if cultivated twice running. This fact has
been familiar to the native for ages; consequently he provides in
time, and, while his crop is growing, prepares the next plot with axe
and firebrand. Next year he plants this with his various crops and
lets the first piece lie fallow. For a short time it remains waste and
desolate; then nature steps in to repair the destruction wrought by
man; a thousand new growths spring out of the exhausted soil, and
even the old stumps put forth fresh shoots. Next year the new growth
is up to one’s knees, and in a few years more it is that terrible,
impenetrable bush, which maintains its position till the black
occupier of the land has made the round of all the available sites and
come back to his starting point.
The Makonde are, body and soul, so to speak, one with this bush.
According to my Yao informants, indeed, their name means nothing
else but “bush people.” Their own tradition says that they have been
settled up here for a very long time, but to my surprise they laid great
stress on an original immigration. Their old homes were in the
south-east, near Mikindani and the mouth of the Rovuma, whence
their peaceful forefathers were driven by the continual raids of the
Sakalavas from Madagascar and the warlike Shirazis[47] of the coast,
to take refuge on the almost inaccessible plateau. I have studied
African ethnology for twenty years, but the fact that changes of
population in this apparently quiet and peaceable corner of the earth
could have been occasioned by outside enterprises taking place on
the high seas, was completely new to me. It is, no doubt, however,
correct.
The charming tribal legend of the Makonde—besides informing us
of other interesting matters—explains why they have to live in the
thickest of the bush and a long way from the edge of the plateau,
instead of making their permanent homes beside the purling brooks
and springs of the low country.
“The place where the tribe originated is Mahuta, on the southern
side of the plateau towards the Rovuma, where of old time there was
nothing but thick bush. Out of this bush came a man who never
washed himself or shaved his head, and who ate and drank but little.
He went out and made a human figure from the wood of a tree
growing in the open country, which he took home to his abode in the
bush and there set it upright. In the night this image came to life and
was a woman. The man and woman went down together to the
Rovuma to wash themselves. Here the woman gave birth to a still-
born child. They left that place and passed over the high land into the
valley of the Mbemkuru, where the woman had another child, which
was also born dead. Then they returned to the high bush country of
Mahuta, where the third child was born, which lived and grew up. In
course of time, the couple had many more children, and called
themselves Wamatanda. These were the ancestral stock of the
Makonde, also called Wamakonde,[48] i.e., aborigines. Their
forefather, the man from the bush, gave his children the command to
bury their dead upright, in memory of the mother of their race who
was cut out of wood and awoke to life when standing upright. He also
warned them against settling in the valleys and near large streams,
for sickness and death dwelt there. They were to make it a rule to
have their huts at least an hour’s walk from the nearest watering-
place; then their children would thrive and escape illness.”
The explanation of the name Makonde given by my informants is
somewhat different from that contained in the above legend, which I
extract from a little book (small, but packed with information), by
Pater Adams, entitled Lindi und sein Hinterland. Otherwise, my
results agree exactly with the statements of the legend. Washing?
Hapana—there is no such thing. Why should they do so? As it is, the
supply of water scarcely suffices for cooking and drinking; other
people do not wash, so why should the Makonde distinguish himself
by such needless eccentricity? As for shaving the head, the short,
woolly crop scarcely needs it,[49] so the second ancestral precept is
likewise easy enough to follow. Beyond this, however, there is
nothing ridiculous in the ancestor’s advice. I have obtained from
various local artists a fairly large number of figures carved in wood,
ranging from fifteen to twenty-three inches in height, and
representing women belonging to the great group of the Mavia,
Makonde, and Matambwe tribes. The carving is remarkably well
done and renders the female type with great accuracy, especially the
keloid ornamentation, to be described later on. As to the object and
meaning of their works the sculptors either could or (more probably)
would tell me nothing, and I was forced to content myself with the
scanty information vouchsafed by one man, who said that the figures
were merely intended to represent the nembo—the artificial
deformations of pelele, ear-discs, and keloids. The legend recorded
by Pater Adams places these figures in a new light. They must surely
be more than mere dolls; and we may even venture to assume that
they are—though the majority of present-day Makonde are probably
unaware of the fact—representations of the tribal ancestress.
The references in the legend to the descent from Mahuta to the
Rovuma, and to a journey across the highlands into the Mbekuru
valley, undoubtedly indicate the previous history of the tribe, the
travels of the ancestral pair typifying the migrations of their
descendants. The descent to the neighbouring Rovuma valley, with
its extraordinary fertility and great abundance of game, is intelligible
at a glance—but the crossing of the Lukuledi depression, the ascent
to the Rondo Plateau and the descent to the Mbemkuru, also lie
within the bounds of probability, for all these districts have exactly
the same character as the extreme south. Now, however, comes a
point of especial interest for our bacteriological age. The primitive
Makonde did not enjoy their lives in the marshy river-valleys.
Disease raged among them, and many died. It was only after they
had returned to their original home near Mahuta, that the health
conditions of these people improved. We are very apt to think of the
African as a stupid person whose ignorance of nature is only equalled
by his fear of it, and who looks on all mishaps as caused by evil
spirits and malignant natural powers. It is much more correct to
assume in this case that the people very early learnt to distinguish
districts infested with malaria from those where it is absent.
This knowledge is crystallized in the
ancestral warning against settling in the
valleys and near the great waters, the
dwelling-places of disease and death. At the
same time, for security against the hostile
Mavia south of the Rovuma, it was enacted
that every settlement must be not less than a
certain distance from the southern edge of the
plateau. Such in fact is their mode of life at the
present day. It is not such a bad one, and
certainly they are both safer and more
comfortable than the Makua, the recent
intruders from the south, who have made USUAL METHOD OF
good their footing on the western edge of the CLOSING HUT-DOOR
plateau, extending over a fairly wide belt of
country. Neither Makua nor Makonde show in their dwellings
anything of the size and comeliness of the Yao houses in the plain,
especially at Masasi, Chingulungulu and Zuza’s. Jumbe Chauro, a
Makonde hamlet not far from Newala, on the road to Mahuta, is the
most important settlement of the tribe I have yet seen, and has fairly
spacious huts. But how slovenly is their construction compared with
the palatial residences of the elephant-hunters living in the plain.
The roofs are still more untidy than in the general run of huts during
the dry season, the walls show here and there the scanty beginnings
or the lamentable remains of the mud plastering, and the interior is a
veritable dog-kennel; dirt, dust and disorder everywhere. A few huts
only show any attempt at division into rooms, and this consists
merely of very roughly-made bamboo partitions. In one point alone
have I noticed any indication of progress—in the method of fastening
the door. Houses all over the south are secured in a simple but
ingenious manner. The door consists of a set of stout pieces of wood
or bamboo, tied with bark-string to two cross-pieces, and moving in
two grooves round one of the door-posts, so as to open inwards. If
the owner wishes to leave home, he takes two logs as thick as a man’s
upper arm and about a yard long. One of these is placed obliquely
against the middle of the door from the inside, so as to form an angle
of from 60° to 75° with the ground. He then places the second piece
horizontally across the first, pressing it downward with all his might.
It is kept in place by two strong posts planted in the ground a few
inches inside the door. This fastening is absolutely safe, but of course
cannot be applied to both doors at once, otherwise how could the
owner leave or enter his house? I have not yet succeeded in finding
out how the back door is fastened.