C++ by Example PDF
C++ by Example PDF
C++ by Example PDF
EXAMPLE
C++
By
Greg Perry
i
Contents ♦
C++ By Example
© 1992 by Que
All rights reserved. Printed in the United States of America. No part of this
book may be used or reproduced, in any form or by any means, or stored
in a database or retrieval system, without prior written permission of the
publisher except in the case of brief quotations embodied in critical articles
and reviews. Making copies of any part of this book for any purpose other
than your own personal use is a violation of United States copyright laws.
For information, address Que, 11711 N. College Ave., Carmel, IN 46032.
Library of Congress Catalog Card Number: 92-64353
ISBN: 1-56529-038-0
This book is sold as is, without warranty of any kind, either express or
implied, respecting the contents of this book, including but not limited to
implied warranties for the book’s quality, performance, merchantability,
or fitness for any particular purpose. Neither Que Corporation nor its
dealers or distributors shall be liable to the purchaser or any other person
or entity with respect to any liability, loss, or damage caused or alleged to
be caused directly or indirectly by this book.
96 95 94 93 92 8 7 6 5 4 3 2 1
Interpretation of the printing code: the rightmost double-digit number is
the year of the book’s printing; the rightmost single-digit number, the
number of the book’s printing. For example, a printing code of 92-1 shows
that the first printing of the book occurred in 1992.
ii
C++ By
EXAMPLE
iii
Contents ♦
Dedication
Dr. Rick Burgess, you shaped my life. Good or bad, I’m what I am
thanks to your help. I appreciate the many hours we’ve shared together.
G.M.P.
iv
C++ By
EXAMPLE
About the Author
Greg Perry has been a programmer and trainer for the past 14 years.
He received his first degree in computer science, then he received a
Masters degree in corporate finance. He currently is a professor of
computer science at Tulsa Junior College, as well as a computer
consultant and a lecturer. Greg Perry is the author of 11 other
computer books, including QBASIC By Example and C By Example. In
addition, he has published articles in several publications, including
PC World, Data Training, and Inside First Publisher. He has attended
computer conferences and trade shows in several countries, and is
fluent in nine computer languages.
v
Contents ♦
vi
C++ By
EXAMPLE
Acknowledgments
Trademark Acknowledgments
Que Corporation has made every attempt to supply trademark
information about company names, products, and services men-
tioned in this book. Trademarks indicated below were derived from
various sources. Que Corporation cannot attest to the accuracy of
this information.
AT&T is a registered trademark of American Telephone &
Telegraph Company.
FORTRAN and COBOL are trademarks of International
Business Machines Corporation (IBM).
Turbo BASIC is a registered trademark of Borland
International, Inc.
Turbo C is a registered trademark of Borland International, Inc.
Microsoft QuickC and MS-DOS are registered trademarks of
Microsoft Corporation.
ANSI is a registered trademark of American National Standards
Institute.
vii
Contents ♦
viii
C++ By
EXAMPLE
Overview
I Introduction to C++
1 Welcome to C++ ...........................................................................11
2 What Is a Program? ......................................................................35
3 Your First C++ Program ..............................................................51
4 Variables and Literals ..................................................................69
5 Character Arrays and Strings .....................................................99
6 Preprocessor Directives .............................................................113
7 Simple Input/Output .................................................................133
ix
Contents ♦
VIII References
A Memory Addressing, Binary, and Hexadecimal Review .....679
B Answers to Review Questions ..................................................701
C ASCII Table ..................................................................................719
D C++ Precedence Table ................................................................729
E Keyword and Function Reference............................................733
F The Mailing List Application ....................................................737
Glossary .......................................................................................747
Index .............................................................................................761
x
C++ By
EXAMPLE
Contents
Introduction ...................................................1
Who Should Use This Book ....................................................1
The Book’s Philosophy ............................................................2
Overview of This Book ............................................................2
Conventions Used in This Book .................................................5
Index to the Icons .....................................................................5
Margin Graphics (Book Diagrams) .......................................6
Companion Disk Offer ................................................................8
I Introduction to C++
xi
Contents ♦
xii
C++ By
EXAMPLE
xiii
Contents ♦
xiv
C++ By
EXAMPLE
13 The for Loop ...............................................273
The for Statement .....................................................................274
The Concept of for Loops ........................................................274
Nested for Loops ......................................................................286
Review Questions .....................................................................292
Review Exercises ......................................................................293
Summary ...................................................................................293
14 Other Loop Options ...................................295
Timing Loops ............................................................................296
The break and for Statements .................................................298
The continue Statement ...........................................................303
Review Questions .....................................................................308
Review Exercises ......................................................................308
Summary ...................................................................................309
15 The switch and goto Statements ..............311
The switch Statement ...............................................................312
The goto Statement ...................................................................321
Review Questions .....................................................................327
Review Exercises ......................................................................328
Summary ...................................................................................328
16 Writing C++ Functions ...............................331
Function Basics .........................................................................332
Breaking Down Problems .......................................................333
More Function Basics ...............................................................335
Calling and Returning Functions ...........................................337
Review Questions .....................................................................349
Summary ...................................................................................350
xv
Contents ♦
V Character Input/Output
and String Functions
xvi
C++ By
EXAMPLE
xvii
Contents ♦
xviii
C++ By
EXAMPLE
28 Structures ..................................................583
Introduction to Structures .......................................................584
Defining Structures ..................................................................587
Initializing Structure Data .......................................................591
Nested Structures .....................................................................600
Review Questions .....................................................................603
Review Exercises ......................................................................604
Summary ...................................................................................604
29 Arrays of Structures ..................................605
Declaring Arrays of Structures ...............................................606
Arrays as Members ..................................................................615
Review Questions .....................................................................623
Review Exercises ......................................................................624
Summary ...................................................................................624
30 Sequential Files .........................................625
Why Use a Disk? .......................................................................626
Types of Disk File Access ........................................................627
Sequential File Concepts .........................................................628
Opening and Closing Files ......................................................629
Writing to a File ........................................................................635
Writing to a Printer ..................................................................637
Adding to a File ........................................................................638
Reading from a File ..................................................................639
Review Questions .....................................................................642
Review Exercises ......................................................................643
Summary ...................................................................................644
31 Random-Access Files ................................645
Random File Records ...............................................................646
Opening Random-Access Files ...............................................647
The seekg() Function ................................................................649
Other Helpful I/O Functions..................................................656
Review Questions .....................................................................658
Review Exercises ......................................................................658
Summary ...................................................................................659
xix
Contents ♦
32 Introduction to Object-Oriented
Programming .............................................661
What Is a Class? ........................................................................662
Data Members ......................................................................662
Member Functions ...............................................................662
Default Member Arguments...................................................670
Class Member Visibility ..........................................................674
Review Questions .....................................................................676
Review Exercise ........................................................................676
Summary ...................................................................................676
VIII References
xx
C++ By
EXAMPLE
F The Mailing List Application .....................737
Index ..........................................................761
xxi
Contents ♦
xxii
C++ By
EXAMPLE
Introduction
Every day, more and more people learn and use the C++ program-
ming language. I have taught C to thousands of students in my life.
I see many of those students now moving to C++ in their school work
or career. The C++ language is becoming an industry-accepted
standard programming language, using the solid foundation of C to
gain a foothold. C++ is simply a better C than C.
C++ By Example is one of several books in Que’s new line of By
Example series. The philosophy of these books is simple: The best
way to teach computer programming concepts is with multiple
examples. Command descriptions, format syntax, and language
references are not enough to teach a newcomer a programming
language. Only by looking at numerous examples and by running
sample programs can programming students get more than just a
“feel” for the language.
1
Introduction ♦
2
C++ By
EXAMPLE
3
Introduction ♦
4
C++ By
EXAMPLE
Level 1 difficulty
5
Introduction ♦
Level 2 difficulty
Level 3 difficulty
Tip
Note
Caution
Pseudocode
The pseudocode icon appears beside pseudocode, which is
typeset in italic immediately before the program. The pseudocode
consists of one or more sentences indicating what the program
instructions are doing, in English. Pseudocode appears before se-
lected programs.
6
C++ By
EXAMPLE
Terminal symbol
({,},Return...)
Input/output
(scanf , print f...)
Calling a function
Input/output of arrays;
assumes implied FOR loop(s)
needed to deal with array I/O
7
Introduction ♦
8
Part I
Introduction to C++
C++ By
1
EXAMPLE
Welcome to C++
C++ is a recent addition to the long list of programming languages
now available. Experts predict that C++ will become one of the most
widely used programming languages within two to three years.
Scan your local computer bookstore’s shelves and you will see that
C++ is taking the programming world by storm. More and more
companies are offering C++ compilers. In the world of PCs, both
Borland and Microsoft, two of the leading names of PC software,
offer full-featured C++ compilers.
Although the C++ language is fairly new, having become
popular within the last three years, the designers of C++ compilers
are perfecting this efficient, standardized language that should soon
be compatible with almost every computer in the world. Whether
you are a beginning, an intermediate, or an expert programmer, C++
has the programming tools you need to make your computer do just
what you want it to do. This chapter introduces you to C++, briefly
describes its history, compares C++ to its predecessor C, shows you
the advantages of C++, and concludes by introducing you to hard-
ware and software concepts.
11
Chapter 1 ♦ Welcome to C++
C++ is called a Companies do not have to follow the AT&T C++ 3.0 standard.
“better C than C.” Many do, but add their own extensions and create their own version
to do more work than the AT&T standard includes. If you are using
the AT&T C++ standard, your program should successfully run on
any other computer that also uses AT&T C++.
12
C++ By
EXAMPLE
13
Chapter 1 ♦ Welcome to C++
14
C++ By
EXAMPLE
today’s familiar spreadsheets, databases, and word processors are
written in C. Now that C++ has improved on C, programmers are
retooling their minds to think in C++ as well.
The programmer help-wanted ads seek more and more C++
programmers every day. By learning this popular language, you
will be learning the latest direction of programming and keeping
your skills current with the market. You have taken the first step:
with this book, you learn the C++ language particulars as well as
many programming tips to use and pitfalls to avoid. This book
attempts to teach you to be not just a C++ programmer, but a better
programmer by applying the structured, long-term programming
habits that professionals require in today’s business and industry.
15
Chapter 1 ♦ Welcome to C++
16
C++ By
EXAMPLE
17
Chapter 1 ♦ Welcome to C++
18
C++ By
EXAMPLE
An Overview of Your
Computer
Your computer system consists of two parts: hardware and
software. The hardware consists of all the physical parts of the
machine. Hardware has been defined as “anything you can kick.”
Although this definition is coarse, it illustrates that your computer’s
hardware consists of the physical components of your PC. The
software is everything else. Software comprises the programs and
data that interact with your hardware. The C++ language is an
example of software. You can use C++ to create even more software
programs and data.
Hardware
Figure 1.1 shows you a typical PC system. Before using C++,
you should have a general understanding of what hardware is and
how your hardware components work together.
Monitor
System Unit
Disk Drives
Modem
Keyboard Printer
Mouse
19
Chapter 1 ♦ Welcome to C++
20
C++ By
EXAMPLE
21
Chapter 1 ♦ Welcome to C++
Disk Storage
A disk is another type of computer memory, sometimes called
external memory. Disk storage is nonvolatile. When you turn off your
computer, the disk’s contents do not go away. This is important.
After typing a long C++ program in RAM, you do not want to retype
the same program every time you turn your computer back on.
Therefore, after creating a C++ program, you save the program to
disk, where it remains until you’re ready to retrieve it again.
Disk storage differs from RAM in ways other than volatility.
Disk storage cannot be processed by the CPU. If you have a program
or data on disk that you want to use, you must transfer it from the
disk to RAM. This is the only way the CPU can work with the
program or data. Luckily, most disks hold many times more data
than the RAM’s 640K. Therefore, if you fill up RAM, you can store
its contents on disk and continue working. As RAM continues to fill
up, you or your C++ program can keep storing the contents of RAM
to the disk.
This process might sound complicated, but you have only to
understand that data must be transferred to RAM before your
computer can process it, and saved to disk before you shut your
computer off. Most the time, a C++ program runs in RAM and
retrieves data from the disk as it needs it. In Chapter 30, “Sequential
Files,” you learn that working with disk files is not difficult.
There are two types of disks: hard disks and floppy disks. Hard
disks (sometimes called fixed disks) hold much more data and are
many times faster to work with than floppy disks. Most of your C++
programs and data should be stored on your hard disk. Floppy disks
22
C++ By
EXAMPLE
are good for backing up hard disks, and for transferring data and
programs from one computer to another. (These removable floppy
disks are often called diskettes.) Figure 1.2 shows two common sizes,
the 5 1/4-inch disk and the 3 1/2-inch disk. These disks can hold
from 360K to 1.4 million bytes of data.
Insert this side into drive
Label
Write-protect notch
Label
Write-protect notch
23
Chapter 1 ♦ Welcome to C++
Disk size is measured in bytes, just as RAM is. Disks can hold
many millions of bytes of data. A 60-million-byte hard disk is
common. In computer terminology, a million bytes is called a
megabyte, or M. Therefore, if you have a 60-megabyte hard disk, it
can hold approximately 60 million characters of data before it runs
out of space.
The Monitor
The television-like screen is called the monitor. Sometimes the
monitor is called the CRT (which stands for the primary component
of the monitor, the cathode-ray tube). The monitor is one place where
the output of the computer can be sent. When you want to look at a
list of names and addresses, you could write a C++ program to list
the information on the monitor.
The advantage of screen output over printing is that screen
output is faster and does not waste paper. Screen output, however,
is not permanent. When text is scrolled off-screen (displaced by
additional text coming on-screen), it is gone and you might not
always be able to see it again.
All monitors have a cursor, which is a character such as a
blinking underline or a rectangle. The cursor moves when you type
letters on-screen, and always indicates the location of the next
character to be typed.
Monitors that can display pictures are called graphics monitors.
Most PC monitors are capable of displaying graphics and text, but
some can display only text. If your monitor cannot display colors, it
is called a monochrome monitor.
Your monitor plugs into a display adapter located in your system
unit. The display adapter determines the amount of resolution and
number of possible on-screen colors. Resolution refers to the number
of row and column intersections. The higher the resolution, the more
rows and columns are present on your screen and the sharper your
text and graphics appear. Some common display adapters are
MCGA, CGA, EGA, and VGA.
24
C++ By
EXAMPLE
The Printer
The printer provides a more permanent way of recording your
computer’s results. It is the “typewriter” of the computer. Your
printer can print C++ program output to paper. Generally, you can
print anything that appears on your screen. You can use your printer
to print checks and envelopes too, because most types of paper work
with computer printers.
The two most common PC printers are the dot-matrix printer
and the laser printer. A dot-matrix printer is inexpensive, fast, and
uses a series of small dots to represent printed text and graphics. A
laser printer is faster than a dot-matrix, and its output is much
sharper because a laser beam burns toner ink into the paper. For
many people, a dot-matrix printer provides all the speed and quality
they need for most applications. C++ can send output to either type
of printer.
The Keyboard
Figure 1.3 shows a typical PC keyboard. Most the keys are the
same as those on a standard typewriter. The letter and number keys
in the center of the keyboard produce their indicated characters on-
screen. If you want to type an uppercase letter, be sure to press one
of the Shift keys before typing the letter. Pressing the CapsLock key
shifts the keyboard to an uppercase mode. If you want to type one
of the special characters above a number, however, you must do so
with the Shift key. For instance, to type the percent sign (%), you
would press Shift-5.
Like the Shift keys, the Alt and Ctrl keys can be used with some
other keys. Some C++ programs require that you press Alt or Ctrl
before pressing another key. For instance, if your C++ program
prompts you to press Alt-F, you should press the Alt key, then press
F while still holding down Alt, then release both keys. Do not hold
them both down for long, however, or the computer keeps repeating
your keystrokes as if you typed them more than once.
The key marked Esc is called the escape key. In many C++
programs, you can press Esc to “escape,” or exit from, something
you started and then wanted to stop. For example, if you prompt
your C++ compiler for help and you no longer need the help
25
Chapter 1 ♦ Welcome to C++
message, you can press Esc to remove the help message from the
screen.
Function keys Alt Shift Spacebar Slash (/) Shift Numeric keypad
26
C++ By
EXAMPLE
27
Chapter 1 ♦ Welcome to C++
The Mouse
The mouse is a relatively new input device. The mouse moves
the cursor to any on-screen location. If you have never used a mouse
before, you should take a little time to become skillful in moving the
cursor with it. Your C++ editor (described in Chapter 2, “What is a
Program?”) might use the mouse for selecting commands from its
menus.
Mouse devices have two or three buttons. Most of the time,
pressing the third button produces the same results as simulta-
neously pressing both keys on a two-button mouse.
The Modem
A modem can be A P C modem enables your PC to communicate with other
used to communi- computers over telephone lines. Some modems, called external
cate between two
distant computers.
modems, sit in a box outside your computer. Internal modems reside
inside the system unit. It does not matter which one you have,
because they operate identically.
Some people have modems so they can share data between
their computer and that of a long-distance friend or off-site co-
worker. You can write programs in C++ that communicate with
your modem.
28
C++ By
EXAMPLE
Software
No matter how fast, large, and powerful your computer’s
hardware is, its software determines what work is done and how the
computer does it. Software is to a computer what music is to a stereo
system. You store software on the computer’s disk and load it in
your computer’s memory when you are ready to process the soft-
ware, just as you store music on a tape and play it when you want
to hear music.
29
Chapter 1 ♦ Welcome to C++
MS-DOS
MS-DOS (Microsoft disk operating system) is a system that lets
your C++ programs interact with hardware. MS-DOS (commonly
called DOS) is always loaded into RAM when you turn on your
computer. DOS controls more than just the disks; DOS is there so
your programs can communicate with all the computer’s hardware,
including the monitor, keyboard, and printer.
Figure 1.5 illustrates the concept of DOS as the “go-between”
with your computer’s hardware and software. Because DOS under-
stands how to control every device hooked to your computer, it
stays in RAM and waits for a hardware request. For instance,
printing the words “C++ is fun!” on your printer takes many
computer instructions. However, you do not have to worry about all
30
C++ By
EXAMPLE
Many people program computers for years and never take the
time to learn why DOS is there. You do not have to be an expert in
DOS, or even know more than a few simple DOS commands, to be
proficient with your PC. Nevertheless, DOS does some things that
C++ cannot do, such as formatting disks and copying files to your
disks. As you learn more about the computer, you might see the
need to better understand DOS. For a good introduction to using
DOS, refer to the book MS-DOS 5 QuickStart (Que).
31
Chapter 1 ♦ Welcome to C++
Figure 1.6 shows you the placement of DOS, C++, and your
C++ data area in RAM. This formation is a typical way to represent
RAM—several boxes stacked on top of each other. Each memory
location (each byte) has a unique address, just as everybody’s resi-
dence has a unique address. The first address in memory begins at
0, the second RAM address is 1, and so on until the last RAM
location, many thousands of bytes later.
Figure 1.6. After MS-DOS and a C++ program, there is less RAM for
data.
32
C++ By
EXAMPLE
Review Questions
The answers to each chapter’s review questions are in Appen-
dix B, aptly named “Answers to Review Questions.”
1. What is the name of one of the programming languages
from which C was developed?
2. True or false: C++ is known as a “better C.”
3. In what decade was C++ developed?
4. True or false: C++ is too large to fit on many micro-
computers.
5. Which usually holds more data: RAM or the hard disk?
6. What device is needed for your PC to communicate over
telephone lines?
7. Which of the following device types best describes the
mouse?
a. Storage
b. Input
c. Output
d. Processing
8. What key would you press to turn off the numbers on the
numeric keypad?
9. What operating system is written almost entirely in C?
10. Why is RAM considered volatile?
11. True or false: The greater the resolution, the better the
appearance of graphics on-screen.
12. How many bytes is 512K?
13. What does modem stand for?
33
Chapter 1 ♦ Welcome to C++
Summary
C++ is an efficient, powerful, and popular programming lan-
guage. Whether you are new to C++ or an experienced programmer,
C++ is all you need to program the computer to work the way you
want it to.
This chapter presented the background of C++ by walking you
through the history of its predecessor, the C programming lan-
guage. C++ adds to C and offers some of the most advanced
programming language commands that exist today.
The rest of this book is devoted to teaching you C++. Chapter
2, “What Is a Program?,” explains program concepts so you can
begin to write C++ programs.
34
C++ By
2
EXAMPLE
What Is a
Program?
This chapter introduces you to fundamental programming con-
cepts. The task of programming computers has been described as
rewarding, challenging, easy, difficult, fast, and slow. Actually, it is
a combination of all these descriptions. Writing complex programs
to solve advanced problems can be frustrating and time-consuming,
but you can have fun along the way, especially with the rich
assortment of features that C++ has to offer.
This chapter also describes the concept of programming, from
a program’s inception to its execution on your computer. The most
difficult part of programming is breaking the problem into logical
steps that the computer can execute. Before you finish this chapter,
you will type and execute your first C++ program.
This chapter introduces you to
♦ The concept of programming
♦ The program’s output
♦ Program design
♦ Using an editor
♦ Using a compiler
35
Chapter 2 ♦ What Is a Program?
Computer Programs
Before you can make C++ work for you, you must write a C++
program. You have seen the word program used several times in this
book. The following note defines a program more formally.
36
C++ By
EXAMPLE
37
Chapter 2 ♦ What Is a Program?
Program Design
Design your You must plan your programs before typing them into your
programs before you
type them. C++ editor. When builders construct houses, for example, they don’t
immediately grab their lumber and tools and start building! They
first find out what the owner of the house wants, then they draw up
the plans, order the materials, gather the workers, and finally start
building the house.
The hardest part of writing a program is breaking it into logical
steps that the computer can follow. Learning the C++ language is a
requirement, but it is not the only thing to consider. There is a
method of writing programs, a formal procedure you should learn,
that makes your programming job easier. To write a program you
should:
1. Define the problem to be solved with the computer.
2. Design the program’s output (what the user should see).
38
C++ By
EXAMPLE
39
Chapter 2 ♦ What Is a Program?
40
C++ By
EXAMPLE
41
Chapter 2 ♦ What Is a Program?
42
C++ By
EXAMPLE
UNIX users might have to use the cfront compiler. Most cfront
compilers actually convert C++ code into regular C code. The C code
is then compiled by the system’s C compiler. This produces an
executable file whose name (by default) is A.OUT. You can then run
the A.OUT file from the UNIX prompt. Mainframe users generally
have company-standard procedures for compiling C++ source pro-
grams and storing their results in a test account.
Unlike many other programming languages, your C++ pro-
gram must be routed through a preprocessor before it is compiled.
The preprocessor reads preprocessor directives that you enter in the
program to control the program’s compilation. Your C++ compiler
automatically performs the preprocessor step, so it requires no
additional effort or commands to learn on your part.
You might have to refer to your compiler’s reference manuals
or to your company’s system personnel to learn how to compile
programs for your programming environment. Again, learning the
programming environment is not as critical as learning the C++
language. The compiler is just a way to transform your program
from a source code file to an executable file.
Your program must go through one additional stage after
compiling and before running. It is called the linking, or the link
editing stage. When your program is linked, a program called the
linker supplies needed runtime information to the compiled pro-
gram. You can also combine several compiled programs into one
executable program by linking them. Most of the time, however,
43
Chapter 2 ♦ What Is a Program?
your compiler initiates the link editing stage (this is especially true
with integrated compilers such as Borland C++ and Microsoft C/
C++) and you do not have to worry about the process.
Figure 2.2 shows the steps that your C++ compiler and link
editor perform to produce an executable program.
44
C++ By
EXAMPLE
#include <iostream.h>
main()
{
const char BELL=’\a’; // Constant that rings the bell
int ctr=0; // Integer variable to count through loop
char fname[20]; // Define character array to hold name
45
Chapter 2 ♦ What Is a Program?
Handling Errors
Because you are typing instructions for a machine, you must be
very accurate. If you misspell a word, leave out a quotation mark, or
make another mistake, your C++ compiler informs you with an
error message. In Borland C++ and Microsoft C/C++, the error
probably appears in a separate window, as shown in Figure 2.3. The
most common error is a syntax error, and this usually implies a
misspelled word.
46
C++ By
EXAMPLE
When you get an error message (or more than one), you must
return to the program editor and correct the error. If you don’t
understand the error, you might have to check your reference
manual or scour your program’s source code until you find the
offending code line.
47
Chapter 2 ♦ What Is a Program?
After you have typed your program correctly using the editor
(and you get no compile errors), the program should run properly
by asking for your first name, then printing it on-screen five times.
After it prints your name for the fifth time, you hear the computer’s
bell ring.
This example helps to illustrate the difference between a pro-
gram and its output. You must type the program (or load one from
disk), then run the program to see its output.
Review Questions
The answers to the review questions are in Appendix B,
“Answers to Review Questions.”
1. What is a program?
2. What are the two ways to obtain a program that does what
you want?
3. True or false: Computers can think.
4. What is the difference between a program and its output?
5. What do you use for typing C++ programs into the
computer?
48
C++ By
EXAMPLE
Summary
After reading this chapter, you should understand the steps
necessary to write a C++ program. You know that planning makes
writing the program much easier, and that your program’s instruc-
tions produce the output only after you run the program.
You also learned how to use your program editor and compiler.
Some program editors are as powerful as word processors. Now
that you know how to run C++ programs, it is time to start learning
the C++ programming language.
49
Chapter 2 ♦ What Is a Program?
50
C++ By
3
EXAMPLE
51
Chapter 3 ♦ Your First C++ Program
Preprocessor directives
go here
#include <iostream.h>
Function name main()
{
.
Block . Program goes here
.
}
// Filename: C3FIRST.CPP
// Initial C++ program that demonstrates the C++ comments
// and shows a few variables and their declarations.
52
C++ By
EXAMPLE
#include <iostream.h>
main()
{
int i, j; // These three lines declare four variables.
char c;
float x;
53
Chapter 3 ♦ Your First C++ Program
can start in any column of any line. You can insert blank lines in a
program if you want. This sample program is called C3FIRST.CPP
(you can find the name of each program in this book in the first line
of each program listing). It contains several blank lines to help
separate parts of the program. In a simple program such as this, the
separation is not as critical as it might be in a longer, more complex
program.
Generally, spaces in C++ programs are free-form as well. Your
goal should not be to make your programs as compact as possible.
Your goal should be to make your programs as readable as possi-
ble. For example, the C3FIRST.CPP program shown in the previous
section could be rewritten as follows:
To your C++ compiler, the two programs are exactly the same,
and they produce exactly the same result. However, to people who
have to read the program, the first style is much more readable.
54
C++ By
EXAMPLE
care. Even if nobody else ever looks at your C++ program, you might
have to change it at a later date. The more readable you make your
program, the faster you can find what needs changing, and change
it accordingly.
If you work as a programmer for a corporation, you can almost
certainly expect to modify someone else’s source code, and others
will probably modify yours. In programming departments, it is said
that long-term employees write readable programs. Given this new
global economy and all the changes that face business in the years
ahead, companies are seeking programmers who write for the
future. Programs that are straightforward, readable, abundant with
white space (separating lines and spaces), and devoid of hard-to-read
“tricks” that create messy programs are the most desirable.
Use ample white space so you can have separate lines and
spaces throughout your programs. Notice the first few lines of
C3FIRST.CPP start in the first column, but the body of the program
is indented a few spaces. This helps programmers “zero in” on the
important code. When you write programs that contain several
sections (called blocks), your use of white space helps the reader’s
eye follow and recognize the next indented block.
55
Chapter 3 ♦ Your First C++ Program
main()
{
The statements that follow main() are executed first. The section
of a C++ program that begins with main(), followed by an opening
brace, {, is called the main function. A C++ program is actually a
collection of functions (small sections of code). The function called
main() is always required and always the first function executed.
A C++ block is In the sample program shown here, almost the entire program
enclosed in two is main() because the matching closing brace that follows main()’s
braces.
opening brace is at the end of the program. Everything between two
matching braces is called a block. You read more about blocks in
Chapter 16, “Writing C++ Functions.” For now, you only have to
realize that this sample program contains just one function, main(),
and the entire function is a single block because there is only one
pair of braces.
All executable C++ All executable C++ statements must have a semicolon (;) after
statements must them so C++ is aware that the statement is ending. Because the
end with a semi-
colon (;). computer ignores all comments, do not put semicolons after your
comments. Notice that the lines containing main() and braces do not
end with semicolons either, because these lines simply define the
beginning and ending of the function and are not executed.
As you become better acquainted with C++, you learn when to
include the semicolon and when to leave it off. Many beginning C++
programmers learn quickly when semicolons are required; your
compiler certainly lets you know if you forget to include a semicolon
where one is needed.
Figure 3.2 repeats the sample program shown in Figure 3.1. It
contains additional markings to help acquaint you with these new
terms as well as other items described in the remainder of this
chapter.
56
C++ By
EXAMPLE
// Filename: C3FIRST.CPP
Comments // Initial C++ program that demonstrates the C++ comments
// and shows a few variables and their declarations.
main()
Begin block {
int i, j; // These three lines declare four variables.
Variable declarations char c;
float x;
Comments in C++
In Chapter 2, “What Is a Program?,” you learned the difference
between a program and its output. Most users of a program do not
see the actual program; they see the output from the execution of the
program’s instructions. Programmers, on the other hand, look at the
program listings, add new routines, change old ones, and update for
advancements in computer equipment.
57
Chapter 3 ♦ Your First C++ Program
58
C++ By
EXAMPLE
programmers capitalize the first letter of sentences in comments,
just as you would in everyday writing. Use whatever case seems
appropriate for the letters in your message.
C++ can also use C-style comments. These are comments that
begin with /* and end with */. For instance, this line contains a
comment in the C and C++ style:
netpay = grosspay - taxes; /* Compute take-home pay. */
Comment As You Go
Insert your comments as you write your programs. You are
most familiar with your program logic at the time you are
typing the program in the editor. Some people put off adding
comments until after the program is written. More often than
not, however, those comments are never added, or else they are
written halfheartedly.
If you comment as you write your code, you can glance back at
your comments while working on later sections of the pro-
gram—instead of having to decipher the previous code. This
helps you whenever you want to search for something earlier
in the program.
Examples
1. Suppose you want to write a C++ program that produces a
fancy boxed title containing your name with flashing dots
around it (like a marquee). The C++ code to do this might be
difficult to understand. Before such code, you might want to
insert the following comment so others can understand the
code later:
59
Chapter 3 ♦ Your First C++ Program
The comment is the first of three lines, but this line tells you
in which disk file the program is stored. Throughout this
book, programs have comments that include a possible
filename under which the program can be stored. They
begin with Cx, where x is the chapter number in which they
appear (for example, C6VARPR.CPP and C10LNIN.CPP).
This method helps you find these programs when they are
discussed in another section of the book.
60
C++ By
EXAMPLE
// Filename: C3FIRST.CPP
// Initial C++ program that demonstrates the C++ comments
// and shows a few variables and their declarations.
This comment lists the filename and explains the purpose of the
program. This is not the only comment in the program; others
appear throughout the code.
The next line beginning with #include is called a preprocessor
directive and is shown here:
#include <iostream.h>
main()
{
61
Chapter 3 ♦ Your First C++ Program
5.6
-45
‘Q’
“Mary”
18.67643
0.0
As you can see, some literals are numeric and some are
character-based. The single and double quotation marks around
two of the literals, however, are not part of the actual literals. A
single-character literal requires single quotation marks around it; a
string of characters, such as “Mary”, requires double quotation marks.
62
C++ By
EXAMPLE
Look for the literals in the sample program. You find these:
4
7
‘A’
9.087
4.5
puts the literal value 25000 into the variable named sales. In the
sample program, you find the following variables:
The three lines of code that follow the opening brace of the
sample program declare these variables. This variable declaration
informs the rest of the program that two integer variables named i
and j as well as a character variable called c and a floating-point
variable called x appear throughout the program. The terms integer
and floating-point basically refer to two different types of numbers:
Integers are whole numbers, and floating-point numbers contain
decimal points.
The next few statements of the sample program assign values
to these variables.
63
Chapter 3 ♦ Your First C++ Program
The first line puts 4 in the integer variable, i. The second line
adds 7 to the variable i’s value to get 11, which then is assigned to (or
put into) the variable called j. The plus sign (+) in C++ works just
like it does in mathematics. The other primary math operators are
shown in Table 3.1.
64
C++ By
EXAMPLE
When the program reaches this line, it prints the contents of the
four variables on-screen. The important part of this line is that the
four values for i, j, c, and x print on-screen.
The output from this line is
4, 11, A, 40.891499
Because this is the only cout in the program, this is the only
output the sample program produces. You might think the program
is rather long for such a small output. After you learn more about
C++, you should be able to write more useful programs.
The cout is not a C++ command. You might recall from Chapter
2, “What Is a Program?,” that C++ has no built-in input/output
commands. The cout is an operator, described to the compiler in the
#include file called iostream.h, and it sends output to the screen.
C++ also supports the printf() function for formatted output.
You have seen one function already, main(), which is one for which
you write the code. The C++ programming designers have already
written the code for the printf function. At this point, you can think
of printf as a command that outputs values to the screen, but it is
actually a built-in function. Chapter 7, “Simple Input/Output”
describes the printf function in more detail.
Put a return The last two lines in the program are shown here:
statement at the end
of each function. return 0; // ALWAYS end programs and functions with return.
}
65
Chapter 3 ♦ Your First C++ Program
Review Questions
The answers to the review questions are in Appendix B, aptly
named “Answers to Review Questions.”
1. What must go before each comment in a C++ program?
2. What is a variable?
3. What is a literal?
66
C++ By
EXAMPLE
4. What are four C++ math operators?
5. What operator assigns a variable its value? (Hint: It is called
the assignment operator.)
6. True or false: A variable can consist of only two types:
integers and characters.
7. What is the operator that writes output to the screen?
8. Is the following a variable name or a string literal?
city
Summary
This chapter focused on teaching you to write helpful and
appropriate comments for your programs. You also learned a little
about variables and literals, which hold the program’s data. Without
them, the term data processing would no longer be meaningful (there
would be no data to process).
Now that you have a feel for what a C++ program looks like, it
is time to begin looking at specifics of the commands. Starting with
the next chapter, you begin to write your own programs. The next
chapter picks up where this one left off; it takes a detailed look at
literals and variables, and better describes their uses and how to
choose their names.
67
Chapter 3 ♦ Your First C++ Program
68
C++ By
4
EXAMPLE
Variables and
Literals
To understand data processing with C++, you must understand
how C++ creates, stores, and manipulates data. This chapter teaches
you how C++ handles data by introducing the following topics:
♦ The concepts of variables and literals
♦ The types of C++ variables and literals
♦ Special literals
♦ Constant variables
♦ Naming and using variables
♦ Declaring variables
♦ Assigning values to variables
Garbage in, garbage Now that you have seen an overview of the C++ programming
out! language, you can begin writing C++ programs. In this chapter, you
begin to write your own programs from scratch.
You learned in Chapter 3, “Your First C++ Program,” that C++
programs consist of commands and data. Datum is the heart of all
C++ programs; if you do not correctly declare or use variables and
literals, your data are inaccurate and your results are going to be
69
Chapter 4 ♦ Variables and Literals
inaccurate as well. A computer adage says the if you put garbage in,
you are going to get garbage out. This is very true. People usually
blame computers for mistakes, but the computers are not always at
fault. Rather, their data are often not entered properly into their
programs.
This chapter spends a long time focusing on numeric variables
and numeric literals. If you are not a “numbers” person, do not fret.
Working with numbers is the computer’s job. You have to under-
stand only how to tell the computer what you want it to do.
Variables
Variables have characteristics. When you decide your program
needs another variable, you simply declare a new variable and C++
ensures that you get it. In C++, variable declarations can be placed
anywhere in the program, as long as they are not referenced until
after they are declared. To declare a variable, you must understand
the possible characteristics, which follow.
♦ Each variable has a name.
♦ Each variable has a type.
♦ Each variable holds a value that you put there, by assigning
it to that variable.
The following sections explain each of these characteristics in
detail.
Naming Variables
Because you can have many variables in a single program, you
must assign names to them to keep track of them. Variable names are
unique, just as house addresses are unique. If two variables have the
same name, C++ would not know to which you referred when you
request one of them.
Variable names can be as short as a single letter or as long as 32
characters. Their names must begin with a letter of the alphabet but,
after the first letter, they can contain letters, numbers, and under-
score ( _ ) characters.
70
C++ By
EXAMPLE
Be very careful with the Shift key when you type a variable
name. Do not inadvertently change the case of a variable name
throughout a program. If you do, C++ interprets them as distinct
and separate variables.
Do not give variables Variables cannot have the same name as a C++ command or
the same name as a
command or built-in
function. Appendix E, “Keyword and Function Reference,” shows
function. a list of all C++ command and function names.
The following are invalid variable names:
81_sales Aug91+Sales MY AGE printf
TIP: Although you can call a variable any name that fits the
naming rules (as long as it is not being used by another variable
in the program), you should always use meaningful variable
names. Give your variables names that help describe the values
they are holding.
For example, keeping track of total payroll in a variable called
total_payroll is much more descriptive than using the variable
name XYZ34. Even though both names are valid, total_payroll is
easier to remember and you have a good idea of what the
variable holds by looking at its name.
71
Chapter 4 ♦ Variables and Literals
Variable Types
Variables can hold different types of data. Table 4.1 lists the
different types of C++ variables. For instance, if a variable holds an
integer, C++ assumes no decimal point or fractional part (the part to
the right of the decimal point) exists for the variable’s value. A large
number of types are possible in C++. For now, the most important
types you should concentrate on are char, int, and float. You can
append the prefix long to make some of them hold larger values than
they would otherwise hold. Using the unsigned prefix enables them
to hold only positive numbers.
72
C++ By
EXAMPLE
The next section more fully describes each of these types. For
now, you have to concentrate on the importance of declaring them
before using them.
Declaring Variables
There are two places you can declare a variable:
♦ Before the code that uses the variable
♦ Before a function name (such as before main() in the
program)
The first of these is the most common, and is used throughout
much of this book. (If you declare a variable before a function name,
it is called a global variable. Chapter 17, “Variable Scope,” addresses
the pros and cons of global variables.) To declare a variable, you
must state its type, followed by its name. In the previous chapter,
you saw a program that declared four variables in the following
way.
Start of the main() function.
Declare the variables i and j as integers.
Declare the variable c as a character.
Declare the variable x as a floating-point variable.
main()
{
int i, j; // These three lines declare four variables.
char c;
float x;
// The rest of program follows.
73
Chapter 4 ♦ Variables and Literals
main()
{
int i;
int j;
// The rest of program follows.
Examples
1. Suppose you had to keep track of a person’s first, middle,
and last initials. Because an initial is obviously a character, it
would be prudent to declare three character variables to
hold the three initials. In C++, you could do that with the
following statement:
main()
{
char first, middle, last;
// The rest of program follows.
74
C++ By
EXAMPLE
main()
{
char first;
char middle;
char last;
// The rest of program follows.
main()
{
int age, weight;
// The rest of program follows.
75
Chapter 4 ♦ Variables and Literals
76
C++ By
EXAMPLE
Type Range*
signed short int –32768 to 32767
long int –2147483648 to 2147483647
signed long int –2147483648 to 2147483647
float –3.4E–38 to 3.4E+38
double –1.7E–308 to 1.7E+308
long double –3.4E–4932 to 1.1E+4932
* Use this table only as a guide; different compilers and different computers can have different
ranges.
Notice that long integers and long doubles tend to hold larger
numbers (and therefore, have a higher precision) than regular
integers and regular double floating-point variables. This is due to
the larger number of memory locations used by many of the C++
compilers for these data types. Again, this is usually—but not
always—the case.
77
Chapter 4 ♦ Variables and Literals
78
C++ By
EXAMPLE
character’s ASCII number, and stores that number rather than the
character. Examples that help illustrate this appear later in the
chapter.
79
Chapter 4 ♦ Variables and Literals
Examples
1. If you want to keep track of your current age, salary, and
dependents, you could store these values in three C++
variables. You first declare the variables by deciding on
correct types and good names for them. You then assign
values to them. Later in the program, these values might
change (for example, if the program calculates a new pay
increase for you).
Good variable names include age, salary, and dependents.
To declare these three variables, the first part of the main()
function would look like this:
80
C++ By
EXAMPLE
age=32;
salary=25000.00;
dependents=2;
// Rest of program follows.
81
Chapter 4 ♦ Variables and Literals
main()
{
char first, middle, last;
first = ‘G’;
middle = ‘M’;
last = ‘P’;
// Rest of program follows.
If you did so, middle would hold a strange value that would
seem to be meaningless. Make sure that values you assign to
variables match the variable’s type. The only major exception
to this occurs when you assign an integer to a character vari-
able, or a character to an integer variable, as you learn shortly.
Literals
As with variables, there are several types of C++ literals.
Remember that a literal does not change. Integer literals are whole
numbers that do not contain decimal points. Floating-point literals
82
C++ By
EXAMPLE
are numbers that contain a fractional portion (a decimal point with
an optional value to the right of the decimal point).
83
Chapter 4 ♦ Variables and Literals
C++ knows you want it to use the sign bit as data and not as the
sign. If you declared the same value as a signed integer,
however, as in
int i_num = 0xFFFF; /* The word “signed” is optional.*/
C++ thinks this is a negative number (–1) because the sign bit
is on. (If you were to convert 0xFFFF to binary, you would get
sixteen 1s.) Appendix A, “Memory Addressing, Binary, and
Hexadecimal Review,” discusses these concepts in more detail.
84
C++ By
EXAMPLE
Examples
1. The following program displays a simple message on-screen.
No variables are needed because no datum is stored or
calculated.
85
Chapter 4 ♦ Variables and Literals
// Filename: C4ST1.CPP
// Display a string on-screen.
#include <iostream.h>
main()
{
cout << “C++ programming is fun!”;
return 0;
}
// Filename: C4ST2.CPP
// Compute sales tax and display it with an appropriate
message.
#include <iostream.h>
main()
{
float sale, tax;
float tax_rate = .08; // Sales tax percentage
return 0;
}
86
C++ By
EXAMPLE
Here is the output from the program:
The sales tax is 1.8032
String-Literal Endings
An additional aspect of string literals sometimes confuses
beginning C++ programmers. All string literals end with a zero. You
do not see the zero, but C++ stores the zero at the end of the string
in memory. Figure 4.1 shows what the string “C++ Program” looks like
in memory.
Null zero
You do not have to worry about putting the zero at the end of
a string literal; C++ does it for you every time it stores a string. If your
program contained the string “C++ Program” , for example, the com-
piler would recognize it as a string literal (from the double quotation
marks) and store the zero at the end.
87
Chapter 4 ♦ Variables and Literals
All string literals end The zero is important to C++. It is called the string delimiter.
in a null zero (also Without it, C++ would not know where the string literal ended in
called binary zero or
ASCII zero). memory. (Remember that the double quotation marks are not stored
as part of the string, so C++ cannot use them to determine where the
string ends.)
The string-delimiting zero is not the same as the character zero.
If you look at the ASCII table in Appendix C, “ASCII Table,” you can
see that the first entry, ASCII number 0, is the null character. (If you
are unfamiliar with the ASCII table, you should read Appendix A,
“Memory Addressing, Binary, and Hexadecimal Review,” for a
brief description.) This string-delimiting zero is different from the
from the character ‘0’, which has an ASCII value of 48.
As explained in Appendix A, “Memory Addressing, Binary,
and Hexadecimal Review,” all memory locations in your computer
actually hold bit patterns for characters. If the letter A is stored in
memory, an A is not actually there; the binary bit pattern for the
ASCII A (01000001) is stored there. Because the binary bit pattern for
the null zero is 00000000, the string-delimiting zero is also called a
binary zero.
To illustrate this further, Figure 4.2 shows the bit patterns for
the following string literal when stored in memory: “I am 30”.
String-terminating zero
Figure 4.2. The bit pattern showing that a null zero and a character zero
are different.
88
C++ By
EXAMPLE
String Lengths
The length of a Many times, your program has to know the length of a string.
string literal does This becomes critical when you learn how to accept string input
not include the null
binary zero.
from the keyboard. The length of a string is the number of characters
up to, but not including, the delimiting null zero. Do not include the
null character in that count, even though you know C++ adds it to
the end of the string.
Examples
1. The following are all string literals:
“0” “C” “A much longer string literal”
89
Chapter 4 ♦ Variables and Literals
C++ does not append a null zero to the end of character literals.
You should know that the following are different to C++.
‘R’ and “R”
90
C++ By
EXAMPLE
This is the way to store (or print) any character from the ASCII table,
even if that character does not have a key on your keyboard.
The single quotation marks still tell C++ that a single character
is inside the quotation marks. Even though ‘\xA5’ contains four
characters inside the quotation marks, those four characters repre-
sent a single character, not a character string. If you were to include
those four characters inside a string literal, C++ would treat \xA5 as
a single character in the string. The following string literal,
“An accented a is \xA0”
91
Chapter 4 ♦ Variables and Literals
92
C++ By
EXAMPLE
Examples
1. To print two names on two different lines, include the \n
between them.
Print the name Harry; drop the cursor down to a new line and
print Jerry.
cout << “Harry\nJerry”;
Harry
Jerry
Because the \n only takes one byte of storage, you can output
it as a character literal by typing ‘\n’ in place of the preced-
ing “\n”.
2. The following short program rings the bell on your com-
puter by assigning the \a escape sequence to a variable, then
printing that variable.
// Filename: C4BELL.CPP
// Rings the bell
#include <iostream.h>
main()
{
char bell=’\a’;
cout << bell; // No newline needed here.
return 0;
}
93
Chapter 4 ♦ Variables and Literals
Constant Variables
The term constant variable might seem like a contradiction. After
all, a constant never changes and a variable holds values that
change. In C++ terminology, you can declare variables to be con-
stants with the const keyword. Throughout your program, the
constants act like variables; you can use a constant variable any-
where you can use a variable, but you cannot change constant
variables. To declare a constant, put the keyword const in front of the
variable declaration, for instance:
const int days_of_week = 7;
NOTE: This book reserves the name constant for C++ pro-
gram constants declared with the const keyword. The term
literal is used for numeric, character, and string data values.
Some books choose to use the terms constant and literal inter-
changeably, but in C++, the difference can be critical.
Example
Suppose a teacher wanted to compute the area of a circle for the
class. To do so, the teacher needs the value of π (mathematically, π
is approximately 3.14159). Because π remains constant, it is a good
candidate for a const keyword, as the following program shows:
94
C++ By
EXAMPLE
// Filename: C4AREAC.CPP
// Computes a circle with radius of 5 and 20.
#include <iostream.h>
main()
{
const float PI=3.14159;
float radius = 5;
float area;
return 0;
}
Review Questions
The answers to the review questions are in Appendix B.
1. Which of the following variable names are valid?
my_name 89_sales sales_89 a-salary
95
Chapter 4 ♦ Variables and Literals
int i, j, k;
char c, d, e;
float x=65.43;
#include <iostream.h>
main()
{
const int age=35;
cout << age << “\n”;
age = 52;
cout << age << “\n”;
return 0;
}
96
C++ By
EXAMPLE
Review Exercises
Now that you have learned some basic C++ concepts, the
remainder of the book will include this section of review exercises so
you can practice your programming skills.
1. Write the C++ code to store three variables: your weight
(you can fib), height in feet, and shoe size. Declare the
variables, then assign their values in the body of your
program.
2. Rewrite your program from Exercise 1, adding proper cout
statements to print the values to the screen. Use appropriate
messages (by printing string literals) to describe the numbers
that are printed.
3. Write a program that stores a value and prints each type of
variable you learned in this chapter.
4. Write a program that stores a value into every type of vari-
able C++ allows. You must declare each variable at the
beginning of your program. Give them values and print
them.
Summary
A firm grasp of C++’s fundamentals is critical to a better
understanding of the more detailed material that follows. This is one
of the last general-topic chapters in the book. You learned about
variable types, literal types, how to name variables, how to assign
variable values, and how to declare constants. These issues are
critical to understanding the remaining concepts in C++.
This chapter taught you how to store almost every type of
literal into variables. There is no string variable, so you cannot store
string literals in string variables (as you can in other programming
languages). However, you can “fool” C++ into thinking it has a string
variable by using a character array to hold strings. You learn this
important concept in the next chapter.
97
Chapter 4 ♦ Variables and Literals
98
C++ By
5
EXAMPLE
Character Arrays
and Strings
Even though C++ has no string variables, you can act as if C++ has
them by using character arrays. The concept of arrays might be new
to you, but this chapter explains how easy they are to declare and
use. After you declare these arrays, they can hold character strings—
just as if they were real string variables. This chapter includes
♦ Character arrays
♦ Comparison of character arrays and strings
♦ Examples of character arrays and strings
After you master this chapter, you are on your way to being
able to manipulate almost every type of variable C++ offers. Ma-
nipulating characters and words is one feature that separates your
computer from a powerful calculator; this capability gives comput-
ers true data-processing capabilities.
99
Chapter 5 ♦ Character Arrays and Strings
Character Arrays
A string literal can be Almost every type of data in C++ has a variable, but there is no
stored in an array of variable for holding character strings. The authors of C++ realized
characters.
that you need some way to store strings in variables, but instead of
storing them in a string variable (as some languages such as BASIC
or Pascal do) you must store them in an array of characters.
If you have never programmed before, an array might be new
to you. An array is a list (sometimes called a table) of variables, and
most programming languages allow the use of such lists. Suppose
you had to keep track of the sales records of 100 salespeople. You
could make up 100 variable names and assign a different salesperson’s
sales record to each one.
All those different variable names, however, are difficult to
track. If you were to put them in an array of floating-point variables,
you would have to keep track of only a single name (the array name)
and reference each of the 100 values by a numeric subscript.
The last few chapters of this book cover array processing in
more detail. However, to work with character string data in your
early programs, you have to become familiar with the concept of
character arrays.
Because a string is simply a list of one or more characters, a
character array is the perfect place to hold strings of information.
Suppose you want to keep track of a person’s full name, age, and
salary in variables. The age and salary are easy because there are
variable types that can hold such data. The following code declares
those two variables:
int age;
float salary;
You have no string variable to hold the name, but you can
create an appropriate array of characters (which is actually one or
more character variables in a row in memory) with the following
declaration:
char name[15];
100
C++ By
EXAMPLE
value to the character array at the time you declare the array. The
following declaration statement not only declares the character
array, but also assigns the name “Michael Jones” at the same time:
Declare the character array called name as 15 characters long, and assign
Michael Jones to the array.
Figure 5.1 shows what this array looks like in memory. Each of
the 15 boxes of the array is called an element. Notice the null zero (the
string-terminating character) at the end of the string. Notice also that
the last character of the array contains no data. You filled only the
first 14 elements of the array with the data and the data’s null zero.
The 15th element actually has a value in it—but whatever follows
the string’s null zero is not a concern.
Figure 5.1. A character array after being declared and assigned a string
value.
101
Chapter 5 ♦ Character Arrays and Strings
This overwrites the h in the name Michael with a k. The string now
looks like the one in Figure 5.2.
Figure 5.2. The array contents (see Figure 5.1) after changing one of the
elements.
All array subscripts All array subscripts start at zero. Therefore, to overwrite the
begin at 0. first element, you must use 0 as the subscript. Assigning name[3] (as
is done in Figure 5.2) changes the value of the fourth element in the
array.
You can print the entire string—or, more accurately, the entire
array—with a single cout statement, as follows:
cout << name;
102
C++ By
EXAMPLE
and
char horse[]=”Stallion”;
If you assign a value to a character array at the same time you declare
the array, C++ counts the string’s length, adds one for the null zero,
and reserves the array space for you.
If you do not assign a value to an array at the time it is declared,
you cannot declare it with empty brackets. The following statement,
char people[];
does not reserve any space for the array called people. Because you
did not assign a value to the array when you declared it, C++
assumes this array contains zero elements. Therefore, you have no
room to put values in this array later. Most compilers generate an
error if you attempt this.
Character Arrays
Versus Strings
In the previous section, you saw how to put a string in
a character array. Strings can exist in C++ only as string literals, or
as stored information in character arrays. At this point, you have
only to understand that strings must be stored in character arrays.
As you read through this book and become more familiar with
arrays and strings, however, you should become more comfortable
with their use.
103
Chapter 5 ♦ Character Arrays and Strings
Look at the two arrays shown in Figure 5.3. The first one, called
cara1, is a character array, but it does not contain a string. Rather than
a string, it contains a list of several characters. The second array,
called cara2, contains a string because it has a null zero at its end.
Null zero
Figure 5.3. Two character arrays: Cara1 contains characters, and Cara2
contains a character string.
104
C++ By
EXAMPLE
char cara1[10]={‘a’, ‘b’, ‘c’, ‘d’, ‘e’, ‘f’, ‘g’, ‘h’, ‘i’,
‘j’};
char cara2[10]=”Excellent”;
char cara1[10];
cara1[0]=’a’;
cara1[1]=’b’;
cara1[2]=’c’;
cara1[3]=’d’;
cara1[4]=’e’;
cara1[5]=’f’;
cara1[6]=’g’;
cara1[7]=’h’;
cara1[8]=’i’;
cara1[9]=’j’; // Last element possible with subscript of nine.
Because the cara1 character array does not contain a null zero,
it does not contain a string of characters. It does contain characters
that can be stored in the array—and used individually—but they
cannot be treated in a program as if they were a string.
105
Chapter 5 ♦ Character Arrays and Strings
#include <iostream.h>
main()
{
char petname[20]; // Reserve space for the pet’s name.
petname = “Alfalfa”; // INVALID!
cout << petname; // The program will never get here.
return;
}
Because the pet’s name was not assigned at the time the character
array was declared, it cannot be assigned a value later. The following
is allowed, however, because you can assign values individually to
a character array:
#include <iostream.h>
main()
{
char petname[20]; // Reserve space for the pet’s name.
petname[0]=’A’; // Assign values one element at a time.
petname[1]=’l’;
petname[2]=’f’;
petname[3]=’a’;
petname[4]=’l’;
petname[5]=’f’;
petname[6]=’a’;
petname[7]=’\0'; // Needed to ensure this is a string!
cout <<petname; // Now the pet’s name prints properly.
return;
}
The petname character array now holds a string because the last
character is a null zero. How long is the string in petname? It is seven
characters long because the length of a string never includes the null
zero.
You cannot assign more than 20 characters to this array because
its reserved space is only 20 characters. However, you can store any
string of 19 (leaving one for the null zero) or fewer characters to the
array. If you assign the “Alfalfa” string in the array as shown, and
then assign a null zero to petname[3] as in:
petname[3]=’\0';
106
C++ By
EXAMPLE
the string in petname is now only three characters long. You have, in
effect, shortened the string. There are still 20 characters reserved for
petname, but the data inside it is the string “Alf” ending with a null
zero.
There are many other ways to assign a value to a string. You can
use the strcpy() function, for example. This is a built-in function that
enables you to copy a string literal in a string. To copy the “Alfalfa”
pet name into the petname array, you type:
strcpy(petname, “Alfalfa”); // Copies Alfalfa into the array.
The strcpy() The strcpy() (“string copy”) function assumes that the first
function puts string value in the parentheses is a character array name, and that the
literals in string
arrays. second value is a valid string literal or another character array that
holds a string. You must be sure that the first character array in the
parentheses is long enough (in number of reserved elements) to hold
whatever string you copy into it.
Examples
1. Suppose you want to keep track of your aunt’s name in a
program so you can print it. If your aunt’s name is Ruth Ann
Cooper, you have to reserve at least 16 elements—15 to hold
the name and one to hold the null character. The following
statement properly reserves a character array to hold her
name:
char aunt_name[16];
107
Chapter 5 ♦ Character Arrays and Strings
2. If you want to put your aunt’s name in the array at the same
time you reserve the array space, you could do it like this:
char aunt_name[16]=”Ruth Ann Cooper”;
You could also leave out the array size and allow C++ to
count the number needed:
char aunt_name[]=”Ruth Ann Cooper”;
char friend1[20];
char friend2[20];
char friend3[20];
// Filename: C5INIT.CPP
// Print the user’s initials.
#include <iostream.h>
main()
{
char first[20]; // Holds the first name
char last[20]; // Holds the last name
108
C++ By
EXAMPLE
cout << “What is your last name? \n”;
cin >> last;
// Filename: C5STR.CPP
// Store and initialize three character arrays for three
friends.
#include <iostream.h>
#include <string.h>
main()
{
// Declare all arrays and initialize the first one.
char friend1[20]=”Jackie Paul Johnson”;
char friend2[20];
char friend3[20];
109
Chapter 5 ♦ Character Arrays and Strings
friend3[11]=’t’;
friend3[12]=’h’;
friend3[13]=’\0';
Review Questions
The answers to the review questions are in Appendix B.
1. How would you declare a character array called my_name that
holds the following string literal?
“This is C++”
char name[25];
char address[25];
110
C++ By
EXAMPLE
Review Exercises
1. Write the C++ code to store your weight, height (in feet),
shoe size, and name with four variables. Declare the vari-
ables, then assign their values in the body of your program.
2. Rewrite the program in Exercise 1, adding proper printf()
statements to print the values. Use appropriate messages (by
printing string literals) to describe the printed values.
3. Write a program to store and print the names of your two
favorite television programs. Store these programs in two
character arrays. Initialize one of the strings (assign it the
first program’s name) at the time you declare the array.
Initialize the second value in the body of the program with
the strcpy() function.
4. Write a program that puts 10 different initials in 10 elements
of a single character array. Do not store a null zero. Print the
list backward, one initial on each line.
Summary
This has been a short, but powerful chapter. You learned about
character arrays that hold strings. Even though C++ has no string
variables, character arrays can hold string literals. After you put a
string in a character array, you can print or manipulate it as if it were
a string.
111
Chapter 5 ♦ Character Arrays and Strings
Starting with the next chapter, you begin to hone the C++ skills
you are building. Chapter 6, “Preprocessor Directives,” introduces
preprocessor directives, which are not actually part of the C++
language but help you work with your source code before your
program is compiled.
112
C++ By
6
EXAMPLE
Preprocessor
Directives
As you might recall from Chapter 2, “What Is a Program?,” the C++
compiler routes your programs through a preprocessor before it
compiles them. The preprocessor can be called a “pre-compiler”
because it preprocesses and prepares your source code for compil-
ing before your compiler receives it.
Because this preprocess is so important to C++, you should
familiarize yourself with it before learning more specialized com-
mands in the language. Regular C++ commands do not affect the
preprocessor. You must supply special non-C++ commands, called
preprocessor directives, to control the preprocessor. These directives
enable you, for example, to modify your source code before the code
reaches the compiler. To teach you about the C++ preprocessor, this
chapter
♦ Defines preprocessor directives
♦ Introduces the #include preprocessor directive
♦ Introduces the #define preprocessor directive
♦ Provides examples of both
113
Chapter 6 ♦ Preprocessor Directives
Understanding Preprocessor
Directives
Preprocessor directives are commands that you supply to the
preprocessor. All preprocessor directives begin with a pound sign
(#). Never put a semicolon at the end of preprocessor directives,
because they are preprocessor commands and not C++ commands.
Preprocessor directives typically begin in the first column of your
source program. They can begin in any column, of course, but you
should try to be consistent with the standard practice and start them
in the first column wherever they appear. Figure 6.1 illustrates a
program that contains three preprocessor directives.
// Filename: C6PRE.CPP
// C++ program that demonstrates preprocessor directives.
#include <iostream.h>
Preprocessor
directives #define AGE 28
#define MESSAGE “Hello, world”
main()
{
int i = 10, age; // i is assigned a value at declaration
// age is still UNDEFINED
cout << i << “ “ << age << “ “ << AGE << “\n”; // 280 5 28
cout << MESSAGE; // Prints “Hello world”.
return 0;
}
114
C++ By
EXAMPLE
or
#include “filename”
#include <INSIDE>
115
Chapter 6 ♦ Preprocessor Directives
Assume you can run the OUTSIDE file through the C++
preprocessor, which finds the #include directive and replaces it with
the entire file called INSIDE. In other words, the C++ preprocessor
directive merges the INSIDE file into the OUTSIDE file—at the
#include location—and OUTSIDE expands to include the merged
text. After the preprocessing ends, OUTSIDE looks like this:
The INSIDE file remains on disk in its original form. Only the
file containing the #include directive is changed. This change is only
temporary; that is, OUTSIDE is expanded by the included file only
for as long as it takes to compile the program.
A few real-life examples might help, because the OUTSIDE and
INSIDE files are not C++ programs. You might want to include a file
containing common code that you frequently use. Suppose you
print your name and address quite often. You can type the following
few lines of code in every program that prints your name and
address:
Instead of having to retype the same five lines again and again,
you type them once and save them in a file called MYADD.C. From
then on, you only have to type the single line:
#include <myadd.c>
116
C++ By
EXAMPLE
117
Chapter 6 ♦ Preprocessor Directives
In the last chapter, you saw the strcpy() function. Its header file
is called string.h. Therefore, if you write a program that contains
strcpy(), include its matching header file at the same time you
include <iostream.h>. These appear on separate lines, such as:
#include <iostream.h>
#include <string.h>
The order of your include files does not matter as long as you
include the files before the functions that need them. Most C++
programmers include all their needed header files before main().
These header files are simply text files. If you like, find a header
file such as stdio.h on your hard drive and look at it. The file might
seem complex at this point, but there is nothing “hidden” about it.
Don’t change the header file in any way while looking at it. If you do,
you might have to reload your compiler to restore the file.
Examples
1. The following program is short. It includes the name-and-
address printing routine described earlier. After printing the
name and address, it ends.
// Filename: C6INC1.CPP
// Illustrates the #include preprocessor directives.
#include <iostream.h>
118
C++ By
EXAMPLE
main()
{
#include “myadd.c”
return 0;
}
The double quotation marks are used because the file called
MYADD.C is stored in the same directory as the source file.
Remember that if you type this program into your computer
(after typing and saving the MYADD.C file) and then com-
pile your program, the MYADD.C file is included only as
long as it takes to compile the program. Your compiler does
not see this file. Your compiler acts as if you have typed the
following:
// Filename: C6INCL1.CPP
// Illustrates the #include preprocessor directive.
#include <iostream.h>
main()
{
cout(“Kelly Jane Peterson\n”;
cout(“Apartment #217\n”;
cout(“4323 East Skelly Drive\n”;
cout(“New York, New York\n”;
cout(“ 10012\n”;
return 0;
}
119
Chapter 6 ♦ Preprocessor Directives
// Filename: C6INCL3.CPP
// Uses two header files.
#include <iostream.h>
#include <string.h>
main()
{
char message[20];
strcpy(message, “This is fun!”);
cout << message;
return 0;
}
The #define where ARGUMENT1 is a single word containing no spaces. Use the same
directive replaces naming rules for the #define statement’s first argument as for vari-
every occurrence of
a first argument with ables (see Chapter 4, “Variables and Literals”). For the first argu-
a second argument. ment, it is traditional to use uppercase letters—one of the only uses
of uppercase in the entire C++ language. At least one space separates
ARGUMENT1 from argument2. The argument2 can be any character, word,
or phrase; it also can contain spaces or anything else you can type on
the keyboard. Because #define is a preprocessor directive and not a
C++ command, do not put a semicolon at the end of its expression.
The #define preprocessor directive replaces the occurrence
o f ARGUMENT1 everywhere in your program with the contents of
120
C++ By
EXAMPLE
// Filename: C6DEF1.CPP
// Defines a string literal and uses it twice.
#include <iostream.h>
#define MYNAME “Phil Ward”
main()
121
Chapter 6 ♦ Preprocessor Directives
{
char name[]=MYNAME;
cout << “My name is “ << name << “\n”; // Prints the array.
cout << “My name is “ << MYNAME << “\n”; // Prints the
// defined literal.
return 0;
}
// Filename: C6DEF2.CPP
// Illustrates that #define literals are not variables.
#include <iostream.h>
#define X1 b+c
#define X2 X1 + X1
#define X3 X2 * c + X1 - d
#define X4 2 * X1 + 3 * X2 + 4 * X3
main()
{
int b = 2; // Declares and initializes four variables.
int c = 3;
int d = 4;
int e = X4;
// Prints the values.
cout << e << “, “ << X1 << “, “ << X2;
cout << “, “ << X3 << “, “ << X4 << “\n”;
return 0;
}
122
C++ By
EXAMPLE
If you treated X1, X2, X3, and X4 as variables, you would not
receive the correct answers. X1 through X4 are not variables; they are
defined literals. Before your program is compiled, the preprocessor
reads the first line and changes every occurrence of X1 to b+c. This
occurs before the next #define is processed. Therefore, after the first
#define, the source code looks like this:
// Filename: C6DEF2.CPP
// Illustrates that #define literals are not variables.
#include <iostream.h>
main()
{
int b=2; // Declares and initializes four variables.
int c=3;
int d=4;
int e=X4;
After the first #define finishes, the second one takes over and
changes every occurrence of X2 to b+c + b+c. Your source code at that
point becomes:
// Filename: C6DEF2.CPP
// Illustrates that #define literals are not variables.
#include <iostream.h>
123
Chapter 6 ♦ Preprocessor Directives
main()
{
int b=2; // Declares and initializes four variables.
int c=3;
int d=4;
int e=X4;
After the second #define finishes, the third one takes over and
changes every occurrence of X3 to b+c + b+c * c + b+c - d. Your source
code then becomes:
// Filename: C6DEF2.CPP
// Illustrates that #define literals are not variables.
#include <iostream.h>
main()
{
int b=2; // Declares and initializes four variables.
int c=3;
int d=4;
int e=X4;
124
C++ By
EXAMPLE
// Filename: C6DEF2.CPP
// Illustrates that #define literals are not variables.
#include <iostream.h>
main()
{
int b=2; // Declares and initializes four variables.
int c=3;
int d=4;
int e=2 * b+c + 3 * b+c + b+c + 4 * b+c + b+c * c + b+c - d;
This is what your compiler actually reads. You did not type this
complete listing; you typed the original listing (shown first). The
preprocessor expanded your source code into this longer form, just
as if you had typed it this way.
This is an extreme example, but it serves to illustrate how
#define works on your source code and doesn’t define any variables.
The #define behaves like a word processor’s search-and-replace
command. Due to #define’s behavior, you can even rewrite the C++
language!
If you are used to BASIC, you might be more comfortable
typing PRINT rather than C++’s cout when you want to print on-
screen. If so, the following #define statement,
#define PRINT cout
125
Chapter 6 ♦ Preprocessor Directives
This works because by the time your compiler reads the pro-
gram, it reads only the following:
126
C++ By
EXAMPLE
C++ language more and more. When you are comfortable with
C++, older programs that you redefined will be confusing—
even to you!
If you are programming in C++, use the language conventions
that C++ provides. Shy away from trying to redefine com-
mands in the language. Think of the #define directive as a way
to define numeric and string literals. If those literals ever
change, you have to change only one line in your program.
“Just say no” to any temptation to redefine commands and
built-in functions. Better yet, modify any older C code that uses
#define, and replace the #define preprocessor directive with the
more useful const command.
Examples
1. Suppose you want to keep track of your company’s target
sales amount of $55,000.00. That target amount has not
changed for the previous two years. Because it probably will
not change soon (sales are flat), you decide to start using a
defined literal to represent this target amount. Then, if target
sales do change, you just have to change the amount on the
#define line to:
amt = TARGETSALES
cout << TARGETSALES;
127
Chapter 6 ♦ Preprocessor Directives
(To use angled brackets, you have to store the file in your
system’s include directory.)
3. Defined literals are appropriate for array sizes. For example,
suppose you declare an array for a customer’s name. When
you write the program, you know you don’t have a cus-
tomer whose name is longer than 22 characters (including
the null). Therefore, you can do this:
#define CNMLENGTH 22
Other statements that need the array size also can use
CNMLENGTH.
Review Questions
The answers to the review questions are in Appendix B.
1. True or false: You can define variables with the preprocessor
directives.
128
C++ By
EXAMPLE
2. Which preprocessor directive merges another file into your
program?
3. Which preprocessor directive defines literals throughout
your program?
4. True or false: You can define character, string, integer, and
floating-point literals with the #define directive.
5. Which happens first: your program is compiled or pre-
processed?
6. What C++ keyword is used to replace the #define prepro-
cessor directive?
7. When do you use the angled brackets in an #include, and
when do you use double quotation marks?
8. Which are easier to change: defined literals or literals that
you type throughout a program? Why?
9. Which header file should you include in almost every C++
program you write?
10. True or false: The #define in the following:
#define MESSAGE “Please press Enter to continue...”
// Filename: C6EXER,C
#include <iostream.h>
#define AMT1 a+a+a
#define AMT2 AMT1 - AMT1
main()
{
int a=1;
cout << “Amount is “ << AMT2 << “\n”;
return 0;
}
129
Chapter 6 ♦ Preprocessor Directives
Even if you get this right, you will appreciate the side effects
of #define. The const keyword (discussed in Chapter 4,
“Variables and Literals”) before a constant variable has none
of the side effects that #define has.
Review Exercises
1. Write a program that prints your name to the screen. Use a
defined literal for the name. Do not use a character array,
and don’t type your actual name inside the cout.
2. Suppose your boss wanted you to write a program that
produced an “exception report.” If the company’s sales are
less than $100,000.00 or more than $750,000.00, your boss
wants your program to print the appropriate message. You
learn how to produce these types of reports later in the book,
but for now just write the #define statements that define
these two floating-point literals.
3. Write the cout statements that print your name and birth
date to the screen. Store these statements in their own file.
Write a second program that includes the first file and
prints your name and birth date. Be sure also to include
<iostream.h>, because the included file contains cout
statements.
4. Write a program that defines the ten digits, 0 through 9, as
literals ZERO through NINE. Add these ten defined digits and
print the result.
Summary
This chapter taught you the #include and #define preprocessor
directives. Despite the fact that these directives are not executed,
they temporarily change your source code by merging and defining
literals into your program.
130
C++ By
EXAMPLE
The next chapter, “Simple Input/Output,” explains input and
output in more detail. There are ways to control precision when
using cin and cout, as well as built-in functions that format input
and output.
131
Chapter 6 ♦ Preprocessor Directives
132
C++ By
7
EXAMPLE
Simple
Input/Output
You have already seen the cout operator. It prints values to the
screen. There is much more to cout than you have learned. Using cout
and the screen (the most common output device), you can print
information any way you want it. Your programs also become much
more powerful if you learn to receive input from the keyboard. cin
is an operator that mirrors the cout. Instead of sending output values
to the screen, cin accepts values that the user types at the keyboard.
The cout and cin operators offer the new C++ programmer
input and output operators they can use with relative ease. Both of
these operators have a limited scope, but they give you the ability to
send output from and receive input to your programs. There are
corresponding functions supplied with all C++ compilers called
printf() and scanf(). These functions are still used by C++ program-
mers due to their widespread use in regular C programs.
This chapter introduces you to
♦ The cout operator
♦ Control operators
♦ The cin operator
133
Chapter 7 ♦ Simple Input/Output
Printing Strings
To print a string constant, simply type the string constant after
the cout operator. For example, to print the string, The rain in Spain,
you would simply type this:
Print the sentence “The rain in Spain” to the screen.
cout << “The rain in Spain”;
134
C++ By
EXAMPLE
Line 1
Line 2
Line 3
135
Chapter 7 ♦ Simple Input/Output
cout << “Here is the age that was found in our files:”;
Examples
1. The following program stores a few values in three vari-
ables, then prints the results:
// Filename: C7PRNT1.CPP
// Prints values in variables.
#include <iostream.h>
main()
{
char first = ‘E’; // Store some character, integer,
char middle = ‘W’; // and floating-point variable.
char last = ‘C’;
int age = 32;
int dependents = 2;
float salary = 25000.00;
float bonus = 575.25;
136
C++ By
EXAMPLE
cout << age << dependents;
cout << salary << bonus;
return 0;
}
2. The last program does not help the user. The output is not
labeled, and it prints on a single line. Here is the same
program with a few messages included and some newline
characters placed where needed:
// Filename: C7PRNT2.CPP
// Prints values in variables with appropriate labels.
#include <iostream.h>
main()
{
char first = ‘E’; // Store some character, integer,
char middle = ‘W’; // and floating-point variable.
char last = ‘C’;
int age = 32;
int dependents = 2;
float salary = 25000.00;
float bonus = 575.25;
137
Chapter 7 ♦ Simple Input/Output
// Filename: C7TEAM.CPP
// Prints a table of team names and hits for three weeks.
#include <iostream.h>
main()
{
cout << “Parrots\tRams\tKings\tTitans\tChargers\n”;
cout << “3\t5\t3\t1\t0\n”;
cout << “2\t5\t1\t0\t1\n”;
cout << “2\t6\t4\t3\t0\n”;
return 0;
}
This program produces the table shown below. You can see
that even though the names are different widths, the num-
bers print correctly beneath them. The \t character forces the
next name or value to the next tab position (every eight
characters).
138
C++ By
EXAMPLE
Control Operators
You have already seen the need for additional program-output
control. All floating-point numbers print with too many decimal
places for most applications. What if you want to print only dollars
and cents (two decimal places), or print an average with a single
decimal place?
You can modify the You can specify how many print positions to use in printing a
way numbers print. number. For example, the following cout prints the number 456,
using three positions (the length of the data):
cout << 456;
You typically use the setw manipulator when you want to print
data in uniform columns. Be sure to include the iomanip.h header
file in any programs that use manipulators because iomanip.h
describes how the setw works to the compiler.
The following program shows you the importance of the width
number. Each cout output is described in the comment to its left.
// Filename: C7MOD1.CPP
// Illustrates various integer width cout modifiers.
#include <iostream.h>
#include <iomanip.h>
main()
{ // The output appears below.
cout << 456 << 456 << 456 << “\n”; // Prints 456456456
cout << setw(5) << 456 << setw(5) << 456 << setw(5) <<
456 << “\n”; // Prints 456 456 456
cout << setw(7) << 456 << setw(7) << 456 << setw(7) <<
456 << “ \n”; // Prints 456 456 456
return 0;
}
139
Chapter 7 ♦ Simple Input/Output
You can control the width of strings in the same manner with
the setw manipulator. If you don’t specify enough width to output
the full string, C++ ignores the width. The mailing list application in the
back of this book uses this technique to print names on mailing labels.
140
C++ By
EXAMPLE
Examples
1. If you want to control the width of your data, use a setw
manipulator. The following program is a revision of the
C7TEAM.CPP shown earlier. Instead of using the tab charac-
ter, \t, which is limited to eight spaces, this program uses the
width specifier to set the tabs. It ensures that each column is
10 characters wide.
// Filename: C7TEAMMD.CPP
// Prints a table of team names and hits for three weeks
// using width-modifying conversion characters.
#include <iostream.h>
#include <iomanip.h>
main()
{
cout << setw(10) << “Parrots” << setw(10) <<
“Rams” << setw(10) << “Kings” << setw(10) <<
“Titans” << setw(10) << “Chargers” << “\n”;
cout << setw(10) << 3 << setw(10) << 5 <<
setw(10) << 2 << setw(10) << 1 <<
setw(10) << 0 << “\n”;
cout << setw(10) << 2 << setw(10) << 5 <<
setw(10) << 1 << setw(10) << 0 <<
setw(10) << 1 << “\n”;
cout << setw(10) << 2 << setw(10) << 6 <<
setw(10) << 4 << setw(10) << 3 <<
setw(10) << 0 << “\n”;
return 0;
}
// Filename: C7PAY1.CPP
// Computes and prints payroll data properly in dollars
// and cents.
141
Chapter 7 ♦ Simple Input/Output
#include <iostream.h>
#include <iomanip.h>
main()
{
char emp_name[ ] = “Larry Payton”;
char pay_date[ ] = “03/09/92”;
int hours_worked = 43;
float rate = 7.75; // Pay per hour
float tax_rate = .32; // Tax percentage rate
float gross_pay, taxes, net_pay;
As of: 03/09/92
Larry Payton worked 43 hours
and got paid 333.25
After taxes of: 106.64
his take-home pay was $226.61
142
C++ By
EXAMPLE
// Filename: C7PAY2.CPP
// Computes and prints payroll data properly
// using the shortcut modifier.
#include <iostream.h>
#include <iomanip.h>
main()
{
char emp_name[ ] = “Larry Payton”;
char pay_date[ ] = “03/09/92”;
int hours_worked = 43;
float rate = 7.75; // Pay per hour
float tax_rate = .32; // Tax percentage rate
float gross_pay, taxes, net_pay;
143
Chapter 7 ♦ Simple Input/Output
144
C++ By
EXAMPLE
The cin has its drawbacks. Therefore, in the next few chapters
you will use cin until you learn more powerful (and flexible) input
methods. The cin operator looks much like cout. It contains one or
more variables that appear to the right of the operator name. The
format of the cin is
cin >> value [>> values];
NOTE: The cin operator uses the same manipulators (setw and
setprecision) as the cout operator.
145
Chapter 7 ♦ Simple Input/Output
Examples
1. If you wanted a program that computed a seven percent
sales tax, you could use the cin statement to figure the sales,
compute the tax, and print the results as the following
program shows:
// Filename: C7SLTX1.CPP
// Prompt for a sales amount and print the sales tax.
#include <iostream.h>
#include <iomanip.h>
main()
{
float total_sale; // User’s sale amount goes here.
float stax;
146
C++ By
EXAMPLE
cout << “The sales tax for “ << setprecision(2) <<
total_sale << “ is “ << setprecision (2) << stax;
return 0;
}
// Filename: C7PHON1.CPP
// Program that requests the user’s name and prints it
// to the screen as it would appear in a phone book.
#include <iostream.h>
#include <iomanip.h>
main()
{
char first[20], last[20];
147
Chapter 7 ♦ Simple Input/Output
// Filename: C7MATH.CPP
// Program to help children with simple addition.
// Prompt child for two values after printing
// a title message.
#include <iostream.h>
#include <iomanip.h>
main()
{
int num1, num2, ans;
int her_ans;
148
C++ By
EXAMPLE
149
Chapter 7 ♦ Simple Input/Output
TIP: Despite its name, printf() sends output to the screen and
not to the printer.
You must include the stdio.h header file when using printf()
and scanf() because stdio.h determines how the input and output
functions work in the compiler. The following program assigns a
message in a character array, then prints that message.
// Filename: C7PS2.CPP
// Prints a string stored in a character array.
#include <stdio.h>
main()
{
char message[] = “Please turn on your printer”;
printf(message);
return 0;
}
150
C++ By
EXAMPLE
Conversion Characters
Inside most printf() control strings are conversion characters.
These special characters tell printf() exactly how the data (following
the characters) are to be interpreted. Table 7.1 shows a list of
common conversion characters. Because any type of data can go
inside the printf()’s parentheses, these conversion characters are
required any time you print more than a single string constant. If you
don’t want to print a string, the string constant must contain at least
one of the conversion characters.
151
Chapter 7 ♦ Simple Input/Output
Figure 7.2 shows how C interprets the control string and the
variables that follow. Be sure you understand this example before
moving on. It is the foundation of the printf() function.
Examples
1. The following program stores a few values in three vari-
ables, then prints the results.
152
C++ By
EXAMPLE
// Filename: C7PRNTF.CPP
// Prints values in variables with appropriate labels.
#include <stdio.h>
main()
{
char first=’E’; // Store some character, integer,
char middle=’W’; // and floating-point variable.
char last=’C’;
int age=32;
int dependents=2;
float salary=25000.00;
float bonus=575.25;
153
Chapter 7 ♦ Simple Input/Output
154
C++ By
EXAMPLE
Despite these strange scanf() rules, you can learn this function
quickly by looking at a few examples.
155
Chapter 7 ♦ Simple Input/Output
Examples
1. If you want a program that computes a seven percent sales
tax, you could use the scanf() statement to receive the sales,
compute the tax, and print the results as the following
program shows.
// Filename: C7SLTXS.CPP
// Compute a sales amount and print the sales tax.
#include <stdio.h>
main()
{
float total_sale; // User’s sale amount goes here.
float stax;
If you run this program, the program waits for you to enter a
value for the total sale. Remember to use the ampersand in
front of the total_sale variable when you enter it in the
scanf() function. After pressing the Enter key, the program
calculates the sales tax and prints the results.
If you entered 10.00 as the sale amount, you would receive
the following output :
The sales tax for 10.00 is 0.70
156
C++ By
EXAMPLE
cannot type more than one word into a single character array
with scanf(). The following program is similar to
C7PHON1.CPP except the scanf() function, rather than cin,
is used. It must store two names in two different character
arrays, because scanf() cannot input both names at once. The
program then prints the names in reverse order.
// Filename: C7PHON2.CPP
// Program that requests the user’s name and prints it
// to the screen as it would appear in a phone book.
#include <stdio.h>
main()
{
char first[20], last[20];
printf(“What is your first name? “);
scanf(“ %s”, first);
printf(“What is your last name? “);
scanf(“ %s”, last);
printf(“\n\n”); // Prints two blank lines.
printf(“In a phone book, your name would look like”
“this:\n”);
printf(“%s, %s”, last, first);
return 0;
}
Review Questions
The answers to the Review Questions are in Appendix B.
] 1. What is the difference between cout and cin?
2. Why is a prompt message important before using cin for
input?
157
Chapter 7 ♦ Simple Input/Output
Review Exercises
1. Write a program that prompts the user for his or her name
and weight. Store these values in separate variables and
print them on-screen.
2. Assume you are a college professor and have to average
grades for 10 students. Write a program that prompts you
for 10 different grades, then displays an average of them.
3. Modify the program in Exercise 2 to ask for each student’s
name as well as her grade. Print the grade list to the screen,
with each student’s name and grade in two columns. Make
sure the columns align by using a setw manipulator on the
grade. At the bottom, print the average of the grades. (Hint:
Store the 10 names and 10 grades in different variables with
different names.) This program is easy, but takes thirty or so
lines, plus appropriate comments and prompts. Later, you
learn ways to streamline this program.
158
C++ By
EXAMPLE
+
/*\
|||
* |||
** |||
/\ __* |||
/ \|| /|||\
/ | / * \
/ |======|\ ***
| + + | *
| || |
____|_+||+_|______________/================\_______
Summary
You now can print almost anything to the screen. By studying
the manipulators and how they behave, you can control your output
more thoroughly than ever before. Also, because you can receive
keyboard values, your programs are much more powerful. No
longer do you have to know your data values when you write the
program. You can ask the user to enter values into variables with cin.
You have the tools to begin writing programs that fit the data
processing model of INPUT->PROCESS->OUTPUT. This chapter
concludes the preliminary discussion of the C++ language. This part
of the book attempted to give you an overview of the language and
to teach you enough of the language elements so you can begin
writing helpful programs.
Chapter 8, “Using C++ Math Operators and Precedence,”
begins a new type of discussion. You learn how C++’s math and
relational operators work on data, and the importance of the prece-
dence table of operators.
159
Chapter 7 ♦ Simple Input/Output
160
Part II
Using C++ Operators
C++ By
8
EXAMPLE
163
Chapter 8 ♦ Using C++ Math Operators and Precedence
Many people who dislike math actually enjoy learning how the
computer handles it. After learning the math operators and a few
simple ways in which C++ uses them, you should feel comfortable
using calculations in your programs. Computers are fast, and they
can perform math operations much faster than you can!
164
C++ By
EXAMPLE
Examples
1. The following section of code assigns four variables a posi-
tive or a negative number. The plus and minus signs are all
unary because they are not used between two values.
The variable a is assigned a negative 25 value.
The variable b is assigned a positive 25 value.
The variable c is assigned a negative a value.
The variable d is assigned a positive b value.
165
Chapter 8 ♦ Using C++ Math Operators and Precedence
2. You generally do not have to use the unary plus sign. C++
assumes a number or variable is positive, even if it has no
plus sign. The following four statements are equivalent to
the previous four, except they do not contain plus signs.
// Filename: C8NEG.CPP
// The negative of a variable that contains a negative value.
#include <iostream.h>
main()
{
signed int temp=-12; // ‘signed’ is not needed because
// it is the default.
cout << -temp << “\n”; // Produces a 12 on-screen.
return 0;
}
166
C++ By
EXAMPLE
Examples
1. Suppose you want to compute your weekly pay. The follow-
ing program asks for your yearly pay, divides it by 52, and
prints the results to two decimal places.
// Filename: C8DIV.CPP
// Displays user’s weekly pay.
#include <stdio.h>
main()
{
float weekly, yearly;
printf(“What is your annual pay? “); // Prompt user.
scanf(“%f”, &yearly);
167
Chapter 8 ♦ Using C++ Math Operators and Precedence
Because this program used scanf() and printf() (to keep you
familiar with both ways of performing input and output),
the stdio.h header file is included rather than iostream.h.
2. Integer division does not round its results. If you divide two
integers and the answer is not a whole number, C++ ignores
the fractional part. The following printf()s help show this.
The output that results from each printf() appears in the
comment to the right of each line.
If you said 10, you are not alone; many people respond with 10.
However, 10 is correct only if you interpret the formula from the left.
What if you calculated the multiplication first? If you took the value
of 3 * 2 and got an answer of 6, then added the 2, you receive an
answer of 8—which is exactly the same answer that C++ computes
(and happens to be the correct way)!
C++ performs
C++ always performs multiplication, division, and modulus
multiplication, first, then addition and subtraction. Table 8.3 shows the order of the
division, and operators you have seen so far. Of course, there are many more
modulus before levels to C++’s precedence table of operators than the ones shown in
addition and Table 8.3. Unlike most computer languages, C++ has 20 levels of
subtraction.
precedence. Appendix D, “C++ Precedence Table,” contains the
complete precedence table. Notice in this appendix that multiplica-
tion, division, and modulus reside on level 8, one level higher than
168
C++ By
EXAMPLE
level 9’s addition and subtraction. In the next few chapters, you learn
how to use the remainder of this precedence table in your C++
programs.
Examples
1. It is easy to follow C++’s order of operators if you follow the
intermediate results one at a time. The three calculations in
Figure 8.1 show you how to do this.
6 + 2 * 3 - 4 / 2
6 + 6 - 4 / 2
6 + 6 - 2
12 - 2
10
3 * 4 / 2 + 3 - 1
12 / 2 + 3 - 1
6 + 3 - 1
9 - 1
20 / 3 + 5 % 2
6 + 5 % 2
6 + 1
169
Chapter 8 ♦ Using C++ Math Operators and Precedence
10 / 5 * 2 - 2 + 1
2 * 2 - 2 + 1
4 - 2 + 1
2 + 1
Figure 8.2. C++’s order of operators from the left, with lines indicating
precedence.
Using Parentheses
If you want to override the order of precedence, you can add
parentheses to the calculation. The parentheses actually reside on a
level above the multiplication, division, and modulus in the prece-
dence table. In other words, any calculation in parentheses—whether
it is addition, subtraction, division, or whatever—is always calcu-
lated before the rest of the line. The other calculations are then
performed in their normal operator order.
170
C++ By
EXAMPLE
Parentheses override The first formula in this chapter, 2 + 3 * 2, produced an 8 because
the usual order of the multiplication was performed before addition. However, by
math.
adding parentheses around the addition, as in (2 + 3) * 2, the answer
becomes 10.
In the precedence table shown in Appendix D, “C++ Prece-
dence Table,” the parentheses reside on level 3. Because they are
higher than the other levels, the parentheses take precedence over
multiplication, division, and all other operators.
Examples
1. The calculations shown in Figure 8.3 illustrate how paren-
theses override the regular order of operators. These are the
same three formulas shown in the previous section, but their
results are calculated differently because the parentheses
override the normal order of operators.
6 + 2 * (3 - 4) / 2
6 + 2 * -1 / 2
6 + -2 / 2
6 + -1
3 * 4 / 2 + (3 - 1)
3 * 4 / 2 + 2
12 / 2 + 2
6 + 2
20 / (3 + 5) % 2
20 / 8 % 2
2 % 2
171
Chapter 8 ♦ Using C++ Math Operators and Precedence
5 * (5 + (6 - 2) + 1)
5 * (5 + 4 + 1)
5 * (9 + 1)
5 * 10
50
// Filename: C8AVG1.CPP
// Compute the average of three grades.
#include <iostream.h>
main()
{
float avg, grade1, grade2, grade3;
grade1 = 87.5;
grade2 = 92.4;
grade3 = 79.6;
172
C++ By
EXAMPLE
avg = grade1 + grade2 + grade3 / 3.0;
cout << “The average is “ << avg << “\n”;
return 0;
}
// Filename: C8AVG2.CPP
// Compute the average of three grades.
#include <iostream.h>
main()
{
float avg, grade1, grade2, grade3;
grade1 = 87.5;
grade2 = 92.4;
grade3 = 79.6;
173
Chapter 8 ♦ Using C++ Math Operators and Precedence
Multiple Assignments
If two or more equal signs appear in an expression, each
performs an assignment. This fact introduces a new aspect of the
precedence order you should understand. Consider the following
expression:
a=b=c=d=e=100;
main()
{
int ctr, num_emp, num_dep;
float sales, salary, amount;
ctr=num_emp=num_dep=0;
sales=salary=amount=0;
// Rest of program follows.
175
Chapter 8 ♦ Using C++ Math Operators and Precedence
value = 5 + (r = 9 - c);
Example
Because C++ does not initialize variables to zero before you use
them, you might want to include a multiple assignment operator to
do so before using the variables. The following section of code
ensures that all variables are initialized before the rest of the pro-
gram uses them.
main()
{
int num_emp, dependents, age;
float salary, hr_rate, taxrate;
Compound Assignments
Many times in programming, you might want to update the
value of a variable. In other words, you have to take a variable’s
current value, add or multiply that value by an expression, then
reassign it to the original variable. The following assignment state-
ment demonstrates this process:
salary=salary*1.2;
176
C++ By
EXAMPLE
-= budget-=50; budget=budget-50;
*= salary*=1.2; salary=salary*1.2;
/= factor/=.50; factor=factor/.50;
%= daynum%=7; daynum=daynum%7;
Examples
1. You have been storing your factory’s production amount
in a variable called prod_amt, and your supervisor has just
informed you that a new addition has to be applied to the
production value. You could code this update in a statement,
as follows:
prod_amt = prod_amt + 2.6; // Add 2.6 to current production.
4-factor+bonus
and
sales = sales * (4 - factor + bonus);
the smaller of the two types into the other. For instance, if you add
a double to an integer, C++ first converts the integer into a double
value, then performs the calculation. This method produces the
most accurate result possible. The automatic conversion of data
types is only temporary; the converted value is back in its original
data type as soon as the expression is finished.
C++ attempts to If C++ converted two different data types to the smaller value’s
convert the smaller
data type to the
type, the higher-precision value is truncated, or shortened, and
larger one in a accuracy is lost. For example, in the following short program, the
mixed data-type floating-point value of sales is added to an integer called bonus.
expression. Before C++ computes the answer, it converts bonus to floating-point,
which results in a floating-point answer.
// Filename: C8DATA.CPP
// Demonstrate mixed data type in an expression.
#include <stdio.h>
main()
{
int bonus=50;
float salary=1400.50;
float total;
Type Casting
Most of the time, you don’t have to worry about C++’s auto-
matic conversion of data types. However, problems can occur if you
mix unsigned variables with variables of other data types. Due to
differences in computer architecture, unsigned variables do not
always convert to the larger data type. This can result in loss of
accuracy, and even incorrect results.
You can override C++’s default conversions by specifying your
own temporary type change. This process is called type casting.
When you type cast, you temporarily change a variable’s data type
179
Chapter 8 ♦ Using C++ Math Operators and Precedence
from its declared data type to a new one. There are two formats of
the type cast. They are
(data type) expression
and
data type(expression)
where data type can be any valid C++ data type, such as int or float,
and the expression can be a variable, literal, or an expression that
combines both. The following code temporarily type casts the
integer variable age into a double floating-point variable, so it can be
multiplied by the double floating-point factor. Both formats of the
type cast are illustrated.
The variable age_factor is assigned the value of the variable age (now
treated like a double floating-point variable) multiplied by the variable
factor.
180
C++ By
EXAMPLE
Examples
1. Suppose you want to verify the interest calculation used by
your bank on a loan. The interest rate is 15.5 percent, stored
as .155 in a floating-point variable. The amount of interest
you owe is computed by multiplying the interest rate by the
amount of the loan balance, then multiplying that by the
number of days in the year since the loan originated. The
following program finds the daily interest rate by dividing
the annual interest rate by 365, the number of days in a year.
C++ must convert the integer 365 to a floating-point literal
automatically, because it is used in combination with a
floating-point variable.
// Filename: C8INT1.CPP
// Calculate interest on a loan.
#include <stdio.h>
main()
{
int days=45; // Days since loan origination.
float principle = 3500.00; // Original loan amount
float interest_rate=0.155; // Annual interest rate
float daily_interest; // Daily interest rate
181
Chapter 8 ♦ Using C++ Math Operators and Precedence
// Filename: C8INT2.CPP
// Calculate interest on a loan using type casting.
#include <stdio.h>
main()
{
int days=45; // Days since loan origination.
float principle = 3500.00; // Original loan amount
float interest_rate=0.155; // Annual interest rate
float daily_interest; // Daily interest rate
Review Questions
The answers to the review questions are in Appendix B.
1. What is the result for each of the following expressions?
a. 1 + 2 * 4 / 2
b. (1 + 2) * 4 / 2
c. 1 + 2 * (4 / 2)
182
C++ By
EXAMPLE
b. (1 + (10 - (2 + 2)))
b. x = (a - b)*(a - c)2
a2
c. f =
b3
(8 - x2) (4 * 2 - 1)
d. d = -
(x - 9) x3
Review Exercises
1. Write a program that prints each of the first eight powers
of 2 (21, 22, 23,...28). Please write comments and include
your name at the top of the program. Print string literals
that describe each answer printed. The first two lines of
your output should look like this:
183
Chapter 8 ♦ Using C++ Math Operators and Precedence
Summary
You now understand C++’s primary math operators and the
importance of the precedence table. Parentheses group operations
so they can override the default precedence levels. Unlike some
other programming languages, every operator in C++ has a mean-
ing, no matter where it appears in an expression. This fact enables
you to use the assignment operator (the equal sign) in the middle of
other expressions.
When you perform math with C++, you also must be aware of
how C++ interprets data types, especially when you mix them in the
same expression. Of course, you can temporarily type cast a variable
or literal so you can override its default data type.
This chapter has introduced you to a part of the book concerned
with C++ operators. The following two chapters (Chapter 9, “Rela-
tional Operators,” and Chapter 10, “Logical Operators”) extend this
introduction to include relational and logical operators. They enable
you to compare data and compute accordingly.
184
C++ By
9
EXAMPLE
Relational
Operators
Sometimes you won’t want every statement in your C++ program to
execute every time the program runs. So far, every program in this
book has executed from the top and has continued, line-by-line,
until the last statement completes. Depending on your application,
you might not always want this to happen.
Programs that don’t always execute by rote are known as data-
driven programs. In data-driven programs, the data dictates what
the program does. You would not want the computer to print every
employee’s paychecks for every pay period, for example, because
some employees might be on vacation, or they might be paid on
commission and not have made a sale during that period. Printing
paychecks with zero dollars is ridiculous. You want the computer to
print checks only for employees who have worked.
This chapter shows you how to create data-driven programs.
These programs do not execute the same way every time. This is
possible through the use of relational operators that conditionally
control other statements. Relational operators first “look” at the
literals and variables in the program, then operate according to what
they “find.” This might sound like difficult programming, but it is
actually straightforward and intuitive.
185
Chapter 9 ♦ Relational Operators
186
C++ By
EXAMPLE
Examples
1. Assume that a program initializes four variables as follows:
int a=5;
int b=10;
int c=15;
int d=5;
b is not equal to c, so b != c
187
Chapter 9 ♦ Relational Operators
a == b
b > c
d < a
d > a
a != d
b >= c
c <= b
188
C++ By
EXAMPLE
“relational logic,” because you just saw how you use it in every-
day life. Nevertheless, symbols confuse some people.
The two primary relational operators, less than (<) and greater
than (>), are easy to remember. You probably learned this
concept in school, but might have forgotten it. Actually, their
signs tell you what they mean.
The arrow points to the lesser of the two values. Notice how, in
the previous Example 1, the arrow (the point of the < or >)
always points to the lesser number. The larger, open part of the
arrow points to the larger number.
The relation is False if the arrow is pointing the wrong way. In
other words, 4 > 9 is False because the operator symbol is
pointing to the 9, which is not the lesser number. In English this
statement says, “4 is greater than 9,” which is clearly false.
The if Statement
You incorporate relational operators in C++ programs with the
if statement. Such an expression is called a decision statement because
it tests a relationship—using the relational operators—and, based
on the test’s result, makes a decision about which statement to
execute next.
The if statement appears as follows:
if (condition)
{ block of one or more C++ statements }
189
Chapter 9 ♦ Relational Operators
If only one statement follows the if, the braces are not required
(but it is always good to include them). The block executes only if
condition is True. If condition is False, C++ ignores the block and
simply executes the next appropriate statement in the program that
follows the if statement.
The if statement Basically, you can read an if statement in the following way: “If
makes a decision. the condition is True, perform the block of statements inside the
braces. Otherwise, the condition must be False; so do not execute
that block, but continue executing the remainder of the program as
though this if statement did not exist.”
The if statement is used to make a decision. The block of
statements following the if executes if the decision (the result of the
relation) is True, but the block does not execute otherwise. As with
relational logic, you also use if logic in everyday life. Consider the
statements that follow.
“If the day is warm, I will go swimming.”
“If I make enough money, we will build a new house.”
“If the light is green, go.”
“If the light is red, stop.”
Each of these statements is conditional. That is, if and only if the
condition is true do you perform the activity.
190
C++ By
EXAMPLE
main()
if (age=85)
191
Chapter 9 ♦ Relational Operators
Examples
1. The following are examples of valid C++ if statements.
If (the variable sales is greater than 5000), then the variable bonus
becomes equal to 500.
If the value in age is less than or equal to 21, the lines of code
within the block execute next. Otherwise, C++ skips the
entire block and continues with the remaining program.
If (the variable balance is greater than the variable low_balance),
then print Past due! to the screen and move the cursor to a new
line.
// Filename: C9PAY1.CPP
// Calculates a salesperson’s pay based on his or her sales.
#include <iostream.h>
#include <stdio.h>
main()
{
char sal_name[20];
int hours;
float total_sales, bonus, pay;
193
Chapter 9 ♦ Relational Operators
return 0;
}
This program uses cout, cin, and printf() for its input and
output. You can mix them. Include the appropriate header
files if you do (stdio.h and iostream.h).
The following output shows the result of running this
program twice, each time with different input values. Notice
that the program does two different things: It computes a
bonus for one employee, but doesn’t for the other. The $500
bonus is a direct result of the if statement. The assignment
of $500 to bonus executes only if the value in total_sales is
more than $8500.
Payroll Calculation
-------------------
What is salesperson’s last name? Harrison
How many hours did the salesperson work? 40
What were the total sales? 6050.64
Harrison made $164.00
and got a bonus of $0.00
194
C++ By
EXAMPLE
Payroll Calculation
-------------------
What is salesperson’s last name? Robertson
How many hours did the salesperson work? 40
What were the total sales? 9800
Robertson made $164.00
and got a bonus of $500.00
// Filename: C9AGE.CPP
// Program that ensures age values are reasonable.
#include <stdio.h>
main()
{
int age;
195
Chapter 9 ♦ Relational Operators
196
C++ By
EXAMPLE
The program takes a value from the user and prints its
square—unless it is more than 180. The message * Square is
not allowed for numbers over 180 * appears on-screen if the
user types a huge number.
// Filename: C9SQR1.CPP
// Print the square of the input value
// if the input value is less than 180.
#include <iostream.h>
main()
{
int num, square;
197
Chapter 9 ♦ Relational Operators
This single line does what it took the previous four lines to
do. Because the assignment on the extreme right has prece-
dence, it is computed first. The program compares the
variable sales to 10000. If it is more than 10000, a True result
of 1 returns. The program then multiplies 1 by 500.00 and
stores the result in commission. If, however, the sales were not
198
C++ By
EXAMPLE
if (condition)
{ A block of 1 or more C++ statements }
else
{ A block of 1 or more C++ statements }
199
Chapter 9 ♦ Relational Operators
Examples
1. The following program asks the user for a number. It then
prints whether or not the number is greater than zero, using
the if-else statement.
// Filename: C9IFEL1.CPP
// Demonstrates if-else by printing whether an
// input value is greater than zero or not.
#include <iostream.h>
main()
{
int num;
if (num > 0)
{ cout << “More than 0\n”; }
else
{ cout << “Less or equal to 0\n”; }
// Filename: C9IFEL2.CPP
// Tests the user’s first initial and prints a message.
#include <iostream.h>
main()
{
200
C++ By
EXAMPLE
char last[20]; // Holds the last name.
cout << “What is your last name? “;
cin >> last;
// Filename: C9PAY2.CPP
// Compute the full overtime pay possibilities.
#include <iostream.h>
#include <stdio.h>
main()
{
int hours;
float dt, ht, rp, rate, pay;
201
Chapter 9 ♦ Relational Operators
// Regular Pay
if (hours >= 40)
{ rp = 40 * rate; }
else
{ rp = (float)hours * rate; }
// Filename: C9SERV.CPP
// Prints a message depending on years of service.
#include <iostream.h>
main()
{
int yrs;
cout << “How many years of service? “;
cin >> yrs; // Determine the years they have worked.
202
C++ By
EXAMPLE
Review Questions
The answers to the review questions are in Appendix B.
1. Which operator tests for equality?
2. State whether each of these relational tests is True or False:
a. 4 >= 5
b. 4 == 4
d. 0 != 25
203
Chapter 9 ♦ Relational Operators
if (3 != 4 != 1)
{ printf(“This will print”); }
Review Exercises
1. Write a weather-calculator program that asks for a list of the
previous five days’ temperatures, then prints Brrrr! every
time a temperature falls below freezing.
2. Write a program that asks for a number and then prints the
square and cube (the number multiplied by itself three
times) of the number you input, if that number is more than
1. Otherwise, the program does not print anything.
204
C++ By
EXAMPLE
Summary
You now have the tools to write powerful data-checking pro-
grams. This chapter showed you how to compare literals, variables,
and combinations of both by using the relational operators. The if
and the if-else statements rely on such data comparisons to deter-
mine which code to execute next. You can now conditionally execute
statements in your programs.
The next chapter takes this one step further by combining
relational operators to create logical operators (sometimes called
compound conditions). These logical operators further improve your
program’s capability to make selections based on data comparisons.
205
Chapter 9 ♦ Relational Operators
206
C++ By
10EXAMPLE
Logical Operators
C++’s logical operators enable you to combine relational operators
into more powerful data-testing statements. The logical operators
are sometimes called compound relational operators. As C++’s prece-
dence table shows, relational operators take precedence over logical
operators when you combine them. The precedence table plays an
important role in these types of operators, as this chapter empha-
sizes.
This chapter introduces you to
♦ The logical operators
♦ How logical operators are used
♦ How logical operators take precedence
This chapter concludes your study of the conditional testing
that C++ enables you to perform, and it illustrates many examples
of if statements in programs that work on compound conditional
tests.
207
Chapter 10 ♦ Logical Operators
The first two logical operators, && and ||, never appear by
themselves. They typically go between two or more relational tests.
Logical operators Table 10.2 shows you how each logical operator works. These
enable the user to tables are called truth tables because they show you how to achieve
compute compound
relational tests. True results from an if statement that uses these operators. Take
some time to study these tables.
208
C++ By
EXAMPLE
If the variable a is less than the variable b, and the variable c is greater than
the variable d, then print Results are invalid. to the screen.
The variable a must be less than b and, at the same time, c must
be greater than d for the printf() to execute. The if statement still
requires parentheses around its complete conditional test. Consider
this portion of a program:
The || is The sales must be more than 5000, or the hrs_worked must be
sometimes called more than 81, before the assignment executes.
inclusive OR. Here is
a program segment
if (!(sales < 2500))
that includes the not
(!) operator: { bonus = 500; }
209
Chapter 10 ♦ Logical Operators
Internal Truths
The True or False results of relational tests occur internally at
the bit level. For example, take the if test:
if (a == 6) ...
210
C++ By
EXAMPLE
C++ only evaluates the first condition, (5 > 4), and realizes it does
not have to look further. Because (5 > 4) is True and because || (OR)
anything that follows it is still True, C++ does not bother with the
rest of the expression. The same holds true for the following state-
ment:
if ((7 < 3) && (age > 15) && (initial == ‘D’))...
inventory_flag) = ‘Y’;
if ((sales > old_sales) || (inventory_flag))...
211
Chapter 10 ♦ Logical Operators
Examples
1. The summer Olympics are held every four years during each
year that is divisible evenly by 4. The U.S. Census is taken
every 10 years, in each year that is evenly divisible by 10.
The following short program asks for a year, and then tells
the user if it is a year of the summer Olympics, a year of the
census, or both. It uses relational operators, logical opera-
tors, and the modulus operator to determine this output.
// Filename: C10YEAR.CPP
// Determines if it is Summer Olympics year,
// U.S. Census year, or both.
#include <iostream.h>
main()
{
int year;
// Ask for a year
cout << “What is a year for the test? “;
cin >> year;
212
C++ By
EXAMPLE
// Filename: C10AGE.CPP
// Program that helps ensure age values are reasonable.
#include <iostream.h>
main()
{
int age;
213
Chapter 10 ♦ Logical Operators
// Filename: C10VIDEO.CPP
// Program that computes video rental amounts and gives
// appropriate discounts based on the day or customer status.
#include <iostream.h>
#include <stdio.h>
main()
{
float tape_charge, discount, rental_amt;
char first_name[15];
char last_name[15];
int num_tapes;
char val_day, sp_stat;
tape_charge = 2.00;
// Before-discount tape fee-per tape.
214
C++ By
EXAMPLE
discount = 0.0; // Increase discount if they are eligible.
if ((val_day == ‘Y’) || (sp_stat == ‘Y’))
{ discount = 0.5;
rental_amt=(num_tapes*tape_charge)
(discount*num_tapes); }
** Rental Club **
215
Chapter 10 ♦ Logical Operators
This still might be confusing, but it is less so. The two multipli-
cations are performed first, followed by the relations < and >. The &&
is performed last because it is lowest in the precedence order of
operators.
To avoid such ambiguous problems, be sure to use ample
parentheses—even if the default precedence order is your intention.
It is also wise to resist combining too many expressions inside a
single if relational test.
Notice that || (OR) has lower precedence than && (AND).
Therefore, the following if tests are equivalent:
216
C++ By
EXAMPLE
Review Questions
The answers to the review questions are in Appendix B.
1. What are the three logical operators?
2. The following compound relational tests produce True or
False comparisons. Determine which are True and which are
False.
a. ! (True || False)
b. 12 - i || k
c. j != k && i != k
// Filename: C10LOGO.CPP
// Logical operator test
#include <iostream.h>
main()
{
int f, g;
g = 5;
f = 8;
if ((g = 25) || (f = 35))
217
Chapter 10 ♦ Logical Operators
b. 8 + 9 != 6 - 1 || 10 % 2 != 5 + 0
c. 17 - 1 > 15 + 1 && 0 + 2 != 1 == 1 || 4 != 1
if (!0)
{ cout << “C++ By Example \n”; }
Review Exercises
1. Write a program (by using a single compound if state-
ment) to determine whether the user enters an odd positive
number.
2. Write a program that asks the user for two initials. Print a
message telling the user if the first initial falls alphabetically
before the second.
3. Write a number-guessing game. Assign a value to a variable
called number at the top of the program. Give a prompt that
asks for five guesses. Receive the user’s five guesses with a
single scanf() for practice with scanf(). Determine whether
any of the guesses match the number and print an appropriate
message if one does.
4. Write a tax-calculation routine, as follows: A family pays no
tax if its income is less than $5,000. It pays a 10 percent tax if
its income is $5,000 to $9,999, inclusive. It pays a 20 percent
tax if the income is $10,000 to $19,999, inclusive. Otherwise,
it pays a 30 percent tax.
218
C++ By
EXAMPLE
Summary
This chapter extended the if statement to include the &&, ||, and
! logical operators. These operators enable you to combine several
relational tests into a single test. C++ does not always have to
look at every relational operator when you combine them in an ex-
pression.
This chapter concludes the explanation of the if statement. The
next chapter explains the remaining regular C++ operators. As you
saw in this chapter, the precedence table is still important to the C++
language. Whenever you are evaluating expressions, keep the pre-
cedence table in the back of your mind (or at your fingertips) at all
times!
219
Chapter 10 ♦ Logical Operators
220
C++ By
11EXAMPLE
Additional C++
Operators
C++ has several other operators you should learn besides those you
learned in Chapters 9 and 10. In fact, C++ has more operators than
most programming languages. Unless you become familiar with
them, you might think C++ programs are cryptic and difficult to
follow. C++’s heavy reliance on its operators and operator prece-
dence produces the efficiency that enables your programs to run
more smoothly and quickly.
This chapter teaches you the following:
♦ The ?: conditional operator
♦ The ++ increment operator
♦ The –– decrement operator
♦ The sizeof operator
♦ The (,) comma operator
♦ The Bitwise Operators (&, |, and ^)
221
Chapter 11 ♦ Additional C++ Operators
222
C++ By
EXAMPLE
if (a > b)
{ ans = 10; }
else
{ ans = 25; }
You can easily rewrite this kind of if-else code by using a single
conditional operator.
If the variable a is greater than the variable b, make the variable ans
equal to 10; otherwise, make ans equal to 25.
a > b ? (ans = 10) : (ans = 25);
223
Chapter 11 ♦ Additional C++ Operators
Examples
1. Suppose you are looking over your early C++ programs, and
you notice the following section of code.
224
C++ By
EXAMPLE
if (testvar < 0)
{ sign = -1; }
else
{ sign = (testvar > 0); } // testvar can only be
// 0 or more here.
++ ++i; prefix i = i + 1; i += 1;
–– i––; postfix i = i - 1; i -= 1;
–– ––i; prefix i = i - 1; i -= 1;
225
Chapter 11 ♦ Additional C++ Operators
Whether you use prefix or postfix does not matter—if you are
incrementing or decrementing single variables on lines by them-
selves. However, when you combine these two operators with other
operators in a single expression, you must be aware of their differ-
ences. Consider the following program section. Here, all variables
are integers because the increment and decrement operators work
only on integer variables.
Make a equal to 6. Increment a, subtract 1 from it, then assign the result
to b.
a = 6;
b = ++a - 1;
What are the values of a and b after these two statements finish?
The value of a is easy to determine: it is incremented in the second
statement, so it is 7. However, b is either 5 or 6 depending on when
the variable a increments. To determine when a increments, consider
the following rule:
226
C++ By
EXAMPLE
a = 6;
b = a++ - 1;
a = 6;
b = a - 1;
a++;
227
Chapter 11 ♦ Additional C++ Operators
There are too many unneeded parentheses here, but even the
redundant parentheses are not enough to increment amt before
adding its value to p. Postfix increments and decrements always
occur after their variables are used in the surrounding expression.
Examples
1. As you should with all other C++ operators, keep the prece-
dence table in mind when you evaluate expressions that
increment and decrement. Figures 11.2 and 11.3 show you
some examples that illustrate these operators.
2. The precedence table takes on even more meaning when you
see a section of code such as that shown in Figure 11.3.
3. Considering the precedence table—and, more importantly,
what you know about C++’s relational efficiencies—what is
the value of the ans in the following section of code?
228
C++ By
EXAMPLE
ans = i || j–– && k++ || ++l && ++m || n–– & !o || p––;
|
1 (TRUE)
int i=1;
int j=2;
int k=3;
ans = i++ * j - ––k;
|
i++ * j - 2
2 - 2
int i=1;
int j=2;
int k=3;
ans = ++i * j - k––;
|
2 * j - k––
4 - k––
229
Chapter 11 ♦ Additional C++ Operators
int i=0;
int j=-1;
int k=0;
int m=1
ans = i++ && ++j || k || m++;
|
i++ && 0 || k || m++
0 || k || m++
0 || m++
230
C++ By
EXAMPLE
or
sizeof(data type)
Examples
1. Suppose you want to know the size, in bytes, of floating-
point variables for your computer. You can determine
this by entering the keyword float in parentheses—after
sizeof—as shown in the following program.
231
Chapter 11 ♦ Additional C++ Operators
// Filename: C11SIZE1.CPP
// Prints the size of floating-point values.
#include <iostream.h>
main()
{
cout << “The size of floating-point variables on \n”;
cout << “this computer is “ << sizeof(float) << “\n”;
return 0;
}
main()
{
int i=10, j=25;
// Remainder of the program follows.
232
C++ By
EXAMPLE
Examples
1. You can put more than one expression on a line, using the
comma as a sequence point. The following program does
this.
// Filename: C11COM1.CPP
// Illustrates the sequence point.
#include <iostream.h>
main()
{
int num, sq, cube;
num = 5;
233
Chapter 11 ♦ Additional C++ Operators
i = 10
j = (i = 12, i + 8);
Bitwise Operators
The bitwise operators manipulate internal representations of
data and not just “values in variables” as the other operators do.
These bitwise operators require an understanding of Appendix A’s
binary numbering system, as well as a computer’s memory. This
section introduces the bitwise operators. The bitwise operators are
used for advanced programming techniques and are generally used
in much more complicated programs than this book covers.
Some people program in C++ for years and never learn the
bitwise operators. Nevertheless, understanding them can help you
improve a program’s efficiency and enable you to operate at a more
advanced level than many other programming languages allow.
234
C++ By
EXAMPLE
0 & 1 = 0
1 & 0 = 0
1 & 1 = 1
continues
235
Chapter 11 ♦ Additional C++ Operators
0 | 1 = 1
1| 0 = 1
1 | 1 = 1
0 ^ 1 = 1
1 ^ 0 = 1
1 ^ 1 = 0
~1 = 0
In bitwise truth tables, you can replace the 1 and 0 with True
and False, respectively, if it helps you to understand the result better.
For the bitwise AND (&) truth table, both bits being compared by the
& operator must be True for the result to be True. In other words,
“True AND True results in True.”
TIP: By replacing the 1s and 0s with True and False, you might
be able to relate the bitwise operators to the regular logical
operators, && and ||, that you use for if comparisons.
For bitwise ^, one The | bitwise operator is sometimes called the bitwise inclusive
side or the other— OR operator. If one side of the | operator is 1 (True)—or if both sides
but not both—must
be 1.
are 1—the result is 1 (True).
The ^ operator is called bitwise exclusive OR. It means that either
side of the ^ operator must be 1 (True) for the result to be 1 (True), but
both sides cannot be 1 (True) at the same time.
236
C++ By
EXAMPLE
Examples
1. If you apply the bitwise & operator to numerals 9 and 14, you
receive a result of 8. Figure 11.4 shows you why this is so.
When the binary values of 9 (1001) and 14 (1110) are com-
pared on a bitwise & basis, the resulting bit pattern is 8
(1000).
237
Chapter 11 ♦ Additional C++ Operators
238
C++ By
EXAMPLE
// Filename: C11ODEV.CPP
// Uses a bitwise & to determine whether a
// number is odd or even.
#include <iostream.h>
main()
{
239
Chapter 11 ♦ Additional C++ Operators
Only bit 6
is different
Only bit 6
is different
Figure 11.6. Bitwise difference between two uppercase and two lower-
case ASCII letters.
240
C++ By
EXAMPLE
// Filename: C11UPCS1.CPP
// Converts the input characters to uppercase
// if they aren’t already.
#include <iostream.h>
main()
{
char first, middle, last; // Will hold user’s initials
int bitmask=223; // 11011111 in binary
241
Chapter 11 ♦ Additional C++ Operators
Review Questions
The answers to the review questions are in Appendix B.
1. What set of statements does the conditional operator
replace?
2. Why is the conditional operator called a “ternary” operator?
3. Rewrite the following conditional operator as an if-else
statement.
ans = (a == b) ? c + 2 : c + 3;
and
var = var + 1;
age = 20;
printf(“You are now %d, and will be %d in one year”,
age, age++);
c. 1 ^ 1 ^ 1 ^ 1
d. ~(1 ^ 0)
242
C++ By
EXAMPLE
Review Exercises
1. Write a program that prints the numerals from 1 to 10. Use
ten different couts and only one variable called result to hold
the value before each cout. Use the increment operator to
add 1 to result before each cout.
2. Write a program that asks users for their ages. Using a single
printf() that includes a conditional operator, print on-screen
the following if the input age is over 21,
You are not a minor.
Summary
Now you have learned almost every operator in the C++
language. As explained in this chapter, conditional, increment, and
decrement are three operators that enable C++ to stand apart from
many other programming languages. You must always be aware of
the precedence table whenever you use these, as you must with all
operators.
243
Chapter 11 ♦ Additional C++ Operators
The sizeof and sequence point operators act unlike most others.
The sizeof is a compile operator, and it works in a manner similar to
the #define preprocessor directive because they are both replaced by
their values at compile time. The sequence point enables you to have
multiple statements on the same line—or in a single expression.
Reserve the sequence point for declaring variables only because it
can be unclear when it’s combined with other expressions.
This chapter concludes the discussion on C++ operators. Now
that you can compute just about any result you will ever need, it is
time to discover how to gain more control over your programs. The
next few chapters introduce control loops that give you repetitive
power in C++.
244
C++ By
12EXAMPLE
245
Chapter 12 ♦ The while Loop
246
C++ By
EXAMPLE
TIP: If the body of the while loop contains only one statement,
the braces surrounding it are not required. It is a good habit to
enclose all while loop statements in braces, however, because if
you have to add statements to the body of the while loop later,
your braces are already there.
247
Chapter 12 ♦ The while Loop
more readable if you indent the body of a while loop a few spaces to
the right. The following examples illustrate this.
Examples
1. Some programs presented earlier in the book require user
input with cin. If users do not enter appropriate values, these
programs display an error message and ask the user to enter
another value, which is an acceptable procedure.
Now that you understand the while loop construct, however,
you should put the error message inside a loop. In this way,
users see the message continually until they type proper
input values, rather than once.
The following program is short, but it demonstrates a while
loop that ensures valid keyboard input. It asks users
whether they want to continue. You can incorporate this
program into a larger one that requires user permission to
continue. Put a prompt, such as the one presented here, at
the bottom of a text screen. The text remains on-screen until
the user tells the program to continue executing.
Identify the file and include the necessary header file. In this
program, you want to ensure the user enters Y or N.
You have to store the user’s answer, so declare the ans variable as a
character. Ask the users whether they want to continue, and get
the response. If the user doesn’t type Y or N, ask the user for
another response.
// Filename: C12WHIL1.CPP
// Input routine to ensure user types a
// correct response. This routine can be part
// of a larger program.
#include <iostream.h>
main()
{
char ans;
248
C++ By
EXAMPLE
while ((ans != ‘Y’) && (ans != ‘N’))
{ cout << “\nYou must type a Y or an N\n”; // Warn
// and ask
cout << “Do you want to continue (Y/N)?”; // again.
cin >> ans;
} // Body of while loop ends here.
return 0;
}
Notice that the two cin functions do the same thing. You
must use an initial cin, outside the while loop, to provide an
answer for the while loop to check. If users type something
other than Y or N, the program prints an error message, asks
for another answer, then checks the new answer. This vali-
dation method is preferred over one where the reader only
has one additional chance to succeed.
The while loop tests the test expression at the top of the loop.
This is why the loop might never execute. If the test is
initially False, the loop does not execute even once. The
output from this program is shown as follows. The program
repeats indefinitely, until the relational test is True (as soon
as the user types either Y or N).
249
Chapter 12 ♦ The while Loop
// Filename: C12WHBAD.CPP
// Bad use of a while loop.
#include <iostream.h>
main()
{
int a=10, b=20;
while (a > 5)
{ cout << “a is “ << a << “, and b is “ << b << “\n”;
b = 20 + a; }
return 0;
}
3. The following program asks users for a first name, then uses
a while loop to count the number of characters in the name.
This is a string length program; it counts characters until it
reaches the null zero. Remember that the length of a string
equals the number of characters in the string, not including
the null zero.
// Filename: C12WHIL2.CPP
// Counts the number of letters in the user’s first name.
#include <iostream.h>
main()
{
char name[15]; // Will hold user’s first name
250
C++ By
EXAMPLE
int count=0; // Will hold total characters in name
// Filename: C12WHIL3.CPP
// Counts the number of letters in the user’s first name.
#include <iostream.h>
main()
{
char name[15]; // Will hold user’s first name
int count=0; // Will hold total characters in name
251
Chapter 12 ♦ The while Loop
do
{ block of one or more C++ statements; }
while (test expression)
Examples
1. The following program is just like the first one you saw with
the while loop (C12WHIL1.CPP), except the do-while is used.
Notice the placement of test expression. Because this expres-
sion concludes the loop, user input does not have to appear
before the loop and again in the body of the loop.
// Filename: C12WHIL4.CPP
// Input routine to ensure user types a
// correct response. This routine might be part
// of a larger program.
252
C++ By
EXAMPLE
#include <iostream.h>
main()
{
char ans;
do
{ cout << “\nYou must type a Y or an N\n”; // Warn
// and ask
cout << “Do you want to continue (Y/N) ?”; // again.
cin >> ans; } // Body of while loop
// ends here.
while ((ans != ‘Y’) && (ans != ‘N’));
return 0;
}
// Filename: C12INV1.CPP
// Gets inventory information from user and prints
// an inventory detail listing with extended totals.
#include <iostream.h>
#include <iomanip.h>
main()
{
int part_no, quantity;
float cost, ext_cost;
253
Chapter 12 ♦ The while Loop
254
C++ By
EXAMPLE
Figure 12.1. Differences between the if statement and the two while
loops.
255
Chapter 12 ♦ The while Loop
NOTE: The break statement exits only the most current loop. If
you have a while loop in another while loop, break exits only the
internal loop.
256
C++ By
EXAMPLE
Examples
1. Here is a simple program that shows you how the exit()
function works. This program looks as though it prints
several messages on-screen, but it doesn’t. Because exit()
appears early in the code, this program quits immediately
after main()’s opening brace.
// C12EXIT1.CPP
// Quits early due to exit() function.
#include <iostream.h>
#include <stdlib.h> // Required for exit().
main()
{
exit(0); // Forces program to end here.
return 0;
}
// Filename: C12BRK.CPP
// Demonstrates the break statement.
#include <iostream.h>
main()
257
Chapter 12 ♦ The while Loop
{
char user_ans;
do
{ cout << “C++ is fun! \n”;
break; // Causes early exit.
cout << “Do you want to see the message again (N/Y)? “;
cin >> user_ans;
} while (user_ans == ‘Y’);
C++ is fun!
That’s all for now
You can tell from this program’s output that the break state-
ment does not allow the do-while loop to reach its natural
conclusion, but causes it to finish early. The final cout prints
because only the current loop—and not the entire pro-
gram—exits with the break statement.
3. Unlike the previous program, break usually appears after an
if statement. This makes it a conditional break, which occurs
only if the relational test of the if statement is True.
A good illustration of this is the inventory program you saw
earlier (C12INV1.CPP). Even though the users enter –999
when they want to quit the program, an additional if test is
needed inside the do-while. The –999 ends the do-while loop,
but the body of the do-while still needs an if test, so the
remaining quantity and cost prompts are not given.
If you insert a break after testing for the end of the user’s
input, as shown in the following program, the do-while will
not need the if test. The break quits the do-while as soon as
the user signals the end of the inventory by entering –999 as
the part number.
258
C++ By
EXAMPLE
// Filename: C12INV2.CPP
// Gets inventory information from user and prints
// an inventory detail listing with extended totals.
#include <iostream.h>
#include <iomanip.h>
main()
{
int part_no, quantity;
float cost, ext_cost;
4. You can use the following program to control the two other
programs. This program illustrates how C++ can pass in-
formation to DOS with exit(). This is your first example of a
menu program. Similar to a restaurant menu, a C++ menu
program lists possible user choices. The users decide what
they want the computer to do from the menu’s available
options. The mailing list application in Appendix F, “The
Mailing List Application,” uses a menu for its user options.
259
Chapter 12 ♦ The while Loop
// Filename: C12EXIT2.CPP
// Asks user for his or her selection and returns
// that selection to the operating system with exit().
#include <iostream.h>
#include <stdlib.h>
main()
{
int ans;
do
{ cout << “Do you want to:\n\n”;
cout << “\t1. Run the word processor \n\n”;
cout << “\t2. Run the database program \n\n”;
cout << “What is your selection? “;
cin >> ans;
} while ((ans != 1) && (ans != 2)); // Ensures user
// enters 1 or 2.
exit(ans); // Return value to operating system.
return 0; // Return does not ever execute due to exit().
}
260
C++ By
EXAMPLE
Examples
1. To illustrate using a counter, the following program prints
“Computers are fun!” on-screen 10 times. You can write a
program that has 10 cout statements, but that would not be
efficient. It would also be too cumbersome to have 5000 cout
statements, if you wanted to print that same message 5000
times.
By adding a while loop and a counter that stops after a
certain total is reached, you can control this printing, as the
following program shows.
// Filename: C12CNT1.CPP
// Program to print a message 10 times.
#include <iostream.h>
main()
{
int ctr = 0; // Holds the number of times printed.
do
{ cout << “Computers are fun!\n”;
ctr++; // Add one to the count,
// after each cout.
} while (ctr < 10); // Print again if fewer
// than 10 times.
return 0;
}
261
Chapter 12 ♦ The while Loop
262
C++ By
EXAMPLE
// Filename: C12PASS1.CPP
// Program to prompt for a password and
// check it against an internal one.
#include <iostream.h>
#include <stdlib.h>
main()
{
int stored_pass = 11862;
int num_tries = 0; // Counter for password attempts.
int user_pass;
263
Chapter 12 ♦ The while Loop
// Filename: C12GUES.CPP
// Letter-guessing game.
#include <iostream.h>
main()
{
int tries = 0;
char comp_ans, user_guess;
264
C++ By
EXAMPLE
Producing Totals
Writing a routine to add values is as easy as counting. Instead
of adding 1 to the counter variable, you add a value to the total
variable. For instance, if you want to find the total dollar amount of
checks you wrote during December, you can start at nothing (0) and
add the amount of every check written in December. Instead of
building a count, you are building a total.
When you want C++ to add values, just initialize a total
variable to zero, then add each value to the total until you have
included all the values.
265
Chapter 12 ♦ The while Loop
Examples
1. Suppose you want to write a program that adds your grades
for a class you are taking. The teacher has informed you that
you earn an A if you can accumulate over 450 points.
The following program keeps asking you for values until
you type –1. The –1 is a signal that you are finished entering
grades and now want to see the total. This program also
prints a congratulatory message if you have enough points
for an A.
// Filename: C12GRAD1.CPP
// Adds grades and determines whether you earned an A.
#include <iostream.h>
include <iomanip.h>
main()
{
float total_grade=0.0;
float grade; // Holds individual grades.
do
{ cout << “What is your grade? (-1 to end) “;
cin >> grade;
if (grade >= 0.0)
{ total_grade += grade; } // Add to total.
} while (grade >= 0.0); // Quit when -1 entered.
return 0;
}
266
C++ By
EXAMPLE
// Filename: C12GRAD2.CPP
// Adds up grades, computes average,
// and determines whether you earned an A.
#include <iostream.h>
#include <iomanip.h>
main()
{
float total_grade=0.0;
float grade_avg = 0.0;
float grade;
int grade_ctr = 0;
do
{ cout << “What is your grade? (-1 to end) “;
cin >> grade;
if (grade >= 0.0)
{ total_grade += grade; // Add to total.
grade_ctr ++; } // Add to count.
} while (grade >= 0.0); // Quit when -1 entered.
267
Chapter 12 ♦ The while Loop
Review Questions
The answers to the review questions are in Appendix B.
1. What is the difference between the while loop and the
do-while loop?
268
C++ By
EXAMPLE
6. What file must you include as a header file if you use exit()?
7. How many times does this printf() print?
int a=0;
do
{ printf(“Careful \n”);
a++; }
while (a > 5);
a = 1;
while (a < 4)
{ cout << “This is the outer loop\n”;
a++;
while (a <= 25)
{ break;
cout << “This prints 25 times\n”; }
}
Review Exercises
1. Write a program with a do-while loop that prints the numer-
als from 10 to 20 (inclusive), with a blank line between each
number.
2. Write a weather-calculator program that asks for a list of the
previous 10 days’ temperatures, computes the average, and
prints the results. You have to compute the total as the input
occurs, then divide that total by 10 to find the average. Use a
while loop for the 10 repetitions.
269
Chapter 12 ♦ The while Loop
Summary
This chapter showed you two ways to produce a C++ loop: the
while loop and the do-while loop. These two variations of while loops
differ in where they test their test condition statements. The while
tests at the beginning of its loop, and the do-while tests at the end.
Therefore, the body of a do-while loop always executes at least once.
You also learned that the exit() function and break statement add
flexibility to the while loops. The exit() function terminates the
program, and the break statement terminates only the current loop.
This chapter explained two of the most important applications
of loops: counters and totals. Your computer can be a wonderful tool
for adding and counting, due to the repetitive capabilities offered
with while loops.
The next chapter extends your knowledge of loops by showing
you how to create a determinate loop, called the for loop. This feature
is useful when you want a section of code to loop for a specified
number of times.
270
Learn programming
By Example with Que!
C By Example
Greg Perry
This is the best way to learn C outside
the classroom! Short chapters help
beginners learn the language one
small step at a time.
Version 1.0
$21.95 USA
0-88022-813-X, 650 pp., 73/8 9 1/4
QBasic By Example Turbo C++ By Example Turbo Pascal by Example Visual Basic By Example
Version 1.0 Version 3 Version 6 Version 1
$21.95 USA $21.95 USA $21.95 USA $21.95 USA
0-88022-811-3, 650 pp., 73/8 x 9 1/4 0-88022-812-1, 650 pp., 73/8 x 9 1/4 0-88022-908-X, 650 pp., 73/8 x 9 1/4 0-88022-904-7, 650 pp., 73/8 x 9 1/4
29EXAMPLE
Arrays of
Structures
This chapter builds on the previous one by showing you how to
create many structures for your data. After creating an array of
structures, you can store many occurrences of your data values.
Arrays of structures are good for storing a complete employee
file, inventory file, or any other set of data that fits in the structure
format. Whereas arrays provide a handy way to store several values
that are the same type, arrays of structures store several values of
different types together, grouped as structures.
This chapter introduces the following concepts:
♦ Creating arrays of structures
♦ Initializing arrays of structures
♦ Referencing elements from a structure array
♦ Arrays as members
Many C++ programmers use arrays of structures as a prelude
to storing their data in a disk file. You can input and calculate your
disk data in arrays of structures, and then store those structures in
memory. Arrays of structures also provide a means of holding data
you read from the disk.
605
Chapter 29 ♦ Arrays of Structures
Declaring Arrays
of Structures
It is easy to declare an array of structures. Specify the number
of reserved structures inside array brackets when you declare the
structure variable. Consider the following structure definition:
struct stores
{ int employees;
int registers;
double sales;
} store1, store2, store3, store4, store5;
606
C++ By
EXAMPLE
Suppose the fifth store just opened and you want to initialize its
members with data. If the stores are a chain and the new store is
similar to one of the others, you can begin initializing the store’s data
by assigning each of its members the same data as another store’s,
like this:
Arrays of structures Such structure declarations are fine for a small number of
make working with structures, but if the stores were a national chain, five structure
large numbers of
structure variables
variables would not be enough. Suppose there were 1000 stores. You
manageable. would not want to create 1000 different store variables and work
with each one individually. It would be much easier to create an
array of store structures.
Consider the following structure declaration:
struct stores
{ int employees;
int registers;
double sales;
} store[1000];
607
Chapter 29 ♦ Arrays of Structures
608
C++ By
EXAMPLE
The rules of arrays are still in force here. Each element of the
array called store is the same data type. The data type of store is the
structure stores. As with any array, each element must be the same
data type; you cannot mix data types in the same array. This array’s
data type happens to be a structure you created containing three
members. The data type for store[316] is the same for store[981] and
store[74].
The name of the array, store, is a pointer constant to the starting
element of the array, store[0]. Therefore, you can use pointer nota-
tion to reference the stores. To assign store[60] the same value as
store[23], you can reference the two elements like this:
*(store+60) = *(store+23);
609
Chapter 29 ♦ Arrays of Structures
Examples
1. Suppose you work for a mail-order company that sells disk
drives. You are given the task of writing a tracking program
for the 125 different drives you sell. You must keep track of
the following information:
Storage capacity in megabytes
Access time in milliseconds
Vendor code (A, B, C, or D)
Cost
Price
Because there are 125 different disk drives in the inventory,
the data fits nicely into an array of structures. Each array
element is a structure containing the five members described
in the list.
The following structure definition defines the inventory:
struct inventory
{
610
C++ By
EXAMPLE
long int storage;
int access_time;
char vendor_code;
double code;
double price;
} drive[125]; // Defines 125 occurrences of the structure.
611
Chapter 29 ♦ Arrays of Structures
// Filename: C29DSINV.CPP
// Data-entry program for a disk drive company.
#include <iostream.h>
#include <stdlib.h>
#include <iomanip.h>
#include <stdio.h>
void disp_menu(void);
struct inventory enter_data();
void see_data(inventory disk[125], int num_items);
void main()
612
C++ By
EXAMPLE
{
inventory disk[125]; // Local array of structures.
int ans;
int num_items=0; // Number of total items
// in the inventory.
do
{
do
{ disp_menu(); // Display menu of user choices.
cin >> ans; // Get user’s request.
} while ((ans<1) || (ans>3));
switch (ans)
{ case (1): { disk[num_items] = enter_data(); // Enter
// disk data.
num_items++; // Increment number of items.
break; }
case (2): { see_data(disk, num_items); // Display
// disk data.
break; }
default : { break; }
}
} while (ans!=3); // Quit program
// when user is done.
return;
}
void disp_menu(void)
{
inventory enter_data()
613
Chapter 29 ♦ Arrays of Structures
{
inventory disk_item; // Local variable to fill
// with input.
return (disk_item);
}
614
C++ By
EXAMPLE
Arrays as Members
Members of structures can be arrays. Array members pose no
new problems, but you have to be careful when you access indi-
vidual array elements. Keeping track of arrays of structures that
contain array members might seem like a great deal of work on your
part, but there is nothing to it.
Consider the following structure definition. This statement
declares an array of 100 structures, each structure holding payroll
information for a company. Two of the members, name and depart-
ment, are arrays.
struct payroll
{ char name[25]; // Employee name array.
615
Chapter 29 ♦ Arrays of Structures
int dependents;
char department[10]; // Department name array.
float salary;
} employee[100]; // An array of 100 employees.
Figure 29.5 shows what these structures look like. The first and
third members are arrays. name is an array of 25 characters, and
department is an array of 10 characters.
Suppose you must save the 25th employee’s initial in a charac-
ter variable. Assuming initial is already declared as a character
variable, the following statement assigns the employee’s initial to
the varible initial:
initial = employee[24].name[0];
The double subscripts might look confusing, but the dot opera-
tor requires a structure variable on its left (employee[24]) and a
member on its right (name’s first array element). Being able to refer to
member arrays makes the processing of character data in structures
simple.
616
C++ By
EXAMPLE
617
Chapter 29 ♦ Arrays of Structures
Examples
1. Suppose an employee got married and wanted her name
changed in the payroll file. (She happens to be the 45th
employee in the array of structures.) Given the payroll
structure described in the previous section, this would
assign a new name to her structure:
// Filename: C29BOOK.CPP
// Bookstore data-entry program.
#include <iostream.h>
#include <stdio.h>
#include <ctype.h>
struct inventory
{ char title[25]; // Book’s title.
char pub_date[19]; // Publication date.
char author[20]; // Author’s name.
int num; // Number in stock.
int on_order; // Number on order.
float retail; // Retail price.
};
void main()
{
inventory book[100];
int total=0; // Total books in inventory.
int ans;
618
C++ By
EXAMPLE
do // This program enters data into the structures.
{ cout << “Book #” << (total+1) << “:\n”, (total+1);
cout << “What is the title? “;
gets(book[total].title);
cout << “What is the publication date? “;
gets(book[total].pub_date);
cout << “Who is the author? “;
gets(book[total].author);
cout << “How many books of this title are there? “;
cin >> book[total].num;
cout << “How many are on order? “;
cin >> book[total].on_order;
cout << “What is the retail price? “;
cin >> book[total].retail;
fflush(stdin);
cout << “\nAre there more books? (Y/N) “;
ans=getchar();
fflush(stdin); // Discard carriage return.
ans=toupper(ans); // Convert to uppercase.
if (ans==’Y’)
{ total++;
continue; }
} while (ans==’Y’);
return;
}
619
Chapter 29 ♦ Arrays of Structures
struct mag_info
{ char title[25];
char pub[25];
int month;
int year;
int stock_copies;
int order_copies;
float price;
} mags[1000]; // Define 1000 occurrences.
620
C++ By
EXAMPLE
// Filename: C29MAG.CPP
// Magazine inventory program for adding and displaying
// a bookstore’s magazines.
#include <iostream.h>
#include <ctype.h>
#include <stdio.h>
struct mag_info
{ char title[25];
char pub[25];
int month;
int year;
int stock_copies;
int order_copies;
float price;
};
void main()
{
mag_info mags[1000];
int mag_ctr=0; // Number of magazine titles.
char ans;
do
{ // Assumes there is
// at least one magazine filled.
mags[mag_ctr] = fill_mags(mags[mag_ctr]);
cout << “Do you want to enter another magazine? “;
fflush(stdin);
ans = getchar();
fflush(stdin); // Discards carriage return.
if (toupper(ans) == ‘Y’)
{ mag_ctr++; }
} while (toupper(ans) == ‘Y’);
print_mags(mags, mag_ctr);
621
Chapter 29 ♦ Arrays of Structures
622
C++ By
EXAMPLE
Review Questions
The answers to the review questions are in Appendix B.
1. True or false: Each element in an array of structures must be
the same type.
2. What is the advantage of creating an array of structures
rather than using individual variable names for each struc-
ture variable?
3. Given the following structure declaration:
struct item
{ char part_no[8];
char descr[20];
float price;
int in_stock;
} inventory[100];
struct item
{ char desc[20];
int num;
float cost;
} inventory[25];
623
Chapter 29 ♦ Arrays of Structures
Review Exercises
1. Write a program that stores an array of friends’ names,
phone numbers, and addresses and prints them two ways:
with their name, address, and phone number, or with only
their name and phone number for a phone listing.
2. Add a sort function to the program in Exercise 1 so you can
print your friends’ names in alphabetical order. (Hint: You
have to make the member holding the names a character
pointer.)
3. Expand on the book data-entry program, C29BOOK.CPP,
by adding features to make it more usable (such as search
book by author, by title, and print an inventory of books on
order).
Summary
You have mastered structures and arrays of structures. Many
useful inventory and tracking programs can be written using struc-
tures. By being able to create arrays of structures, you can now create
several occurrences of data.
The next step in the process of learning C++ is to save these
structures and other data to disk files. The next two chapters explore
the concepts of disk file processing.
624
C++ By
30EXAMPLE
Sequential Files
So far, every example in this book has processed data that resided
inside the program listing or came from the keyboard. You assigned
constants and variables to other variables and created new data
values from expressions. The programs also received input with cin,
gets(), and the character input functions.
The data created by the user and assigned to variables with
assignment statements is sufficient for some applications. With the
large volumes of data most real-world applications must process,
however, you need a better way of storing that data. For all but the
smallest computer programs, disk files offer the solution.
After storing data on the disk, the computer helps you enter,
find, change, and delete the data. The computer and C++ are simply
tools to help you manage and process data. This chapter focuses on
disk- and file-processing concepts and teaches you the first of two
methods of disk access, sequential file access.
This chapter introduces you to the following concepts:
♦ An overview of disk files
♦ The types of files
♦ Processing data on the disk
♦ Sequential file access
♦ File I/O functions
625
Chapter 30 ♦ Sequential Files
After this chapter, you will be ready to tackle the more ad-
vanced random-file-access methods covered in the next chapter. If
you have programmed computerized data files with another pro-
gramming language, you might be surprised at how C++ borrows
from other programming languages, especially BASIC, when work-
ing with disk files. If you are new to disk-file processing, disk files
are simple to create and to read.
626
C++ By
EXAMPLE
By storing data on your disk, you are much less limited because
you have more storage. Your disk can hold as much data as you have
disk capacity. Also, if your program requirements grow, you can
usually increase your disk space, whereas you cannot always add
more RAM to your computer.
When working with disk files, C++ does not have to access
much RAM because C++ reads data from your disk drive and
processes the data only parts at a time. Not all your disk data has to
reside in RAM for C++ to process it. C++ reads some data, processes
it, and then reads some more. If C++ requires disk data a second
time, it rereads that place on the disk.
627
Chapter 30 ♦ Sequential Files
628
C++ By
EXAMPLE
To open a file, you must call the open() function. To close a file,
call the close() function. Here is the format of these two function
calls:
file_ptr.open(file_name, access);
and
file_ptr.close();
629
Chapter 30 ♦ Sequential Files
The default access mode for file access is a text mode. A text file
is an ASCII file, compatible with most other programming lan-
guages and applications. Text files do not always contain text, in the
word-processing sense of the word. Any data you have to store can
go in a text file. Programs that read ASCII files can read data you
create as C++ text files. For a discussion of binary file access, see the
box that follows.
630
C++ By
EXAMPLE
Binary Modes
If you specify binary access, C++ creates or reads the file in a
binary format. Binary data files are “squeezed”—they take less
space than text files. The disadvantage of using binary files is
that other programs cannot always read the data files. Only
C++ programs written to access binary files can read and write
to them. The advantage of binary files is that you save disk
space because your data files are more compact. Other than the
access mode in the open() function, you use no additional
commands to access binary files with your C++ programs.
The binary format is a system-specific file format. In other
words, not all computers can read a binary file created on
another computer.
If you open a file for writing, C++ creates the file. If a file by
that name already exists, C++ overwrites the old file with
no warning. You must be careful when opening files so you do
not overwrite existing data that you want to save.
631
Chapter 30 ♦ Sequential Files
Examples
1. Suppose you want to create a file for storing your house
payment records for the previous year. Here are the first few
lines in the program which creates a file called HOUSE.DAT
on your disk:
#include <fstream.h>
main()
{
ofstream file_ptr; // Declares a file pointer for writing
file_ptr.open(“house.dat”, ios::out); // Creates the file
TIP: Because files are not part of your program, you might
find it useful to declare file pointers globally. Unlike data in
variables, there is rarely a reason to keep file pointers local.
632
C++ By
EXAMPLE
Before finishing with the program, you should close the file.
The following close() function closes the house file:
file_ptr.close(); // Close the house payment file.
2. If you want, you can put the complete pathname in the file’s
name. The following opens the household payment file in a
subdirectory on the D: disk drive:
file_ptr.open(“d:\mydata\house.dat”, ios::out);
4. You should check the return value from open() to ensure the
file opened properly. Here is code after open() that checks for
an error:
#include <fstream.h>
main()
{
ofstream file_ptr; // Declares a file pointer.
633
Chapter 30 ♦ Sequential Files
5. You can open and write to several files in the same program.
Suppose you wanted to read data from a payroll file and
create a backup payroll data file. You have to open the
current payroll file using the in reading mode, and the
backup file in the output out mode.
For each open file in your program, you must declare a
different file pointer. The file pointers used by your input
and output statement determine on which file they operate.
If you have to open many files, you can declare an array of
file pointers.
Here is a way you can open the two payroll files:
#include <fstream.h>
main()
{
file_in.open(“payroll.dat”, ios::in); // Existing file
file_out.open(“payroll.BAK”, ios::out); // New file
When you finish with these files, be sure to close them with
these two close() function calls:
file_in.close();
file_out.close();
634
C++ By
EXAMPLE
Writing to a File
Any input or output function that requires a device performs
input and output with files. You have seen most of these already.
The most common file I/O functions are
There is always more than one way to write data to a disk file.
Most the time, more than one function will work. For example, if
you write many names to a file, both puts() and file_ptr << work.
You also can write the names using put(). You should use which-
ever function you are most comfortable with. If you want a newline
character (\n) at the end of each line in your file, the file_ptr << and
puts() are probably easier than put(), but all three will do the job.
Examples
1. The following program creates a file called NAMES.DAT.
The program writes five names to a disk file using
file_ptr <<.
// Filename: C30WR1.CPP
// Writes five names to a disk file.
#include <fstream.h>
ofstream fp;
635
Chapter 30 ♦ Sequential Files
void main()
{
fp.open(“NAMES.DAT”, ios::out); // Creates a new file.
Michael Langston
Sally Redding
Jane Kirk
Stacy Wikert
Joe Hiquet
// Filename: C30WR2.CPP
// Writes 1 to 100 to a disk file.
#include <fstream.h>
ofstream fp;
void main()
636
C++ By
EXAMPLE
{
int ctr;
The numbers are not written one per line, but with a space
between each of them. The format of the file_ptr << deter-
mines the format of the output data. When writing data to
disk files, keep in mind that you have to read the data later.
You have to use “mirror-image” input functions to read data
you output to files.
Writing to a Printer
Functions such as open() and others were not designed to write
only to files. They were designed to write to any device, including
files, the screen, and the printer. If you must write data to a printer,
you can treat the printer as if it were a file. The following program
opens a file pointer using the MS-DOS name for a printer located at
LPT1 (the MS-DOS name for the first parallel printer port):
// Filename: C30PRNT.CPP
// Prints to the printer device
#include <fstream.h>
void main()
637
Chapter 30 ♦ Sequential Files
{
prnt.open(“LPT1”, ios::out);
prnt << “Printer line 1\n”; // 1st line printed.
prnt << “Printer line 2\n”; // 2nd line printed.
prnt << “Printer line 3\n”; // 3rd line printed.
prnt.close();
return;
}
Make sure your printer is on and has paper before you run this
program. When you run the program, you see this printed on the
printer:
Printer line 1
Printer line 2
Printer line 3
Adding to a File
You can easily add data to an existing file or create new files, by
opening the file in append access mode. Data files on the disk are
rarely static; they grow almost daily due to (hopefully!) increased
business. Being able to add to data already on the disk is very useful,
indeed.
Files you open for append access (using ios::app) do not have
to exist. If the file exists, C++ appends data to the end of the file when
you write the data. If the file does not exist, C++ creates the file (as
is done when you open a file for write access).
Example
The following program adds three more names to the
NAMES.DAT file created in an earlier example.
// Filename: C30AP1.CPP
// Adds three names to a disk file.
#include <fstream.h>
638
C++ By
EXAMPLE
ofstream fp;
void main()
{
fp.open(“NAMES.DAT”, ios::app); // Adds to file.
fp << “Johnny Smith\n”;
fp << “Laura Hull\n”;
fp << “Mark Brown\n”;
fp.close(); // Release the file.
return;
}
Michael Langston
Sally Redding
Jane Kirk
Stacy Wikert
Joe Hiquet
Johnny Smith
Laura Hull
Mark Brown
NOTE: If the file does not exist, C++ creates it and stores the
three names to the file.
639
Chapter 30 ♦ Sequential Files
Examples
1. This program asks the user for a filename and prints the
contents of the file to the screen. If the file does not exist, the
program displays an error message.
// Filename: C30RE1.CPP
// Reads and displays a file.
#include <fstream.h>
#include <stdlib.h>
ifstream fp;
void main()
{
char filename[12]; // Holds user’s filename.
char in_char; // Input character.
cout << “What is the name of the file you want to see? “;
cin >> filename;
fp.open(filename, ios::in);
if (!fp)
{
cout << “\n\n*** That file does not exist ***\n”;
exit(0); // Exit program.
}
while (fp.get(in_char))
{ cout << in_char; }
fp.close();
return;
}
640
C++ By
EXAMPLE
// Filename: C30RE2.CPP
// Makes a copy of a file.
#include <fstream.h>
#include <stdlib.h>
ifstream in_fp;
ofstream out_fp;
void main()
{
char in_filename[12]; // Holds original filename.
char out_filename[12]; // Holds backup filename.
char in_char; // Input character.
641
Chapter 30 ♦ Sequential Files
cout << “What is the name of the file you want to back up?
“;
cin >> in_filename;
cout << “What is the name of the file “;
cout << “you want to copy “ << in_filename << “ to? “;
cin >> out_filename;
in_fp.open(in_filename, ios::in);
if (!in_fp)
{
cout << “\n\n*** “ << in_filename << “ does not exist
***\n”;
exit(0); // Exit program
}
out_fp.open(out_filename, ios::out);
if (!out_fp)
{
cout << “\n\n*** Error opening “ << in_filename << “
***\n”;
exit(0); // Exit program
}
cout << “\nCopying...\n”; // Waiting message.
while (in_fp.get(in_char))
{ out_fp.put(in_char); }
cout << “\nThe file is copied.\n”;
in_fp.close();
out_fp.close();
return;
}
Review Questions
Answers to the review questions are in Appendix B.
1. What are the three ways to access sequential files?
2. What advantage do disk files have over holding data in
memory?
3. How do sequential files differ from random-access files?
642
C++ By
EXAMPLE
4. What happens if you open a file for read access and the file
does not exist?
5. What happens if you open a file for write access and the file
already exists?
6. What happens if you open a file for append access and the
file does not exist?
7. How does C++ inform you that you have reached the end-
of-file condition?
Review Exercises
1. Write a program that creates a file containing the following
data:
Your name
Your address
Your phone number
Your age
2. Write a second program that reads and prints the data file
you created in Exercise 1.
3. Write a program that takes your data created in Exercise 1
and writes it to the screen one word per line.
4. Write a program for PCs that backs up two important files:
the AUTOEXEC.BAT and CONFIG.SYS. Call the backup
files AUTOEXEC.SAV and CONFIG.SAV.
5. Write a program that reads a file and creates a new file with
the same data, except reverse the case on the second file.
Everywhere uppercase letters appear in the first file, write
lowercase letters to the new file, and everywhere lowercase
letters appear in the first file, write uppercase letters to the
new file.
643
Chapter 30 ♦ Sequential Files
Summary
You can now perform one of the most important requirements
of data processing: writing and reading to and from disk files. Before
this chapter, you could only store data in variables. The short life of
variables (they only last as long as your program is running) made
long-term storage of data impossible. You can now save large
amounts of data in disk files to process later.
Reading and writing sequential files involves learning more
concepts than actual commands or functions. The open() and close()
functions are the most important functions you learned in this
chapter. You are now familiar with most of the I/O functions needed
to retrieve data to and from disk files.
The next chapter concludes the discussion of disk files in this
book. You will learn how to create and use random-access files. By
programming with random file access, you can read selected data
from a file, as well as change data without having to rewrite the
entire file.
644
C++ By
31EXAMPLE
Random-Access
Files
This chapter introduces the concept of random file access. Random
file access enables you to read or write any data in your disk file
without having to read or write every piece of data before it. You can
quickly search for, add, retrieve, change, and delete information in
a random-access file. Although you need a few new functions to
access files randomly, you find that the extra effort pays off in
flexibility, power, and speed of disk access.
This chapter introduces
♦ Random-access files
♦ File records
♦ The seekg() function
♦ Special-purpose file I/O functions
With C++’s sequential and random-access files, you can do
everything you would ever want to do with disk data.
645
Chapter 31 ♦ Random-Access Files
646
C++ By
EXAMPLE
array element, sequentially looking at the next one, until you get the
element you need. You can view your random-access file in the same
way, accessing the data in any order.
Most random file records are fixed-length records. Each record
(usually a row in the file) takes the same amount of disk space.
Most of the sequential files you read and wrote in the previous
chapters were variable-length records. When you are reading or
writing sequentially, there is no need for fixed-length records be-
cause you input each value one character, word, string, or number
at a time, and look for the data you want. With fixed-length records,
your computer can better calculate where on the disk the desired
record is located.
Although you waste some disk space with fixed-length records
(because of the spaces that pad some of the fields), the advantages
of random file access compensate for the “wasted” disk space (when
the data do not actually fill the structure size).
Opening Random-Access
Files
Just as with sequential files, you must open random-access files
before reading or writing to them. You can use any of the read access
modes mentioned in Chapter 30 (such as ios::in) only to read a file
randomly. However, to modify data in a file, you must open the file
in one of the update modes, repeated for you in Table 31.1.
647
Chapter 31 ♦ Random-Access Files
Examples
1. Suppose you want to write a program to create a file of your
friends’ names. The following open() function call suffices,
assuming fp is declared as a file pointer:
fp.open(“NAMES.DAT”, ios::out);
if (!fp)
{ cout << “\n*** Cannot open file ***\n”; }
648
C++ By
EXAMPLE
This code enables you to create the file, then change data
you wrote to the file.
2. As with sequential files, the only difference between using a
binary open() access mode and a text mode is that the file
you create is more compact and saves disk space. You
cannot, however, read that file from other programs as an
ASCII text file. The previous open() function can be rewritten
to create and allow updating of a binary file. All other file-
related commands and functions work for binary files just as
they do for text files.
You can read file_ptr is the pointer to the file that you want to access,
forwards or initialized with an open() statement. long_num is the number of bytes
backwards from any in the file you want to skip. C++ does not read this many bytes, but
point in the file with
seekg(). literally skips the data by the number of bytes specified in long_num.
Skipping the bytes on the disk is much faster than reading them. If
long_num is negative, C++ skips backwards in the file (this allows for
rereading of data several times). Because data files can be large, you
must declare long_num as a long integer to hold a large amount of
bytes.
origin is a value that tells C++ where to begin the skipping of
bytes specified by long_num. origin can be any of the three values
shown in Table 31.2.
649
Chapter 31 ♦ Random-Access Files
Examples
1. No matter how far into a file you have read, the following
seekg() function positions the file pointer back to the begin-
ning of a file:
fp.seekg(0L, SEEK_SET); // Position file pointer at beginning.
650
C++ By
EXAMPLE
// Filename: C31TWIC.CPP
// Writes a file to the printer, rereads it,
// and sends it to the screen.
#include <fstream.h>
#include <stdlib.h>
#include <stdio.h>
void main()
{
char in_char;
in_file.open(“MYFILE.TXT”, ios::in);
if (!in_file)
{
cout << “\n*** Error opening MYFILE.TXT ***\n”;
exit(0);
}
scrn.open(“CON”, ios::out); // Open screen device.
while (in_file.get(in_char))
{ scrn << in_char; } // Output characters to the screen.
scrn.close(); // Close screen because it is no
// longer needed.
in_file.seekg(0L, SEEK_SET); // Reposition file pointer.
prnt.open(“LPT1”, ios::out); // Open printer device.
while (in_file.get(in_char))
{ prnt << in_char; } // Output characters to the
// printer.
prnt.close(); // Always close all open files.
in_file.close();
return;
}
651
Chapter 31 ♦ Random-Access Files
You also can close then reopen a file to position the file
pointer at the beginning, but using seekg() is a more efficient
method.
Of course, you could have used regular I/O functions to
write to the screen, rather than having to open the screen as
a separate device.
3. The following seekg() function positions the file pointer at
the 30th byte in the file. (The next byte read is the 31st byte.)
// Filename: C31ALPH.CPP
// Stores the alphabet in a file, then reads
// two letters from it.
#include <fstream.h>
#include <stdlib.h>
#include <stdio.h>
fstream fp;
void main()
{
char ch; // Holds A through Z.
652
C++ By
EXAMPLE
// Open in update mode so you can read file after writing to it.
fp.open(“alph.txt”, ios::in | ios::out);
if (!fp)
{
cout << “\n*** Error opening file ***\n”;
exit(0);
}
for (ch = ‘A’; ch <= ‘Z’; ch++)
{ fp << ch; } // Write letters.
fp.seekg(8L, ios::beg); // Skip eight letters, point to I.
fp >> ch;
cout << “The first character is “ << ch << “\n”;
fp.seekg(16L, ios::beg); // Skip 16 letters, point to Q.
fp >> ch;
cout << “The second character is “ << ch << “\n”;
fp.close();
return;
}
5. To point to the end of a data file, you can use the seekg()
function to position the file pointer at the last byte. Subse-
quent seekg()s should then use a negative long_num value to
skip backwards in the file. The following seekg() function
makes the file pointer point to the end of the file:
// Filename: C31BACK.CPP
// Reads and prints a file backwards.
653
Chapter 31 ♦ Random-Access Files
#include <fstream.h>
#include <stdlib.h>
#include <stdio.h>
ifstream fp;
void main()
{
int ctr; // Steps through the 26 letters in the file.
char in_char;
fp.open(“ALPH.TXT”, ios::in);
if (!fp)
{
cout << “\n*** Error opening file ***\n”;
exit(0);
}
fp.seekg(-1L, SEEK_END); // Point to last byte in
// the file.
for (ctr = 0; ctr < 26; ctr++)
{
fp >> in_char;
fp.seekg(-2L, SEEK_CUR);
cout << in_char;
}
fp.close();
return;
}
This program also uses the SEEK_CUR origin value. The last
seekg() in the program seeks two bytes backwards from the
current position, not the beginning or end as the previous
examples have. The for loop towards the end of the program
performs a “skip-two-bytes-back, read-one-byte-forward”
method to skip through the file backwards.
7. The following program performs the same actions as Ex-
ample 4 (C31ALPH.CPP), with one addition. When the
letters I and Q are found, the letter x is written over the I and
Q. The seekg() must be used to back up one byte in the file to
overwrite the letter just read.
654
C++ By
EXAMPLE
// Filename: C31CHANG.CPP
// Stores the alphabet in a file, reads two letters from it,
// and changes those letters to xs.
#include <fstream.h>
#include <stdlib.h>
#include <stdio.h>
fstream fp;
void main()
{
char ch; // Holds A through Z.
// Open in update mode so you can read file after writing to it.
fp.open(“alph.txt”, ios::in | ios::out);
if (!fp)
{
cout << “\n*** Error opening file ***\n”;
exit(0);
}
for (ch = ‘A’; ch <= ‘Z’; ch++)
{ fp << ch; } // Write letters
fp.seekg(8L, SEEK_SET); // Skip eight letters, point to I.
fp >> ch;
// Change the Q to an x.
fp.seekg(-1L, SEEK_CUR);
fp << ‘x’;
cout << “The first character is “ << ch << “\n”;
fp.seekg(16L, SEEK_SET); // Skip 16 letters, point to Q.
fp >> ch;
cout << “The second character is “ << ch << “\n”;
// Change the Q to an x.
fp.seekg(-1L, SEEK_CUR);
fp << ‘x’;
fp.close();
return;
}
655
Chapter 31 ♦ Random-Access Files
656
C++ By
EXAMPLE
The buffered I/O file functions enable you to read and write
entire arrays (including arrays of structures) to the disk in a single
function call.
Examples
1. The following program requests a filename from the user
and erases the file from the disk using the remove() function.
// Filename: C31ERAS.CPP
// Erases the file specified by the user.
#include <stdio.h>
#include <iostream.h>
void main()
{
char filename[12];
657
Chapter 31 ♦ Random-Access Files
Review Questions
The answers to the review questions are in Appendix B.
1. What is the difference between records and structures?
2. True or false: You have to create a random-access file before
reading from it randomly.
3. What happens to the file pointer as you read from a file?
4. What are the two buffered file I/O functions?
5. What is wrong with this program?
#include <fstream.h>
ifstream fp;
void main()
{
char in_char;
fp.open(ios::in | ios::binary);
if (fp.get(in_char))
{ cout << in_char; } // Write to the screen
fp.close();
return;
}
Review Exercises
1. Write a program that asks the user for a list of five names,
then writes the names to a file. Rewind the file and display
its contents on-screen using the seekg() and get() functions.
658
C++ By
EXAMPLE
Summary
C++ supports random-access files with several functions. These
functions include error checking, file pointer positioning, and the
opening and closing of files. You now have the tools you need to save
your C++ program data to disk for storage and retrieval.
The mailing-list application in Appendix F offers a complete
example of random-access file manipulation. The program enables
the user to enter names and addresses, store them to disk, edit them,
change them, and print them from the disk file. The mailing-list
program combines almost every topic from this book into a com-
plete application that “puts it all together.”
659
Chapter 31 ♦ Random-Access Files
660
C++ By
32EXAMPLE
Introduction to
Object-Oriented
Programming
The most widely used object-oriented programming language to-
day is C++. C++ provides classes—which are its objects. Classes
really distinguish C++ from C. In fact, before the name C++ was
coined, the C++ language was called “C with classes.”
This chapter attempts to expose you to the world of object-
oriented programming, often called OOP. You will probably not
become a master of OOP in these few short pages, however, you are
ready to begin expanding your C++ knowledge.
This chapter introduces the following concepts:
♦ C++ classes
♦ Member functions
♦ Constructors
♦ Destructors
This chapter concludes your introduction to the C++ language.
After mastering the techniques taught in this book, you will be ready
to modify the mailing list program in Appendix F to suit your own
needs.
661
Chapter 32 ♦ Introduction to Object-Oriented Programming
What Is a Class?
A class is a user-defined data type that resembles a structure. A
class can have data members, but unlike the structures you have
seen thus far, classes can also have member functions. The data
members can be of any type, whether defined by the language or by
you. The member functions can manipulate the data, create and
destroy class variables, and even redefine C++’s operators to act on
the class objects.
Classes have several types of members, but they all fall into two
categories: data members and member functions.
Data Members
Data members can be of any type. Here is a simple class:
// A sphere class.
class Sphere
{
public:
float r; // Radius of sphere
float x, y, z; // Coordinates of sphere
};
Member Functions
A class can also have member functions (members of a class that
manipulate data members). This is one of the primary features that
distinguishes a class from a structure. Here is the Sphere class again,
with member functions added:
662
C++ By
EXAMPLE
#include <math.h>
663
Chapter 32 ♦ Introduction to Object-Oriented Programming
Examples
1. The following program uses the Sphere() class to initialize a
class variable (called a class instance) and print it.
// Filename: C32CON.CPP
// Demonstrates use of a class constructor function.
#include <iostream.h>
const float PI = 3.14159; // Approximate value of pi.
// A sphere class.
class Sphere
{
public:
float r; // Radius of sphere
float x, y, z; // Coordinates of sphere
Sphere(float xcoord, float ycoord,
float zcoord, float radius)
{ x = xcoord; y = ycoord; z = zcoord; r = radius; }
~Sphere() { }
float volume()
{
return (r * r * r * 4 * PI / 3);
}
float surface_area()
{
return (r * r * 4 * PI);
}
};
void main()
{
Sphere s(1.0, 2.0, 3.0, 4.0);
664
C++ By
EXAMPLE
// Filename: C32DES.CPP
// Demonstrates use of a class destructor function.
665
Chapter 32 ♦ Introduction to Object-Oriented Programming
#include <iostream.h>
#include <math.h>
const float PI = 3.14159; // Approximate value of pi.
// A sphere class
class Sphere
{
public:
float r; // Radius of sphere
float x, y, z; // Coordinates of sphere
Sphere(float xcoord, float ycoord,
float zcoord, float radius)
{ x = xcoord; y = ycoord; z = zcoord; r = radius; }
~Sphere()
{
cout << “Sphere (“ << x << “, “ << y
<< “, “ << z << “, “ << r << “) destroyed\n”;
}
float volume()
{
return (r * r * r * 4 * PI / 3);
}
float surface_area()
{
return (r * r * 4 * PI);
}
};
void main(void)
{
Sphere s(1.0, 2.0, 3.0, 4.0);
// Construct a class instance.
cout << “X = “ << s.x << “, Y = “
<< s.y << “, Z = “ << s.z << “, R = “ << s.r << “\n”;
return;
}
X = 1, Y = 2, Z = 3, R = 4
Sphere (1, 2, 3, 4) destroyed
666
C++ By
EXAMPLE
// Filename: C32MEM.CPP
// Demonstrates use of class member functions.
#include <iostream.h>
#include <math.h>
const float PI = 3.14159; // Approximate value of pi.
// A sphere class.
class Sphere
{
public:
float r; // Radius of sphere
float x, y, z; // Coordinates of sphere
Sphere(float xcoord, float ycoord,
float zcoord, float radius)
{ x = xcoord; y = ycoord; z = zcoord; r = radius; }
~Sphere()
{
cout << “Sphere (“ << x << “, “ << y
<< “, “ << z << “, “ << r << “) destroyed\n”;
}
float volume()
{
return (r * r * r * 4 * PI / 3);
}
float surface_area()
{
return (r * r * 4 * PI);
}
}; // End of class.
void main()
{
Sphere s(1.0, 2.0, 3.0, 4.0);
cout << “X = “ << s.x << “, Y = “ << s.y
<< “, Z = “ << s.z << “, R = “ << s.r << “\n”;
667
Chapter 32 ♦ Introduction to Object-Oriented Programming
// Filename: C32MEM1.CPP
// Demonstrates use of in-line class member functions.
#include <iostream.h>
#include <math.h>
const float PI = 3.14159; // Approximate value of pi.
// A sphere class.
class Sphere
{
public:
float r; // Radius of sphere
float x, y, z; // Coordinates of sphere
Sphere(float xcoord, float ycoord, float zcoord, float radius)
{ x = xcoord; y = ycoord; z = zcoord; r = radius; }
~Sphere()
{
cout << “Sphere (“ << x << “, “ << y
<< “, “ << z << “, “ << r << “) destroyed\n”;
}
inline float volume()
{
return (r * r * r * 4 * PI / 3);
}
float surface_area()
{
return (r * r * 4 * PI);
668
C++ By
EXAMPLE
}
};
void main()
{
Sphere s(1.0, 2.0, 3.0, 4.0);
cout << “X = “ << s.x << “, Y = “ << s.y
<< “, Z = “ << s.z << “, R = “ << s.r << “\n”;
cout << “The volume is “ << s.volume() << “\n”;
cout << “The surface area is “ << s.surface_area() << “\n”;
}
// C32MEM1A.CPP
// Demonstrates use of in-line class member functions.
#include <iostream.h>
#include <math.h>
const float PI = 3.14159; // Approximate value of pi.
// A sphere class
class Sphere
{
public:
float r; // Radius of sphere
float x, y, z; // Coordinates of sphere
Sphere(float xcoord, float ycoord, float zcoord, float radius)
{ x = xcoord; y = ycoord; z = zcoord; r = radius; }
~Sphere()
{
cout << “Sphere (“ << x << “, “ << y
<< “, “ << z << “, “ << r << “) destroyed\n”;
}
inline float volume()
{
return (r * r * r * 4 * PI / 3);
}
float surface_area()
{
return (r * r * 4 * PI);
}
};
669
Chapter 32 ♦ Introduction to Object-Oriented Programming
void main()
{
Sphere s(1.0, 2.0, 3.0, 4.0);
cout << “X = “ << s.x << “, Y = “ << s.y
<< “, Z = “ << s.z << “, R = “ << s.r << “\n”;
cout << “The volume is “ << (s.r * s.r * s.r * 4 * PI / 3)
<< “\n”;
cout << “The surface area is “ << s.surface_area() << “\n”;
}
670
C++ By
EXAMPLE
Examples
1. Default arguments are used in the following code.
// Filename: C32DEF.CPP
// Demonstrates use of default arguments in
// class member functions.
#include <iostream.h>
#include <math.h>
const float PI = 3.14159; // Approximate value of pi.
// A sphere class.
class Sphere
{
public:
float r; // Radius of sphere
float x, y, z; // Coordinates of sphere
Sphere(float xcoord, float ycoord = 2.0,
float zcoord = 2.5, float radius = 1.0)
{ x = xcoord; y = ycoord; z = zcoord; r = radius; }
~Sphere()
{
cout << “Sphere (“ << x << “, “ << y
<< “, “ << z << “, “ << r << “) destroyed\n”;
}
inline float volume()
{
return (r * r * r * 4 * PI / 3);
}
float surface_area()
{
return (r * r * 4 * PI);
}
};
void main()
{
Sphere s(1.0); // use all default
Sphere t(1.0, 1.1); // override y coord
Sphere u(1.0, 1.1, 1.2); // override y and z
Sphere v(1.0, 1.1, 1.2, 1.3); // override all defaults
cout << “s: X = “ << s.x << “, Y = “ << s.y
<< “, Z = “ << s.z << “, R = “ << s.r << “\n”;
671
Chapter 32 ♦ Introduction to Object-Oriented Programming
s: X = 1, Y = 2, Z = 2.5, R = 1
The volume of s is 4.188787
The surface area of s is 12.56636
t: X = 1, Y = 1.1, Z = 2.5, R = 1
The volume of t is 4.188787
The surface area of t is 12.56636
u: X = 1, Y = 1.1, Z = 1.2, R = 1
The volume of u is 4.188787
The surface area of u is 12.56636
v: X = 1, Y = 1.1, Z = 1.2, R = 1.3
The volume of v is 9.202764
The surface area of v is 21.237148
Sphere (1, 1.1, 1.2, 1.3) destroyed
Sphere (1, 1.1, 1.2, 1) destroyed
Sphere (1, 1.1, 2.5, 1) destroyed
Sphere (1, 2, 2.5, 1) destroyed
Notice that when you use a default value, you must also use
the other default values to its right. Similarly, once you
define a function’s parameter as having a default value,
every parameter to its right must have a default value as well.
672
C++ By
EXAMPLE
2. You also can call more than one constructor; this is called
overloading the constructor. When having more than one
constructor, all with the same name of the class, you must
give them each a different parameter list so the compiler can
determine which one you intend to use. A common use of
overloaded constructors is to create an uninitialized object
on the receiving end of an assignment, as you see done here:
// C32OVCON.CPP
// Demonstrates use of overloaded constructors.
#include <iostream.h>
#include <math.h>
const float PI = 3.14159; // Approximate value of pi.
// A sphere class.
class Sphere
{
public:
float r; // Radius of sphere
float x, y, z; // Coordinates of sphere
Sphere() { /* doesn’t do anything... */ }
Sphere(float xcoord, float ycoord,
float zcoord, float radius)
{ x = xcoord; y = ycoord; z = zcoord; r = radius; }
~Sphere()
{
cout << “Sphere (“ << x << “, “ << y
<< “, “ << z << “, “ << r << “) destroyed\n”;
}
inline float volume()
{
return (r * r * r * 4 * PI / 3);
}
float surface_area()
{
return (r * r * 4 * PI);
}
};
void main()
{
Sphere s(1.0, 2.0, 3.0, 4.0);
673
Chapter 32 ♦ Introduction to Object-Oriented Programming
// Filename: C32VISIB.CPP
// Demonstrates use of class visibility labels.
#include <iostream.h>
#include <math.h>
const float PI = 3.14159; // Approximate value of pi.
// A sphere class.
class Sphere
{
private:
float r; // Radius of sphere
float x, y, z; // Coordinates of sphere
float cube() { return (r * r * r); }
float square() { return (r * r); }
674
C++ By
EXAMPLE
public:
Sphere(float xcoord, float ycoord, float zcoord, float radius)
{ x = xcoord; y = ycoord; z = zcoord; r = radius; }
~Sphere()
{
cout << “Sphere (“ << x << “, “ << y
<< “, “ << z << “, “ << r << “) destroyed\n”;
}
float volume()
{
return (cube() * 4 * PI / 3);
}
float surface_area()
{
return (square() * 4 * PI);
}
};
void main()
{
Sphere s(1.0, 2.0, 3.0, 4.0);
cout << “The volume is “ << s.volume() << “\n”;
cout << “The surface area is “ << s.surface_area() << “\n”;
return;
}
675
Chapter 32 ♦ Introduction to Object-Oriented Programming
Review Questions
The answers to the review questions are in Appendix B.
1. What are the two types of class members called?
2. Is a constructor always necessary?
3. Is a destructor always necessary?
4. What is the default visibility of a class data member?
5. How do you make a class member visible outside its class?
Review Exercise
Construct a class to hold personnel records. Use the following
data members, and keep them private:
char name[25];
float salary;
char date_of_birth[9];
Summary
You have now been introduced to classes, the data type that
distinguishes C++ from its predecessor, C. This was only a cursory
glimpse of object-oriented programming. However, you saw that
OOP offers an advanced view of your data, combining the data with
the member functions that manipulate that data. If you desire to
learn more about C++ and become a “guru” of sorts, try Using
Microsoft C/C++ 7 (Que, 0-88022-809-1).
676
Part VIII
References
C++ By
A
EXAMPLE
Memory
Addressing,
Binary, and
Hexadecimal
Review
You do not have to understand the concepts in this appendix to
become well-versed in C++. You can master C++, however, only if
you spend some time learning about the behind-the-scenes roles
played by binary numbers. The material presented here is not
difficult, but many programmers do not take the time to study it;
hence, there are a handful of C++ masters who learn this material
and understand how C++ works “under the hood,” and there are
those who will never master the language as they could.
You should take the time to learn about addressing, binary
numbers, and hexadecimal numbers. These fundamental principles
are presented here for you to learn, and although a working knowl-
edge of C++ is possible without knowing them, they greatly enhance
your C++ skills (and your skills in every other programming lan-
guage).
679
Appendix A ♦ Memory Addressing, Binary, and Hexadecimal Review
Computer Memory
Each memory location inside your computer holds a single
character called a byte. A byte is any character, whether it is a letter
of the alphabet, a numeric digit, or a special character such as a
period, question mark, or even a space (a blank character). If your
computer contains 640K of memory, it can hold a total of approxi-
mately 640,000 bytes of memory. This means that as soon as you fill
your computer’s memory with 640K, there is no room for an addi-
tional character unless you overwrite something.
Before describing the physical layout of your computer’s
memory, it is best to take a detour and explain exactly what 640K
means.
680
C++ By
EXAMPLE
M means Because extended memory and many disk drives can hold such
approximately a large amount of data, typically several million characters, there is
1,000,000 bytes
and exactly
an additional memory measurement shortcut called M, which stands
1,048,576 bytes. for meg, or megabytes. The M is a shortcut for approximately one
million bytes. Therefore, 20M is approximately 20,000,000 charac-
ters, or bytes, of storage. As with K, the M literally stands for
1,048,576 because that is the closest power of 2 (2 to the 20th power)
to one million.
How many bytes of storage is 60 megabytes? It is approxi-
mately 60 million characters, or 62,914,560 characters to be exact.
Memory Addresses
Each memory location in your computer, just as with each
house in your town, has a unique address. A memory address is
simply a sequential number, starting at 0, that labels each memory
location. Figure A.1 shows how your computer memory addresses
are numbered if you have 640K of RAM.
681
Appendix A ♦ Memory Addressing, Binary, and Hexadecimal Review
Figure A.2. DOS, your C++ program, and your program’s data share the
same memory.
682
C++ By
EXAMPLE
683
Appendix A ♦ Memory Addressing, Binary, and Hexadecimal Review
Each memory location in your computer holds eight bits each. These
bits can be any combination of eight 1s and 0s. This brings us to the
following fundamental rule of computers.
Computer
Your Keyboard
Printer
684
C++ By
EXAMPLE
685
Appendix A ♦ Memory Addressing, Binary, and Hexadecimal Review
Binary Numbers
Because a computer works best with 1s and 0s, its internal
numbering method is limited to a base-2 (binary) numbering system.
People work in a base-10 numbering system in the “real” world. The
base-10 numbering system is sometimes called the decimal number-
ing system. There are always as many different digits as the base in
a numbering system. For example, in the base-10 system, there are
ten digits, 0 through 9. As soon as you count to 9 and run out of digits,
you have to combine some that you already used. The number 10 is
a representation of ten values, but it combines the digits 1 and 0.
686
C++ By
EXAMPLE
The same is true of base-2. There are only two digits, 0 and 1.
As soon as you run out of digits, after the second one, you have to
reuse digits. The first seven binary numbers are 0, 1, 10, 11, 100, 101,
and 110.
It is okay if you do not understand how these numbers were
derived; you will see how in a moment. For the time being, you
should realize that no more than two digits, 0 and 1, can be used to
represent any base-2 number, just as no more than ten digits, 0
through 9, can be used to represent any base-10 number in the
regular numbering system.
You should know that a base-10 number, such as 2981, does not
really mean anything by itself. You must assume what base it is. You
get very used to working with base-10 numbers because you use
them every day. However, the number 2981 actually represents a
quantity based on powers of 10. For example, Figure A.5 shows what
the number 2981 actually represents. Notice that each digit in the
number represents a certain number of a power of 10.
A binary number This same concept applies when you work in a base-2 number-
can contain only the
ing system. Your computer does this because the power of 2 is just
digits 1 and 0.
as common to your computer as the power of 10 is to you. The only
difference is that the digits in a base-2 number represent powers of
2 and not powers of 10. Figure A.6 shows you what the binary
numbers 10101 and 10011110 are in base-10. This is how you convert
any binary number to its base-10 equivalent.
687
Appendix A ♦ Memory Addressing, Binary, and Hexadecimal Review
688
C++ By
EXAMPLE
689
Appendix A ♦ Memory Addressing, Binary, and Hexadecimal Review
Binary Arithmetic
At their lowest level, computers can only add and convert
binary numbers to their negative equivalents. Computers cannot
truly subtract, multiply, or divide, although they simulate these
operations through judicious use of the addition and negative-
conversion techniques.
If a computer were to add the numbers 7 and 6, it could do so
(at the binary level). The result is 13. If, however, the computer were
instructed to subtract 7 from 13, it could not do so. It can, however,
take the negative value of 7 and add that to 13. Because –7 plus 13
equals 6, the result is a simulated subtraction.
To multiply, computers perform repeated addition. To multi-
ply 6 by 7, the computer adds seven 6s together and gets 42 as the
answer. To divide 42 by 7, a computer keeps subtracting 7 from 42
repeatedly until it gets to a 0 answer (or less than 0 if there is a
remainder), then counts the number of times it took to reach 0.
690
C++ By
EXAMPLE
691
Appendix A ♦ Memory Addressing, Binary, and Hexadecimal Review
692
C++ By
EXAMPLE
693
Appendix A ♦ Memory Addressing, Binary, and Hexadecimal Review
0011010110100101
1001100110101010
1000000000000000
These numbers are unsigned, so the bit 15 is not the sign bit, but
simply another power of 2. You should practice converting these
large 16-bit numbers to decimal. The decimal equivalents are
13733
39338
32768
If, on the other hand, these numbers are signed numbers, the
high-order bit (bit 15) indicates the sign. If the sign bit is 0, the
numbers are positive and you convert them to decimal in the usual
manner. If the sign bit is 1, you must convert the numbers to their 2’s
complement to find what they equal. Their decimal equivalents are
+13733
–26198
–32768
To compute the last two binary numbers to their decimal
equivalents, take their 2’s complement and convert it to decimal. Put
a minus sign in front of the result and you find what the original
number represents.
TIP: To make sure that you convert a number to its 2’s com-
plement correctly, you can add the 2’s complement to its
original positive value. If the answer is 0 (ignoring the extra
carry to the left), you know that the 2’s complement number is
correct. This is similar to the concept that decimal opposites,
such as –72 + 72, add up to zero.
694
C++ By
EXAMPLE
Hexadecimal Numbers
Hexadecimal All those 1s and 0s get confusing. If it were up to your com-
numbers use 16 puter, however, you would enter everything as 1s and 0s! This is
unique digits, 0
through F. unacceptable to people because we do not like to keep track of all
those 1s and 0s. Therefore, a hexadecimal numbering system (some-
times called hex) was devised. The hexadecimal numbering system
is based on base-16 numbers. As with other bases, there are 16
unique digits in the base-16 numbering system. Here are the first 19
hexadecimal numbers:
0 1 2 3 4 5 6 7 8 9 A B C D E F 10 11 12
Because there are only 10 unique digits (0 through 9), the letters
A through F represent the remaining six digits. (Anything could
have been used, but the designers of the hexadecimal numbering
system decided to use the first six letters of the alphabet.)
To understand base-16 numbers, you should know how to
convert them to base-10 so they represent numbers with which
people are familiar. Perform the conversion to base-10 from base-16
the same way you did with base-2, but instead of using powers of 2,
represent each hexadecimal digit with powers of 16. Figure A.7
shows how to convert the number 3C5 to decimal.
695
Appendix A ♦ Memory Addressing, Binary, and Hexadecimal Review
696
C++ By
EXAMPLE
697
Appendix A ♦ Memory Addressing, Binary, and Hexadecimal Review
698
C++ By
EXAMPLE
you could convert the hex 41 to decimal (65 decimal) if you want to
know what is being assigned. Also, C++ systems programmers find
that they can better interface with assembly-language programs
when they understand the concepts presented in this appendix.
If you gain only a cursory knowledge of this material at this
point, you will be very much ahead of the game when you program
in C++!
699
Appendix A ♦ Memory Addressing, Binary, and Hexadecimal Review
700
C++ By
B
EXAMPLE
Answers to
Review Questions
Chapter 1
1. BCPL or Algol
2. True
3. 1980s
4. False. C++’s compact size makes it an excellent program-
ming language for smaller computers.
5. The hard disk
6. A modem
7. b. Input. By moving the mouse, you give cursor-direction
commands to the computer.
8. NumLock
9. UNIX
701
Appendix B ♦ Answers to Review Questions
10. When you turn off the computer, the contents of RAM are
destroyed.
11. True
12. 524,288 bytes (512 times 1,024)
13. Modulate, demodulate
Chapter 2
1. A set of detailed instructions that tells the computer what
to do.
2. Buy one or write it yourself.
3. False
4. The program produces the output.
5. A program editor
6. The .CPP extension
7. You must first plan the program by deciding which steps
you will take to produce the final program.
8. To get the errors out of your program
9. So your programs work with various compilers and com-
puter equipment
10. False. You must compile a program before linking it. Most
compilers link the program automatically.
Chapter 3
1. Two comment markers (//)
2. A holding place for data that can be changed
3. A value that cannot be changed
4. The +, -, *, and / operators
702
C++ By
EXAMPLE
Chapter 4
1. my_name and sales_89
2. Characters: ‘X’and ‘0’
Strings: “2.0” and “X”
Integers: 0 and -708
Floating-point literals: -12.0 and 65.4
3. Seven variables are declared: three integers, three characters,
and one floating-point variable.
4. A null zero, also called a binary zero or an ASCII zero.
5. True
6. 1
7. It is stored as a series of ASCII values, representing the
characters and blanks in the string, ending in an ASCII 0.
8. It is stored as a single ASCII 0.
9. The constant value called age cannot be changed.
Chapter 5
1. char my_name[] “This is C++”;
703
Appendix B ♦ Answers to Review Questions
3. It consumes 12 bytes.
4. All string literals end with a binary zero.
5. Two character arrays are declared, each with 25 elements.
6. False. The keyword char must precede the variable name.
7. True. The binary zero terminates the string.
8. False. The characters do not represent a string because there
is no terminating zero.
Chapter 6
1. False. You can define only constants with the #define prepro-
cessor directive.
2. The #include directive
3. The #define directive
4. True
5. The preprocessor changes your source code before the
compiler reads the source code.
6. The const keyword
7. Use angled brackets when the include files reside in the
compiler’s include subdirectory. Use quotation marks when
the include file resides in the same subdirectory as the source
program.
8. Defined literals are easier to change because you have to
change only the line with #define and not several other lines
in the program.
9. iostream.h
10. False. You cannot define constants enclosed in quotation
marks (as “MESSAGE” is in the cout statement).
11. Amount is 4
704
C++ By
EXAMPLE
Chapter 7
1. coutsends output to the screen, and cin gets input from the
keyboard.
2. The prompt tells the user what is expected.
3. The user enters four values.
4. cin assigns values to variables when the user types them,
whereas the programmer must assign data when using the
assignment operator (=).
5. True. When printing strings, you do not need %s.
6. Arrays
7. The backslash “\” character is special
Chapter 8
1. a. 5
b. 6
c. 5
2. a. 2
b. 7
3. a. a = (3+3) / (4+4);
c. f = (a*a)/(b*b*b);
#include stdio.h>
const float PI = 3.14159;
main()
705
Appendix B ♦ Answers to Review Questions
{
printf(“%f”, (PI*(4*4));
return;
}
r = 100%4;
cout << r;
Chapter 9
1. The == operator
2. a. True
b. True
c. True
d. True
3. True
4. The if statement determines what code executes when the
relational test is true. The if-else statement determines what
happens for both the True and the False relational test.
5. No
6. a. False
b. False
c. False
Chapter 10
1. The &&, ||, and ! operators are the three logical operators.
2. a. False
b. False
706
C++ By
EXAMPLE
c. True
d. True
3. a. True
b. True
c. True
4. g is 25 and f got changed to 8
5. a. True
b. True
c. False
d. True
6. Yes
Chapter 11
1. The if-else statement
2. The conditional operator is the only C++ operator with three
arguments.
3. if (a == b)
{ ans = c + 2; }
else
{ ans = c + 3; }
4. True
5. The increment and decrement operators compile into single
assembly instructions.
6. A comma operator (,), which forces a left-to-right execution
of the statements on either side
7. The output cannot be determined reliably. Do not pass an
increment operator as an argument.
707
Appendix B ♦ Answers to Review Questions
9. a. True
b. True
c. False
d. False
Chapter 12
1. The while loop tests for a true condition at the beginning of
the loop. The do-while tests for the condition at the end of the
loop.
2. A counter variable increments by one. A total variable
increments by the addition to the total you are performing.
3. The ++ operator
4. If the body of the loop is a single statement, the braces are
not required. However, braces are always recommended.
5. There are no braces. The second cout always executes, re-
gardless of the result of the while loop’s relational test.
6. The stdlib.h header file
7. One time
8. By returning a value inside the exit() function’s parentheses
9. This is the outer loop
708
C++ By
EXAMPLE
Chapter 13
1. A loop is a sequence of one or more instructions executed
repeatedly.
2. False
3. A nested loop is a loop within a loop.
4. Because the expressions might be initialized elsewhere, such
as before the loop or in the body of the loop
5. The inner loop
6. 10
7
7. True
8. The body of the for loop stops repeating.
9. False, due to the semicolon after the first for loop
10. There is no output. The value of start is already less than end
when the loop begins; therefore, the for loop’s test is imme-
diately False.
Chapter 14
1. Timing loops force a program to pause.
2. Because some computers are faster than others.
3. If the continue and break statements were unconditional,
there would be little use for them.
4. Because of the unconditional continue statement, there is no
output.
5. *****
709
Appendix B ♦ Answers to Review Questions
Chapter 15
1. The program does not execute sequentially, as it would
without goto.
2. The switch statement
3. A break statement
4. False because you should place the case most likely to
execute at the beginning of the case options.
5. switch (num)
{ case (1) : { cout << “Alpha”;
break; }
case (2) : { cout << “Beta”;
break; }
case (3) : { cout << “Gamma”;
break; }
default : { cout << “Other”;
break; }
}
6. do
{ cout << “What is your first name? “;
cin >> name;
} while ((name[0] < ‘A’) || (name[0] > ‘Z’));
Chapter 16
1. True
2. main()
710
C++ By
EXAMPLE
Chapter 17
1. True
2. Local variables are passed as arguments.
3. False
4. The variable data types
5. Static
6. You should never pass global variables—they do not need to
be passed.
7. Two arguments (the string “The rain has fallen %d inches”,
and the variable, rainf)
Chapter 18
1. Arrays
2. Nonarray variables are always passed by value, unless you
override the default with & before each variable name.
3. True
4. No
5. Yes
711
Appendix B ♦ Answers to Review Questions
Chapter 19
1. By putting the return type to the left of the function name.
2. One
3. To prototype built-in functions.
4. int
5. False
6. Prototypes ensure that the correct number of parameters is
being passed.
7. Global variables are already known across functions.
8. The return type is float. Three parameters are passed: a
character, an integer, and a floating-point variable.
Chapter 20
1. In the function prototypes.
2. Overloaded functions
3. Overloaded functions
4. False. You can specify multiple default arguments.
5. void my_fun(float x, int i=7, char ch=’A’);
712
C++ By
EXAMPLE
Chapter 21
1. For portability between different computers
2. False. The standard output can be redirected to any device
through the operating system.
3. getch() assumes stdin for the input device.
4. get
7. False. The input from get goes to a buffer as you type it.
8. Enter
9. True
Chapter 22
1. The character-testing functions do not change the character
passed to them.
2. gets() and fgets()
3. floor() rounds down and ceil() rounds up.
4. The function returns 0 (false) because islower(‘s’) returns a 1
(true) and isalpha(1) is 0.
5. PeterParker
6. 8 9
7. True
8. Prog with a null zero at the end.
9. True
713
Appendix B ♦ Answers to Review Questions
Chapter 23
1. False
2. The array subscripts differentiate array elements.
3. C does not initialize arrays for you.
4. 0
Chapter 24
1. False
2. From the low numbers floating to the top of the array like
bubbles.
3. Ascending order
4. The name of an array is an address to the starting element of
that array.
5. a. Eagles
b. Rams
c. les
d. E
e. E
714
C++ By
EXAMPLE
Chapter 25
1. int scores[5][6];
2. char initials[4][10][20]
Chapter 26
1. a. Integer pointer
b. Character pointer
c. Floating-point pointer
2. “Address of “
3. The * operator
4. pt_sal = &salary;
5. False
6. Yes
7. a. 2313.54
715
Appendix B ♦ Answers to Review Questions
b. 2313.54
c. invalid
d. invalid
8. b
Chapter 27
1. Array names are pointer constants, not pointer variables.
2. 8
3. a, c, and d are equivalent. Parentheses are needed around
iptr+4 and iptr+1 to make b and e valid.
Chapter 28
1. Structures hold groups of more than one value, each of
which can be a different data type.
2. Members
3. At declaration time and at runtime
4. Structures pass by copy.
5. False. Memory is reserved only when structure variables are
declared.
6. Globally
7. Locally
8. 4
716
C++ By
EXAMPLE
Chapter 29
1. True
2. Arrays are easier to manage.
3. a. inventory[32].price = 12.33;
b. inventory[11].part_no[0] = ‘X’;
c. inventory[96] = inventory[62];
Chapter 30
1. Write, append, and read.
2. Disks hold more data than memory.
3. You can access sequential files only in the same order that
they were originally written.
4. An error condition occurs.
5. The old file is overwritten.
6. The file is created.
7. C++ returns an end-of-file condition.
Chapter 31
1. Records are stored in files and structures are stored in
memory.
2. False
3. The file pointer continually updates to point to the next byte
to read.
717
Appendix B ♦ Answers to Review Questions
Chapter 32
1. Data members and member functions
2. No
3. No
4. Private
5. Declare it with the public keyword.
718
C++ By
C
EXAMPLE
ASCII Table
(Including IBM Extended
Character Codes)
719
Appendix C ♦ ASCII Table
720
C++ By
EXAMPLE
721
Appendix C ♦ ASCII Table
722
C++ By
EXAMPLE
723
Appendix C ♦ ASCII Table
724
C++ By
EXAMPLE
725
Appendix C ♦ ASCII Table
726
C++ By
EXAMPLE
727
Appendix C ♦ ASCII Table
728
C++ By
D
EXAMPLE
C++ Precedence
Table
Precedence
Level Symbol Description Associativity
1
Highest () Function call Left to right
[] Array subscript
→ C++ indirect component
selector
:: C++ scope access/resolution
. C++ direct component selector
2
Unary ! Logical negation Right to left
~ Bitwise (1’s) complement
+ Unary plus
- Unary minus
729
Appendix D ♦ C++ Precedence Table
Precedence
Level Symbol Description Associativity
++ Preincrement or postincrement
–– Predecrement or postdecrement
& Address of
* Indirection
sizeof (Returns size of operand, in
bytes.)
new (Dynamically allocates
C++ storage.)
delete (Dynamically deallocates
C++ storage.)
3
Member Left to right
Access .* C++ dereference
→* C++ dereference
4
Multipli-
cative * Multiply Left to right
/ Divide
% Remainder (modulus)
5
Additive + Binary plus Left to right
- Binary minus
6
Shift << Shift left Left to right
>> Shift right
730
C++ By
EXAMPLE
Precedence
Level Symbol Description Associativity
7
Relational < Less than Left to right
<= Less than or equal to
> Greater than
>= Greater than or equal to
8
Equality == Equal to Left to right
!= Not equal to
14
Condi-
tional ?: Right to left
15
Assignment = Simple assignment Right to left
*= Assign product
/= Assign quotient
731
Appendix D ♦ C++ Precedence Table
Precedence
Level Symbol Description Associativity
%= Assign remainder Right to left
+= Assign sum
-= Assign difference
&= Assign bitwise AND
^= Assign bitwise XOR
|= Assign bitwise OR
<<= Assign left shift
>>= Assign right shift
16
Comma , Evaluate Left to right
732
C++ By
E
EXAMPLE
Keyword and
Function
Reference
These are the 46 C++ standard keywords:
auto double new* switch
asm* else operator* template
break enum private* this*
case extern protected typedef
catch* float public* union
char for register unsigned
class* friend* return virtual*
const goto short void
continue if signed volatile
default inline* sizeof while
delete* int static
do long struct
* These keywords are specific to C++. All others exist in both C and C++.
733
Appendix E ♦ Keyword and Function Reference
stdio.h
int fclose(FILE *stream);
int feof(FILE *stream);
int ferror(FILE *stream);
int fflush(FILE *stream);
int fgetc(FILE *stream);
char *fgets(char *, int, FILE *stream);
FILE *fopen(const char *filename, const char *mode);
int fprintf(FILE *stream, const char *format, ...);
int fputc(int, FILE *stream);
int fputs(const char *, FILE *stream);
size_t fread(void *, size_t, size_t, FILE *stream);
int fscanf(FILE *stream, const char *format, ...);
int fseek(FILE *stream, long offset, int origin);
size_t fwrite(const void *, size_t, size_t, FILE *stream);
int getc(FILE *stream);
int getchar(void);
char *gets(char *);
void perror(const char *);
int putc(int, FILE *stream);
int putchar(int);
int puts(const char *);
int remove(const char *filename);
void rewind(FILE *stream);
int scanf(const char *format, ...);
ctype.h
int isalnum(unsigned char);
int asalpha(unsigned char);
int iscntrl(unsigned char);
int isdigit(unsigned char);
int isgraph(unsigned char);
int islower(unsigned char);
734
C++ By
EXAMPLE
int isprint(unsigned char);
int ispunct(unsigned char);
int isspace(unsigned char);
int isupper(unsigned char);
int isxdigit(unsigned char);
int tolower(int);
int toupper(int);
string.h
char *strcat(char *, char *);
int strcmp(char *, char *);
int strcpy(char *, char *);
size_t strlen(char *);
math.h
double ceil(double);
double cos(double);
double exp(double);
double fabs(double);
double floor(double);
double fmod(double, double);
double log(double);
double log10(double);
double pow(double, double);
double sin(double);
double sqrt(double);
double tan(double);
stdlib.h
double atof(const char *);
int atoi(const char *);
long atol(const char *);
void exit(int);
int rand(void);
void srand(unsigned int);
735
Appendix E ♦ Keyword and Function Reference
736
C++ By
F
EXAMPLE
// Filename: MAILING.CPP
// * Mailing List Application *
// ------------------------
//
// This program enables the user to enter, edit, maintain, and
// print a mailing list of names and addresses.
//
// All commands and concepts included in this program are
// explained throughout the text of C++ By Example.
737
Appendix F ♦ The Mailing List Application
//
//
//
// These are items you might want to add or change:
// 1. Find your compiler’s clear screen function to
// improve upon the screen-clearing function.
// 2. Add an entry for the ‘code’ member to track different
// types of names and addresses (i.e., business codes,
// personal codes, etc.)
// 3. Search for a partial name (i.e., typing “Sm” finds
// “Smith” and “Smitty” and “Smythe” in the file).
// 4. When searching for name matches, ignore case (i.e.,
// typing “smith” finds “Smith” in the file).
// 5. Print mailing labels on your printer.
// 6. Allow for sorting a listing of names and address by name
// or ZIP code.
#include <conio.h>
#include <ctype.h>
#include <fstream.h>
#include <iostream.h>
#include <string.h>
char get_answer(void);
void disp_menu (void);
void clear_sc (void);
void change_na (void);
void print_na (void);
void err_msg (char err_msg[ ]);
void pause_sc (void);
738
C++ By
EXAMPLE
const int STATE_SIZE = 3;
const int ZIPCODE_SIZE = 6;
const int CODE_SIZE = 7;
cout << “\nEnter new name and address information below\n(Press the “;
cout << “Enter key without typing data to retain old "
“information)\n\n”;
cout << “What is the new name? “;
cin.getline(temp_item.name, NAME_SIZE);
if (strlen(temp_item.name)) // Only save new data if user
{ strcpy((*item).name, temp_item.name); } // types something.
cout << “What is the address? “;
cin.getline(temp_item.address, ADDRESS_SIZE);
739
Appendix F ♦ The Mailing List Application
if (strlen(temp_item.address))
{ strcpy((*item).address, temp_item.address); }
cout << “What is the city? “;
cin.getline(temp_item.city, CITY_SIZE);
if (strlen(temp_item.city))
{ strcpy((*item).city, temp_item.city); }
cout << “What is the state? (2 letter abbreviation only) “;
cin.getline(temp_item.state, STATE_SIZE);
if (strlen(temp_item.state))
{ strcpy((*item).state, temp_item.state); }
cout << “What is the ZIP code? “;
cin.getline(temp_item.zipcode, ZIPCODE_SIZE);
if (strlen(temp_item.zipcode))
{ strcpy((*item).zipcode, temp_item.zipcode); }
(*item).code[0] = 0; // Null out the code member
// (unused here).
}
void Mail::change_na(void)
{
// This search function can be improved by using the
// code member to assign a unique code to each person on the
// list. Names are difficult to search for since there are
// so many variations (such as Mc and Mac and St. and Saint).
Mail item;
fstream file;
int ans;
int s; // Holds size of structure.
int change_yes = 0; // Will become TRUE if user finds
char test_name[25]; // a name to change.
cout << “\nWhat is the name of the person you want to change? “;
cin.getline(test_name, NAME_SIZE);
s = sizeof(Mail); // To ensure fread() reads properly.
740
C++ By
EXAMPLE
file.open(FILENAME, ios::in | ios::out);
if (!file)
{
err_msg(“*** Read error - Ensure file exists before "
"reading it ***”);
return;
}
do
{
file.read((unsigned char *)&item, sizeof(Mail));
if (file.gcount() != s)
{
if (file.eof())
{ break; }
}
if (strcmp(item.name, test_name) == 0)
{
item.pr_data(&item); // Print name and address.
cout << “\nIs this the name and address to “ <<
“change? (Y/N) “;
ans = get_answer();
if (toupper(ans) == ‘N’)
{ break; } // Get another name.
get_new_item(&item); // Enable user to type new
// information.
file.seekg((long)-s, ios::cur); // Back up a structure.
file.write((const unsigned char *)(&item),
sizeof(Mail)); // Rewrite information.
change_yes = 1; // Changed flag.
break; // Finished
}
}
while (!file.eof());
if (!change_yes)
{ err_msg(“*** End of file encountered before finding the name ***”);}
}
741
Appendix F ♦ The Mailing List Application
int bad_zip;
do
{
bad_zip = 0;
cout << “What is the ZIP code? “;
cin.getline((*item).zipcode, ZIPCODE_SIZE);
for (ctr = 0; ctr < 5; ctr++)
{
if (isdigit((*item).zipcode[ ctr ]))
{ continue; }
else
{
err_msg(“*** The ZIP code must consist of digits only ***”);
bad_zip = 1;
break;
}
}
}
while (bad_zip);
}
742
C++ By
EXAMPLE
do
{
cout << “\n\n\n\n\nWhat is the name? “;
cin.getline((*item).name, NAME_SIZE);
cout << “What is the address? “;
cin.getline((*item).address, ADDRESS_SIZE);
cout << “What is the city? “;
cin.getline((*item).city, CITY_SIZE);
cout << “What is the state? (2 letter abbreviation only)”;
cin.getline((*item).state, STATE_SIZE);
getzip(item); // Ensure that ZIP code is all digits.
strcpy((*item).code, “ “); // Null out the code member.
add_to_file(item); // Write new information to disk file.
cout << “\n\nDo you want to enter another name “ <<
“and address? (Y/N) “;
ans = get_answer();
}
while (toupper(ans) == ‘Y’);
}
//************************************************************
// Defined constants
// MAX is total number of names allowed in memory for
// reading mailing list.
//************************************************************
int main(void)
{
char ans;
Mail item;
do
{
disp_menu(); // Display the menu for the user.
ans = get_answer();
switch (ans)
{
case ‘1’:
743
Appendix F ♦ The Mailing List Application
item.enter_na(&item);
break;
case ‘2’:
item.change_na();
break;
case ‘3’:
print_na();
break;
case ‘4’:
break;
default:
err_msg(“*** You have to enter 1 through 4 ***”);
break;
}
}
while (ans != ‘4’);
return 0;
}
//************************************************************
//************************************************************
744
C++ By
EXAMPLE
{ cout << “\n”; }
}
//************************************************************
void print_na(void)
{
Mail item;
ifstream file;
int s;
int linectr = 0;
745
Appendix F ♦ The Mailing List Application
//************************************************************
//************************************************************
void pause_sc()
{
cout << “\nPress the Enter key to continue...”;
while (getch() != ‘\r’)
{ ; } // Wait for Enter key.
}
//************************************************************
char get_answer(void)
{
char ans;
ans = getch();
while (kbhit())
{ getch(); }
putch(ans);
return ans;
}
746
C++ By
EXAMPLE
Glossary
Address. Each memory (RAM) location (each byte) has a unique
address. The first address in memory is 0, the second RAM location’s
address is 1, and so on until the last RAM location (thousands of
bytes later).
ANSI. American National Standards Institute, the committee that
approves computer standards.
Argument. The value sent to a function or procedure. This can be
a constant or a variable and is enclosed inside parentheses.
Array. A list of variables, sometimes called a table of variables.
Array of Structures. A table of one or more structure variables.
ASCII. Acronym for American Standard Code for Information
Interchange.
ASCII File. A file containing characters that can be used by any
program on most computers. Sometimes called a text file or an
ASCII text file.
AUTOEXEC.BAT. A batch file in PCs that executes a series of
commands whenever you start or reset the computer.
Automatic Variables. Local variables that lose their values when
their block (the one in which they are defined) ends.
747
Glossary ♦
748
C++ By
EXAMPLE
749
Glossary ♦
750
C++ By
EXAMPLE
751
Glossary ♦
752
C++ By
EXAMPLE
753
Glossary ♦
754
C++ By
EXAMPLE
755
Glossary ♦
756
C++ By
EXAMPLE
757
Glossary ♦
758
C++ By
EXAMPLE
759
Glossary ♦
760
C++ By
EXAMPLE
Index
761
Index ♦
762
C++ By
EXAMPLE
arguments, 747 multidimensional, see multidi-
alphabetical, testing for, 451 mensional arrays
default names
lists, 415-417, 750 as pointers, 558-559
multiple, 417-420 changing, 560
member functions, 670-674 notation, 608-610
mismatched, 407 parallel, 756
numeric, testing for, 451 passing, 388
passing, 364-366 by address, 386
receiving, 550 functions, 387
see also variables to functions, 484
arithmetic (of) pointers, 551-553
binary, 690-692 pointers, 493
pointers, 568-574 printing with cout operator,
arrays, 100, 474-479, 747 102
as sizeof argument, 231 ragged-edge, 574
assigning to arrays, 486 referencing, 508-515, 558
brackets ([ ]), printing, 102 reserving memory, 476
character pointers, 574 searching, 494-495
character, see character arrays for statement, 496
contents, changing, 563 for values, 496-501
data types, mixing, 609 if statement, 496
declaring, 100, 475 sizes, 128, 476-477, 480
strings, 478 sorting, 494-495, 501-508, 758
subscripts, 482 ascending sort, 506
defining, data type, 475 bubble sort, 502-505, 748
elements, 101, 751 character arrays, 508
accessing, 101 descending sort, 494, 506
initializing all to zero, 481 nested loops, 504
inputting to, 611 numeric arrays, 508
subscripts, 101-102 quicksort, 502, 757
filling shell sort, 502, 758
random values, 497 (of) strings, 574-578
user input, 389 strings
global, see global arrays printing, 563
individual characters, 105 storing, 574
initializing, 104-105, 479-490 (of) structures, 589, 747
assignment operator, 480 structures, declaring, 606-615
braces ({ }), 527 subscripts, 474
brackets [ ], 480 two-dimensional, 525
multidimensional, 529 type, specifying, 390
mapping to memory, 524-526 values, assigning, 103
members, 615-622 see also nonarrays
763
Index ♦
764
C++ By
EXAMPLE
blank C
characters, 680
expressions, see null expres- C++
sion comparing to other languages,
lines, 136 16
blocks, 55 origination, 15-16
braces ({ }), 56 calculations
case, break statements, 312 data types, mixing, 178-182
statements, 246, 748 strings, 460
body (program) structure members, 597
functions, 336, 345 called functions, 364
loops, indenting, 279 recognizing, 368-369
statements, 189, 342 return values, 398
boilerplates, 117 variables, changing, 387
booting, 748 calling functions, 337-349
braces ({ }), 46, 56-57, 340 repeatedly, 417
functions, 336 carriage returns, 439
initializing arrays, 527 case blocks, break statements,
loops, 287 312
brackets ([ ]), 46, 100 case expressions, 312
angled (< >), 117 case statements, 313, 319
arrays, initializing, 480 cathode ray tube (CRT), 24, 748
dimensions, 523 ceil(x) function, 461
printing arrays, 102 ceiling function, 461
branching, 321 central processing unit (CPU),
break statement, 256-260, 298-303 20-22, 748
case blocks, 312 cfront (UNIX) compiler, 43
nested loops, 299 CGA display adapter, 24
unconditional, 299 character arrays, 100-103
breaks, conditional, 257-258 control_string, 149
bubble sort, see sorting arrays erasing, passing to functions,
buffered input functions, 440-442 390
bugs, see debugging filenames, storing, 633
built-in editors, 40 initializing, 480
built-in functions, prototypes, pointing, to new strings, 563
734-735 reserving, 100, 480
bytes, 20, 682-685, 748 sorting, 508
K (kilobytes), 20, 753 string values, assigning, 105
M (megabytes), 24, 754 strings
reserving, arrays, 476 comparing, 103-110
multiple, 512
printing, 135, 510
storing, 104
765
Index ♦
766
C++ By
EXAMPLE
compiling, 43, 113, 749 controlling
compound assignments, 176-178 format string, 149
compound operators, 177 function calls, 338
compound relational operators, statements conditionally, 185
see logical operators conversion characters, 151-154
compound relational tests, 207 floating-point, 151
computers functions, 453-455
digital, 29, 750 for printing, 297
microcomputers, 754 setw manipulator, 140
personal (PCs), 757 converting
see also microcomputers binary numbers
concatenation, 456, 749 to 2's complement, 692
conditional breaks, 257-258 to hexadecimal, 697
conditional loops, 749 data types automatically, 179
conditional operators, 222-225 hexadecimal numbers to
CONFIG.SYS file, FILES= state- binary numbers, 697
ment, 629 strings to numbers, 460-461
console, 434 to floating-point number,
const keyword, 94, 120, 749 460
constant variables, 94-95 to integers, 460
constants, 94, 749, 759 to uppercase, 240
defining copy, passing by, 379, 547, 756
character formatting, 440 copying
variables as, 120 literals, in strings, 107
numeric, printing, 151 members, structure variables,
pointers, 560-562 598
string cos(x) function, 464
changing, 566 count expressions
printing, 150 increments, 281
see also literals and pointer loops, 274, 278
constants counter variables, 262, 265, 360
construct statements, 246 nested loops, 288
constructor functions, 663, 749 counters, 260-268
multiple, 673 cout, 65, 85
overloading, 673 \n, 91
constructs, loops, 276 appending, 93
continue statement, 303-307 combining with ofstream, 437
control characters, I/O functions, format, 134
433 labeling output, 136
control operators, 139-144 literals, printing, 83
control_string, 149, 155 printing
arrays, 102
strings, 134-144
767
Index ♦
768
C++ By
EXAMPLE
variables, 365 directories, 750
after opening brace, 355 paths, 756
as constants, 120 subdirectories, 750
outside functions, 355 disk drives, 23, 750
structure, 595 disk operating system (DOS), 751
definition line, 406, 750 diskettes, see floppy disks
Del key, 27 disks, 22-24, 626-627, 750
delay value, 296 files
delimiters, strings, 88, 759 accessing, 625-628
demodulated signals, 29, 750 appending, 628
dereferencing (*) pointer opera- creating, 628
tor, 542, 750 opening/closing, 629-634
descending sort, 494, 506 fixed, see hard disks
see also sorting arrays floppy, see floppy disks
designating literals formatting, 23, 752
floating-point, 79 hard, see hard disks
long, 79 measurements, 680-681
unsigned, 79 sectors, 758
designing programs, 38-39 size, 24
destructor function, 665, 750 tracks, 23, 760
determinate loops, 750 disk drives, 23
devices see also hard disks
default, overriding, 436 display adapters, 24, 751
flushing, 458 CGA, 24
get( ) function, 438 EGA, 24
I/O (standard), 434 MCGA, 24
input, standard, 759 VGA, 24
output, 134, 756, 759 see also monitors; screens
redirecting from MS-DOS, displaying error messages,
435-436 nested loops, 296
standard, 434 division (/) math operator, 64,
digital computer, 29, 750 164, 167-168
digital testing, functions, 451 do-while loop, 252-255
digits DOS (disk operating system),
binary, 683 30-32, 751
testing for, character func- dot (.) operator, 592, 608, 616
tions, 451 dot-matrix printer, 25, 751, 753
dimensions, designating with double subscripts, 616
braces ({ }), 523, 527 dynamic memory allocation, 665
directives, 757
#define, 94
#include, 61
769
Index ♦
E escape key, 25
escape-sequence characters,
EDIT editor, 41 91-92
editing, linking, 753 executable files, 42
editors, 37-42 executing, 751
built-in, 40 functions repeatedly, 347
EDIT, 41 programs
EDLIN, 41 falling through, 312
ISPF, 42 stopping, manually, 250
EGA display adapters, 24 see also running programs
electricity (states), 21, 683 exit( ) function, 256-260
elements (arrays), 101, 751 isolating, 256
accessing, 101 stdlib.h header file, 256
assigning values, 479 exiting
initializing, 486-492 conditional breaks, 257-258
all to zero, 481 loops, 256-260, 303
at declaration time, exp(x) function, 465
479-486 expanded memory, 21, 751
inputting, 611 see also extended memory
members, 584 expressions
referencing with subscripts, case, 312
476 count, 274
reserving, 103 increments, 281
space between, 476 loops, 278
storing, 476 incrementing/decrementing,
subscripts, 101-102, 474 228
elements (pointers), loops
dereferencing, 576 start, 278
else statement, 198-203 test, 275, 283
embedding functions, 668 nonconditional, 190
endless loops, 323 null, 285
environments start, 274
integrated, 40-41 switch statement, 312
variables, 256 test, 274
equal sign (=), 80, 105, 400 parentheses, 246
equal to (==) relational operator, extended memory, 21, 681, 751
186 see also expanded memory
equality testing, 187 extensions (filenames), 42, 751
erasing character arrays by external functions, 117
passing to functions, 390 external memory, 22
error messages, 46-48 external modem, 28, 751
displaying, nested loops, 296
illegal initialization, 102
syntax, 46
770
C++ By
EXAMPLE
F reading to specific points,
649-656
fabs(x) function, 461 records, 635, 758
factorial, 290 fields, 646
fflush( ) function, 458 fixed-length, 647
fgets( ) function, 457 sequential, 627-629, 758
fields, 751 string.h, 107
file pointers, 631, 650 writing to, 634-637
declaring globally, 632 FILES= statement, 629
positioning, 650-656 fill_structs( ) function, 597
file_ptr pointer, 629 filling arrays
filenames, 751 random values, 497
#include directive, 115 user input, 389
character pointers, 633 fixed disks, see hard disks
conventions, 43 fixed-length records, 647, 751
extensions, 42, 751 floating-point
recommended, 43 conversion characters, 151
storing character arrays, 633 literals, 79
files, 751 defining, 127
accessing, 627-628 designating, 79
modes, 630, 639, 648 numbers, 63, 76
random access, 627 converting to, 460
sequential file access, printing, 140
625-627 value, 138
text mode, 630 variables, 100, 142
appending, 628, 638-639 assigning to integer
ASCII, 630, 747 addresses, 549
AUTOEXEC.BAT, 747 printing, 152
backup, 748 floor(x) mathematical function,
CONFIG.SYS, FILES= state- 462
ment, 629 floppy disks, 22, 750-751
creating, 648 flushing devices, 458
directories, 750 fmod(x, y) function, 462
disk, creating, 628 for loops, 273-286
executable, 42 body, 279
formats, binary, 631 expressions
header, see header files count, 274
include, order, 118 start, 274
opening/closing, 629-634, 647 test, 274
pointing, 629 nested, 286-291
random, see random files tables, multidimensional,
random-access, 628, 757 530-537
reading, 639-642
771
Index ♦
772
C++ By
EXAMPLE
get( ), 438-444 next_fun( ), 338
getch( ), 444-446 nonbuffered, 444
I/O, 656-658 numeric, 461-467, 755
character, 437-446 ofstream, 436-437
control characters, 433 open( ), 629, 648
fgets(s, len, dev), 457 overloading, 415, 420-425, 756
fputs(s, dev), 457 parentheses, 336, 365
gets( ), 457, 635 passing arrays, 484
puts( ), 457, 635 pr_msg( ), 416
read(array, count), 656 print_it( ), 525
remove(filename), 656 printf( ), 65, 126, 149-150,
write(array, count), 656 191, 407
in-line, 668-670, 752 prototypes, 338, 397, 405-411
input ctype.h header file, 734
buffered, 440 math.h header file, 461, 735
building, 442 self-prototyping, 406
mirror-image, 637 stdio.h header file, 734
keyboard values, 392 stdlib.h header file, 460, 735
length, 335 string.h header file, 735
logarithmic, 465 put( ), 438-444
exp(x), 465 putch( ), 444-446
log(x), 465 rand( ), 465-466, 497
log10(x), 465 receiving, 364, 382
main, 56 redefining, 121-126
main( ), 56-57, 61, 332, 335 return statements, 337, 345
OOP, 665 return values, 398-405
prototyping, 409 returning, 337-349
mathematical, 461-464 scanf( ), 126, 149, 154-157
ceil(x), 461 passing variables, 546
fabs(x), 461 prototyping, 407
floor(x), 462 seekg( ), 649-656
fmod(x, y), 462 separating, 345
pow( ), 463 setw( ), 140
pow(x, y), 462 sizeof( ), 476-477
sqrt(x), 462 sort, saving, 508
member, 754 Sphere( ), 663-670
arguments, 670-674 square( ), 674
classes, 662-676 strcat( ), 456
multiple execution, 347 strcpy( ), 107, 408
naming, 335-337 string, 455-461
_ (underscore), 336 fgets(s, len, dev), 457
name-mangling, 422 fputs(s, dev), 457
rules, 335
773
Index ♦
gets(s), 457 H
I/O, 456-459
puts(s), 457 hard copy, 752
strcat(s1, s2), 456 hard disks, 22, 751-752
strcmp(s1, s2), 456 see also disk drives
strlen(s1), 456 hardware, 17-29, 752
testing, 456 disks, 22-24
strlen( ), 251 indepedence, 17
surface_area( ), 663-670 memory, 20-22
testing modems, 28-29
alphabetic conditions, monitors, 24
450-451 mouse, 28
digits, 451 printers, 25
numeric arguments, 451 system unit, 20-22
third_fun( ), 338 header files, 117-118, 752
trigonometric ctype.h
cos(x), 464 function prototypes, 734
sin(x), 464 prototypes, 450
tan(x), 464 iomanip.h, 408
values, returning, 374 iostream.h, 117, 408
variables, types, 152 math.h
volume( ), 663-670 function prototypes, 735
writing, 332-337 prototypes, 461
see also routines stdio.h
function prototypes, 408,
G 734
printf( ) function, 150
get( ) function, 438-444
stdlib.h
getch( ) function, 444-446
exit( ) function, 256
gets( ) function, 457, 635
function prototypes, 735
global arrays, initializing, 479 prototypes, 460
global pointers, declaring, 542 string.h, 118
global variables, 73, 354-369, 752 function prototypes, 735
declaring, 358 prototypes, 456
passing, 364 hexadecimals, 17, 83, 695-698, 752
returning, 398 converting
goto statement, 321-326
from binary, 697
graphics monitors, 24 to binary numbers, 697
greater than (>) relational ope- hiding data, 675
rator, 186 hierarchy of operators, see order
greater than or equal to (>=) of precedence
relational operator, 186 high-order bit, 686
hyphen (-), 336
774
C++ By
EXAMPLE
I brackets [ ], 480
global, 479
I/O (input/output), 753 multidimensional, 529
character, 432-436 character arrays, reserved, 480
devices (standard), 434 elements, 479-492
functions, 656-658 illegal, 102
character, 437-446 members individually, 591
control characters, 433 multidimensional arrays,
fgets(s, len, dev), 457 526-530
fputs(s, dev), 457 pointers, 545
gets( ), 635 assignment statements, 548
gets(s), 457 while declaring, 545
puts( ), 457, 635 structures, 591
read(array, count), 656 dot (.) operator, 592
remove(filename), 656 members, 591-600
strings, 456-459 variables
write(array, count), 656 structures, 591
rerouting, 434 to zero, 176
statements, 17 inline functions, 752
stream, 432-436 input, 30, 753
strings, 457 arrays, filling, 389
if loop, 189-199, 255, 496 buffered, 441-442
if tests, relational, 209 characters, echoing, 444
illegal initialization, 102 devices, standard, 759
in-line functions, 668-670 functions
include files, order, 118 buffered, 440
increment (++) operator, 225, 233 building, 442
incrementing mirror-image, 637
expressions, 228 keyboard, 435
pointers, 568 statements, 17
variables, 225-230 stdin, 434-435
increments as count expressions, stream header, 117
281 terminating
indeterminate loops, 752 fgets( ), 457
infinite loops, 246, 752 gets( ), 457
initial values of static variables, values, 248
370 input redirection symbol (<), 435
initializing input-output-process model, 30
arrays, 104-105, 479-490 input/output, see I/O
assignment operator, 480 Ins key, 27
braces ({ }), 527 int data type, 400
integer literals, 83-84
integer variables, 73, 152, 753
775
Index ♦
776
C++ By
EXAMPLE
defined, 121, 365 order of precedence, 216
replacing, 126 truth tables, 208
variables, 122 loop variables, 282
designating loop-counting variables, 361
floating-point, 79 looping statements, 246
long, 79 loops, 247-252, 753
unsigned, 79 conditional, 749
floating-point, 79, 127 constructs, 276
integer, 83-84 conversion characters for
numeric printing, 297
defining, 127 determinate, 750
overriding default, 79 do-while, 252-255
octal, 83 endless, 323
printing with cout operator, 83 exiting, 256-260, 303
relational operators, 186 expressions
string count, 274, 278
assigning, 85 start, 274, 278
defining, 127 test, 274-275, 283
endings, 87-89 for, 273-286
printing, 85 body, indenting, 279
suffixes, 79 multidimensional tables,
local pointers, 542 530-537
local variables, 354-369, 753 nested, 286-291
automatic, 369, 747 if (compared to while loop),
changing, 354 255
defining, 355 indeterminate, 752
multiple functions, 363 infinite, 246, 752
names, overlapping, 360 nested, 755
passing, 363-364 braces, 287
receiving functions, 368 break statement, 299
value, losing, 355 counter variables, 288
log(x) function, 465 multidimensional tables,
log10(x) function, 465 530
logarithmic functions, 465 sorting arrays, 504
exp(x), 465 timing loops, 296
log(x), 465 statements, 277
log10(x), 465 timing, 295-298, 759
logic, 211-215, 222 iterations, 296
logical operators, 207-215 nested loops, 296
! (NOT), 208 while, 245, 255
&& (AND), 208 low-order bit, 686
|| (OR), 208 lowercase letters, 55, 122
bitwise, 235-244
777
Index ♦
778
C++ By
EXAMPLE
menu-driven programs, 754 N
menus, 754
messages, error, see error name-mangling, 422
messages naming
microchips, 18, 754 arrays
microcomputers, 17, 754 as pointers, 558-559
microprocessors, 754 changing, 560
minimum routine, 224 disks drives, 23
mirror-image input functions, files, 751
637 functions, 335-337
models, see prototypes overloading, 415
modems, 28-29, 754 rules, 335
external, 751 pointers, 542, 543
internal, 753 structures, 585
modes variables, 70-71, 360
binary, 631 invalid names, 71
file access, 630 local, overlapping, 360
text, 630 spaces, 71
modifers, setprecision, 408 negative numbers, 166
modular programming, 332, 754 binary, 692-694
modulated signals, 29 nested
modules of code, 331 function calls, 402
modulus (%) math operator, 164, structures, 600-603
167-168, 755 nested loops, 755
monitors, 24 braces, 287
graphics, 24 break statement, 299
monochrome, 24 counter variables, 288
see also displays; screens error messages, displaying,
most-significant bit, 686 296
mouse, 28, 755 for, 286-291
moving cursor with arrow keys, multidimensional tables, 530
27 sorting arrays, 504
MS-DOS, 30-32, 435-436, 755 timing loops, 296
multidimensional arrays, newline (\n) character, 135-136,
520-522, 755 433, 635
for loops, 530-537 next_fun( ) function, 338
initializing, 526-530 nonarrays, passing by address,
reserving, 522-524 391-396
storing, row order, 526 nonbuffered functions, 444
subscripts, 520-522 nonconditional expressions, 190
see also tables; matrices nonzero values, 451
multiple-choice statement, 312 NOT (!) logical operator, 208, 452
multiplication (*) math operator, not equal to (!=) relational
64, 164 operator, 186
779
Index ♦
notation O
array, 608-610
mixing, 609 object code, 755
scientific, 758 object-oriented programming, see
see also pointer notation OOP
null objects, 663, 755
character, 88 octal literals, 83
expression, 285 ofstream function, 436-437
strings, 755 on-screen printing, 125
zero, 101, 755 OOP (object-oriented program-
numbers ming), 14, 661, 665, 755
2's complement, 692 open( ) function, 629, 648
absolute value, 461 opening files, 629-634, 647-649
binary, 17, 165, 748 operations
see also binary numbers binary, 165
comparing, 199 direction, 175-176
converting from strings, operators, 16-17, 408, 755
460-461 ! (NOT), 452
floating-point, 63, 76, 140 . (dot), 608, 616
hexadecimal, see hexadecimal assignment (=), 174-178
numbers arrays, initializing, 480
integers, 63 binary, 165
justification, 140 bitwise, 234-241, 748
negative, 166, 692-694 logical, 235-244
printing, 139 cin, 144-148
random-number processing, comma (,), 232-234, 758
465-469 compile-time, 231
real, 76, 758 compound, 177
rounding, 461-462 conditional, 222-225
signed, 693 control, 139-144
square, 196 cout, 83, 93, 134-148
tables, printing, 138 decrement (--), 225, 233
unsigned, 693 dot (.), 592
numeric increment (++), 225, 233
arguments, testing functions, logical, 207-215
451 ! (NOT), 208
arrays, sorting, 508 && (AND), 208
constants, printing, 151 || (OR), 208
functions, 461-467, 755 truth tables, 208
keypad, 27 math, 754
literals * (multiplication), 64
defining, 127 + (addition), 64
overriding default, 79 - (subtraction), 64
variables, printing, 151 / (division), 64
780
C++ By
EXAMPLE
order of precedence, 216, 752 overloading, 756
overloaded, 542 constructor functions, 673
pointers functions, 415, 420-425
& (address of), 542 name-mangling, 422
* (dereferencing), 542 operators, 542
postfix, 225-227 overriding
precedence, 16, 756 keyboard default device, 436
prefix, 225-227 passing by copy, 547
primary, order of overwriting variables, 354, 363
precendence, 169
relational, 185-189, 209, 758 P
see also relational operators
padding memory, 476
sizeof, 230-232
parallel arrays, 756
ternary, 222
parallel port, 756
unary, 165-166, 760
parameters, 756
OR (||) logical operator, 208
passing, 374-375
order of case statements, 319
pointers, 546-551
order of bits, 686
receiving, 364
order of precedence, 752, 756-757
types, declaring, 366
logical operators, 216
see also variables
math operators, 168-174
parentheses ( ), 46
parentheses, 170-174
conditional_expression, 223
primary operators, 169
empty, 365
table, 729-732
functions, 336
origin values, 650
order of precedence, 170-174,
origins of C++, 15-16
216
output
type casting, 180
controlling, operators, 139-144
passing
devices, 134, 756
arguments, see passing vari-
standard, 759
ables
formatting
arrays, 388
carriage returns, 439
by address, 386
printing, 436-437
functions, 387
labeling, 86, 136
to functions, 484
redirecting, 134
by copy, overriding, 547
rerouting to printer, 436
local variables, 364
screen, 24
nonarrays by address, 391-396
stdout, 435
one-way, 398
stream, 434
parameters, 374-375
output redirection symbol (>),
values to character functions,
435
451
output statements, 17
overlapping names of local
variables, 360
781
Index ♦
782
C++ By
EXAMPLE
line, 753 programming languages, see
rerouting, 436 languages
writing to, 637-638 programs, 30, 36-38, 757
printf( ) function, 65, 126, comments, 749
149-150, 191 data-driven, 185
prototyping, 407 designing, 38-39
stdio.h header file, 150 formats, 53-54
strings, constants, 150 mailing list, 737-746
printing maintainability, 174
arrays menu-driven, 754
brackets ([ ]), 102 modular programming, 332
cout operator, 102 multiple-function formats, 338
blank lines, 136 readability, 54-55
columns, 534 routines, 332
setw manipulator, 139-140 sample, 44-46
constants, numeric, 151 skeleton, 333
conversion characters, 297 string length, 250
floating-point values, zeros, structured programming, 332
153 typing, 37
literals prototypes, 338, 757
cout operator, 83 built-in functions, 397,
string, 85 405-411, 734-735
numbers, 139-140 character functions, 450
on-screen, 125 ctype.h header file, 734
output, formatted, 436-437 character functions, 450
rows, 534 fill_structs( ) function, 597
strings, 102 header files, 408
cout operator, 134-144 lists, multiple default argu-
from character arrays, 135 ments, 417
in arrays, 563 main( ) function, 409
in character arrays, 510 math.h header file, 461, 735
printf( ) function, 150 printf( ) function, 407
tables, numbers, 138 scanf( ) function, 407
titles, 535 self-prototyping functions, 406
values, ASCII, 154 string.h header file, 735
variables stdio.h header file, 408, 734
floating-point, 152 stdlib.h header file, 460, 735
integer, 152 ato( ) function, 460
numeric, 151 string.h header file (string
private class members, 757 functions), 456
program editors, see editors public class members, 662, 674,
program listings, 38 757
programming, object-oriented, put( ) function, 438-444
see OOP putch( ) function, 444-446
puts( ) function, 457, 635
783
Index ♦
784
C++ By
EXAMPLE
resolution (screens), 24 sections, see blocks
return statements, 337, 345 sectors, 758
return values, 374, 402 seekg( ) function, 649-656
calling functions, 398 self-prototyping function, 406
function calls, 401 semicolon (;), 56, 114, 120, 190,
functions, 398-405 339
global variables, 398 separating functions, 345
type, 400 sequence point, see comma
returning functions, 337-349 operator
ROM (read-only memory), 758 sequential files, 625-629, 758
rounding serial ports, 758
fractions, 140 setprecision modifier, 408
numbers, 461-462 setw manipulator, 408
routines, 332 conversion characters, 140
minimum, 224 printing columns, 139-140
see also functions string width, 140
row order, multidimensional setw( ) function, 140
arrays, 526 shell sort, see sorting arrays
rows, printing, 534 Shift keys, 25
running programs, see executing sign bit, 693
programs signals
analog, 29
S demodulated, 29, 750
modulated, 29
sample programs, 44-46
signed
saving sort functions, 508
numbers, 693
scanf( ) function, 126, 149,
prefix, variables, declaring,
154-157
166
& (ampersand), 155
variables, numeric, 78
passing variables, 546
sin(x) function, 464
pointer variables, 155
size
prototyping, 407
arrays, 476-477, 480
variable names
variables, 76-77
scientific notation, 758
sizeof operator, 230-232
scope, variable, 760
sizeof( ) function, 476-477
screens
skeleton programs, 333
cursor, 24
slashes (//), 46
output, 24
software, 19, 29-34, 758
resolution, 24
sort functions, saving, 508
see also displays; monitor
sort_ascend file, 508
scrolling text, 24
sort_descend file, 508
searching arrays, 494-495
for statement, 496
for values, 496-501
if statement, 496
785
Index ♦
786
C++ By
EXAMPLE
strings, 100, 104, 563 concatenating, 456
user input, strings, 565 constants, 759
variables, 385-386 control_string, 149, 155
strcat( ) function, 456 converting to numbers,
strcmp( ) function, 456 460-461
strcpy( ) function, 107, 408 empty, 755
stream I/O, 432-436 format, controlling, 149
streams, 434, 759 I/O, 457
string constants, 566 inputting, 442
string delimiter, 88, 759 length, 89, 251
string functions, 455-461 literals, 107, 759
fgets(s, len, dev), 457 mathematical calculations, 460
fputs(s, dev), 457 null, 755
gets(s), 457 printing, 102
I/O, 456-459 cout operator, 134-144
prototypes, string.h header from character arrays, 135
file, 456 in character arrays, 510
puts(s), 457 printf( ) function, 150
testing, 456 reserving elements, 103
strcat( ), 456 shortening, 107
strcmp( ), 456 storing, 100, 104, 563
strlen( ), 456 terminating character, 101
string length programs, 250 user input, storing, 565
string literals values
assigning, 85 assigning, 107
defining, 127 assigning to character
endings, 87-89 arrays, 105
printing, 85 width, 140
string variables, 100 strlen( ) function, 251, 456
string-terminating characters, struct statement, 587-591
457-458, 755 structured programming, 332
string.h header file, 107, 118 structures, 584-587, 759
function prototypes, 456, 735 arrays, declaring, 606-615
strings, 759 arrays of, 747
arrays declaring, 591
declaring, 478 defining, 587-591
printing, 563 arrays of, 589
storing, 574 globally, 595
arrays of, 574-578 initializing, 591-592
character variables, 100 members
character arrays calculations, 597
comparing, 103-110 initializing, 591-600
multiple, 512 names, 585
787
Index ♦
788
C++ By
EXAMPLE
transistors (electricity), 21 out-of-range subscripts, 479
trigonometric functions to pointers, 545-546
cos(x), 464 to variables, 145
sin(x), 464 data types, truncating, 179
tan(x), 464 delay, 296
truncation, 179, 760 floating-point, 138
truth tables, 208, 235-236 initial, static variables, 370
truths, internal, 210 keyboard, 392
two-dimensional arrays, 525 members, assigning with dot
see also multidimensional operator, 602
arrays nonzero, 451
two's complement, 692 origin, 650
type casting (data types), 179-182 local variables, 355
types passing variables by, 379-384,
arrays, specifying, 390 756
parameters, declaring, 366 passing to character functions,
return values, 400 451
variables, 584 returning from functions, 374
see also structures strings, assigning, 105-107
see also data types testing, 749
typing programs, 37 totaling, 265
variables
U assigning, 80-82
assignment operator (=), 63
unary operators, 165-166, 760
cin function, 145
unconditional break statements,
entering directly, 154
299
updating, 176
underscore ( _ ), 336
see also return values
UNIX, cfront compiler, 43
variable scope, 353-362, 760
unreachable code, 305
variable-length records, 760
unsigned literals, designating, 79
variables, 62-63, 70-82, 760
unsigned numbers, 693
addresses, 385-386
unsigned variables, 84
arrays, 747, 751
uppercase letters, 55, 240
automatic, 369-374, 747
V changing, called functions, 387
character, 75
validating data, 195 character strings, 100
values comparing to literals, 192
arrays, searching for, 495, constant, 94-95
496-501 counter, 262, 265, 288, 360
ASCII, printing, 154 data types, 179
assigning declaring, 62, 73, 166
arrays, 103 decrementing, 225-230
elements, 479 defined literals, 122
789
Index ♦
790
Computer Books from Que Mean PC Performance!
Look Your Best with WordPerfect 5.1 .............................................. $24.95
Spreadsheets Look Your Best with WordPerfect forWindows ............................... $24.95 Macintosh/Apple II
Microsoft Word Quick Reference ...................................................... $ 9.95
1-2-3 Beyond the Basics .................................................................... $24.95 Using Ami Pro .................................................................................... $24.95 Easy Macintosh .................................................................................. $19.95
1-2-3 for DOS Release 2.3 Quick Reference ..................................... $ 9.95 Using LetterPerfect ............................................................................ $22.95 HyperCard 2 QuickStart ..................................................................... $19.95
1-2-3 for DOS Release 2.3 QuickStart ............................................... $19.95 Using Microsoft Word 5.5: IBM Version, 2nd Edition ..................... $24.95 PageMaker 4 for the Mac Quick Reference ....................................... $ 9.95
1-2-3 for DOS Release 3.1+ Quick Reference ................................... $ 9.95 Using MultiMate ................................................................................ $24.95 The Big Mac Book, 2nd Edition ........................................................ $29.95
1-2-3 for DOS Release 3.1+ QuickStart ............................................ $19.95 Using PC-Write .................................................................................. $22.95 The Little Mac Book .......................................................................... $12.95
1-2-3 for Windows Quick Reference ................................................. $ 9.95 Using Professional Write ................................................................... $22.95 QuarkXPress 3.1 Quick Reference .................................................... $ 9.95
1-2-3 for Windows QuickStart ........................................................... $19.95 Using Professional Write Plus for Windows ..................................... $24.95 Que's Big Mac Book, 3rd Edition ...................................................... $29.95
1-2-3 Personal Money Manager ......................................................... $29.95 Using Word for Windows 2, Special Edition ..................................... $27.95 Que's Little Mac Book, 2nd Edition ................................................... $12.95
1-2-3 Power Macros ........................................................................... $39.95 Using WordPerfect 5 .......................................................................... $27.95 Que's Mac Classic Book ..................................................................... $24.95
1-2-3 Release 2.2 QueCards ............................................................... $19.95 Using WordPerfect 5.1, Special Edition ............................................ $27.95 Que’s Macintosh Multimedia Handbook ........................................... $24.95
Easy 1-2-3 .......................................................................................... $19.95 Using WordPerfect for Windows, Special Edition ............................ $29.95 System 7 Quick Reference ................................................................. $ 9.95
Easy Excel .......................................................................................... $19.95 Using WordStar 7 ............................................................................... $19.95 Using 1-2-3 for the Mac ..................................................................... $24.95
Easy Quattro Pro ................................................................................ $19.95 Using WordStar, 3rd Edition .............................................................. $27.95 Using AppleWorks, 3rd Edition ......................................................... $24.95
Excel 3 for Windows QuickStart ....................................................... $19.95 WordPerfect 5.1 Power Macros ......................................................... $39.95 Using Excel 3 for the Macintosh ........................................................ $24.95
Excel for Windows Quick Reference ................................................. $ 9.95 WordPerfect 5.1 QueCards ................................................................ $19.95 Using FileMaker Pro .......................................................................... $24.95
Look Your Best with 1-2-3 ................................................................ $24.95 WordPerfect 5.1 Quick Reference ..................................................... $ 9.95 Using MacDraw Pro ........................................................................... $24.95
Quatrro Pro 3 QuickStart ................................................................... $19.95 WordPerfect 5.1 QuickStart ............................................................... $19.95 Using MacroMind Director ................................................................ $29.95
Quattro Pro Quick Reference ............................................................. $ 9.95 WordPerfect 5.1 Tips, Tricks, and Traps ........................................... $24.95 Using MacWrite Pro .......................................................................... $24.95
Using 1-2-3 for DOS Release 2.3, Special Edition ............................ $29.95 WordPerfect for Windows Power Pack ............................................. $39.95 Using Microsoft Word 5 for the Mac ................................................. $27.95
Using 1-2-3 for Windows ................................................................... $29.95 WordPerfect for Windows Quick Reference ..................................... $ 9.95 Using Microsoft Works: Macintosh Version,
Using 1-2-3 for DOS Release 3.1+, Special Edition .......................... $29.95 WordPerfect for Windows Quick Start .............................................. $19.95 2nd Edition ....................................................................................... $24.95
Using Excel 4 for Windows, Special Edition ..................................... $29.95 WordPerfect Power Pack ................................................................... $39.95 Using Microsoft Works for the Mac .................................................. $24.95
Using Quattro Pro 4, Special Edition ................................................. $27.95 WordPerfect Quick Reference ........................................................... $ 9.95 Using PageMaker 4 for the Macintosh ............................................... $24.95
Using Quattro Pro for Windows ........................................................ $24.95 Using Quicken 3 for the Mac ............................................................. $19.95
Using SuperCalc5, 2nd Edition .......................................................... $29.95 Using the Macintosh with System 7 ................................................... $24.95
Hardware/Systems Using Word for the Mac, Special Edition .......................................... $24.95
Using WordPerfect 2 for the Mac ...................................................... $24.95
Databases Batch File and Macros Quick Reference ........................................... $ 9.95 Word for the Mac Quick Reference ................................................... $ 9.95
Computerizing Your Small Business ................................................. $19.95
dBASE III Plus Handbook, 2nd Edition ............................................ $24.95 DR DOS 6 Quick Reference .............................................................. $ 9.95
dBASE IV 1.1 Qiuck Reference ........................................................ $ 9.95 Easy DOS ........................................................................................... $19.95 Programming/Technical
dBASE IV 1.1 QuickStart .................................................................. $19.95 Easy Windows .................................................................................... $19.95
Introduction to Databases ................................................................... $19.95 Fastback Quick Reference .................................................................. $ 8.95 Borland C++ 3 By Example ............................................................... $21.95
Paradox 3.5 Quick Reference ............................................................. $ 9.95 Hard Disk Quick Reference ............................................................... $ 8.95 Borland C++ Programmer's Reference .............................................. $29.95
Paradox Quick Reference, 2nd Edition .............................................. $ 9.95 Hard Disk Quick Reference, 1992 Edition ........................................ $ 9.95 C By Example .................................................................................... $21.95
Using AlphaFOUR ............................................................................. $24.95 Introduction to Hard Disk Management ............................................ $24.95 C Programmer’s Toolkit, 2nd Edition ................................................ $39.95
Using Clipper, 3rd Edition ................................................................. $29.95 Introduction to Networking ................................................................ $24.95 Clipper Programmer's Reference ....................................................... $29.95
Using DataEase .................................................................................. $24.95 Introduction to PC Communications .................................................. $24.95 DOS Programmer’s Reference, 3rd Edition ....................................... $29.95
Using dBASE IV ................................................................................ $29.95 Introduction to Personal Computers, 2nd Edition .............................. $19.95 FoxPro Programmer's Reference ........................................................ $29.95
Using FoxPro 2 .................................................................................. $29.95 Introduction to UNIX ......................................................................... $24.95 Network Programming in C ............................................................... $49.95
Using ORACLE ................................................................................. $29.95 Laplink Quick Reference ................................................................... $ 9.95 Paradox Programmer's Reference ...................................................... $29.95
Using Paradox 3.5, Special Edition .................................................... $29.95 MS-DOS 5 Que Cards ........................................................................ $19.95 Programming in Windows 3.1 ........................................................... $39.95
Using Paradox for Windows .............................................................. $26.95 MS-DOS 5 Quick Reference .............................................................. $ 9.95 QBasic By Example ........................................................................... $21.95
Using Paradox, Special Edition .......................................................... $29.95 MS-DOS 5 QuickStart ....................................................................... $19.95 Turbo Pascal 6 By Example ............................................................... $21.95
Using PC-File ..................................................................................... $24.95 MS-DOS Quick Reference ................................................................. $ 8.95 Turbo Pascal 6 Programmer's Reference ........................................... $29.95
Using R:BASE ................................................................................... $29.95 MS-DOS QuickStart, 2nd Edition ...................................................... $19.95 UNIX Programmer’s Reference ......................................................... $29.95
Networking Personal Computers, 3rd Edition ................................... $24.95 UNIX Shell Commands Quick Reference ......................................... $ 8.95
Que's Computer Buyer's Guide, 1992 Edition ................................... $14.95 Using Assembly Language, 2nd Edition ............................................ $29.95
Que's Guide to CompuServe .............................................................. $12.95 Using Assembly Language, 3rd Edition ............................................ $29.95
Business Applications Que's Guide to DataRecovery ............................................................ $29.95 Using BASIC ..................................................................................... $24.95
Que's Guide to XTree ......................................................................... $12.95 Using Borland C++ ............................................................................ $29.95
CheckFree Quick Reference .............................................................. $ 9.95
Que's MS-DOS User's Guide, Special Edition ................................... $29.95 Using Borland C++ 3, 2nd Edition .................................................... $29.95
Easy Quicken ..................................................................................... $19.95
Que's PS/1 Book ................................................................................. $22.95 Using C ............................................................................................... $29.95
Microsoft Works Quick Reference .................................................... $ 9.95
TurboCharging MS-DOS ................................................................... $24.95 Using Microsoft C .............................................................................. $29.95
Norton Utilities 6 Quick Reference .................................................... $ 9.95
Upgrading and Repairing PCs ............................................................ $29.95 Using QBasic ..................................................................................... $24.95
PC Tools 7 Quick Reference .............................................................. $ 9.95
Upgrading and Repairing PCs, 2nd Edition ....................................... $29.95 Using QuickBASIC 4 ......................................................................... $24.95
Q&A 4 Database Techniques ............................................................. $29.95
Upgrading to MS-DOS 5 ................................................................... $14.95 Using QuickC for Windows ............................................................... $29.95
Q&A 4 Quick Reference .................................................................... $ 9.95
Using GeoWorks Pro ......................................................................... $24.95 Using Turbo Pascal 6, 2nd Edition .................................................... $29.95
Q&A 4 QuickStart .............................................................................. $19.95
Using Microsoft Windows 3, 2nd Edition ......................................... $24.95 Using Turbo Pascal for Windows ...................................................... $29.95
Q&A 4 Que Cards .............................................................................. $19.95
Using MS-DOS 5 ............................................................................... $24.95 Using Visual Basic ............................................................................. $29.95
Que’s Computer User’s Dictionary, 2nd Edition ............................... $10.95
Using Novell NetWare, 2nd Edition .................................................. $29.95 Visual Basic by Example ................................................................... $21.95
Que’s Using Enable ............................................................................ $29.95
Using OS/2 2.0 ................................................................................... $24.95 Visual Basic Programmer's Reference ............................................... $29.95
Quicken 5 Quick Reference ............................................................... $ 9.95
Using PC DOS, 3rd Edition ............................................................... $27.95 Windows 3.1 Programmer's Reference .............................................. $39.95
SmartWare Tips, Tricks, and Traps, 2nd Edition ............................... $26.95
Using Prodigy ..................................................................................... $19.95
Using DacEasy, 2nd Edition .............................................................. $24.95
Using UNIX ....................................................................................... $29.95
Using Microsoft Money ..................................................................... $19.95
Using Windows 3.1 ............................................................................ $26.95
Using Microsoft Works: IBM Version .............................................. $22.95
Using Your Hard Disk ....................................................................... $29.95
Using Microsoft Works for Windows, Special Edition ..................... $24.95
Using MoneyCounts ........................................................................... $19.95
Windows 3 Quick Reference ............................................................. $ 8.95 For More Information,
Windows 3 QuickStart ....................................................................... $19.95
Using Pacioli 2000 ............................................................................. $19.95
Using Norton Utilities 6 ..................................................................... $24.95
Windows 3.1 Quick Reference .......................................................... $ 9.95 Call Toll Free!
Windows 3.1 QuickStart .................................................................... $19.95
Using PC Tools Deluxe 7 ................................................................... $24.95
Using PFS: First Choice ..................................................................... $22.95
1-800-428-5331
Using PFS: WindowWorks ................................................................ $24.95
Using Q&A 4 ..................................................................................... $27.95 All prices and titles subject to change without notice.
Using Quicken 5 ................................................................................. $19.95 Desktop Publishing/Graphics Non-U.S. prices may be higher. Printed in the U.S.A.
Using Quicken for Windows .............................................................. $19.95
Using Smart ........................................................................................ $29.95 CorelDRAW! Quick Reference ......................................................... $ 8.95
Using TimeLine ................................................................................. $24.95 Harvard Graphics 3 Quick Reference ................................................ $ 9.95
Using TurboTax: 1992 Edition .......................................................... $19.95 Harvard Graphics Quick Reference ................................................... $ 9.95
Que’s Using Ventura Publisher .......................................................... $29.95
Using DrawPerfect ............................................................................. $24.95
CAD Using Freelance Plus .......................................................................... $24.95
Using Harvard Graphics 3 .................................................................. $29.95
AutoCAD Quick Reference, 2nd Edition ........................................... $ 8.95 Using Harvard Graphics for Windows ............................................... $24.95
Using AutoCAD, 3rd Edition ............................................................. $29.95 Using Harvard Graphics, 2nd Edition ................................................ $24.95
Using Microsoft Publisher ................................................................. $22.95
Using PageMaker 4 for Windows ...................................................... $29.95
Using PFS: First Publisher, 2nd Edition ............................................ $24.95
Using PowerPoint ............................................................................... $24.95
Word Processing Using Publish It! ................................................................................ $24.95
24EXAMPLE
Array Processing
C++ provides many ways to access arrays. If you have programmed
in other computer languages, you will find that some of C++’s array
indexing techniques are unique. Arrays in the C++ language are
closely linked with pointers. Chapter 26, “Pointers,” describes the
many ways pointers and arrays interact. Because pointers are so
powerful, and because learning about arrays provides a good foun-
dation for learning about pointers, this chapter attempts to describe
in detail how to reference arrays.
This chapter discusses the different types of array processing.
You learn how to search an array for one or more values, find the
highest and lowest values in an array, and sort an array into
numerical or alphabetical order.
This chapter introduces the following concepts:
♦ Searching arrays
♦ Finding the highest and lowest values in arrays
♦ Sorting arrays
♦ Advanced subscripting with arrays
Many programmers see arrays as a turning point. Gaining an
understanding of array processing makes your programs more
accurate and allows for more powerful programming.
493
Chapter 24 ♦ Array Processing
Searching Arrays
Arrays are one of the primary means by which data is stored in
C++ programs. Many types of programs lend themselves to process-
ing lists (arrays) of data, such as an employee payroll program, a
scientific research of several chemicals, or customer account pro-
cessing. As mentioned in the previous chapter, array data usually is
read from a disk file. Later chapters describe disk file processing. For
now, you should understand how to manipulate arrays so you see
the data exactly the way you want to see it.
Array elements do Chapter 23, “Introducing Arrays,” showed how to print arrays
not always appear in in the same order that you entered the data. This is sometimes done,
the order in which but it is not always the most appropriate method of looking at data.
they are needed.
For instance, suppose a high school used C++ programs for its
grade reports. Suppose also that the school wanted to see a list of the
top 10 grade-point averages. You could not print the first 10 grade-
point averages in the list of student averages because the top 10
GPAs might not (and probably will not) appear as the first 10 array
elements. Because the GPAs would not be in any sequence, the
program would have to sort the array into numeric order, from high
GPAs to low, or else search the array for the 10 highest GPAs.
You need a method for putting arrays in a specific order. This
is called sorting an array. When you sort an array, you put that array
in a specific order, such as in alphabetical or numerical order. A
dictionary is in sorted order, and so is a phone book.
When you reverse the order of a sort, it is called a descending
sort. For instance, if you wanted to look at a list of all employees in
descending salary order, the highest-paid employees would be
printed first.
Figure 24.1 shows a list of eight numbers in an array called
unsorted. The middle list of numbers is an ascending sorted version
of unsorted. The third list of numbers is a descending version of
unsorted.
494
C++ By
EXAMPLE
495
Chapter 24 ♦ Array Processing
Examples
1. To find the highest number in an array, compare each
element with the first one. If you find a higher value, it
becomes the basis for the rest of the array. Continue until
you reach the end of the array and you will have the highest
value, as the following program shows.
Identify the program and include the I/O header file. You want to
find the highest value in an array, so define the array size as a
constant, then initialize the array.
Loop through the array, comparing each element to the highest
value. If an element is higher than the highest value saved, store
the element as the new high value. Print the highest value found in
the array.
// Filename: C24HIGH.CPP
// Finds the highest value in the array.
#include <iostream.h>
const int SIZE = 15;
void main()
496
C++ By
EXAMPLE
{
// Puts some numbers in the array.
int ara[SIZE]={5,2,7,8,36,4,2,86,11,43,22,12,45,6,85};
int high_val, ctr;
497
Chapter 24 ♦ Array Processing
// Filename: C24HILO.CPP
// Finds the highest and the lowest value in the array.
#include <iostream.h>
#include <stdlib.h>
const int SIZE = 15;
void main()
{
int ara[SIZE];
int high_val, low_val, ctr;
498
C++ By
EXAMPLE
// Filename: C24SERCH.CPP
// Searches a part number array for the input value. If
499
Chapter 24 ♦ Array Processing
void main()
{
long int search_part; // Holds user request.
long int parts[MAX];
int ctr;
int num_parts=5; // Beginning inventory count.
500
C++ By
EXAMPLE
break;
}
}
}
} while (search_part != -9999); // Loops until user
// signals end.
return;
}
Sorting Arrays
There are many times when you must sort one or more arrays.
Suppose you were to take a list of numbers, write each number on
a separate piece of paper, and throw all the pieces of paper into the
air. The steps you take—shuffling and changing the order of the
501
Chapter 24 ♦ Array Processing
Why doesn’t this work? In the first line, the value of score1 is
replaced with score2’s value. When the first line finishes, both score1
and score2 contain the same value. Therefore, the second line cannot
work as desired.
To swap two variables, you have to use a third variable to hold
the intermediate result. (This is the only function of this third
variable.) For instance, to swap score1 and score2, use a third variable
(called hold_score in this code), as in
502
C++ By
EXAMPLE
finally sorted (no more passes are needed). Other types of sorts
improve on the bubble sort. The bubble sort procedure is easy to
program, but it is slower compared to many of the other methods.
503
Chapter 24 ♦ Array Processing
Examples
1. The following program assigns 10 random numbers between
0 and 99 to an array, then sorts the array. A nested for loop is
perfect for sorting numbers in the array (as shown in the
sort_array() function). Nested for loops provide a nice mech-
anism for working on pairs of values, swapping them if
needed. As the outside loop counts down the list, referenc-
ing each element, the inside loop compares each of the
remaining values to those array elements.
// Filename: C24SORT1.CPP
// Sorts and prints a list of numbers.
const int MAX = 10;
#include <iostream.h>
#include <stdlib.h>
void fill_array(int ara[MAX]);
void print_array(int ara[MAX]);
void sort_array(int ara[MAX]);
void main()
{
int ara[MAX];
504
C++ By
EXAMPLE
// Puts random numbers in the array.
int ctr;
for (ctr=0; ctr<MAX; ctr++)
{ ara[ctr] = (rand() % 100); } // Forces number to
// 0-99 range.
return;
}
The output from this program appears next. If any two ran-
domly generated numbers were the same, the bubble sort
would work properly, placing them next to each other in the
list.
505
Chapter 24 ♦ Array Processing
506
C++ By
EXAMPLE
void print_array(int ara[MAX]);
void sort_array(int ara[MAX]);
void main()
{
int ara[MAX];
507
Chapter 24 ♦ Array Processing
TIP: You can save the previous programs’ sort functions in two
separate files named sort_ascend and sort_descend. When you
must sort two different arrays, #include these files inside your
own programs. Even better, compile each of these routines
separately and link the one you need to your program. (You
must check your compiler’s manual to learn how to do this.)
You can sort character arrays just as easily as you sort numeric
arrays. C++ uses the ASCII character set for its sorting comparisons.
If you look at the ASCII table in Appendix C, you will see that
numbers sort before letters and that uppercase letters sort before
lowercase letters.
Advanced Referencing
of Arrays
The array notation you have seen so far is common in computer
programming languages. Most languages use subscripts inside
brackets (or parentheses) to refer to individual array elements. For
instance, you know the following array references describe the first
508
C++ By
EXAMPLE
and fifth element of the array called sales (remember that the
starting subscript is always 0):
sales[0]
sales[4]
509
Chapter 24 ♦ Array Processing
Figure 24.3. The array name amounts holds the address of amounts[0].
Figure 24.4 shows how this array might look in memory. The
array name, names, contains the address of the first element, names[0]
(the letter T).
510
C++ By
EXAMPLE
Figure 24.4. Storing more than one string in a single character array.
511
Chapter 24 ♦ Array Processing
You have yet to see a character array that holds more than one
string, but C++ allows it. The problem with such an array is how
you reference, and especially how you print, the second and third
strings. If you were to print this array using cout:
cout << names;
cout prints strings Because cout requires a starting address, you can print the three
in arrays starting at strings with the following couts:
the array’s address
and continuing until cout << names; // Prints Ted
it reaches the null
cout << (names+4); // Prints Eva
zero.
cout << (names+8); // Prints Sam
The first cout prints ed. The characters ed begin at (names+1) and
the cout stops printing when it reaches the null zero. The second cout
prints a. Adding six to the address at names produces the address
where the a is located. The “string” is only one character long
because the null zero appears in the array immediately after the a.
To sum up character arrays, the following refer to individual
array elements (single characters):
names[2] and (names+1)[1]
The following refer to addresses only, and as such, you can print the
full strings with cout:
names and (names+4)
512
C++ By
EXAMPLE
Examples
1. The following program stores the numbers from 100 to 600
in an array, then prints elements using the new method of
array subscripting.
// Filename: C24REF1.CPP
// Print elements of an integer array in different ways.
#include <iostream.h>
void main()
{
int num[6] = {100, 200, 300, 400, 500, 600};
num[0] is 100
(num+0)[0] is 100
(num-2)[2] is 100
513
Chapter 24 ♦ Array Processing
num[1] is 200
(num+1)[0] is 200
num[5] is 600
(num+5)[0] is 600
(num+2)[3] is 600
(3+num)[1] is 500
3+num[1] is 203
// Filename: C24REF2.CPP
// Prints elements and strings from an array.
#include <iostream.h>
void main()
{
char names[]={‘T’,’e’,’d’,’\0',’E’,’v’,’a’,’\0',
’S’, ‘a’,’m’,’\0'};
return;
}
514
C++ By
EXAMPLE
names Ted
names+0 Ted
names+1 ed
names+2 d
names+3
names+5 va
names+8 Sam
(names+0)[0] T
(names+0)[1] e
(names+0)[2] d
(names+0)[3]
(names+0)[4] E
(names+0)[5] v
(names+2)[0] d
(names+2)[1]
(names+1)[4] v
Review Questions
The answers to the review questions are in Appendix B.
1. True or false: You must access an array in the same order
you initialized it.
2. Where did the bubble sort get its name?
3. Are the following values sorted in ascending or descending
order?
33 55 78 78 90 102 435 859
976 4092
4. How does C++ use the name of an array?
515
Chapter 24 ♦ Array Processing
Review Exercises
1. Write a program to store six of your friends’ ages in a single
array. Assign the ages in random order. Print the ages, from
low to high, on-screen.
2. Modify the program in Exercise 1 to print the ages in de-
scending order.
3. Using the new approach of subscripting arrays, rewrite the
programs in Exercises 1 and 2. Always put a 0 in the sub-
script brackets, modifying the address instead (use
(ages+3)[0] rather than ages[3]).
516
C++ By
EXAMPLE
for 100 parts in the inventory. Present the user with an input
screen. When the user enters a part number, search the part
number array. When you locate the position of the part,
print the corresponding price and quantity. If the part does
not exist, enable the user to add it to the inventory, along
with the matching price and quantity.
Summary
You are beginning to see the true power of programming
languages. Arrays give you the ability to search and sort lists of
values. Sorting and searching are what computers do best; comput-
ers can quickly scan through hundreds and even thousands of
values, looking for a match. Scanning through files of paper by hand,
looking for just the right number, takes much more time. By step-
ping through arrays, your program can quickly scan, print, sort, and
calculate a list of values. You now have the tools to sort lists of
numbers, as well as search for values in a list.
You will use the concepts learned here for sorting and search-
ing lists of character string data as well, when you learn a little more
about the way C++ manipulates strings and pointers. To help build
a solid foundation for this and more advanced material, you now
know how to reference array elements without using conventional
subscripts.
Now that you have mastered this chapter, the next one will be
easy. Chapter 25, “Multidimensional Arrays,” shows you how you
can keep track of arrays in a different format called a matrix. Not all
lists of data lend themselves to matrices, but you should be prepared
for when you need them.
517
Chapter 24 ♦ Array Processing
518
C++ By
25 EXAMPLE
Multidimensional
Arrays
Some data fits in lists, such as the data discussed in the previous two
chapters, and other data is better suited for tables of information.
This chapter takes arrays one step further. The previous chapters
introduced single-dimensional arrays; arrays that have only one
subscript and represent lists of values.
This chapter introduces arrays of more than one dimension,
called multidimensional arrays. Multidimensional arrays, sometimes
called tables or matrices, have at least two dimensions (rows and
columns). Many times they have more than two.
This chapter introduces the following concepts:
♦ Multidimensional arrays
♦ Reserving storage for multidimensional arrays
♦ Putting data in multidimensional arrays
♦ Using nested for loops to process multidimensional arrays
If you understand single-dimensional arrays, you should have
no trouble understanding arrays that have more than one dimen-
sion.
519
Chapter 25 ♦ Multidimensional Arrays
Multidimensional Array
Basics
A multidimensional A multidimensional array is an array with more than one
array has more than subscript. Whereas a single-dimensional array is a list of values, a
one subscript.
multidimensional array simulates a table of values, or multiple
tables of values. The most commonly used table is a two-
dimensional table (an array with two subscripts).
Suppose a softball team wanted to keep track of its players’
batting records. The team played 10 games, and there are 15 players
on the team. Table 25.1 shows the team’s batting record.
520
C++ By
EXAMPLE
521
Chapter 25 ♦ Multidimensional Arrays
4 deep
6 rows
3 columns
Reserving Multidimensional
Arrays
When you reserve a multidimensional array, you must inform
C++ that the array has more than one dimension by putting more
than one subscript in brackets after the array name. You must put a
separate number, in brackets, for each dimension in the table. For
example, to reserve the team data from Table 25.1, you use the
following multidimensional array declaration.
522
C++ By
EXAMPLE
rows
523
Chapter 25 ♦ Multidimensional Arrays
The far-right When creating a two-dimensional table, always put the maxi-
dimension always mum number of rows first, and the maximum number of columns
represents columns,
the next represents
second. C++ always uses 0 as the starting subscript of each dimen-
rows, and so on. sion. The last element, the lower-right element of the teams table, is
teams[2][14][9].
Examples
1. Suppose you wanted to keep track of utility bills for the
year. You can store 12 months of four utilities in a two-
dimensional table of floating-point amounts, as the follow-
ing array declaration demonstrates:
float utilities[12][4]; // Reserves 48 elements.
524
C++ By
EXAMPLE
or
or
525
Chapter 25 ♦ Multidimensional Arrays
arrays, but you must designate the second. If scores were a three-
dimensional table, dimensioned as 10 by 5 by 6, you would receive
it with print_it() as
or
You should not have to worry too much about the way tables
are physically stored. Even though a two-dimensional table is
actually an array of arrays (and each of those arrays contains another
array if it is a three-dimensional table), you can use subscripts to
program multidimensional arrays as if they were stored in row-and-
column order.
C++ stores Multidimensional arrays are stored in row order. Suppose you
multidimensional want to keep track of a 3-by-4 table. The top of Figure 25.3 shows
arrays in row order.
how that table (and its subscripts) are visualized. Despite the
two-dimensional table organization, your memory is still sequen-
tial storage. C++ has to map multidimensional arrays to single-
dimensional memory, and it does so in row order.
Each row fills memory before the next row is stored. Figure 25.3
shows how a 3-by-4 table is mapped to memory.
The entire first row (table[0][0] through table[0][3]) is stored
first in memory before any of the second row. A table is actually an
array of arrays, and, as you learned in previous chapters, array
elements are always stored sequentially in memory. Therefore, the
first row (array) completely fills memory before the second row.
Figure 25.3 shows how two-dimensional arrays map to memory.
Defining Multidimensional
Arrays
C++ is not picky about the way you define a multidimensional
array when you initialize it at declaration time. As with single-
dimensional arrays, you initialize multidimensional arrays with
526
C++ By
EXAMPLE
Memory
First row
Second row
Third row
Fourth row
The following three array definitions fill the three arrays ara1,
ara2, and ara3, as shown in Figure 25.4:
527
Chapter 25 ♦ Multidimensional Arrays
ara1
ara2
ara3
528
C++ By
EXAMPLE
529
Chapter 25 ♦ Multidimensional Arrays
0 0
0 1
0 2
1 0
1 1
1 2
530
C++ By
EXAMPLE
ara name
An array of arrays
First row
Second
row
Third
row
Fourth
row
531
Chapter 25 ♦ Multidimensional Arrays
Nested loops work Notice there are as many for loops as there are subscripts in the
well with multi- array (two). The outside loop represents the first subscript (the
dimensional arrays.
rows), and the inside loop represents the second subscript (the
columns). The nested for loop steps through each element of the
table.
You can use cin, gets(), get, and other input functions to fill a
table, and you also can assign values to the elements when declaring
the table. More often, the data comes from data files on the disk.
Regardless of what method stores the values in multidimensional
arrays, nested for loops are excellent control statements to step
through the subscripts. The following examples demonstrate how
nested for loops work with multidimensional arrays.
Examples
1. The following statements reserve enough memory elements
for a television station’s ratings (A through D) for one week:
char ratings[7][48];
532
C++ By
EXAMPLE
// Filename: C25DISK1.CPP
// Assigns disk prices to a table.
#include <iostream.h>
#include <iomanip.h>
void main()
{
float disks[2][4]; // Table of disk prices.
int row, col; // Subscript variables.
return;
}
533
Chapter 25 ♦ Multidimensional Arrays
$2.39
$2.75
$3.29
$3.59
$1.75
$2.19
$2.69
$2.95
// Filename: C25DISK2.CPP
// Assigns disk prices to a table
// and prints them in a table format.
#include <iostream.h>
#include <iomanip.h>
void main()
{
534
C++ By
EXAMPLE
float disks[2][4]; // Table of disk prices.
int row, col;
return;
}
4. To add the titles, simply print a row of titles before the first
row of values, then print a new column title before each
column, as shown in the following program:
// Filename: C25DISK3.CPP
// Assigns disk prices to a table
// and prints them in a table format with titles.
#include <iostream.h>
#include <iomanip.h>
535
Chapter 25 ♦ Multidimensional Arrays
void main()
{
float disks[2][4]; // Table of disk prices.
int row, col;
return;
}
536
C++ By
EXAMPLE
Review Questions
The answers to the review questions are in Appendix B.
1. What statement reserves a two-dimensional table of integers
called scores with five rows and six columns?
2. What statement reserves a three-dimensional table of four
character arrays called initials with 10 rows and 20 columns?
3. In the following statement, which subscript (first or second)
represents rows and which represents columns?
int weights[5][10];
4 1 3 5 9
10 2 12 1 6
25 42 2 91 8
b. ara[0][1]
c. ara[2][3]
d. ara[2][4]
537
Chapter 25 ♦ Multidimensional Arrays
b. grades[2][4]
c. grades[0][1]
Review Exercises
1. Write a program that stores and prints the numbers from 1
to 21 in a 3-by-7 table. (Hint: Remember C++ begins sub-
scripts at 0.)
2. Write a program that reserves storage for three years’ worth
of sales data for five salespeople. Use assignment statements
to fill the table with data, then print it, one value per line.
3. Instead of using assignment statements, use the cin function
to fill the salespeople data from Exercise 2.
4. Write a program that tracks the grades for five classes, each
having 10 students. Input the data using the cin function.
Print the table in its native row and column format.
Summary
You now know how to create, initialize, and process multidi-
mensional arrays. Although not all data fits in the compact format
of tables, much does. Using nested for loops makes stepping through
a multidimensional array straightforward.
538
C++ By
EXAMPLE
539
Chapter 25 ♦ Multidimensional Arrays
540
C++ By
26EXAMPLE
Pointers
C++ reveals its true power through pointer variables. Pointer vari-
ables (or pointers, as they generally are called) are variables that
contain addresses of other variables. All variables you have seen so
far have held data values. You understand that variables hold
various data types: character, integer, floating-point, and so on.
Pointer variables contain the location of regular data variables; they
in effect point to the data because they hold the address of the data.
When first learning C++, students of the language tend to shy
away from pointers, thinking that pointers will be difficult. Pointers
do not have to be difficult. In fact, after you work with them for a
while, you will find they are easier to use than arrays (and much
more flexible).
This chapter introduces the following concepts:
♦ Pointers
♦ Pointers of different data types
♦ The “address of” (&) operator
♦ The dereferencing (*) operator
♦ Arrays of pointers
541
Chapter 26 ♦ Pointers
Introduction to Pointer
Variables
Pointers contain Pointers are variables. They follow all the normal naming rules
addresses of other of regular, nonpointer variables. As with regular variables, you
variables.
must declare pointer variables before using them. There is a type of
pointer for every data type in C++; there are integer pointers,
character pointers, floating-point pointers, and so on. You can
declare global pointers or local pointers, depending on where you
declare them.
About the only difference between pointer variables and regu-
lar variables is the data they hold. Pointers do not contain data in the
usual sense of the word. Pointers contain addresses of data. If you
need a quick review of addresses and memory, see Appendix A,
“Memory Addressing, Binary, and Hexadecimal Review.”
There are two pointer operators in C++:
& The “address of” operator
* The dereferencing operator
Don’t let these operators throw you; you might have seen them
before! The & is the bitwise AND operator (from Chapter 11, “Addi-
tional C++ Operators”) and the * means, of course, multiplication.
These are called overloaded operators. They perform more than one
function, depending on how you use them in your programs. C++
does not confuse * for multiplication when you use it as a
dereferencing operator with pointers.
542
C++ By
EXAMPLE
Any time you see the & used with pointers, think of the words
“address of.” The & operator always produces the memory address
of whatever it precedes. The * operator, when used with pointers,
either declares a pointer or dereferences the pointer’s value. The
next section explains each of these operators.
Declaring Pointers
Because you must declare all pointers before using them, the
best way to begin learning about pointers is to understand how to
declare and define them. Actually, declaring pointers is almost as
easy as declaring regular variables. After all, pointers are variables.
If you must declare a variable that holds your age, you could do
so with the following variable declaration:
int age=30; // Declare a variable to hold my age.
543
Chapter 26 ♦ Pointers
figure assumes C++ stored age at the address 350,606. Your C++
compiler, however, arbitrarily determines the address of age, so it
could be anything.
Figure 26.1. p_age contains the address of age; p_age points to the age
variable.
544
C++ By
EXAMPLE
Either method is okay, but you must remember the * is not part
of the name. When you later use p_age, you will not prefix the name
with the *, unless you are dereferencing it at the time (as later
examples show).
Consider the declaration for p_age if the asterisk were not there:
C++ would think you were declaring a regular integer variable. The
* is important, because it tells C++ to interpret p_age as a pointer
variable, not as a normal, data variable.
What value is now in p_age? You do not know exactly, but you
know it is the address of age, wherever that is. Rather than assign the
address of age to p_age with an assignment operator, you can declare
and initialize pointers at the same time. These lines declare and
initialize both age and p_age:
545
Chapter 26 ♦ Pointers
546
C++ By
EXAMPLE
This scanf() does not pass the three variables, but passes the
addresses of the three variables. Because scanf() knows the exact
locations of these parameters in memory (because their addresses
were passed), it goes to those addresses and puts the keyboard input
values into those addresses.
This is the only way scanf() could work. If you passed these
variables by copy, without putting the “address of” operator (&)
before them, scanf() would get the keyboard input and fill a copy of
the variables, but not the actual variables num1, num2, and num3. When
scanf() then returned control to your program, you would not have
the input values. Of course, the cin operator does not have the
ampersand (&) requirement and is easier to use for most C++
programs.
You might recall from Chapter 18, “Passing Values,” that you
can override C++’s normal default of passing by copy (or “by
value”). To pass by address, receive the variable preceded by an & in
the receiving function. The following function receives tries by
address:
Examples
1. The following section of code declares three regular vari-
ables of three different data types, and three corresponding
pointer variables:
547
Chapter 26 ♦ Pointers
Notice that you do not put the * operator before the pointer
variable names when assigning them values. You would
prefix a pointer variable with the * only if you were
dereferencing it.
548
C++ By
EXAMPLE
Keep the data type of each pointer consistent with its corre-
sponding variable. Do not assign a floating-point variable to
an integer’s address. For instance, you cannot make the
following assignment statement:
p_initial = &sales; // Invalid pointer assignment.
// Filename: C26POINT.CPP
// Demonstrates the use of pointer declarations
// and operators.
#include <iostream.h>
void main()
{
int num=123; // A regular integer variable.
int *p_num; // Declares an integer pointer.
cout << “num is “ << num << “\n”; // Prints value of num.
cout << “The address of num is “ << &num << “\n”;
// Prints num’s location.
p_num = # // Puts address of num in p_num,
// in effect making p_num point
// to num.
// No * in front of p_num.
cout << “*p_num is “ << *p_num << “\n”; // Prints value
// of num.
cout << “p_num is “ << p_num << “\n”; // Prints location
// of num.
return;
}
549
Chapter 26 ♦ Pointers
num is 123
The address of num is 0x8fbd0ffe
*p_num is 123
p_num is 0x8fbd0ffe
550
C++ By
EXAMPLE
Identify the program and include the I/O header file. This program swaps
two integers, so initialize two integer variables in main(). Pass the variables
to the swapping function, called swap_them, then switch their values. Print
the results of the swap in main().
// Filename: C26SWAP.CPP
// Program that includes a function that swaps
// any two integers passed to it
#include <iostream.h>
void swap_them(int &num1, int &num2);
void main()
{
int i=10, j=20;
cout << “\n\nBefore swap, i is “ << i <<
“ and j is “ << j << “\n\n”;
swap_them(i, j);
cout << “\n\nAfter swap, i is “ << i <<
“ and j is “ << j << “\n\n”;
return;
}
void swap_them(int &num1, int &num2)
{
int temp; // Variable that holds
// in-between swapped value.
temp = num1; // The calling function’s variables
num1 = num2; // (and not copies of them) are
num2 = temp; // changed in this function.
return;
}
Arrays of Pointers
If you have to reserve many pointers for many different values,
you might want to declare an array of pointers. You know that you
can reserve an array of characters, integers, long integers, and
floating-point values, as well as an array of every other data type
available. You also can reserve an array of pointers, with each
pointer being a pointer to a specific data type.
551
Chapter 26 ♦ Pointers
Figure 26.2 shows how C++ views this array. Each element
holds an address (after being assigned values) that points to other
values in memory. Each value pointed to must be an integer. You can
assign an element from iptr an address just as you would for
nonarray pointer variables. You can make iptr[4] point to the
address of an integer variable named age by assigning it like this:
iptr[4] = &age; // Make iptr[4] point to address of age.
Again, the asterisk is not part of the array name. The asterisk
lets C++ know that this is an array of integer pointers and not just
an array of integers.
552
C++ By
EXAMPLE
Some beginning C++ students get confused when they see such
a declaration. Pointers are one thing, but reserving storage for arrays
of pointers tends to bog novices down. However, reserving storage
for arrays of pointers is easy to understand. Remove the asterisk
from the previous declaration as follows,
char cpoint[20];
and what do you have? You have just reserved a simple array of 20
characters. Adding the asterisk tells C++ to go one step further:
rather than an array of character variables, you want an array of
character pointing variables. Rather than having each element be a
character variable, you have each element hold an address that
points to characters.
Reserving arrays of pointers will be much more meaningful
after you learn about structures in the next few chapters. As with
regular, nonpointing variables, an array makes processing several
pointer variables much easier. You can use a subscript to reference
each variable (element) without having to use a different variable
name for each value.
Review Questions
Answers to review questions are in Appendix B.
1. What type of variable is reserved in each of the following?
a. int *a;
b. char * cp;
c. float * dp;
2. What words should come to mind when you see the &
operator?
3. What is the dereferencing operator?
4. How would you assign the address of the floating-point
variable salary to a pointer called pt_sal?
5. True or false: You must define a pointer with an initial value
when declaring it.
553
Chapter 26 ♦ Pointers
int i;
int * pti;
i=56;
pti = &i;
and
int i;
int * pti;
pti = &i; // These two lines are reversed
i=56; // from the preceding example.
is the value of pti the same after the fourth line of each
section?
7. In the following section of code:
float pay;
float *ptr_pay;
pay=2313.54;
ptr_pay = &pay;
b. *ptr_pay
c. *pay
d. &pay
554
C++ By
EXAMPLE
Summary
Declaring and using pointers might seem troublesome at this
point. Why assign *p_num a value when it is easier (and clearer) to
assign a value directly to num? If you are asking yourself that
question, you probably understand everything you should from
this chapter and are ready to begin learning the true power of
pointers: combining pointers and array processing.
555
Chapter 26 ♦ Pointers
556
C++ By
27 EXAMPLE
Pointers and
Arrays
Arrays and pointers are closely related in the C++ programming
language. You can address arrays as if they were pointers and
address pointers as if they were arrays. Being able to store and access
pointers and arrays gives you the ability to store strings of data in
array elements. Without pointers, you could not store strings of data
in arrays because there is no fundamental string data type in C++ (no
string variables, only string literals).
This chapter introduces the following concepts:
♦ Array names and pointers
♦ Character pointers
♦ Pointer arithmetic
♦ Ragged-edge arrays of string data
This chapter introduces concepts you will use for much of your
future programming in C++. Pointer manipulation is important to
the C++ programming language.
557
Chapter 27 ♦ Pointers and Arrays
If you printed ara[0], you would see 10. Because you now fully
understand arrays, this is the value you would expect.
An array name is a But what if you were to print *ara? Would *ara print anything?
pointer. If so, what? If you thought an error message would print because ara
is not a pointer but an array, you would be wrong. An array name
is a pointer. If you print *ara, you also would see 10.
Recall how arrays are stored in memory. Figure 27.1 shows
how ara would be mapped in memory. The array name, ara, is
nothing more than a pointer pointing to the first element of the array.
Therefore, if you dereference that pointer, you dereference the value
stored in the first element of the array, which is 10. Dereferencing ara
is exactly the same thing as referencing to ara[0], because they both
produce the same value.
ara
You now see that you can reference an array with subscripts or
with pointer dereferencing. Can you use pointer notation to print
the third element of ara? Yes, and you already have the tools to do
so. The following cout prints ara[2] (the third element of ara) without
using a subscript:
cout << *(ara+2) ; // Prints ara[2].
558
C++ By
EXAMPLE
Internal Locations
C++ knows the internal data size requirements of characters,
integers, floating-points, and the other data types on your
computer. Therefore, because ara is an integer array, and
because each element in an integer array consumes two to four
bytes of storage, depending on the computer, C++ adds two or
four bytes to the address if you reference arrays as just shown.
If you write *(ara+3) to refer to ara[3], C++ would add six or
twelve bytes to the address of ara to get the third element. C++
does not add an actual three. You do not have to worry about
this, because C++ handles these internals. When you write
*(ara+3), you are actually requesting that C++ add three integer
addresses to the address of ara. If ara were a floating-point
array, C++ would add three floating-point addresses to ara.
559
Chapter 27 ♦ Pointers and Arrays
Pointer Advantages
An array name is a Although arrays are actually pointers in disguise, they are
pointer constant. special types of pointers. An array name is a pointer constant, not a
pointer variable. You cannot change the value of an array name,
because you cannot change constants. This explains why you cannot
assign an array new values during a program’s execution. For
instance, even if cname is a character array, the following is not valid
in C++:
cname = “Christine Chambers”; // Invalid array assignment.
because you cannot change the constant 5 to any other value. C++
knows that you cannot assign anything to 5, and C++ prints an error
message if you attempt to change 5. C++ also knows an array name
is a constant and you cannot change an array to another value. (You
can assign values to an array only at declaration time, one element
at a time during execution, or by using functions such as strcpy().)
This brings you to the most important reason to learn pointers:
pointers (except arrays referenced as pointers) are variables. You
can change a pointer variable, and being able to do so makes
processing virtually any data, including arrays, much more power-
ful and flexible.
Examples
1. By changing pointers, you make them point to different
values in memory. The following program demonstrates
how to change pointers. The program first defines two
floating-point values. A floating-point pointer points to the
first variable, v1, and is used in the cout. The pointer is then
changed so it points to the second floating-point variable, v2.
// Filename: C27PTRCH.CPP
// Changes the value of a pointer variable.
#include <iostream.h>
560
C++ By
EXAMPLE
#include <iomanip.h>
void main()
{
float v1=676.54; // Defines two
float v2=900.18; // floating-point variables.
float * p_v; / Defines a floating-point pointer.
// Filename: C27ARPTR.CPP
// References arrays like pointers and
// pointers like arrays.
#include <iostream.h>
void main()
{
int ctr;
int iara[5] = {10, 20, 30, 40, 50};
561
Chapter 27 ♦ Pointers and Arrays
int *iptr;
return;
}
562
C++ By
EXAMPLE
Character pointers Figure 27.2 shows how C++ stores these two strings in memory.
can point to the first C++ stores both in basically the same way. You are familiar with the
character of a string.
array definition. When assigning a string to a character pointer, C++
finds enough free memory to hold the string and assign the address
of the first character to the pointer. The previous two string defini-
tion statements do almost exactly the same thing; the only difference
between them is that the two pointers can easily be exchanged (the
array name and the character pointers).
Because cout prints strings starting at the array or pointer name
until the null zero is reached, you can print each of these strings with
the following cout statements:
Because you cannot change the array name, you cannot assign
it a new value. The only way to change the contents of the array is by
assigning the array characters from the string an element at a time,
or by using a built-in function such as strcpy(). You can, however,
make the character array point to the new string like this:
563
Chapter 27 ♦ Pointers and Arrays
Figure 27.2. Storing two strings: One in an array and one pointed to by a
pointer variable.
564
C++ By
EXAMPLE
Examples
1. Suppose you want to store your sister’s full name and print
it. Rather than using arrays, you can use a character pointer.
The following program does just that.
// Filename: C27CP1.CPP
// Stores a name in a character pointer.
#include <iostream.h>
void main()
{
char *c=”Bettye Lou Horn”;
565
Chapter 27 ♦ Pointers and Arrays
// Filename: C27CP2.CPP
// Illustrates changing a character string.
#include <iostream.h>
void main()
{
char *c=”Bettye Lou Horn”;
cout << “My sister’s maiden name was “ << c << “\n”;
// Filename: C27CP3.CPP
// Illustrates changing a character string improperly.
#include <iostream.h>
void main()
566
C++ By
EXAMPLE
{
char *c=”Bettye Lou Horn”;
cout << “My sister’s maiden name was “ << c << “\n”;
// Filename: C27CP4.C
// Illustrates changing a character string improperly.
#include <iostream.h>
void main()
{
char *c=”Bettye Lou Horn”;
cout << “My sister’s maiden name was “ << c << “\n”;
567
Chapter 27 ♦ Pointers and Arrays
Pointer Arithmetic
You saw an example of pointer arithmetic when you accessed
array elements with pointer notation. By now you should be com-
fortable with the fact that both of these array or pointer references
are identical:
ara[sub] and *(ara + sub)
568
C++ By
EXAMPLE
Figure 27.3. Two string constants appear in memory because two string
constants are used in the program.
569
Chapter 27 ♦ Pointers and Arrays
Incrementing a If you print the value of *f_ptr, you see 100.5. Suppose you
pointer can add increment f_ptr by one with the following statement:
more than one byte
to the pointer. f_ptr++;
C++ does not add one to the address in f_ptr, even though it
seems as though one should be added. In this case, because floating-
point values take four bytes each on this machine, C++ adds four to
f_ptr. How does C++ know how many bytes to add to f_ptr? C++
knows from the pointer’s declaration how many bytes of memory
pointers take. This is why you have to declare the pointer with the
correct data type.
After incrementing f_ptr, if you were to print *f_ptr, you would
see 201.45, the second element in the array. If C++ added only one to
the address in f_ptr, f_ptr would point only to the second byte, 100.5.
This would output garbage to the screen.
NOTE: When you increment a pointer, C++ adds one full data-
type size (in bytes) to the pointer, not one byte. When you
decrement a pointer, C++ subtracts one full data type size (in
bytes) from the pointer.
570
C++ By
EXAMPLE
Examples
1. The following program defines an array with five values. An
integer pointer is then initialized to point to the first element
in the array. The rest of the program prints the dereferenced
value of the pointer, then increments the pointer so it points
to the next integer in the array.
Just to show you what is going on, the size of integer values
is printed at the bottom of the program. Because (in this
case) integers take two bytes, C++ increments the pointer by
two so it points to the next integer. (The integers are two
bytes apart from each other.)
// Filename: C27PTI.CPP
// Increments a pointer through an integer array.
#include <iostream.h>
void main()
{
int iara[] = {10,20,30,40,50};
int *ip = iara; // The pointer points to
// The start of the array.
cout << *ip << “\n”;
ip++; // Two are actually added.
cout << *ip << “\n”;
ip++; // Two are actually added.
cout << *ip << “\n”;
ip++; // Two are actually added.
cout << *ip << “\n”;
ip++; // Two are actually added.
cout << *ip << “\n\n”;
cout << “The integer size is “ << sizeof(int);
cout << “ bytes on this machine \n\n”;
return;
}
571
Chapter 27 ♦ Pointers and Arrays
10
20
30
40
50
// Filename: C27PTC.CPP
// Increments a pointer through a character array.
#include <iostream.h>
void main()
{
char cara[] = {‘a’, ‘b’, ‘c’, ‘d’, ‘e’};
char *cp = cara; // The pointers point to
// the start of the array.
cout << *cp << “\n”;
cp++; // One is actually added.
cout << *cp << “\n”;
cp++; // One is actually added.
cout << *cp << “\n”;
cp++; // One is actually added.
cout << *cp << “\n”;
cp++; // One is actually added.
cout << *cp << “\n\n”;
cout << “The character size is “ << sizeof(char);
cout << “ byte on this machine\n”;
return;
}
3. The next program shows the many ways you can add to,
subtract from, and reference arrays and pointers. The pro-
gram defines a floating-point array and a floating-point
pointer. The body of the program prints the values from the
array using array and pointer notation.
572
C++ By
EXAMPLE
// Filename: C27ARPT2.CPP
// Comprehensive reference of arrays and pointers.
#include <iostream.h>
void main()
{
float ara[] = {100.0, 200.0, 300.0, 400.0, 500.0};
float *fptr; // Floating-point pointer.
100.0
200.0
300.0
400.0
573
Chapter 27 ♦ Pointers and Arrays
500.0
300.0
100.0 100.0
200.0 200.0
500.0 500.0
Arrays of Strings
You now are ready for one of the most useful applications of
character pointers: storing arrays of strings. Actually, you cannot
store an array of strings, but you can store an array of character
pointers, and each character pointer can point to a string in memory.
An array that a By defining an array of character pointers, you define a ragged-
character pointer edge array. A ragged-edge array is similar to a two-dimensional
defines is a ragged-
edge array.
table, except each row contains a different number of characters
(instead of being the same length).
The word ragged-edge derives from the use of word processors.
A word processor typically can print text fully justified or with a
ragged-right margin. The columns of this paragraph are fully justi-
fied, because both the left and the right columns align evenly. Letters
you write by hand and type on typewriters (remember what a
typewriter is?) generally have ragged-right margins. It is difficult to
type so each line ends in exactly the same right column.
All two-dimensional tables you have seen so far have been fully
justified. For example, if you declared a character table with five
rows and 20 columns, each row would contain the same number of
characters. You could define the table with the following statement:
This table is shown in Figure 27.5. Notice that much of the table
is wasted space. Each row takes 20 characters, even though the data
in each row takes far fewer characters. The unfilled elements contain
null zeros because C++ nullifies all elements you do not initialize in
arrays. This type of table uses too much memory.
574
C++ By
EXAMPLE
Columns
Rows
575
Chapter 27 ♦ Pointers and Arrays
Figure 27.6. The array that points to each of the five strings.
Examples
1. Here is a full program that uses the pointer array with five
names. The for loop controls the cout function, printing each
name in the string data. Now you can see why learning
about pointer notation for arrays pays off!
// Filename: C27PTST1.CPP
// Prints strings pointed to by an array.
#include <iostream.h>
576
C++ By
EXAMPLE
void main()
{
char *name[5]={ {“George”}, // Defines a ragged-edge
{“Michelle”}, // array of pointers to
{“Joe”}, // strings.
{“Marcus”},
{“Stephanie”} };
int ctr;
return;
}
String #1 is George
String #2 is Michelle
String #3 is Joe
String #4 is Marcus
String #5 is Stephanie
// Filename: C27PTST2.CPP
// Prints the day of the week based on an input value.
#include <iostream.h>
void main()
{
char *days[] = {“Sunday”, // The seven separate sets
“Monday”, // of braces are optional.
“Tuesday”,
“Wednesday”,
“Thursday”,
“Friday”,
“Saturday”};
int day_num;
577
Chapter 27 ♦ Pointers and Arrays
do
{ cout << “What is a day number (from 1 to 7)? “;
cin >> day_num;
} while ((day_num<1) || (day_num>7)); // Ensures
// an accurate number.
Review Questions
The answers to the review questions are in Appendix B.
1. What is the difference between an array name and a pointer?
2. If you performed the following statement (assume ipointer
points to integers that take four bytes of memory),
ipointer += 2;
578
C++ By
EXAMPLE
c. ara = 15;
Review Exercises
1. Write a program to store your family members’ names in a
character array of pointers. Print the names.
2. Write a program that asks the user for 15 daily stock market
averages and stores those averages in a floating-point array.
Using only pointer notation, print the array forward and
backward. Again using only pointer notation, print the
highest and lowest stock market quotes in the list.
3. Modify the bubble sort shown in Chapter 24, “Array Pro-
cessing,” so that it sorts using pointer notation. Add this
bubble sort to the program in Exercise 2 to print the stock
market averages in ascending order
4. Write a program that requests 10 song titles from the user.
Store the titles in an array of character pointers (a ragged-
edge array). Print the original titles, print the alphabetized
titles, and print the titles in reverse alphabetical order (from
Z to A).
579
Chapter 27 ♦ Pointers and Arrays
Summary
You deserve a break! You now understand the foundation of
C++’s pointers and array notation. When you have mastered this
section, you are on your way to thinking in C++ as you design your
programs. C++ programmers know that C++’s arrays are pointers
in disguise, and they program them accordingly.
Being able to use ragged-edge arrays offers two advantages:
You can hold arrays of string data without wasting extra space, and
you can quickly change the pointers without having to move the
string data around in memory.
As you progress into advanced C++ concepts, you will appre-
ciate the time you spend mastering pointer notation. The next
chapter introduces a new topic called structures. Structures enable
you to store data in a more unified manner than simple variables
have allowed.
580
Part VII
Structures and File
Input/Output
C++ By
28EXAMPLE
Structures
Using structures, you have the ability to group data and work with
the grouped data as a whole. Business data processing uses the
concept of structures in almost every program. Being able to ma-
nipulate several variables as a single group makes your programs
easier to manage.
This chapter introduces the following concepts:
♦ Structure definitions
♦ Initializing structures
♦ The dot operator (.)
♦ Structure assignment
♦ Nested structures
This chapter is one of the last in the book to present new
concepts. The remainder of the book builds on the structure con-
cepts you learn in this chapter.
583
Chapter 28 ♦ Structures
Introduction to Structures
Structures can have A structure is a collection of one or more variable types. As you
members of different know, each element in an array must be the same data type, and you
data types.
must refer to the entire array by its name. Each element (called a
member) in a structure can be a different data type.
Suppose you wanted to keep track of your CD music collection.
You might want to track the following pieces of information about
each CD:
Title
Artist
Number of songs
Cost
Date purchased
There would be five members in this CD structure.
584
C++ By
EXAMPLE
585
Chapter 28 ♦ Structures
Examples
1. Suppose you were asked to write a program for a company’s
inventory system. The company had been using a card-file
inventory system to track the following items:
Item name
Quantity in stock
Quantity on order
Retail price
Wholesale price
This would be a perfect use for a structure containing five
members. Before defining the structure, you have to deter-
mine the data types of each member. After asking questions
about the range of data (you must know the largest item
name, and the highest possible quantity that would appear
on order to ensure your data types can hold the data), you
decide to use the following structure tag and data types:
586
C++ By
EXAMPLE
Defining Structures
To define a structure, you must use the struct statement. The
statement defines a new data type, with more than one
struct
member, for your program. The format of the struct statement is
587
Chapter 28 ♦ Structures
struct cd_collection
{
char title[25];
char artist[20];
int num_songs;
float price;
char date_purch[9];
} cd1, cd2, cd3;
588
C++ By
EXAMPLE
If you had 1000 CDs, you would have to declare 1000 structure
variables. Obviously, you would not want to list that many structure
variables at the end of a structure definition. To help define struc-
tures for a large number of occurrences, you must define an array of
structures. Chapter 29, “Arrays of Structures,” shows you how to do
that. For now, concentrate on familiarizing yourself with structure
definitions.
Examples
1. Here is a structure definition of the inventory application
described earlier in this chapter.
589
Chapter 28 ♦ Structures
struct inventory
{
char item_name[20];
long int in_stock;
long int order_qty;
float retail;
float wholesale;
} item1, item2, item3, item4;
struct employees
{
char emp_name[25]; // Employee’s full name.
char address[30]; // Employee’s address.
char city[10];
char state[2];
long int zip;
double salary; // Annual salary.
} emp1, emp2, emp3, emp4, emp5;
struct customers
{
char cust_name[25]; // Customer’s full name.
char address[30]; // Customer’s address.
char city[10];
char state[2];
long int zip;
double balance; // Balance owed to company.
} cust1, cust2, cust3, cust4, cust5;
590
C++ By
EXAMPLE
struct cd_collection
{
char title[25];
char artist[20];
int num_songs;
float price;
char date_purch[9];
} cd1 = {“Red Moon Men”, “Sam and the Sneeds”,
12, 11.95, “02/13/92”};
591
Chapter 28 ♦ Structures
Examples
1. Here is a simple program using the CD collection structure
and the dot operator to initialize the structure. Notice the
program treats members as if they were regular variables
when combined with the dot operator.
Identify the program and include the necessary header file. Define
a CD structure variable with five members. Fill the CD structure
variable with data, then print it.
// Filename: C28ST1.CPP
// Structure initialization with the CD collection.
#include <iostream.h>
#include <string.h>
void main()
{
struct cd_collection
{
char title[25];
char artist[20];
int num_songs;
float price;
char date_purch[9];
} cd1;
592
C++ By
EXAMPLE
// Initialize members here.
strcpy(cd1.title, “Red Moon Men”);
strcpy(cd1.artist, “Sam and the Sneeds”);
cd1.num_songs=12;
cd1.price=11.95;
strcpy(cd1.date_purch, “02/13/92”);
return;
}
// Filename: C28ST2.CPP
// Structure input with student data.
#include <iostream.h>
#include <string.h>
#include <iomanip.h>
#include <stdio.h>
593
Chapter 28 ♦ Structures
void main()
{
struct students
{
char name[25];
int age;
float average;
} student1, student2;
return;
}
594
C++ By
EXAMPLE
Student #1:
Name: Larry
Age: 14
Average: 87.67
Student #2:
Name: Judy
Age: 15
Average: 95.38
Define structures The structure tag plays an important role in the local/global
globally and problem. Use the structure tag to define local structure
structure variables
locally.
variables. The following program is similar to the previous
one. Notice the student structure is defined globally with no
595
Chapter 28 ♦ Structures
// Filename: C28ST3.CPP
// Structure input with student data passed to functions.
#include <iostream.h>
#include <string.h>
#include <stdio.h>
#include <iomanip.h>
struct students fill_structs(struct students student_var);
void pr_students(struct students student_var);
void main()
{
students student1, student2; // Defines two
// local variables.
return;
}
596
C++ By
EXAMPLE
struct students fill_structs(struct students student_var)
{
// Get student’s data
fflush(stdin); // Clears input buffer for next input.
cout << “What is student’s name? “;
gets(student_var.name);
cout << “What is the student’s age? “;
cin >> student_var.age;
cout << “What is the student’s average? “;
cin >> student_var.average;
return (student_var);
}
597
Chapter 28 ♦ Structures
// Filename: C28CUST.CPP
// Updates a customer balance in a structure.
#include <iostream.h>
#include <iomanip.h>
struct customer_rec
{
char cust_name[25];
double balance;
float dis_rate;
} ;
void main()
{
struct customer_rec customer = {“Steve Thompson”,
431.23, .25};
598
C++ By
EXAMPLE
// Filename: C28STCPY.CPP
// Demonstrates assigning one structure to another.
#include <iostream.h>
#include <iomanip.h>
struct student
{
char st_name[25];
char grade;
int age;
float average;
};
void main()
{
student std1 = {“Joe Brown”, ‘A’, 13, 91.4};
struct student std2, std3; // Not initialized
599
Chapter 28 ♦ Structures
Nested Structures
C++ gives you the ability to nest one structure definition in
another. This saves time when you are writing programs that use
similar structures. You have to define the common members only
once in their own structure and then use that structure as a member
in another structure.
The following two structure definitions illustrate this point:
struct employees
{
char emp_name[25]; // Employee’s full name.
char address[30]; // Employee’s address.
char city[10];
char state[2];
long int zip;
double salary; // Annual salary.
};
struct customers
{
char cust_name[25]; // Customer’s full name.
char address[30]; // Customer’s address.
char city[10];
char state[2];
long int zip;
double balance; // Balance owed to company.
};
600
C++ By
EXAMPLE
struct address_info
{
char address[30]; // Common address information.
char city[10];
char state[2];
long int zip;
};
struct employees
{
char emp_name[25]; // Employee’s full name.
address_info e_address; // Employee’s address.
double salary; // Annual salary.
};
struct customers
{
char cust_name[25]; // Customer’s full name.
address_info c_address; // Customer’s address.
double balance; // Balance owed to company.
};
601
Chapter 28 ♦ Structures
602
C++ By
EXAMPLE
Review Questions
The answers to the review questions are in Appendix B.
1. What is the difference between structures and arrays?
2. What are the individual elements of a structure called?
3. What are the two ways to initialize members of a structure?
4. Do you pass structures by copy or by address?
5. True or false: The following structure definition reserves
storage in memory:
struct crec
{ char name[25];
int age;
float sales[5];
long int num;
}
struct item
{
int quantity;
part_rec item_desc;
float price;
char date_purch[8];
};
603
Chapter 28 ♦ Structures
Review Exercises
1. Write a structure in a program that tracks a video store’s
tape inventory. Be sure the structure includes the tape title,
the length of the tape (in minutes), the initial purchase price
of the tape, the rental price of the tape, and the date of the
movie’s release.
2. Write a program using the structure you declared in Exer-
cise 1. Define three structure variables and initialize them
when you declare the variables with data. Print the data to
the screen.
3. Write a teacher’s program to keep track of 10 students’
names, ages, letter grades, and IQs. Use 10 different struc-
ture variable names and retrieve the data for the students in
a for loop from the keyboard. Print the data on the printer
when the teacher finishes entering the information for all the
students.
Summary
With structures, you have the ability to group data in more
flexible ways than with arrays. Your structures can contain mem-
bers of different data types. You can initialize the structures either
at declaration time or during the program with the dot operator.
Structures become even more powerful when you declare
arrays of structure variables. Chapter 29, “Arrays of Structures,”
shows you how to declare several structure variables without giving
them each a different name. This enables you to step through
structures much quicker with loop constructs.
604
C++ By
17 EXAMPLE
Variable Scope
The concept of variable scope is most important when you write
functions. Variable scope determines which functions recognize
certain variables. If a function recognizes a variable, the variable is
visible to that function. Variable scope protects variables in one
function from other functions that might overwrite them. If a
function doesn’t need access to a variable, that function shouldn’t be
able to see or change the variable. In other words, the variable
should not be “visible” to that particular function.
This chapter introduces you to
♦ Global and local variables
♦ Passing arguments
♦ Automatic and static variables
♦ Passing parameters
The previous chapter introduced the concept of using a differ-
ent function for each task. This concept is much more useful when
you learn about local and global variable scope.
353
Chapter 17 ♦ Variable Scope
354
C++ By
EXAMPLE
Global variables are Global variables are visible (“known”) from their point of
visible from their definition to the end of the program. If you define a global variable,
definition through
the remainder of the
any line throughout the rest of the program—no matter how many
program. functions and code lines follow it—is able to use that global variable.
355
Chapter 17 ♦ Variable Scope
Examples
1. The following section of code defines two local variables,
i and j.
main()
{
int i, j; // Local because they’re
// defined after the brace.
// Rest of main() goes here.
}
#include <iostream.h>
int g, h; // Global because they’re
// defined before a function.
main()
{
// main()’s code goes here.
}
// Filename: C17GLO.CPP
// Program that contains two global variables.
#include <iostream.h>
do_fun();
third_fun(); // Prototype discussed later.
main()
{
cout << “No variables defined in main() \n\n”;
do_fun(); // Call the first function.
356
C++ By
EXAMPLE
return 0;
}
third_fun()
{
cout << “In the third function: \n”;
cout << “The sales in the third function are “ <<
sales << “\n”;
cout << “The profit in the third function is “ <<
profit << “\n”;
// If sales and profit were local, they would not be
// visible by more than one function.
return 0;
}
Notice that the main() function can never use sales and profit
because they are not visible to main()—even though they are
global. Remember, global variables are visible only from
their point of definition downward in the program. State-
ments that appear before global variable definitions can-
not use those variables. Here is the result of running this
program.
357
Chapter 17 ♦ Variable Scope
// Filename: C17GLLO.CPP
// Program with both local and global variables.
// Local Variables Global Variables
// j, p i, z
#include <iostream.h>
pr_again(); // Prototype
358
C++ By
EXAMPLE
float z = 9.0; // Global variable because it’s
// defined before a function.
pr_again()
{
int j = 5; // Local to only pr_again().
cout << j << “, “ << z; // This can’t print p!.
cout << “, “ << i << “\n”;
return 0; // Return to main().
}
// Filename: C17LOC1.CPP
// Two different local variables with the same name.
#include <iostream.h>
get_age(); // Prototype
main()
{
int age;
cout << “What is your age? “;
cin >> age;
359
Chapter 17 ♦ Variable Scope
return 0;
}
get_age()
{
int age; // A different age. This one
// is local to get_age().
cout << “What is your age again? “;
cin >> age;
return 0;
}
Variables local to
main() cannot be The output of this program follows. Study this output
used in another carefully. Notice that main()’s last cout does not print the
function that newly changed age. Rather, it prints the age known to
main() calls.
main()—the age that is local to main(). Even though they are
named the same, main()’s age has nothing to do with
get_age()’s age. They might as well have two different vari-
able names.
// Filename: C17LOC2.CPP
// Using two local variables with the same name
360
C++ By
EXAMPLE
// as counting variables.
#include <iostream.h>
do_fun(); // Prototype
main()
{
int ctr; // Loop counter.
for (ctr=0; ctr<=10; ctr++)
{ cout << “main()’s ctr is “ << ctr << “\n”; }
do_fun(); // Call second function.
return 0;
}
do_fun()
{
int ctr;
for (ctr=10; ctr>=0; ctr--)
{ cout << “do_fun()’s ctr is “ << ctr << “\n”; }
return 0; // Return to main().
}
361
Chapter 17 ♦ Variable Scope
// Filename: C17MULI.CPP
// Program with multiple local variables called i.
#include <iostream.h>
main()
{
int i; // Outer i
i = 10;
All local variables are local to the block in which they are
defined. This program has three blocks, each one nested
within another. Because you can define local variables
immediately after an opening brace of a block, there are
three distinct i variables in this program.
The local i disappears completely when its block ends (when
the closing brace is reached). C++ always prints the variable
that it interprets as the most local—the one that resides
within the innermost block.
362
C++ By
EXAMPLE
363
Chapter 17 ♦ Variable Scope
You pass an When you pass a local variable from one function to another,
argument when you you pass an argument from the first function to the next. You can pass
pass one local
more than one argument (variable) at a time, if you want several
variable to another
function. local variables to be sent from one function to another. The receiving
function receives a parameter (variable) from the function that sends
it. You shouldn’t worry too much about what you call them—either
arguments or parameters. The important thing to remember is that
you are sending local variables from one function to another.
If a function name
To pass a local variable from one function to another, you must
has empty
parentheses, nothing place the local variable in parentheses in both the calling func-
is being passed to it. tion and the receiving function. For example, the local and global
364
C++ By
EXAMPLE
examples presented earlier did not pass local variables from main()
to do_fun(). If a function name has empty parentheses, nothing is
being passed to it. Given this, the following line passes two vari-
ables, total and discount, to a function called do_fun().
do_fun(total, discount);
int i, j;
int m=9;
float x;
char ara[] = “Tulsa”;
These statements tell the program that you need these variables
to be reserved. A function is defined when the C++ compiler reads
the first statement in the function that describes the name and when
it reads any variables that might have been passed to that function
as well. Never follow a function definition with a semicolon, but
always follow the statement that calls a function with a semicolon.
365
Chapter 17 ♦ Variable Scope
Examples
1. Here is a main() function that contains three local variables.
main() passes one of these variables to the first function and
two of them to the second function.
366
C++ By
EXAMPLE
// Filename: C17LOC3.CPP
// Pass three local variables to functions.
#include <iostream.h>
#include <iomanip.h>
pr_init(char initial); // Prototypes discussed later.
pr_other(int age, float salary);
main()
{
char initial; // Three variables local to
// main().
int age;
float salary;
return 0;
}
367
Chapter 17 ♦ Variable Scope
“ is a LOT of money!”;
return 0; // Return to main().
}
// Filename: C17LOC4.CPP
// Second function has its own local variable.
#include <iostream.h>
#include <iomanip.h>
compute_sale(int gallons); // Prototypes discussed later.
main()
{
int gallons;
compute_sale(int gallons)
{
float price_per = 12.45; // Local to compute_sale().
368
C++ By
EXAMPLE
do_it()
main()
{
int i;
auto float x;
// Rest of main() goes here.
369
Chapter 17 ♦ Variable Scope
Because auto is the default, you did not have to include the term
auto with x.
If local variables are Always assign an initial value to a static variable when you
static, their values declare it, as shown here in the last two lines. This initial value is
remain in case the placed in the static variable only the first time my_fun() executes. If
function is called
again.
you don’t assign a static variable an initial value, C++ initializes it to
zero.
TIP: Static variables are good to use when you write functions
that keep track of a count or add to a total. If the counting or
totaling variables were local and automatic, their values would
disappear when the function finished—destroying the totals.
370
C++ By
EXAMPLE
Examples
1. Consider this program:
// Filename: C17STA1.CPP
// Tries to use a static variable
// without a static declaration.
#include <iostream.h>
triple_it(int ctr);
main()
{
int ctr; // Used in the for loop to
// call a function 25 times.
for (ctr=1; ctr<=25; ctr++)
{ triple_it(ctr); } // Pass ctr to a function
// called triple_it().
return 0;
}
triple_it(int ctr)
{
int total=0, ans; // Local automatic variables.
371
Chapter 17 ♦ Variable Scope
// Filename: C17STA2.CPP
// Uses a static variable with the static declaration.
#include <iostream.h>
triple_it(int ctr);
main()
372
C++ By
EXAMPLE
{
int ctr; // Used in the for loop to
// call a function 25 times.
for (ctr=1; ctr<=25; ctr++)
{ triple_it(ctr); } // Pass ctr to a function
// called triple_it().
return 0;
}
triple_it(int ctr)
{
static int total=0; // Local and static
int ans; // Local and automatic
// total is set to 0 only the first time this
// function is called.
373
Chapter 17 ♦ Variable Scope
This does not mean that local static variables become global.
The main program cannot refer, use, print, or change total
because it is local to the second function. Static simply
means that the local variable’s value is still there if the
program calls the function again.
374
C++ By
EXAMPLE
The first two concepts deal with the way local variables are
passed and received. The third concept describes how receiving
functions send values back to the calling functions. Chapter 18,
“Passing Values,” concludes this discussion by explaining these
three methods for passing parameters and returning values.
Review Questions
The answers to the review questions are in Appendix B.
1. True or false: A function should always include a return
statement as its last command, even though return is not
required.
2. When a local variable is passed, is it called an argument or a
parameter?
3. True or false: A function that is passed variables from an-
other function cannot also have its own local variables.
4. What must appear inside the receiving function’s parenthe-
ses, other than the variables passed to it?
5. If a function keeps track of a total or count every time it is
called, should the counting or totaling variable be automatic
or static?
6. When would you pass a global variable to a function? (Be
careful—this might be a trick question!)
7. How many arguments are there in the following statement?
printf(“The rain has fallen %d inches.”, rainf);
Review Exercises
1. Write a program that asks, in main(), for the age of the user’s
dog. Write a second function called people() that computes
the dog’s age in human years (by multiplying the dog’s age
by seven).
375
Chapter 17 ♦ Variable Scope
// Filename: C17BAD.CPP
// Program with bad uses of variable declarations.
#include <iostream.h>
#define NUM 10
do_var_fun(); // Prototypes discussed later.
main()
{
int abc;
count = NUM;
abc = 5;
do_var_fun();
cout << abc << “ “ << count << “ “ << pgm_var << “ “
<< xyz;
return 0;
}
int pgm_var = 7;
do_var_fun()
376
C++ By
EXAMPLE
{
char xyz = ‘A’;
xyz = ‘b’;
cout << xyz << “ “ << pgm_var << “ “ abc << “ “ << city;
return 0;
}
Summary
Parameter passing is necessary because local variables are
better than global. Local variables are protected in their own rou-
tines, but sometimes they must be shared with other routines. If
local data are to remain in those variables (in case the function is
called again in the same program), the variables should be static
because otherwise their automatic values disappear.
Most the information in this chapter becomes more obvious as
you use functions in your own programs. Chapter 18, “Passing
Values,” covers the actual passing of parameters in more detail and
shows you two different ways to pass them.
377
Chapter 17 ♦ Variable Scope
378
C++ By
18EXAMPLE
Passing Values
C++ passes variables between functions using two different meth-
ods. The one you use depends on how you want the passed variables
to be changed. This chapter explores these two methods. The con-
cepts discussed here are not new to the C++ language. Other
programming languages, such as Pascal, FORTRAN, and QBasic,
pass parameters using similar techniques. A computer language
must have the capability to pass information between functions
before it can be called truly structured.
This chapter introduces you to the following:
♦ Passing variables by value
♦ Passing arrays by address
♦ Passing nonarrays by address
Pay close attention because most of the programs in the remain-
der of the book rely on the methods described in this chapter.
379
Chapter 18 ♦ Passing Values
5
5
380
C++ By
EXAMPLE
All C++’s nonarray variables you have seen so far are passed by
value. You do not have to do anything special to pass variables by
value, except to pass them in the calling function’s argument list and
receive them in the receiving function’s parameter list.
Examples
1. The following program asks users for their weight. It then
passes that weight to a function that calculates the equiva-
lent weight on the moon. Notice the second function uses the
passed value, and calculates with it. After weight is passed to
the second function, that function can treat weight as though
it were a local variable.
Identify the program and include the necessary input/output file.
You want to calculate the user’s weight on the moon. Because you
have to hold the user’s weight somewhere, declare the variable
weight as an integer. You also need a function that does the
calculations, so create a function called moon().
Ask the user how much he or she weighs. Put the user’s answer in
weight. Now pass the user’s weight to the moon() function, which
divides the weight by six to determine the equivalent weight on the
moon. Display the user’s weight on the moon.
You have finished, so leave the moon() function, then leave the
main() function.
// Filename: C18PASS1.CPP
// Calculate the user’s weight in a second function.
#include <iostream.h>
moon(int weight); // Prototypes discussed later.
381
Chapter 18 ♦ Passing Values
main()
{
int weight; // main()’s local weight.
cout << “How many pounds do you weigh? “;
cin >> weight;
// Filename: C18PASS2.CPP
// Calculate the user’s weight in a second function.
#include <iostream.h>
moon(int earth_weight);
main()
382
C++ By
EXAMPLE
{
int weight; // main()’s local weight.
cout << “How many pounds do you weigh? “;
cin >> weight;
// Filename: C18PASS3.CPP
// Get grade information for a student.
#include <iostream.h>
#include <iomanip.h>
check_grade(char lgrade, float average, int tests);
383
Chapter 18 ♦ Passing Values
main()
{
char lgrade; // Letter grade.
int tests; // Number of tests not yet taken.
float average; // Student’s average based on 4.0 scale.
384
C++ By
EXAMPLE
Passing by Address
(by Reference)
When you pass by The two phrases “by address” and “by reference” mean the
address, the address
of the variable is
same thing. The previous section described passing arguments by
passed to the value (or by copy). This section teaches you how to pass arguments
receiving function. by address.
When you pass an argument (local variable) by address, the
variable’s address is sent to—and is assigned to—the receiving
function’s parameter. (If you pass more than one variable by ad-
dress, each of their addresses is sent to—and is assigned to—the
receiving function’s parameters.)
Variable Addresses
All variables in memory (RAM) are stored at memory ad-
dresses—see Figure 18.2. If you want more information on the
internal representation of memory, refer to Appendix A, “Memory
Addressing, Binary, and Hexadecimal Review.”
When you tell C++ to define a variable (such as int i;), you are
requesting C++ to find an unused place in memory and assign that
place (or memory address) to i. When your program uses the
variable called i, C++ goes to i’s address and uses whatever is there.
385
Chapter 18 ♦ Passing Values
int i;
float x=9.8;
char ara[2] = {‘A’, ‘B’};
int j=8, k=3;
Sample Program
All C++ arrays are The address of the variable, not its value, is copied to the
passed by address. receiving function when you pass a variable by address. In C++, all
arrays are automatically passed by address. (Actually, a copy of their
address is passed, but you will understand this better when you
learn more about arrays and pointers.) The following important rule
holds true for programs that pass by address:
386
C++ By
EXAMPLE
// Filename: C18ADD1.CPP
// Passing by address example.
#include <iostream.h>
#include <string.h>
change_it(char c[4]); // Prototype discussed later.
main()
{
char name[4]=”ABC”;
ABC
USA
387
Chapter 18 ♦ Passing Values
ara
Figure 18.5. The array being passed is the same array in both functions.
388
C++ By
EXAMPLE
Examples
1. You can now use a function to fill an array with user input.
The following function asks users for their first name in the
function called get_name(). As users type the name in the
array, it is also entered in main()’s array. The main() function
then passes the array to pr_name(), where it is printed. (If
arrays were passed by value, this program would not work.
Only the array value would be passed to the called func-
tions.)
// Filename: C18ADD2.CPP
// Get a name in an array, then print it using
// separate functions.
#include <iostream.h>
get_name(char name[25]); // Prototypes discussed later.
print_name(char name[25]);
main()
{
char name[25];
get_name(name); // Get the user’s name.
print_name(name); // Print the user’s name.
return 0;
}
print_name(char name[25])
{
cout << “\n\n Here you are, “ << name;
return 0;
}
389
Chapter 18 ♦ Passing Values
390
C++ By
EXAMPLE
Examples
1. The following program passes a variable by address from
main() to a function. The function changes it and returns to
main(). Because the variable is passed by address, main()
recognizes the new value.
// Filename: C18ADD3.CPP
// Demonstrate passing nonarrays by address.
#include <iostream.h>
do_fun(int &amt); // Prototypes discussed later.
main()
{
int amt;
391
Chapter 18 ♦ Passing Values
// Filename: C18POOL.CPP
// Calculates the cubic feet in a swimming pool.
#include <iostream.h>
get_values(int &length, int &width, int &depth);
calc_cubic(int &length, int &width, int &depth, int &cubic);
print_cubic(int &cubic);
392
C++ By
EXAMPLE
main()
{
int length, width, depth, cubic;
return 0;
}
print_cubic(int &cubic)
{
cout << “\nThe pool has “ << cubic << “ cubic feet\n”;
return 0;
}
393
Chapter 18 ♦ Passing Values
Review Questions
The answers to the review questions are in Appendix B.
1. What type of variable is automatically passed by address?
2. What type of variable is automatically passed by value?
3. True or false: If a variable is passed by value, it is passed also
by copy.
4. If a variable is passed to a function by value and the function
changes the variable, is it changed in the calling function?
5. If a variable is passed to a function by address and the
function changes the variable, is it changed in the calling
function?
6. What is wrong with the following function?
do_fun(x, y, z)
{
cout << “The variables are “ << x << y << z;
return 0;
}
394
C++ By
EXAMPLE
Review Exercises
1. Write a main() function and a second function that main()
calls. Ask users for their annual income in main(). Pass the
income to the second function and print a congratulatory
message if the user makes more than $50,000 or an encour-
agement message if the user makes less.
2. Write a three-function program, consisting of the following
functions:
main()
fun1()
fun2()
395
Chapter 18 ♦ Passing Values
Summary
You now have a complete understanding of the various meth-
ods for passing data to functions. Because you will be using local
variables as much as possible, you have to know how to pass local
variables between functions but also keep the variables away from
functions that don’t need them.
You can pass data in two ways: by value and by address. When
you pass data by value, which is the default method for nonarrays,
only a copy of the variable’s contents are passed. If the called
function modifies its parameters, those variables are not modified in
the calling function. When you pass data by address, as is done with
arrays and nonarray variables preceded by an ampersand, the
receiving function can change the data in both functions.
Whenever you pass values, you must ensure that they match in
number and type. If you don’t match them, you could have prob-
lems. For example, suppose you pass an array and a floating-point
variable, but in the receiving function, you receive a floating-point
variable followed by an array. The data does not reach the receiving
function properly because the parameter data types do not match
the variables being passed. Chapter 19, “Function Return Values
and Prototypes,” shows you how to protect against such disasters
by prototyping all your functions.
396
C++ By
19EXAMPLE
Function Return
Values and
Prototypes
So far, you have passed variables to functions in only one direc-
tion—a calling function passed data to a receiving function. You
have yet to see how data are passed back from the receiving function
to the calling function. When you pass variables by address, the data
are changed in both functions—but this is different from passing
data back. This chapter focuses on writing function return values
that improve your programming power.
After you learn to pass and return values, you have to prototype
your own functions as well as C++’s built-in functions, such as cout
and cin. By prototyping your functions, you ensure the accuracy of
passed and returned values.
This chapter introduces you to the following:
♦ Returning values from functions
♦ Prototyping functions
♦ Understanding header files
By returning values from functions, you make your functions
fully modular. They can now stand apart from the other functions.
397
Chapter 19 ♦ Function Return Values and Prototypes
They can receive and return values and act as building blocks that
compose your complete application.
The calling function must have a use for the return value. For
example, suppose you wrote a function that calculated the average
of any three integer variables passed to it. If you return the average,
the calling function has to receive that return value. The following
sample program helps to illustrate this principle.
// Filename: C19AVG.CPP
// Calculates the average of three input values.
#include <iostream.h>
int calc_av(int num1, int num2, int num3); //Prototype
398
C++ By
EXAMPLE
main()
{
int num1, num2, num3;
int avg; // Holds the return value.
return (local_avg);
}
The average is 40
399
Chapter 19 ♦ Function Return Values and Prototypes
You typed a function call to the right of the equal sign, but the
program replaces a function call with its return value when the
return takes place. In other words, a function that returns a value
400
C++ By
EXAMPLE
becomes that value. You must put such a function anywhere you put
any variable or literal (usually to the right of an equal sign, in an
expression, or in cout). The following is an incorrect way of calling
calc_av():
If you did this, C++ would have nowhere to put the return
value.
Examples
1. The following program passes a number to a function called
doub(). The function doubles the number and returns the
result.
// Filename: C19DOUB.CPP
// Doubles the user’s number.
#include <iostream.h>
int doub (int num);
main()
{
int number; // Holds user’s input.
int d_number; // Holds double the user’s input.
cout << “What number do you want doubled? “;
cin >> number;
401
Chapter 19 ♦ Function Return Values and Prototypes
// Filename: C19DOUB2.CPP
// Doubles the user’s number.
#include <iostream.h>
int doub(int num); // Prototype
main()
{
int number; // Holds user’s input.
cout << “What number do you want doubled? “;
cin >> number;
402
C++ By
EXAMPLE
// The third cout parameter is
// replaced with a return value.
cout << number << “ doubled is “ << doub(number);
return 0;
}
// Filename: C19SUMD.CPP
// Compute the sum of the digits.
#include <iostream.h>
int sum(int num); // Prototype
main()
{
int num, sumd;
sumd = sum(num);
cout << “The sum of the digits is “ << sumd;
return 0;
}
403
Chapter 19 ♦ Function Return Values and Prototypes
// Filename: C19MINMX.CPP
// Finds minimum and maximum values in functions.
#include <iostream.h>
main()
{
int num1, num2; // User’s two numbers.
int min, max;
404
C++ By
EXAMPLE
cout << “The minimum number is “ << min << “\n”;
cout << “The maximum number is “ << max << “\n”;
return 0;
}
If the user types the same number, minimum and maximum are
the same.
These two functions can be passed any two integer values. In
such a simple example as this one, the user certainly already
knows which number is lower or higher. The point of such
an example is to show how to code return values. You might
want to use similar functions in a more useful application,
such as finding the highest paid employee from a payroll
disk file.
Function Prototypes
The word prototype is sometimes defined as a model. In C++, a
function prototype models the actual function. Before completing
405
Chapter 19 ♦ Function Return Values and Prototypes
406
C++ By
EXAMPLE
In doing so, you tell the compiler to check this function for
accuracy. You inform the compiler to expect nothing after the return
statement, not even 0, (due to the void keyword) and to expect an
integer followed by a floating-point in the parentheses.
If you break any of the prototype’s rules, the compiler informs
you of the problem and you can correct it.
407
Chapter 19 ♦ Function Return Values and Prototypes
This is the header file for the strcpy() function. Without it, the
program does not work.
408
C++ By
EXAMPLE
Examples
1. Prototype all functions in all programs except main(). Even
main() must be prototyped if it returns nothing (not even 0).
The following program includes two prototypes: one for
main() because it returns nothing, and one for the built-in
printf() and scanf() functions.
// Filename: C19PRO1.CPP
// Calculates sales tax on a sale
#include <stdio.h> // Prototype built-in functions.
void main(void);
void main(void)
{
float total_sale;
float tax_rate = .07; // Assume seven percent
// tax rate.
409
Chapter 19 ♦ Function Return Values and Prototypes
// Filename: C19ASC.CPP
// Prints the ASCII character of the user’s number.
// Prototypes follow.
#include <iostream.h>
char ascii(int num);
void main()
{
int num;
char asc_char;
asc_char = ascii(num);
cout << “The ASCII character for “ << num
<< “ is “ << asc_char;
return;
}
410
C++ By
EXAMPLE
// Filename: C19NPAY.CPP
// Defines a function that computes net pay.
#include <iostream.h> // Needed for cout and cin.
void main(void);
float netpayfun(float hours, float rate, float taxrate);
void main(void)
{
float net_pay;
return;
}
411
Chapter 19 ♦ Function Return Values and Prototypes
Review Questions
The answers to the review questions are in Appendix B.
1. How do you declare function return types?
2. What is the maximum number of return values a function
can return?
3. What are header files for?
4. What is the default function return type?
5. True or false: a function that returns a value can be passed
only a single parameter.
6. How do prototypes protect the programmer from bugs?
7. Why don’t you have to return global variables?
8. What is the return type, given the following function
prototype?
float my_fun(char a, int b, float c);
Review Exercises
1. Write a program that contains two functions. The first
function returns the square of the integer passed to it, and
the second function returns the cube. Prototype main() so
you do not have to return a value.
2. Write a function that returns the double-precision area of a
circle, given that a double-precision radius is passed to it.
The formula for calculating the area of a circle is
area = 3.14159 * (radius * radius)
412
C++ By
EXAMPLE
Summary
You learned how to build your own collection of functions.
When you write a function, you might want to use it in more than
one program—there is no need to reinvent the wheel. Many pro-
grammers write useful functions and use them in more than one
program.
You now understand the importance of prototyping functions.
You should prototype all your own functions, and include the
appropriate header file when you use one of C++’s built-in func-
tions. Furthermore, when a function returns a value other than an
integer, you must prototype so C++ recognizes the noninteger
return value.
413
Chapter 19 ♦ Function Return Values and Prototypes
414
C++ By
20EXAMPLE
Default Arguments
and Function
Overloading
All functions that receive arguments do not have to be sent values.
C++ enables you to specify default argument lists. You can write
functions that assume argument values even if you do not pass them
any arguments.
C++ also enables you to write more than one function with the
same function name. This is called overloading functions. As long as
their argument lists differ, the functions are differentiated by C++.
This chapter introduces you to the following:
♦ Default argument lists
♦ Overloaded functions
♦ Name-mangling
Default argument lists and overloaded functions are not avail-
able in regular C. C++ extends the power of your programs by
providing these time-saving procedures.
415
Chapter 20 ♦ Default Arguments and Function Overloading
This command prints the message “Turn printer on” for a period
of five seconds or so. To request that pr_msg() print the line “Press
any key to continue...”, you call it this way:
As you write more of the program, you begin to realize that you
are printing one message, for instance the “Turn printer on” message,
more often than any other message. It seems as if the pr_msg()
function is receiving that message much more often than any
other. This might be the case if you were writing a program that
printed many reports to the printer. You still will use pr_msg() for
other delayed messages, but the “Turn printer on” message is most
frequently used.
Instead of calling the function over and over, typing the same
message each time, you can set up the prototype for pr_msg() so it
defaults to the “Turn printer on” in this way:
void pr_msg(char note[]=”Turn printer on”);// Prototype
List default argument After prototyping pr_msg() with the default argument list, C++
values in the assumes you want to pass “Turn printer on” to the function unless
prototype.
you override the default by passing something else to it. For in-
stance, in main(), you call pr_msg() this way:
pr_msg(); // C++ assumes you mean “Turn printer on”.
416
C++ By
EXAMPLE
argument list takes care of the message and you do not have to pass
the message when you call the function. However, those few times
when you want to pass something else, simply pass a different
message. For example, to make pr_msg() print “Incorrect value” you
type:
pr_msg(“Incorrect value”); // Pass a new message.
TIP: Any time you call a function several times and find
yourself passing that function the same parameters most of the
time, consider using a default argument list.
There are several ways you can call this function. Here are some
samples:
funct1();
417
Chapter 20 ♦ Default Arguments and Function Overloading
Examples
1. Here is a complete program that illustrates the message-
printing function described earlier in this chapter. The main()
function simply calls the delayed message-printing function
three times, each time passing it a different set of argument
lists.
// Filename: C20DEF1.CPP
// Illustrates default argument list.
#include <iostream.h>
void main()
{
pr_msg(); // Prints default message.
pr_msg(“A new message”); // Prints another message.
pr_msg(); // Prints default message again.
return;
}
418
C++ By
EXAMPLE
{
long int delay;
cout << note << “\n”;
for (delay=0; delay<500000; delay++)
{ ; /* Do nothing while waiting */ }
return;
}
Turn printer on
A new message
Turn printer on
// Filename: C20DEF2.CPP
// Demonstrates default argument list with several parameters.
#include <iostream.h>
#include <iomanip.h>
void main()
{
de_fun(); // All defaults used.
de_fun(2); // First default overridden.
de_fun(2, 75037); // First and second default overridden.
de_fun(2, 75037, 35.88); // First, second, and third
de_fun(2, 75037, 35.88, ‘G’); // First, second, third,
// and fourth
de_fun(2, 75037, 35.88, ‘G’, .0023); // No defaulting.
419
Chapter 20 ♦ Default Arguments and Function Overloading
return;
}
Overloaded Functions
Unlike regular C, C++ enables you to have more than one
function with the same name. In other words, you can have three
functions called abs() in the same program. Functions with the same
names are called overloaded functions. C++ requires that each
overloaded function differ in its argument list. Overloaded func-
tions enable you to have similar functions that work on different
types of data.
For example, suppose you wrote a function that returned the
absolute value of whatever number you passed to it. The absolute
value of a number is its positive equivalent. For instance, the
absolute value of 10.25 is 10.25 and the absolute value of –10.25
is 10.25.
Absolute values are used in distance, temperature, and weight
calculations. The difference in the weights of two children is always
420
C++ By
EXAMPLE
Because the code for these two functions differ only in their
parameter lists, they are perfect candidates for overloaded func-
tions. Call both functions abs(), prototype both of them, and code
each of them separately in your program. After overloading the two
functions (each of which works on two different types of parameters
with the same name), you pass your floating-point or integer value
to abs(). The C++ compiler determines which function you wanted
to call.
421
Chapter 20 ♦ Default Arguments and Function Overloading
C++ determines that you want the absi() function called. As far
as you know, C++ is not mangling the names; you never see the
name differences in your program’s source code. However, the
compiler performs the name-mangling so it can keep track of
different functions that have the same name.
422
C++ By
EXAMPLE
Examples
1. Here is the complete absolute value program described in
the previous text. Notice that both functions are prototyped.
(The two prototypes signal C++ that it must perform name-
mangling to determine the correct function names to call.)
// Filename: C20OVF1.CPP
// Overloads two absolute value functions.
#include <iostream.h> // Prototype cout and cin.
#include <iomanip.h> // Prototype setprecision(2).
void main()
{
int ians; // To hold return values.
float fans;
int i = -15; // To pass to the two overloaded functions.
float x = -64.53;
423
Chapter 20 ♦ Default Arguments and Function Overloading
2. As you write more and more C++ programs, you will see
many uses for overloaded functions. The following program
is a demonstration program showing how you can build
your own output functions to suit your needs. main() calls
three functions named output(). Each time it’s called, main()
passes a different value to the function.
When main() passes output() a string, output() prints the
string, formatted to a width (using the setw() manipulator
described in Chapter 7, “Simple Input/Output”) of 30
characters. When main() passes output() an integer, output()
prints the integer with a width of five. When main() passes
output() a floating-point value, output() prints the value to
two decimal places and generalizes the output of different
types of data. You do not have to format your own data.
output() properly formats the data and you only have to
remember one function name that outputs all three types of
data.
// Filename: C20OVF2.CPP
// Outputs three different types of
// data with same function name.
#include <iostream.h>
#include <iomanip.h>
void output(char []); // Prototypes for overloaded functions.
void output(int i);
void output(float x);
424
C++ By
EXAMPLE
void main()
{
char name[] = “C++ By Example makes C++ easy!”;
int ivalue = 2543;
float fvalue = 39.4321;
return;
}
425
Chapter 20 ♦ Default Arguments and Function Overloading
Review Questions
The answers to the review questions are in Appendix B.
1. Where in the program do you specify the defaults for default
argument lists?
2. What is the term for C++ functions that have the same
name?
3. Does name-mangling help support default argument lists or
overloaded functions?
4. True or false: You can specify only a single default
argument.
5. Fix the following prototype for a default argument list.
void my_fun(int i=7, float x, char ch=’A’);
Review Exercises
1. Write a program that contains two functions. The first
function returns the square of the integer passed to it, and
the second function returns the square of the float passed
to it.
2. Write a program that computes net pay based on the values
the user types. Ask the user for the hours worked, the rate
per hour, and the tax rate. Because the majority of employees
work 40 hours per week and earn $5.00 per hour, use these
values as default values in the function that computes the
net pay. If the user presses Enter in response to your ques-
tions, use the default values.
426
C++ By
EXAMPLE
Summary
Default argument lists and overloaded functions speed up
your programming time. You no longer have to specify values for
common arguments. You do not have to remember several different
names for those functions that perform similar routines and differ
only in their data types.
The remainder of this book elaborates on earlier concepts so
you can take advantage of separate, modular functions and local
data. You are ready to learn more about how C++ performs input
and output. Chapter 21, “Device and Character Input/Output,”
teaches you the theory behind I/O in C++, and introduces more
built-in functions.
427
Chapter 20 ♦ Default Arguments and Function Overloading
428
Part V
Character Input/Output and
String Functions
C++ By
21EXAMPLE
Device and
Character
Input/Output
Unlike many programming languages, C++ contains no input or
output commands. C++ is an extremely portable language; a C++
program that compiles and runs on one computer is able also to
compile and run on another type of computer. Most incompatibili-
ties between computers reside in their input/output mechanics.
Each different device requires a different method of performing
I/O (Input/Output).
By putting all I/O capabilities in common functions supplied
with each computer’s compiler, not in C++ statements, the design-
ers of C++ ensured that programs were not tied to specific hardware
for input and output. A compiler has to be modified for every
computer for which it is written. This ensures the compiler works
with the specific computer and its devices. The compiler writers
write I/O functions for each machine; when your C++ program
writes a character to the screen, it works the same whether you have
a color PC screen or a UNIX X/Windows terminal.
This chapter shows you additional ways to perform input and
output of data besides the cin and cout functions you have seen
431
Chapter 21 ♦ Device and Character Input/Output
432
C++ By
EXAMPLE
433
Chapter 21 ♦ Device and Character Input/Output
Standard Devices
Table 21.1 shows a listing of standard I/O devices. C++ always
assumes input comes from stdin, meaning the standard input device.
This is usually the keyboard, although you can reroute this default.
C++ assumes all output goes to stdout, or the standard output device.
There is nothing magic in the words stdin and stdout; however,
many people learn their meanings for the first time in C++.
434
C++ By
EXAMPLE
Examples
1. Suppose you write a program that uses only cin and cout for
input and output. Instead of receiving input from the key-
board, you want the program to get the input from a file
called MYDATA. Because cin receives input from stdin, you
must redirect stdin. After compiling the program in a file
called MYPGM.EXE, you can redirect its input away from
the keyboard with the following DOS command:
C:>MYPGM < MYDATA
435
Chapter 21 ♦ Device and Character Input/Output
The program reads from the file called ANSWERS every time cin
required input.
436
C++ By
EXAMPLE
ofstream uses The following examples show how you can combine cout and
the fstream.h header ofstreamto write to both the screen and printer.
file.
Example
The following program asks the user for his or her first and last
name. It then prints the name, last name first, to the printer.
// Filename: C21FPR1.CPP
// Prints a name on the printer.
#include <fstream.h>
void main()
{
char first[20];
char last[20];
437
Chapter 21 ♦ Device and Character Input/Output
The get() device can be any standard input device. If you were
receiving character input from the keyboard, you use cin as the
device. If you initialize your modem and want to receive characters
from it, use ofstream to open the modem device and read from the
device.
The format of put() is
device.put(char_val);
Examples
1. The following program asks the user for her or his initials a
character at a time. Notice the program uses both cout and
put(). The cout is still useful for formatted output such as
messages to the user. Writing individual characters is best
achieved with put().
The program has to call two get() functions for each char-
acter typed. When you answer a get() prompt by typing a
438
C++ By
EXAMPLE
// Filename: C21CH1.CPP
// Introduces get() and put().
#include <fstream.h>
void main()
{
char in_char; // Holds incoming initial.
char first, last; // Holds converted first and last initial.
439
Chapter 21 ♦ Device and Character Input/Output
// Filename: C21CH2.CPP
// Introduces get() and put() and uses put() to output
newline.
#include <fstream.h>
void main()
{
char in_char; // Holds incoming initial.
char first, last; // Holds converted first and last
// initial.
440
C++ By
EXAMPLE
Buffer
Figure 21.2. get() input goes to a buffer. The buffer is released when
you press Enter.
and use get() for input, the user can press a Y, but the program does
not receive the input until the user also presses Enter. The Y and
Enter then are sent, one character at a time, to the program where it
processes the input. If you want immediate response to a user’s
typing (such as the INKEY$ in BASIC allows), you have to use getch().
441
Chapter 21 ♦ Device and Character Input/Output
Example
When receiving C21CH2.CPP must discard the newline character. It did so by
characters, you assigning the input character—from get()—to an extra variable.
might have to
discard the newline Obviously, the get() returns a value (the character typed). In this
keypress. case, it’s acceptable to ignore the return value by not using the
character returned by get(). You know the user has to press Enter (to
end the input) so it’s acceptable to discard it with an unused get()
function call.
When inputting strings such as names and sentences, cin only
allows one word to be entered at a time. The following string asks the
user for his or her full name with these two lines:
The array names only receives the first name; cin ignores all data
to the right of the first space.
You can build your own input function using get() that doesn’t
have a single-word limitation. When you want to receive a string of
characters from the user, such as his or her first and last name, you
can call the get_in_str() function shown in the next program.
The main() function defines an array and prompts the user for
a name. After the prompt, the program calls the get_in_str() func-
tion and builds the input array a character at a time using get(). The
function keeps looping, using the while loop, until the user presses
Enter (signaled by the newline character, \n, to C++) or until the
maximum number of characters are typed. You might want to use
442
C++ By
EXAMPLE
#include <fstream.h>
void get_in_str(char str[], int len);
void main()
{
char input_str[MAX]; // Keyboard input fills this.
cout << “What is your full name? “;
get_in_str(input_str, MAX); // String from keyboard
cout << “After return, your name is “ << input_str << “\n”;
return;
}
//**********************************************************
// The following function requires a string and the maximum
// length of the string be passed to it. It accepts input
// from the keyboard, and sends keyboard input in the string.
// On return, the calling routine has access to the string.
//**********************************************************
443
Chapter 21 ♦ Device and Character Input/Output
i++; // at a time.
cin.get(input_char); // Receive next character in string.
}
str[i] = ‘\0’; // Make the char array a string.
return;
}
NOTE: The loop checks for len - 1 to save room for the null-
terminating zero at the end of the input string.
and
putch(int_var);
getch() and putch() are not AT&T C++ standard functions, but
getch() and they are usually available with most C++ compilers. getch() and
putch() offer putch() are nonbuffered functions. The putch() character output
nonbuffered input
function is a mirror-image function to getch(); it is a nonbuffered
and output that grab
the user’s characters output function. Because almost every output device made, except
immediately after the for the screen and modem, are inherently buffered, putch() effec-
user types them. tively does the same thing as put().
Another difference in getch() from the other character input
functions is that getch() does not echo the input characters on the
screen as it receives them. When you type characters in response to
get(), you see the characters as you type them (as they are sent to the
buffer). If you want to see characters received by getch(), you must
follow getch() with a putch(). It is handy to echo the characters on the
screen so the user can verify that she or he has typed correctly.
444
C++ By
EXAMPLE
Characters input Some programmers want to make the user press Enter after
with getch() are answering a prompt or selecting from a menu. They feel the extra
not echoed to the
screen as the user time given with buffered input gives the user more time to decide if
types them. she or he wants to give that answer; the user can press Backspace and
correct the input before pressing Enter.
getch() and Other programmers like to grab the user’s response to a single-
putch() use the character answer, such as a menu response, and act on it immedi-
conio.h header file.
ately. They feel that pressing Enter is an added and unneeded
burden for the user so they use getch(). The choice is yours. You
should understand both buffered and nonbuffered input so you can
use both.
Example
The following program shows the getch() and putch() func-
tions. The user is asked to enter five letters. These five letters are
added (by way of a for loop) to the character array named letters.
As you run this program, notice that the characters are not echoed
to the screen as you type them. Because getch() is unbuffered, the
program actually receives each character, adds it to the array, and
loops again, as you type them. (If this were buffered input, the
program would not loop through the five iterations until you
pressed Enter.)
A second loop prints the five letters using putch(). A third loop
prints the five letters to the printer using put().
// Filename: C21GCH1.CPP
// Uses getch() and putch() for input and output.
#include <fstream.h>
445
Chapter 21 ♦ Device and Character Input/Output
#include <conio.h>
void main()
{
int ctr; // for loop counter
char letters[5]; // Holds five input characters. No
// room is needed for the null zero
// because this array never will be
// treated as a string.
cout << “Please type five letters... \n”;
for (ctr = 0; ctr < 5; ctr++)
{
letters[ctr] = getch(); // Add input to array.
}
for (ctr = 0; ctr < 5; ctr++) // Print them to screen.
{
putch(letters[ ctr ]);
}
ofstream prn(“PRN”);
for (ctr = 0; ctr < 5; ctr++) // Print them to printer.
{
prn.put(letters[ ctr ]);
}
return;
}
When you run this program, do not press Enter after the five
letters. The getch() function does not use the Enter. The loop auto-
matically ends after the fifth letter because of the unbuffered input
and the for loop.
Review Questions
The answers to the review questions are found in Appendix B.
1. Why are there no input or output commands in C++?
2. True or false: If you use the character I/O functions to send
output to stdout, it always goes to the screen.
446
C++ By
EXAMPLE
Review Exercises
1. Write a program that asks the user for five letters and prints
them in reverse order to the screen, and then to the printer.
2. Write a miniature typewriter program, using get() and put().
In a loop, get characters until the user presses Enter while he
or she is getting a line of user input. Write the line of user
input to the printer. Because get() is buffered, nothing goes
to the printer until the user presses Enter at the end of each
line of text. (Use the string-building input function shown in
C21IN.CPP.)
3. Add a putch() inside the first loop of C21CH1.CPP (this
chapter’s first get() example program) so the characters are
echoed to the screen as the user types them.
4. A palindrome is a word or phrase spelled the same forwards
and backwards. Two example palindromes are
447
Chapter 21 ♦ Device and Character Input/Output
Write a C++ program that asks the user for a phrase. Build
the input, a character at a time, using a character input
function such as get(). Once you have the full string (store it
in a character array), determine whether the phrase is a
palindrome. You have to filter special characters (nonalpha-
betic), storing only alphabetic characters to a second charac-
ter array. You also must convert the characters to uppercase
as you store them. The first palindrome becomes:
MADAMIMADAM
Using one or more for or while loops, you can now test the
phrase to determine whether it is a palindrome. Print the
result of the test on the printer. Sample output should look
like:
“Madam, I’m Adam” is a palindrome.
Summary
You now should understand the generic methods C++ pro-
grams use for input and output. By writing to standard I/O devices,
C++ achieves portability. If you write a program for one computer,
it works on another. If C++ were to write directly to specific
hardware, programs would not work on every computer.
If you still want to use the formatted I/O functions, such as cout,
you can do so. The ofstream() function enables you to write format-
ted output to any device, including the printer.
The methods of character I/O might seem primitive, and they
are, but they give you the flexibility to build and create your own
input functions. One of the most often-used C++ functions, a string-
building character I/O function, was demonstrated in this chapter
(the C21IN.CPP program).
The next two chapters (Chapter 22, “Character, String, and
Numeric Functions,” and Chapter 23, “Introducing Arrays”) intro-
duce many character and string functions, including string I/O
functions. The string I/O functions build on the principles pre-
sented here. You will be surprised at the extensive character and
string manipulation functions available in the language as well.
448
C++ By
22EXAMPLE
Character, String,
and Numeric
Functions
C++ provides many built-in functions in addition to the cout, getch(),
and strcpy() functions you have seen so far. These built-in functions
increase your productivity and save you programming time. You
don’t have to write as much code because the built-in functions
perform many useful tasks for you.
This chapter introduces you to
♦ Character conversion functions
♦ Character and string testing functions
♦ String manipulation functions
♦ String I/O functions
♦ Mathematical, trigonometric, and logarithmic functions
♦ Random-number processing
449
Chapter 22 ♦ Character, String, and Numeric Functions
Character Functions
This section explores many of the character functions available
in AT&T C++. Generally, you pass character arguments to the
functions, and the functions return values that you can store or print.
By using these functions, you off-load much of your work to C++
and allow it to perform the more tedious manipulations of character
and string data.
450
C++ By
EXAMPLE
451
Chapter 22 ♦ Character, String, and Numeric Functions
Example
The following program asks users for their initials. If a user
types anything but alphabetic characters, the program displays an
error and asks again.
Identify the program and include the input/output header files. The
program asks the user for his or her first initial, so declare the character
variable initial to hold the user’s answer.
1. Ask the user for her or his first initial, and retrieve the user’s answer.
2. If the answer was not an alphabetic character, tell the user this and
repeat step one.
Print a thank-you message on-screen.
// Filename: C22INI.CPP
// Asks for first initial and tests
// to ensure that response is correct.
#include <iostream.h>
#include <ctype.h>
void main()
{
char initial;
cout << “What is your first initial? “;
cin >> initial;
while (!isalpha(initial))
{
cout << “\nThat was not a valid initial! \n”;
cout << “\nWhat is your first initial? “;
cin >> initial;
}
This use of the not operator (!) is quite clear. The program
continues to loop as long as the entered character is not alphabetic.
452
C++ By
EXAMPLE
Special Character-Testing
Functions
A few character functions become useful when you have to
read from a disk file, a modem, or another operating system device
that you route input from. These functions are not used as much as
the character functions you saw in the previous section, but they are
useful for testing specific characters for readability.
The character-testing The remaining character-testing functions follow:
functions do not
change characters. ♦ iscntrl(c):Returns True (nonzero) if c is a control character
(any character from the ASCII table numbered 0 through 31).
Returns False (zero) if c is not a control character.
♦ isgraph(c):Returns True (nonzero) if c is any printable
character (a noncontrol character) except a space. Returns
False (zero) if c is a space or anything other than a printable
character.
♦ isprint(c):Returns True (nonzero) if c is a printable charac-
ter (a noncontrol character) from ASCII 32 to ASCII 127,
including a space. Returns False (zero) if c is not a printable
character.
♦ ispunct(c): Returns True (nonzero) if c is any punctuation
character (any printable character other than a space, a letter,
or a digit). Returns False (zero) if c is not a punctuation
character.
♦ isspace(c): Returns True (nonzero) if c is a space, newline
(\n), carriage return (\r), tab (\t), or vertical tab (\v) charac-
ter. Returns False (zero) if c is anything else.
453
Chapter 22 ♦ Character, String, and Numeric Functions
Example
Here is a program that prints an appropriate message if the user
is a girl or a boy. The program tests for G and B after converting the
user’s input to uppercase. No check for lowercase has to be done.
Identify the program and include the input/output header files. The
program asks the user a question requiring an alphabetic answer, so declare
the character variable ans to hold the user’s response.
Ask whether the user is a girl or a boy, and store the user’s answer in ans.
The user must press Enter, so incorporate and then discard the Enter
keypress. Change the value of ans to uppercase. If the answer is G, print a
message. If the answer is B, print a different message. If the answer is
something else, print another message.
// Filename: C22GB.CPP
// Determines whether the user typed a G or a B.
#include <iostream.h>
#include <conio.h>
#include <ctype.h>
void main()
{
454
C++ By
EXAMPLE
char ans; // Holds user’s response.
cout << “Are you a girl or a boy (G/B)? “;
ans=getch(); // Get answer.
getch(); // Discard newline.
cout <<ans<<“\n”;
ans = toupper(ans); // Convert answer to uppercase.
switch (ans)
{ case (‘G’): { cout << “You look pretty today!\n”;
break; }
case (‘B’): { cout << “You look handsome today!\n”;
break; }
default : { cout << “Your answer makes no sense!\n”;
break; }
}
return;
}
String Functions
Some of the most powerful built-in C++ functions are the string
functions. They perform much of the tedious work for which you
have been writing code so far, such as inputting strings from the
keyboard and comparing strings.
As with the character functions, there is no need to “reinvent
the wheel” by writing code when built-in functions do the same task.
Use these functions as much as possible.
Now that you have a good grasp of the foundations of C++, you
can master the string functions. They enable you to concentrate on
your program’s primary purpose, rather than spend time coding
your own string functions.
455
Chapter 22 ♦ Character, String, and Numeric Functions
The string functions String functions that test or manipulate strings follow:
work on string
literals or on ♦ strcat(s1, s2): Concatenates (merges) the s2 string to the end
character arrays that of the s1 character array. The s1 array must have enough
contain strings. reserved elements to hold both strings.
♦ strcmp(s1, s2): Compares the s1 string with the s2 string on
an alphabetical, element-by-element basis. If s1 alphabetizes
before s2, strcmp() returns a negative value. If s1 and s2 are
the same strings, strcmp() returns 0. If s1 alphabetizes after
s2, strcmp() returns a positive value.
456
C++ By
EXAMPLE
457
Chapter 22 ♦ Character, String, and Numeric Functions
input would not be a string.) When you output a string, the null
zero at the end of the string becomes a newline character. This is
preferred because a newline is at the end of a line of output and the
cursor begins automatically on the next line.
Because fgets() and fputs() can input and output strings from
devices such as disk files and telephone modems, it can be critical
that the incoming newline characters are retained for the data’s
integrity. When outputting strings to these devices, you do not want
C++ inserting extra newline characters.
458
C++ By
EXAMPLE
Example
The following program shows you how easy it is to use gets()
and puts(). The program requests the name of a book from the user
using a single gets() function call, then prints the book title with
puts().
Identify the program and include the input/output header files. The
program asks the user for the name of a book. Declare the character array
book with 30 elements to hold the user’s answer.
Ask the user for the book’s title, and store the user’s response in the book
array. Display the string stored in book to an output device, probably your
screen. Print a thank-you message.
// C22GPS1.CPP
// Inputs and outputs strings.
#include <iostream.h>
#include <stdio.h>
#include <string.h>
void main()
{
char book[30];
459
Chapter 22 ♦ Character, String, and Numeric Functions
The string must contain a valid number. Here is a string that can
be converted to an integer:
“1232”
The string must hold a string of digits short enough to fit in the
target numeric data type. The following string could not be con-
verted to an integer with the atoi() function:
“-1232495.654”
460
C++ By
EXAMPLE
Numeric Functions
This section presents many of the built-in C++ numeric func-
tions. As with the string functions, these functions save you time by
converting and calculating numbers instead of your having to write
functions that do the same thing. Many of these are trigonometric
and advanced mathematical functions. You might use some of these
numeric functions only rarely, but they are there if you need them.
This section concludes the discussion of C++’s standard built-
in functions. After mastering the concepts in this chapter, you are
ready to learn more about arrays and pointers. As you develop more
skills in C++, you might find yourself relying on these numeric,
string, and character functions when you write more powerful
programs.
These numeric Here are the functions listed with their descriptions:
functions return
double-precision ♦ ceil(x):The ceil(), or ceiling, function rounds numbers up to
values. the nearest integer.
♦ fabs(x):Returns the absolute value of x. The absolute value
of a number is its positive equivalent.
461
Chapter 22 ♦ Character, String, and Numeric Functions
462
C++ By
EXAMPLE
Example
The following program uses the fabs() function to compute the
difference between two ages.
// Filename: C22ABS.CPP
// Computes the difference between two ages.
#include <iostream.h>
#include <math.h>
void main()
{
float age1, age2, diff;
cout << “\nWhat is the first child’s age? “;
cin >> age1;
cout << “What is the second child’s age? “;
cin >> age2;
463
Chapter 22 ♦ Character, String, and Numeric Functions
The output from this program follows. Due to fabs(), the order
of the ages doesn’t matter. Without absolute value, this program
would produce a negative age difference if the first age was less than
the second. Because the ages are relatively small, floating-point
variables are used in this example. C++ automatically converts
floating-point arguments to double precision when passing them to
fabs().
Trigonometric Functions
The following functions are available for trigonometric appli-
cations:
♦ cos(x): Returns the cosine of the angle x, expressed in radians.
♦ sin(x): Returns the sine of the angle x, expressed in radians.
♦ tan(x): Returns the tangent of the angle x, expressed in radians.
These are probably the least-used functions. This is not to
belittle the work of scientific and mathematical programmers who
need them, however. Certainly, they are grateful that C++ supplies
these functions! Otherwise, programmers would have to write their
own functions to perform these three basic trigonometric calcula-
tions.
Most C++ compilers supply additional trigonometric func-
tions, including hyperbolic equivalents of these three functions.
464
C++ By
EXAMPLE
Logarithmic Functions
Three highly mathematical functions are sometimes used in
business and mathematics. They are listed as follows:
♦ exp(x): Returns the base of natural logarithm (e) raised to a
power specified by x (ex); e is the mathematical expression
for the approximate value of 2.718282.
♦ log(x):
Returns the natural logarithm of the argument x,
mathematically written as ln(x). x must be positive.
♦ log10(x):
Returns the base-10 logarithm of argument x,
mathematically written as log10(x). x must be positive.
Random-Number Processing
Random events happen every day. You wake up and it is sunny
or rainy. You have a good day or a bad day. You get a phone call from
an old friend or you don’t. Your stock portfolio might go up or down
in value.
Random events are especially important in games. Part of the
fun in games is your luck with rolling dice or drawing cards,
combined with your playing skills.
Simulating random events is an important task for computers.
Computers, however, are finite machines; given the same input,
they always produce the same output. This fact can create some
boring games!
The rand() The designers of C++ knew this computer setback and found a
function produces way to overcome it. They wrote a random-number generating
random integer
numbers.
function called rand(). You can use rand() to compute a dice roll or
draw a card, for example.
To call the rand() function and assign the returned random
number to test, use the following syntax:
test = rand();
465
Chapter 22 ♦ Character, String, and Numeric Functions
however, rand() returns the same set of random numbers. One way
to receive a different set of random numbers is to call the srand()
function. The format of srand() follows:
srand(seed);
466
C++ By
EXAMPLE
Review Questions
The answers to the review questions are in Appendix B.
1. How do the character testing functions differ from the
character conversion functions?
2. What are the two string input functions?
3. What is the difference between floor() and ceil()?
4. What does the following nested function return?
isalpha(islower(‘s’));
5. If the character array str1 contains the string Peter and the
character array str2 contains Parker, what does str2 contain
after the following line of code executes?
strcat(str1, str2);
467
Chapter 22 ♦ Character, String, and Numeric Functions
Review Exercises
1. Write a program that asks users for their ages. If a user types
anything other than two digits, display an error message.
2. Write a program that stores a password in a character array
called pass. Ask users for the password. Use strcmp() to
inform users whether they typed the proper password. Use
the string I/O functions for all the program’s input and
output.
3. Write a program that rounds up and rounds down the
numbers –10.5, –5.75, and 2.75.
4. Ask users for their names. Print every name in reverse case;
print the first letter of each name in lowercase and the rest of
the name in uppercase.
5. Write a program that asks users for five movie titles. Print
the longest title. Use only the string I/O and manipulation
functions presented in this chapter.
6. Write a program that computes the square root, cube root,
and fourth root of the numbers from 10 to 25, inclusive.
468
C++ By
EXAMPLE
7. Ask users for the titles of their favorite songs. Discard all the
special characters in each title. Print the words in the title,
one per line. For example, if they enter My True Love Is Mine,
Oh, Mine!, you should output the following:
My
True
Love
Is
Mine
Oh
Mine
Summary
You have learned the character, string, and numeric functions
that C++ provides. By including the ctype.h header file, you can test
and convert characters that a user types. These functions have many
useful purposes, such as converting a user’s response to uppercase.
This makes it easier for you to test user input.
The string I/O functions give you more control over both string
and numeric input. You can receive a string of digits from the
keyboard and convert them to a number with the ato() functions.
The string comparison and concatenation functions enable you to
test and change the contents of more than one string.
Functions save you programming time because they take over
some of your computing tasks, leaving you free to concentrate on
your programs. C++’s numeric functions round and manipulate
numbers, produce trigonometric and logarithmic results, and pro-
duce random numbers.
Now that you have learned most of C++’s built-in functions,
you are ready to improve your ability to work with arrays. Chap-
ter 23, “Introducing Arrays,” extends your knowledge of character
arrays and shows you how to produce arrays of any data type.
469
Chapter 22 ♦ Character, String, and Numeric Functions
470
Part VI
Arrays and Pointers
C++ By
23EXAMPLE
Introducing Arrays
This chapter discusses different types of arrays. You are already
familiar with character arrays, which are the only method for storing
character strings in the C++ language. A character array isn’t the
only kind of array you can use, however. There is an array for every
data type in C++. By learning how to process arrays, you greatly
improve the power and efficiency of your programs.
This chapter introduces
♦ Array basics of names, data types, and subscripts
♦ Initializing an array at declaration time
♦ Initializing an array during program execution
♦ Selecting elements from arrays
The sample programs in these next few chapters are the most
advanced that you have seen in this book. Arrays are not difficult to
use, but their power makes them well-suited to more advanced
programming.
473
Chapter 23 ♦ Introducing Arrays
Array Basics
An array is a list of Although you have seen arrays used as character strings, you
more than one still must have a review of arrays in general. An array is a list of more
variable having the
same name.
than one variable having the same name. Not all lists of variables are
arrays. The following list of four variables, for example, does not
qualify as an array.
sales bonus_92 first_initial ctr
or
char name[11] = “Ray Krebbs”;
Because C++ reserves an extra element for the null zero at the
end of every string, you don’t have to specify the 11 as long as you
initialize the array with a value. The variable name is an array because
brackets follow its name. The array has a single name, name, and it
contains 11 elements. The array is stored in memory, as shown in
Figure 23.1. Each element is a character.
474
C++ By
EXAMPLE
You can define an array as any data type in C++. You can have
integer arrays, long integer arrays, double floating-point arrays,
short integer arrays, and so on. C++ recognizes that the brackets []
following the array name signify that you are defining an array, and
not a single nonarray variable.
The following line defines an array called ages, consisting of
five integers:
int ages[5];
The first element in the ages array is ages[0]. The second element
is ages[1], and the last one is ages[4]. This declaration of ages does not
assign values to the elements, so you don’t know what is in ages and
your program does not automatically zero ages for you.
Here are some more array definitions:
475
Chapter 23 ♦ Introducing Arrays
ara[4]
sales[ctr+1]
bonus[month]
salary[month[i]*2]
476
C++ By
EXAMPLE
Figure 23.2 shows how C++ reserves memory for these arrays.
The figure assumes a two-byte integer size, although this might
differ on some computers. Notice that C++ reserves five elements
for exemptions from the array declaration. C++ starts reserving
memory for sal_codes after it reserves all five elements for exemptions.
If you declare several more variables—either locally or globally—
after these two lines, C++ always protects these reserved five
elements for exemptions and sal_codes.
C++ protects only as Because C++ does its part to protect data in the array, so must
many array elements you. If you reserve five elements for exemptions, you have five inte-
as you specify.
ger array elements referred to as exemptions[0], exemptions[1],
exemptions[2], exemptions[3], and exemptions[4]. C++ does not protect
477
Chapter 23 ♦ Introducing Arrays
more than five elements for exemptions! Suppose you put a value in
an exemptions element you did not reserve:
Although you can define an array of any data type, you cannot
declare an array of strings. A string is not a C++ variable data type.
You learn how to hold multiple strings in an array-like structure in
Chapter 27, “Pointers and Arrays.”
478
C++ By
EXAMPLE
Initializing Arrays
You must assign values to array elements before using them.
Here are the two ways to initialize elements in an array:
♦ Initialize the elements at declaration time
♦ Initialize the elements in the program
Initializing Elements
at Declaration Time
You already know how to initialize character arrays that hold
strings when you define the arrays: You simply assign them a string.
For example, the following declaration reserves six elements in a
character array called city:
char city[6]; // Reserve space for city.
If you want also to initialize city with a value, you can do it like
this:
479
Chapter 23 ♦ Introducing Arrays
The array initials is not a string! Its data does not end in a null
zero. There is nothing wrong with defining an array of characters
such as this one, but you must remember that you cannot treat the
array as if it were a string. Do not use string functions with it, or
attempt to print the array with cout.
By using brackets, you can initialize any type of array. For
example, if you want to initialize an integer array that holds your
five children’s ages, you can do it with the following declaration:
480
C++ By
EXAMPLE
child–ages
Integers
sales
Floating-points
C++ assigns zero Although C++ does not automatically initialize the array ele-
nulls to all array ments, if you initialize some but not all the elements when you
values that you do
not define explicitly declare the array, C++ finishes the job for you by assigning the
at declaration time. remainder to zero.
67654.43
46472.34
63451.93
00000.00
00000.00
00000.00
481
Chapter 23 ♦ Introducing Arrays
C++ does not know how many elements to reserve for count, so
it reserves none. If you then assign values to count’s nonreserved
elements, you can (and probably will) overwrite other data.
The only time you can leave the brackets empty is if you also
assign values to the array, such as the following:
int count[] = {15, 9, 22, -8, 12}; // Good definition.
C++ can determine, from the list of values, how many elements
to reserve. In this case, C++ reserves five elements for count.
Examples
1. Suppose you want to track the stock market averages for the
previous 90 days. Instead of storing them in 90 different
variables, it is much easier to store them in an array. You can
declare the array like this:
float stock[90];
// Filename: C23ARA1.CPP
// Averages six test scores.
#include <iostream.h>
#include <iomanip.h>
void main()
482
C++ By
EXAMPLE
{
char s_name[] = “Tri Star University”;
float scores[6] = {88.7, 90.4, 76.0, 97.0, 100.0, 86.7};
float average=0.0;
int ctr;
// Filename: C23ARA2.CPP
// Prints and averages six test scores.
#include <iostream.h>
#include <iomanip.h>
void pr_scores(float scores[]); // Prototype
483
Chapter 23 ♦ Introducing Arrays
void main()
{
char s_name[] = “Tri Star University”;
float scores[6] = {88.7, 90.4, 76.0, 97.0, 100.0, 86.7};
float average=0.0;
int ctr;
484
C++ By
EXAMPLE
// Filename: C23ARA3.CPP
// Prints and averages six test scores.
#include <iostream.h>
#include <iomanip.h>
void pr_scores(float scores[]);
const int CLASS_NUM = 6; // Constant holds array size.
void main()
{
char s_name[] = “Tri Star University”;
float scores[CLASS_NUM] = {88.7, 90.4, 76.0, 97.0,
100.0, 86.7};
float average=0.0;
int ctr;
485
Chapter 23 ♦ Introducing Arrays
{
// Prints the six scores.
int ctr;
486
C++ By
EXAMPLE
Rather, you have to copy the arrays one element at a time, using
a loop, such as the following section of code does:
You want to copy one array to another. You have to do so one element at a
time, so you need a counter. Initialize a variable called ctr to 0; the value of
ctr represents a position in the array.
1. Assign the element that occupies the position in the first array
represented by the value of ctr to the same position in the second
array.
2. If the counter is less than the size of the array, add one to the
counter. Repeat step one.
Examples
1. The following program uses the assignment operator to
assign 10 temperatures to an array.
// Filename: C23ARA4.CPP
// Fills an array with 10 temperature values.
#include <iostream.h>
#include <iomanip.h>
const int NUM_TEMPS = 10;
void main()
{
float temps[NUM_TEMPS];
int ctr;
487
Chapter 23 ♦ Introducing Arrays
temps[5] = 71.8;
temps[6] = 73.3;
temps[7] = 69.5;
temps[8] = 74.1;
temps[9] = 75.7;
return;
}
// Filename: C23TOT.CPP
// Totals eight input values from the user.
#include <iostream.h>
const int NUM = 8;
void main()
{
int nums[NUM];
int total = 0; // Holds total of user’s eight numbers.
int ctr;
cout << “The total of the numbers is “ << total << “\n”;
return;
}
488
C++ By
EXAMPLE
// Filename: C23SAL.CPP
// Stores twelve months of sales and
// prints selected ones.
#include <iostream.h>
#include <ctype.h>
#include <conio.h>
#include <iomanip.h>
const int NUM = 12;
void main()
{
float sales[NUM];
int ctr, ans;
int req_month; // Holds user’s request.
489
Chapter 23 ♦ Introducing Arrays
490
C++ By
EXAMPLE
Review Questions
Answers to the review questions are in Appendix B.
1. True or false: A single array can hold several values of
different data types.
2. How do C++ programs tell one array element from another
if all elements have identical names?
3. Why must you initialize an array before using it?
4. Given the following definition of an array, called weights,
what is the value of weights[5]?
int weights[10] = {5, 2, 4};
Review Exercises
1. Write a program to store the ages of six of your friends in a
single array. Store each of the six ages using the assignment
operator. Print the ages on-screen.
2. Modify the program in Exercise 1 to print the ages in reverse
order.
3. Write a simple data program to track a radio station’s ratings
(1, 2, 3, 4, or 5) for the previous 18 months. Use cin to initial-
ize the array with the ratings. Print the ratings on-screen
with an appropriate title.
4. Write a program to store the numbers from 1 to 100 in an
array of 100 integer elements. (Hint: The subscripts should
begin at 0 and end at 99.)
491
Chapter 23 ♦ Introducing Arrays
Summary
You now know how to declare and initialize arrays consisting
of various data types. You can initialize an array either when you
declare it or in the body of your program. Array elements are much
easier to process than other variables because each has a different
name.
C++ has powerful sorting and searching techniques that make
your programs even more serviceable. The next chapter introduces
these techniques and shows you still other ways to access array
elements.
492
C++ By
10EXAMPLE
Logical Operators
C++’s logical operators enable you to combine relational operators
into more powerful data-testing statements. The logical operators
are sometimes called compound relational operators. As C++’s prece-
dence table shows, relational operators take precedence over logical
operators when you combine them. The precedence table plays an
important role in these types of operators, as this chapter empha-
sizes.
This chapter introduces you to
♦ The logical operators
♦ How logical operators are used
♦ How logical operators take precedence
This chapter concludes your study of the conditional testing
that C++ enables you to perform, and it illustrates many examples
of if statements in programs that work on compound conditional
tests.
207
Chapter 10 ♦ Logical Operators
The first two logical operators, && and ||, never appear by
themselves. They typically go between two or more relational tests.
Logical operators Table 10.2 shows you how each logical operator works. These
enable the user to tables are called truth tables because they show you how to achieve
compute compound
relational tests. True results from an if statement that uses these operators. Take
some time to study these tables.
208
C++ By
EXAMPLE
If the variable a is less than the variable b, and the variable c is greater than
the variable d, then print Results are invalid. to the screen.
The variable a must be less than b and, at the same time, c must
be greater than d for the printf() to execute. The if statement still
requires parentheses around its complete conditional test. Consider
this portion of a program:
The || is The sales must be more than 5000, or the hrs_worked must be
sometimes called more than 81, before the assignment executes.
inclusive OR. Here is
a program segment
if (!(sales < 2500))
that includes the not
(!) operator: { bonus = 500; }
209
Chapter 10 ♦ Logical Operators
Internal Truths
The True or False results of relational tests occur internally at
the bit level. For example, take the if test:
if (a == 6) ...
210
C++ By
EXAMPLE
C++ only evaluates the first condition, (5 > 4), and realizes it does
not have to look further. Because (5 > 4) is True and because || (OR)
anything that follows it is still True, C++ does not bother with the
rest of the expression. The same holds true for the following state-
ment:
if ((7 < 3) && (age > 15) && (initial == ‘D’))...
inventory_flag) = ‘Y’;
if ((sales > old_sales) || (inventory_flag))...
211
Chapter 10 ♦ Logical Operators
Examples
1. The summer Olympics are held every four years during each
year that is divisible evenly by 4. The U.S. Census is taken
every 10 years, in each year that is evenly divisible by 10.
The following short program asks for a year, and then tells
the user if it is a year of the summer Olympics, a year of the
census, or both. It uses relational operators, logical opera-
tors, and the modulus operator to determine this output.
// Filename: C10YEAR.CPP
// Determines if it is Summer Olympics year,
// U.S. Census year, or both.
#include <iostream.h>
main()
{
int year;
// Ask for a year
cout << “What is a year for the test? “;
cin >> year;
212
C++ By
EXAMPLE
// Filename: C10AGE.CPP
// Program that helps ensure age values are reasonable.
#include <iostream.h>
main()
{
int age;
213
Chapter 10 ♦ Logical Operators
// Filename: C10VIDEO.CPP
// Program that computes video rental amounts and gives
// appropriate discounts based on the day or customer status.
#include <iostream.h>
#include <stdio.h>
main()
{
float tape_charge, discount, rental_amt;
char first_name[15];
char last_name[15];
int num_tapes;
char val_day, sp_stat;
tape_charge = 2.00;
// Before-discount tape fee-per tape.
214
C++ By
EXAMPLE
discount = 0.0; // Increase discount if they are eligible.
if ((val_day == ‘Y’) || (sp_stat == ‘Y’))
{ discount = 0.5;
rental_amt=(num_tapes*tape_charge)
(discount*num_tapes); }
** Rental Club **
215
Chapter 10 ♦ Logical Operators
This still might be confusing, but it is less so. The two multipli-
cations are performed first, followed by the relations < and >. The &&
is performed last because it is lowest in the precedence order of
operators.
To avoid such ambiguous problems, be sure to use ample
parentheses—even if the default precedence order is your intention.
It is also wise to resist combining too many expressions inside a
single if relational test.
Notice that || (OR) has lower precedence than && (AND).
Therefore, the following if tests are equivalent:
216
C++ By
EXAMPLE
Review Questions
The answers to the review questions are in Appendix B.
1. What are the three logical operators?
2. The following compound relational tests produce True or
False comparisons. Determine which are True and which are
False.
a. ! (True || False)
b. 12 - i || k
c. j != k && i != k
// Filename: C10LOGO.CPP
// Logical operator test
#include <iostream.h>
main()
{
int f, g;
g = 5;
f = 8;
if ((g = 25) || (f = 35))
217
Chapter 10 ♦ Logical Operators
b. 8 + 9 != 6 - 1 || 10 % 2 != 5 + 0
c. 17 - 1 > 15 + 1 && 0 + 2 != 1 == 1 || 4 != 1
if (!0)
{ cout << “C++ By Example \n”; }
Review Exercises
1. Write a program (by using a single compound if state-
ment) to determine whether the user enters an odd positive
number.
2. Write a program that asks the user for two initials. Print a
message telling the user if the first initial falls alphabetically
before the second.
3. Write a number-guessing game. Assign a value to a variable
called number at the top of the program. Give a prompt that
asks for five guesses. Receive the user’s five guesses with a
single scanf() for practice with scanf(). Determine whether
any of the guesses match the number and print an appropriate
message if one does.
4. Write a tax-calculation routine, as follows: A family pays no
tax if its income is less than $5,000. It pays a 10 percent tax if
its income is $5,000 to $9,999, inclusive. It pays a 20 percent
tax if the income is $10,000 to $19,999, inclusive. Otherwise,
it pays a 30 percent tax.
218
C++ By
EXAMPLE
Summary
This chapter extended the if statement to include the &&, ||, and
! logical operators. These operators enable you to combine several
relational tests into a single test. C++ does not always have to
look at every relational operator when you combine them in an ex-
pression.
This chapter concludes the explanation of the if statement. The
next chapter explains the remaining regular C++ operators. As you
saw in this chapter, the precedence table is still important to the C++
language. Whenever you are evaluating expressions, keep the pre-
cedence table in the back of your mind (or at your fingertips) at all
times!
219
Chapter 10 ♦ Logical Operators
220
C++ By
11EXAMPLE
Additional C++
Operators
C++ has several other operators you should learn besides those you
learned in Chapters 9 and 10. In fact, C++ has more operators than
most programming languages. Unless you become familiar with
them, you might think C++ programs are cryptic and difficult to
follow. C++’s heavy reliance on its operators and operator prece-
dence produces the efficiency that enables your programs to run
more smoothly and quickly.
This chapter teaches you the following:
♦ The ?: conditional operator
♦ The ++ increment operator
♦ The –– decrement operator
♦ The sizeof operator
♦ The (,) comma operator
♦ The Bitwise Operators (&, |, and ^)
221
Chapter 11 ♦ Additional C++ Operators
222
C++ By
EXAMPLE
if (a > b)
{ ans = 10; }
else
{ ans = 25; }
You can easily rewrite this kind of if-else code by using a single
conditional operator.
If the variable a is greater than the variable b, make the variable ans
equal to 10; otherwise, make ans equal to 25.
a > b ? (ans = 10) : (ans = 25);
223
Chapter 11 ♦ Additional C++ Operators
Examples
1. Suppose you are looking over your early C++ programs, and
you notice the following section of code.
224
C++ By
EXAMPLE
if (testvar < 0)
{ sign = -1; }
else
{ sign = (testvar > 0); } // testvar can only be
// 0 or more here.
++ ++i; prefix i = i + 1; i += 1;
–– i––; postfix i = i - 1; i -= 1;
–– ––i; prefix i = i - 1; i -= 1;
225
Chapter 11 ♦ Additional C++ Operators
Whether you use prefix or postfix does not matter—if you are
incrementing or decrementing single variables on lines by them-
selves. However, when you combine these two operators with other
operators in a single expression, you must be aware of their differ-
ences. Consider the following program section. Here, all variables
are integers because the increment and decrement operators work
only on integer variables.
Make a equal to 6. Increment a, subtract 1 from it, then assign the result
to b.
a = 6;
b = ++a - 1;
What are the values of a and b after these two statements finish?
The value of a is easy to determine: it is incremented in the second
statement, so it is 7. However, b is either 5 or 6 depending on when
the variable a increments. To determine when a increments, consider
the following rule:
226
C++ By
EXAMPLE
a = 6;
b = a++ - 1;
a = 6;
b = a - 1;
a++;
227
Chapter 11 ♦ Additional C++ Operators
There are too many unneeded parentheses here, but even the
redundant parentheses are not enough to increment amt before
adding its value to p. Postfix increments and decrements always
occur after their variables are used in the surrounding expression.
Examples
1. As you should with all other C++ operators, keep the prece-
dence table in mind when you evaluate expressions that
increment and decrement. Figures 11.2 and 11.3 show you
some examples that illustrate these operators.
2. The precedence table takes on even more meaning when you
see a section of code such as that shown in Figure 11.3.
3. Considering the precedence table—and, more importantly,
what you know about C++’s relational efficiencies—what is
the value of the ans in the following section of code?
228
C++ By
EXAMPLE
ans = i || j–– && k++ || ++l && ++m || n–– & !o || p––;
|
1 (TRUE)
int i=1;
int j=2;
int k=3;
ans = i++ * j - ––k;
|
i++ * j - 2
2 - 2
int i=1;
int j=2;
int k=3;
ans = ++i * j - k––;
|
2 * j - k––
4 - k––
229
Chapter 11 ♦ Additional C++ Operators
int i=0;
int j=-1;
int k=0;
int m=1
ans = i++ && ++j || k || m++;
|
i++ && 0 || k || m++
0 || k || m++
0 || m++
230
C++ By
EXAMPLE
or
sizeof(data type)
Examples
1. Suppose you want to know the size, in bytes, of floating-
point variables for your computer. You can determine
this by entering the keyword float in parentheses—after
sizeof—as shown in the following program.
231
Chapter 11 ♦ Additional C++ Operators
// Filename: C11SIZE1.CPP
// Prints the size of floating-point values.
#include <iostream.h>
main()
{
cout << “The size of floating-point variables on \n”;
cout << “this computer is “ << sizeof(float) << “\n”;
return 0;
}
main()
{
int i=10, j=25;
// Remainder of the program follows.
232
C++ By
EXAMPLE
Examples
1. You can put more than one expression on a line, using the
comma as a sequence point. The following program does
this.
// Filename: C11COM1.CPP
// Illustrates the sequence point.
#include <iostream.h>
main()
{
int num, sq, cube;
num = 5;
233
Chapter 11 ♦ Additional C++ Operators
i = 10
j = (i = 12, i + 8);
Bitwise Operators
The bitwise operators manipulate internal representations of
data and not just “values in variables” as the other operators do.
These bitwise operators require an understanding of Appendix A’s
binary numbering system, as well as a computer’s memory. This
section introduces the bitwise operators. The bitwise operators are
used for advanced programming techniques and are generally used
in much more complicated programs than this book covers.
Some people program in C++ for years and never learn the
bitwise operators. Nevertheless, understanding them can help you
improve a program’s efficiency and enable you to operate at a more
advanced level than many other programming languages allow.
234
C++ By
EXAMPLE
0 & 1 = 0
1 & 0 = 0
1 & 1 = 1
continues
235
Chapter 11 ♦ Additional C++ Operators
0 | 1 = 1
1| 0 = 1
1 | 1 = 1
0 ^ 1 = 1
1 ^ 0 = 1
1 ^ 1 = 0
~1 = 0
In bitwise truth tables, you can replace the 1 and 0 with True
and False, respectively, if it helps you to understand the result better.
For the bitwise AND (&) truth table, both bits being compared by the
& operator must be True for the result to be True. In other words,
“True AND True results in True.”
TIP: By replacing the 1s and 0s with True and False, you might
be able to relate the bitwise operators to the regular logical
operators, && and ||, that you use for if comparisons.
For bitwise ^, one The | bitwise operator is sometimes called the bitwise inclusive
side or the other— OR operator. If one side of the | operator is 1 (True)—or if both sides
but not both—must
be 1.
are 1—the result is 1 (True).
The ^ operator is called bitwise exclusive OR. It means that either
side of the ^ operator must be 1 (True) for the result to be 1 (True), but
both sides cannot be 1 (True) at the same time.
236
C++ By
EXAMPLE
Examples
1. If you apply the bitwise & operator to numerals 9 and 14, you
receive a result of 8. Figure 11.4 shows you why this is so.
When the binary values of 9 (1001) and 14 (1110) are com-
pared on a bitwise & basis, the resulting bit pattern is 8
(1000).
237
Chapter 11 ♦ Additional C++ Operators
238
C++ By
EXAMPLE
// Filename: C11ODEV.CPP
// Uses a bitwise & to determine whether a
// number is odd or even.
#include <iostream.h>
main()
{
239
Chapter 11 ♦ Additional C++ Operators
Only bit 6
is different
Only bit 6
is different
Figure 11.6. Bitwise difference between two uppercase and two lower-
case ASCII letters.
240
C++ By
EXAMPLE
// Filename: C11UPCS1.CPP
// Converts the input characters to uppercase
// if they aren’t already.
#include <iostream.h>
main()
{
char first, middle, last; // Will hold user’s initials
int bitmask=223; // 11011111 in binary
241
Chapter 11 ♦ Additional C++ Operators
Review Questions
The answers to the review questions are in Appendix B.
1. What set of statements does the conditional operator
replace?
2. Why is the conditional operator called a “ternary” operator?
3. Rewrite the following conditional operator as an if-else
statement.
ans = (a == b) ? c + 2 : c + 3;
and
var = var + 1;
age = 20;
printf(“You are now %d, and will be %d in one year”,
age, age++);
c. 1 ^ 1 ^ 1 ^ 1
d. ~(1 ^ 0)
242
C++ By
EXAMPLE
Review Exercises
1. Write a program that prints the numerals from 1 to 10. Use
ten different couts and only one variable called result to hold
the value before each cout. Use the increment operator to
add 1 to result before each cout.
2. Write a program that asks users for their ages. Using a single
printf() that includes a conditional operator, print on-screen
the following if the input age is over 21,
You are not a minor.
Summary
Now you have learned almost every operator in the C++
language. As explained in this chapter, conditional, increment, and
decrement are three operators that enable C++ to stand apart from
many other programming languages. You must always be aware of
the precedence table whenever you use these, as you must with all
operators.
243
Chapter 11 ♦ Additional C++ Operators
The sizeof and sequence point operators act unlike most others.
The sizeof is a compile operator, and it works in a manner similar to
the #define preprocessor directive because they are both replaced by
their values at compile time. The sequence point enables you to have
multiple statements on the same line—or in a single expression.
Reserve the sequence point for declaring variables only because it
can be unclear when it’s combined with other expressions.
This chapter concludes the discussion on C++ operators. Now
that you can compute just about any result you will ever need, it is
time to discover how to gain more control over your programs. The
next few chapters introduce control loops that give you repetitive
power in C++.
244
C++ By
12EXAMPLE
245
Chapter 12 ♦ The while Loop
246
C++ By
EXAMPLE
TIP: If the body of the while loop contains only one statement,
the braces surrounding it are not required. It is a good habit to
enclose all while loop statements in braces, however, because if
you have to add statements to the body of the while loop later,
your braces are already there.
247
Chapter 12 ♦ The while Loop
more readable if you indent the body of a while loop a few spaces to
the right. The following examples illustrate this.
Examples
1. Some programs presented earlier in the book require user
input with cin. If users do not enter appropriate values, these
programs display an error message and ask the user to enter
another value, which is an acceptable procedure.
Now that you understand the while loop construct, however,
you should put the error message inside a loop. In this way,
users see the message continually until they type proper
input values, rather than once.
The following program is short, but it demonstrates a while
loop that ensures valid keyboard input. It asks users
whether they want to continue. You can incorporate this
program into a larger one that requires user permission to
continue. Put a prompt, such as the one presented here, at
the bottom of a text screen. The text remains on-screen until
the user tells the program to continue executing.
Identify the file and include the necessary header file. In this
program, you want to ensure the user enters Y or N.
You have to store the user’s answer, so declare the ans variable as a
character. Ask the users whether they want to continue, and get
the response. If the user doesn’t type Y or N, ask the user for
another response.
// Filename: C12WHIL1.CPP
// Input routine to ensure user types a
// correct response. This routine can be part
// of a larger program.
#include <iostream.h>
main()
{
char ans;
248
C++ By
EXAMPLE
while ((ans != ‘Y’) && (ans != ‘N’))
{ cout << “\nYou must type a Y or an N\n”; // Warn
// and ask
cout << “Do you want to continue (Y/N)?”; // again.
cin >> ans;
} // Body of while loop ends here.
return 0;
}
Notice that the two cin functions do the same thing. You
must use an initial cin, outside the while loop, to provide an
answer for the while loop to check. If users type something
other than Y or N, the program prints an error message, asks
for another answer, then checks the new answer. This vali-
dation method is preferred over one where the reader only
has one additional chance to succeed.
The while loop tests the test expression at the top of the loop.
This is why the loop might never execute. If the test is
initially False, the loop does not execute even once. The
output from this program is shown as follows. The program
repeats indefinitely, until the relational test is True (as soon
as the user types either Y or N).
249
Chapter 12 ♦ The while Loop
// Filename: C12WHBAD.CPP
// Bad use of a while loop.
#include <iostream.h>
main()
{
int a=10, b=20;
while (a > 5)
{ cout << “a is “ << a << “, and b is “ << b << “\n”;
b = 20 + a; }
return 0;
}
3. The following program asks users for a first name, then uses
a while loop to count the number of characters in the name.
This is a string length program; it counts characters until it
reaches the null zero. Remember that the length of a string
equals the number of characters in the string, not including
the null zero.
// Filename: C12WHIL2.CPP
// Counts the number of letters in the user’s first name.
#include <iostream.h>
main()
{
char name[15]; // Will hold user’s first name
250
C++ By
EXAMPLE
int count=0; // Will hold total characters in name
// Filename: C12WHIL3.CPP
// Counts the number of letters in the user’s first name.
#include <iostream.h>
main()
{
char name[15]; // Will hold user’s first name
int count=0; // Will hold total characters in name
251
Chapter 12 ♦ The while Loop
do
{ block of one or more C++ statements; }
while (test expression)
Examples
1. The following program is just like the first one you saw with
the while loop (C12WHIL1.CPP), except the do-while is used.
Notice the placement of test expression. Because this expres-
sion concludes the loop, user input does not have to appear
before the loop and again in the body of the loop.
// Filename: C12WHIL4.CPP
// Input routine to ensure user types a
// correct response. This routine might be part
// of a larger program.
252
C++ By
EXAMPLE
#include <iostream.h>
main()
{
char ans;
do
{ cout << “\nYou must type a Y or an N\n”; // Warn
// and ask
cout << “Do you want to continue (Y/N) ?”; // again.
cin >> ans; } // Body of while loop
// ends here.
while ((ans != ‘Y’) && (ans != ‘N’));
return 0;
}
// Filename: C12INV1.CPP
// Gets inventory information from user and prints
// an inventory detail listing with extended totals.
#include <iostream.h>
#include <iomanip.h>
main()
{
int part_no, quantity;
float cost, ext_cost;
253
Chapter 12 ♦ The while Loop
254
C++ By
EXAMPLE
Figure 12.1. Differences between the if statement and the two while
loops.
255
Chapter 12 ♦ The while Loop
NOTE: The break statement exits only the most current loop. If
you have a while loop in another while loop, break exits only the
internal loop.
256
C++ By
EXAMPLE
Examples
1. Here is a simple program that shows you how the exit()
function works. This program looks as though it prints
several messages on-screen, but it doesn’t. Because exit()
appears early in the code, this program quits immediately
after main()’s opening brace.
// C12EXIT1.CPP
// Quits early due to exit() function.
#include <iostream.h>
#include <stdlib.h> // Required for exit().
main()
{
exit(0); // Forces program to end here.
return 0;
}
// Filename: C12BRK.CPP
// Demonstrates the break statement.
#include <iostream.h>
main()
257
Chapter 12 ♦ The while Loop
{
char user_ans;
do
{ cout << “C++ is fun! \n”;
break; // Causes early exit.
cout << “Do you want to see the message again (N/Y)? “;
cin >> user_ans;
} while (user_ans == ‘Y’);
C++ is fun!
That’s all for now
You can tell from this program’s output that the break state-
ment does not allow the do-while loop to reach its natural
conclusion, but causes it to finish early. The final cout prints
because only the current loop—and not the entire pro-
gram—exits with the break statement.
3. Unlike the previous program, break usually appears after an
if statement. This makes it a conditional break, which occurs
only if the relational test of the if statement is True.
A good illustration of this is the inventory program you saw
earlier (C12INV1.CPP). Even though the users enter –999
when they want to quit the program, an additional if test is
needed inside the do-while. The –999 ends the do-while loop,
but the body of the do-while still needs an if test, so the
remaining quantity and cost prompts are not given.
If you insert a break after testing for the end of the user’s
input, as shown in the following program, the do-while will
not need the if test. The break quits the do-while as soon as
the user signals the end of the inventory by entering –999 as
the part number.
258
C++ By
EXAMPLE
// Filename: C12INV2.CPP
// Gets inventory information from user and prints
// an inventory detail listing with extended totals.
#include <iostream.h>
#include <iomanip.h>
main()
{
int part_no, quantity;
float cost, ext_cost;
4. You can use the following program to control the two other
programs. This program illustrates how C++ can pass in-
formation to DOS with exit(). This is your first example of a
menu program. Similar to a restaurant menu, a C++ menu
program lists possible user choices. The users decide what
they want the computer to do from the menu’s available
options. The mailing list application in Appendix F, “The
Mailing List Application,” uses a menu for its user options.
259
Chapter 12 ♦ The while Loop
// Filename: C12EXIT2.CPP
// Asks user for his or her selection and returns
// that selection to the operating system with exit().
#include <iostream.h>
#include <stdlib.h>
main()
{
int ans;
do
{ cout << “Do you want to:\n\n”;
cout << “\t1. Run the word processor \n\n”;
cout << “\t2. Run the database program \n\n”;
cout << “What is your selection? “;
cin >> ans;
} while ((ans != 1) && (ans != 2)); // Ensures user
// enters 1 or 2.
exit(ans); // Return value to operating system.
return 0; // Return does not ever execute due to exit().
}
260
C++ By
EXAMPLE
Examples
1. To illustrate using a counter, the following program prints
“Computers are fun!” on-screen 10 times. You can write a
program that has 10 cout statements, but that would not be
efficient. It would also be too cumbersome to have 5000 cout
statements, if you wanted to print that same message 5000
times.
By adding a while loop and a counter that stops after a
certain total is reached, you can control this printing, as the
following program shows.
// Filename: C12CNT1.CPP
// Program to print a message 10 times.
#include <iostream.h>
main()
{
int ctr = 0; // Holds the number of times printed.
do
{ cout << “Computers are fun!\n”;
ctr++; // Add one to the count,
// after each cout.
} while (ctr < 10); // Print again if fewer
// than 10 times.
return 0;
}
261
Chapter 12 ♦ The while Loop
262
C++ By
EXAMPLE
// Filename: C12PASS1.CPP
// Program to prompt for a password and
// check it against an internal one.
#include <iostream.h>
#include <stdlib.h>
main()
{
int stored_pass = 11862;
int num_tries = 0; // Counter for password attempts.
int user_pass;
263
Chapter 12 ♦ The while Loop
// Filename: C12GUES.CPP
// Letter-guessing game.
#include <iostream.h>
main()
{
int tries = 0;
char comp_ans, user_guess;
264
C++ By
EXAMPLE
Producing Totals
Writing a routine to add values is as easy as counting. Instead
of adding 1 to the counter variable, you add a value to the total
variable. For instance, if you want to find the total dollar amount of
checks you wrote during December, you can start at nothing (0) and
add the amount of every check written in December. Instead of
building a count, you are building a total.
When you want C++ to add values, just initialize a total
variable to zero, then add each value to the total until you have
included all the values.
265
Chapter 12 ♦ The while Loop
Examples
1. Suppose you want to write a program that adds your grades
for a class you are taking. The teacher has informed you that
you earn an A if you can accumulate over 450 points.
The following program keeps asking you for values until
you type –1. The –1 is a signal that you are finished entering
grades and now want to see the total. This program also
prints a congratulatory message if you have enough points
for an A.
// Filename: C12GRAD1.CPP
// Adds grades and determines whether you earned an A.
#include <iostream.h>
include <iomanip.h>
main()
{
float total_grade=0.0;
float grade; // Holds individual grades.
do
{ cout << “What is your grade? (-1 to end) “;
cin >> grade;
if (grade >= 0.0)
{ total_grade += grade; } // Add to total.
} while (grade >= 0.0); // Quit when -1 entered.
return 0;
}
266
C++ By
EXAMPLE
// Filename: C12GRAD2.CPP
// Adds up grades, computes average,
// and determines whether you earned an A.
#include <iostream.h>
#include <iomanip.h>
main()
{
float total_grade=0.0;
float grade_avg = 0.0;
float grade;
int grade_ctr = 0;
do
{ cout << “What is your grade? (-1 to end) “;
cin >> grade;
if (grade >= 0.0)
{ total_grade += grade; // Add to total.
grade_ctr ++; } // Add to count.
} while (grade >= 0.0); // Quit when -1 entered.
267
Chapter 12 ♦ The while Loop
Review Questions
The answers to the review questions are in Appendix B.
1. What is the difference between the while loop and the
do-while loop?
268
C++ By
EXAMPLE
6. What file must you include as a header file if you use exit()?
7. How many times does this printf() print?
int a=0;
do
{ printf(“Careful \n”);
a++; }
while (a > 5);
a = 1;
while (a < 4)
{ cout << “This is the outer loop\n”;
a++;
while (a <= 25)
{ break;
cout << “This prints 25 times\n”; }
}
Review Exercises
1. Write a program with a do-while loop that prints the numer-
als from 10 to 20 (inclusive), with a blank line between each
number.
2. Write a weather-calculator program that asks for a list of the
previous 10 days’ temperatures, computes the average, and
prints the results. You have to compute the total as the input
occurs, then divide that total by 10 to find the average. Use a
while loop for the 10 repetitions.
269
Chapter 12 ♦ The while Loop
Summary
This chapter showed you two ways to produce a C++ loop: the
while loop and the do-while loop. These two variations of while loops
differ in where they test their test condition statements. The while
tests at the beginning of its loop, and the do-while tests at the end.
Therefore, the body of a do-while loop always executes at least once.
You also learned that the exit() function and break statement add
flexibility to the while loops. The exit() function terminates the
program, and the break statement terminates only the current loop.
This chapter explained two of the most important applications
of loops: counters and totals. Your computer can be a wonderful tool
for adding and counting, due to the repetitive capabilities offered
with while loops.
The next chapter extends your knowledge of loops by showing
you how to create a determinate loop, called the for loop. This feature
is useful when you want a section of code to loop for a specified
number of times.
270
Part III
C++ Constructs
C++ By
13EXAMPLE
273
Chapter 13 ♦ The for Loop
The for loop Every time the body of the loop repeats, the count expression
iterates for a executes, usually incrementing or decrementing a variable. The test
specified number
expression evaluates to True (nonzero) or False (zero), then deter-
of times.
mines whether the body of the loop repeats again.
TIP: If only one C++ statement resides in the for loop’s body,
braces are not required, but they are recommended. If you add
more statements, the braces are there already, reminding you
that they are now needed.
274
C++ By
EXAMPLE
NOTE: The for loop tests the test expression at the top of the
loop. If the test expression is False when the for loop begins, the
body of the loop never executes.
275
Chapter 13 ♦ The for Loop
Examples
1. To give you a glimpse of the for loop’s capabilities, this
example shows you two programs: one that uses a for loop
and one that does not. The first one is a counting program.
Before studying its contents, look at the output. The results
illustrate the for loop concept very well.
Identify the program and include the necessary header file. You
need a counter, so make ctr an integer variable.
1. Add one to the counter.
2. If the counter is less than or equal to 10, print its value and
repeat step one.
The program with a for loop follows:
// Filename: C13FOR1.CPP
// Introduces the for loop.
#include <iostream.h>
main()
{
int ctr;
for (ctr=1; ctr<=10; ctr++) // Start ctr at one.
// Increment through loop.
{ cout << ctr << “\n”; } // Body of for loop.
return 0;
}
276
C++ By
EXAMPLE
1
2
3
4
5
6
7
8
9
10
// Filename: C13WHI1.CPP
// Simulating a for loop with a do-while loop.
#include <iostream.h>
main()
{
int ctr=1;
do
{ cout << ctr << “\n”; // Body of do-while loop.
ctr++; }
while (ctr <= 10);
return 0;
}
277
Chapter 13 ♦ The for Loop
// Filename: C13FOR2.CPP
// Demonstrates totaling using a for loop.
#include <iostream.h>
main()
{
int total, ctr;
// Filename: C13WHI2.CPP
// A totaling program using a do-while loop.
#include <iostream.h>
main()
{
int total=0; // Initialize total
int num=100; // Starting value
do
{ total += num; // Add to total
num++; // Increment counter
278
C++ By
EXAMPLE
} while (num <= 200);
cout << “The total is “ << total << “\n”;;
return 0;
}
TIP: Notice how the body of the for loop is indented. This is a
good habit to develop because it makes it easier to see the
beginning and ending of the loop’s body.
3. The body of the for loop can have more than one statement.
The following example requests five pairs of data values:
children’s first names and their ages. It prints the teacher
assigned to each child, based on the child’s age. This illus-
trates a for loop with cout functions, a cin function, and an if
statement in its body. Because exactly five children are
checked, the for loop ensures the program ends after the
fifth child.
// Filename: C13FOR3.CPP
// Program that uses a loop to input and print
// the teacher assigned to each child.
#include <iostream.h>
main()
{
char child[25]; // Holds child’s first name
int age; // Holds child’s age
int ctr; // The for loop counter variable
279
Chapter 13 ♦ The for Loop
return 0;
}
Below is the output from this program. You can improve this
program even more after learning the switch statement in the
next chapter.
280
C++ By
EXAMPLE
// Filename: C13EVOD.CPP
// Prints the even numbers from 1 to 20,
// then the odd numbers from 1 to 20.
#include <iostream.h>
main()
{
int num; // The for loop variable
return 0;
}
There are two loops in this program. The body of each one
consists of a single printf() function. In the first half of the
program, the loop variable, num, is 2 and not 1. If it were 1,
the number 1 would print first, as it does in the odd number
section.
The two cout statements that print the titles are not part of
either loop. If they were, the program would print a title
before each number. The following shows the result of
running this program.
281
Chapter 13 ♦ The for Loop
5. You can decrement the loop variable as well. If you do, the
value is subtracted from the loop variable each time through
the loop.
The following example is a rewrite of the counting program.
It produces the reverse effect by showing a countdown.
// Filename: C13CNTD1.CPP
// Countdown to the liftoff.
#include <iostream.h>
main()
{
int ctr;
10
9
8
7
6
5
4
3
282
C++ By
EXAMPLE
2
1
*** Blast Off! ***
6. You also can make a for loop test for something other than a
literal value. The following program combines much of what
you have learned so far. It asks for student grades and
computes an average. Because there might be a different
number of students each semester, the program first asks the
user for the number of students. Next, the program iterates
until the user enters an equal number of scores. It then com-
putes the average based on the total and the number of
student grades entered.
// Filename: C13FOR4.CPP
// Computes a grade average with a for loop.
#include <iostream.h>
#include <iomanip.h>
main()
{
float grade, avg;
float total=0.0;
int num; // Total number of grades.
int loopvar; // Used to control the for loop
283
Chapter 13 ♦ The for Loop
Due to the for loop, the total and the average calculations do
not have to be changed if the number of students changes.
7. Because characters and integers are so closely associated in
C++, you can increment character variables in a for loop.
The following program prints the letters A through Z with a
simple for loop.
// Filename: C13FOR5.CPP
// Prints the alphabet with a simple for loop.
#include <iostream.h>
main()
{
char letter;
return 0;
}
284
C++ By
EXAMPLE
for (;;)
{ printf(“Over and over...”); }
// Filename: C13FOR6.CPP
// Uses only the test expression in
// the for loop to count by fives.
#include <iostream.h>
main()
{
int num=5; // Starting value
return 0;
}
Counting by 5s:
5
10
15
285
Chapter 13 ♦ The for Loop
20
25
30
35
40
45
50
55
60
65
70
75
80
85
90
95
100
286
C++ By
EXAMPLE
Outside Inside
Loop Loop
First
Inner
Loop
Outside
Loop Second
Inner
Loop
287
Chapter 13 ♦ The for Loop
Examples
1. The following program contains a loop in a loop—a nested
loop. The inside loop counts and prints from 1 to 5. The
outside loop counts from 1 to 3. The inside loop repeats, in
its entirety, three times. In other words, this program prints
the values 1 to 5 and does so three times.
// Filename: C13NEST1.CPP
// Print the numbers 1-5 three times.
// using a nested loop.
#include <iostream.h>
main()
{
int times, num; // Outer and inner for loop variables
return 0;
}
12345
12345
12345
288
C++ By
EXAMPLE
// Filename: C13NEST2.CPP
// An inside loop controlled by the outer loop’s
// counter variable.
#include <iostream.h>
main()
{
int outer, inner;
12345
1234
123
12
1
289
Chapter 13 ♦ The for Loop
Σ (i / 3 * 2)
i = 1
can be rewritten as
total = 0;
{ total += (i / 3 * 2); }
290
C++ By
EXAMPLE
// Filename: C13FACT.CPP
// Computes the factorial of numbers through
// the user’s number.
#include <iostream.h>
main()
{
int outer, num, fact, total;
return 0;
}
The following shows the factorial of seven. You can run this
program, entering different values when asked, and see
various factorials. Be careful: factorials multiply quickly.
(A factorial of 11 won’t fit in an integer variable.)
291
Chapter 13 ♦ The for Loop
Review Questions
The answers to the review questions are in Appendix B.
1. What is a loop?
2. True or false: The body of a for loop contains at most one
statement.
3. What is a nested loop?
4. Why might you want to leave one or more expressions out
of the for statement’s parentheses?
5. Which loop “moves” fastest: the inner loop or the outer
loop?
6. What is the output from the following program?
i=1;
start=1;
end=5;
step=1;
292
C++ By
EXAMPLE
for (; start>=end;)
{ cout << i << “\n”;
start+=step;
end--;}
Review Exercises
1. Write a program that prints the numerals 1 to 15 on-screen.
Use a for loop to control the printing.
2. Write a program to print the numerals 15 to 1 on-screen. Use
a for loop to control the printing.
3. Write a program that uses a for loop to print every odd
number from 1 to 100.
4. Write a program that asks the user for her or his age. Use a
for loop to print “Happy Birthday!” for every year of the
user’s age.
5. Write a program that uses a for loop to print the ASCII
characters from 32 to 255 on-screen. (Hint: Use the %c conver-
sion character to print integer variables.)
6. Using the ASCII table numbers, write a program to print the
following output, using a nested for loop. (Hint: The outside
loop should loop from 1 to 5, and the inside loop’s start
variable should be 65, the value of ASCII A.)
A
AB
ABC
ABCD
ABCDE
Summary
This chapter taught you how to control loops. Instead of
writing extra code around a while loop, you can use the for loop to
control the number of iterations at the time you define the loop. All
293
Chapter 13 ♦ The for Loop
294
C++ By
14EXAMPLE
Other Loop
Options
Now that you have mastered the looping constructs, you should
learn some loop-related statements. This chapter teaches the con-
cepts of timing loops, which enable you to slow down your programs.
Slowing program execution can be helpful if you want to display a
message for a fixed period of time or write computer games with
slower speeds so they are at a practical speed for recreational use.
You can use two additional looping commands, the break and
continue statements, to control the loops. These statements work
with while loops and for loops.
This chapter introduces you to the following:
♦ Timing loops
♦ The break statement with for loops
♦ The continue statement with for loops
When you master these concepts, you will be well on your way
toward writing powerful programs that process large amounts of
data.
295
Chapter 14 ♦ Other Loop Options
Timing Loops
Computers are fast, and at times you would probably like them
to be even faster. Sometimes, however, you want to slow down the
computer. Often, you have to slow the execution of games because
the computer’s speed makes the game unplayable. Messages that
appear on-screen many times clear too fast for the user to read if you
don’t delay them.
A nested loop is a perfect place for a timing loop, which simply
cycles through a for or while loop many times. The larger the end
value of the for loop, the longer the time in which the loop repeats.
A nested loop is appropriate for displaying error messages to
your user. If the user requested a report—but had not entered
enough data for your program to print the report—you might print
a warning message on-screen for a few seconds, telling users that
they cannot request the report yet. After displaying the message for
a few seconds, you can clear the message and give the user another
chance. (The example program in Appendix F, “The Mailing List
Application,” uses timing loops to display error messages.)
Timing loops make There is no way to determine how many iterations a timing
the computer wait. loop takes for one second (or minute or hour) of delay because
computers run at different speeds. You therefore have to adjust your
timing loop’s end value to set the delay to your liking.
Examples
1. Timing loops are easy to write—simply put an empty for
loop inside the program. The following program is a rewrit-
ten version of the countdown program (C13CNTD1.CPP)
you saw in Chapter 13. Each number in the countdown is
delayed so the countdown does not seem to take place
instantly. (Adjust the delay value if this program runs too
slowly or too quickly on your computer.)
Identify the program and include the input/output header file. You
need a counter and a delay, so make cd and delay integer variables.
Start the counter at 10, and start the delay at 1.
1. If the delay is less than or equal to 30,000, add 1 to its value
and repeat step one.
296
C++ By
EXAMPLE
// Filename: C14CNTD1.CPP
// Countdown to the liftoff with a delay.
#include <iostream.h>
main()
{
int cd, delay;
297
Chapter 14 ♦ Other Loop Options
// Filename: C14TIM.CPP
// Displays an error message for a few seconds.
#include <stdio.h>
main()
{
int outer, inner, age;
NOTE: Notice the inside loop has a semicolon (;) after the for
statement—with no loop body. There is no need for a loop body
here because the computer is only cycling through the loop to
waste some time.
298
C++ By
EXAMPLE
the counting variable has reached its final value. As with while loops,
you use the break statement to quit a for loop early.
The break statement is nested in the body of the for loop.
Programmers rarely put break on a line by itself, and it almost always
comes after an if test. If the break were on a line by itself, the loop
would always quit early, defeating the purpose of the for loop.
Examples
1. The following program shows what can happen when C++
encounters an unconditional break statement (one not pre-
ceeded by an if statement).
Identify the program and include the input/output header files.
You need a variable to hold the current number, so make num
an integer variable. Print a “Here are the numbers” message.
1. Make num equal to 1. If num is less than or equal to
20, add one to it each time through the loop.
2. Print the value of num.
3. Break out of the loop.
Print a goodbye message.
// Filename: C14BRAK1.CPP
// A for loop defeated by the break statement.
#include <iostream.h>
main()
{
int num;
299
Chapter 14 ♦ Other Loop Options
// Filename: C14BRAK2.CPP
// A for loop running at the user’s request.
#include <iostream.h>
main()
{
int num; // Loop counter variable
char ans;
300
C++ By
EXAMPLE
If you nest one loop inside another, the break terminates the
“most active” loop (the innermost loop in which the break
statement resides).
3. Use the conditional break (an if statement followed by a break)
when you are missing data. For example, when you process
data files or large amounts of user data-entry, you might
expect 100 input numbers and receive only 95. You can use a
break to terminate the for loop before it iterates the 96th time.
301
Chapter 14 ♦ Other Loop Options
// Filename: C14BRAK3.CPP
// Computes a grade average with a for loop,
// allowing an early exit with a break statement.
#include <iostream.h>
#include <iomanip.h>
main()
{
float grade, avg;
float total=0.0;
int num, count=0; // Total number of grades and counter
int loopvar; // Used to control for loop
Notice that grade is tested for less than 0, not –99.0. You
cannot reliably use floating-point values to compare for
302
C++ By
EXAMPLE
You use the continue statement when data in the body of the
loop is bad, out of bounds, or unexpected. Instead of acting on the
bad data, you might want to go back to the top of the loop and try
another data value. The following examples help illustrate the use of
the continue statement.
303
Chapter 14 ♦ Other Loop Options
Figure 14.1 shows the difference between the break and continue
statements.
break terminates
loop immediately
Examples
1. Although the following program seems to print the numbers
1 through 10, each followed by “C++ Programming,” it does
not. The continue in the body of the for loop causes an early
finish to the loop. The first cout in the for loop executes, but
the second does not—due to the continue.
304
C++ By
EXAMPLE
// Filename: C14CON1.CPP
// Demonstrates the use of the continue statement.
#include <iostream.h>
main()
{
int ctr;
// Filename: C14CON2.CPP
// Prints uppercase equivalents of five lowercase letters.
#include <iostream.h>
main()
305
Chapter 14 ♦ Other Loop Options
{
char letter;
int ctr;
// Filename: C14CON3.CPP
// Average salaries over $10,000
#include <iostream.h>
#include <iomanip.h>
main()
{
float month, year; // Monthly and yearly salaries
float avg=0.0, total=0.0;
int count=0;
306
C++ By
EXAMPLE
do
{ cout << “What is the next monthly salary (-1) “ <<
“to quit)? “;
cin >> month;
if ((year=month*12.00) <= 10000.00) // Do not add
{ continue; } // low salaries.
if (month < 0.0)
{ break; } // Quit if user entered -1.
count++; // Add 1 to valid counter.
total += year; // Add yearly salary to total.
} while (month > 0.0);
307
Chapter 14 ♦ Other Loop Options
Review Questions
The answers to the review questions are in Appendix B.
1. For what do you use timing loops?
2. Why do timing loop ranges have to be adjusted for different
types of computers?
3. Why do continue and break statements rarely appear without
an if statement controlling them?
4. What is the output from the following section of code?
Review Exercises
1. Write a program that prints C++ is fun on-screen for ten
seconds. (Hint: You might have to adjust the timing loop.)
2. Make the program in Exercise 1 flash the message C++ is fun
for ten seconds. (Hint: You might have to use several timing
loops.)
3. Write a grade averaging program for a class of 20 students.
Ignore any grade less than 0 and continue until all 20 student
grades are entered, or until the user types –99 to end the
program early.
308
C++ By
EXAMPLE
Summary
In this chapter, you learned several additional ways to use and
modify your program’s loops. By adding timing loops, continue
statements, and break statements, you can better control how each
loop behaves. Being able to exit early (with the break statement) or
continue the next loop iteration early (with the continue statement)
gives you more freedom when processing different types of data.
The next chapter (Chapter 15, “The switch a n d goto State-
ments”) shows you a construct of C++ that does not loop, but relies
on the break statement to work properly. This is the switch statement,
and it makes your program choices much easier to write.
309
Chapter 14 ♦ Other Loop Options
310
C++ By
15EXAMPLE
311
Chapter 15 ♦ The switch and goto Statements
switch (expression)
{ case (expression1): { one or more C++ statements; }
case (expression2): { one or more C++ statements; }
case (expression3): { one or more C++ statements; }
.
.
.
default: { one or more C++ statements; }
}
TIP: Use a break statement after each case block to keep execu-
tion from “falling through” to the remaining case statements.
312
C++ By
EXAMPLE
Using the switch statement is easier than its format might lead
you to believe. Anywhere an if-else-if combination of statements
can go, you can usually put a clearer switch statement. The switch
statement is much easier to follow than an if-in-an-if-in-an-if
statement, as you have had to write previously.
However, the if and else-if combinations of statements are not
difficult to follow. When the relational test that determines the
choice is complex and contains many && and || operators, the if
statement might be a better candidate. The switch statement is
preferred whenever multiple-choice possibilities are based on a
single literal, variable, or expression.
Examples
1. Suppose you are writing a program to teach your child how
to count. Your program will ask the child for a number. It
then beeps (rings the computer’s alarm bell) as many times
as necessary to match that number.
The following program assumes the child presses a number
key from 1 to 5. This program uses the if-else-if combina-
tion to accomplish this counting-and-beeping teaching
method.
Identify the program and include the necessary header file. You
want to sound a beep and move the cursor to the next line, so
define a global variable called BEEP that does this. You need a
variable to hold the user’s answer, so make num an integer variable.
Ask the user for a number. Assign the user’s number to num. If num
is 1, call BEEP once. If num is 2, call BEEP twice. If num is 3, call BEEP
three times. If num is 4, call BEEP four times. If num is 5, call BEEP five
times.
313
Chapter 15 ♦ The switch and goto Statements
// Filename: C15BEEP1.CPP
// Beeps a designated number of times.
#include <iostream.h>
314
C++ By
EXAMPLE
// Filename: C15BEEP2.CPP
// Beeps a certain number of times using a switch.
#include <iostream.h>
switch (num)
{ case (1): { BEEP;
break; }
case (2): { BEEP; BEEP;
break; }
case (3): { BEEP; BEEP; BEEP;
break; }
case (4): { BEEP; BEEP; BEEP; BEEP;
break; }
case (5): { BEEP; BEEP; BEEP; BEEP; BEEP;
break; }
}
return 0;
}
315
Chapter 15 ♦ The switch and goto Statements
// Filename: C15BEEP3.CPP
// Beeps a designated number of times using a switch.
#include <iostream.h>
switch (num)
{ case (1): { BEEP;
break; }
case (2): { BEEP; BEEP;
break; }
case (3): { BEEP; BEEP; BEEP;
break; }
case (4): { BEEP; BEEP; BEEP; BEEP;
break; }
case (5): { BEEP; BEEP; BEEP; BEEP; BEEP;
break; }
default: { cout << “You must enter a number from “ <<
“1 to 5\n”;
316
C++ By
EXAMPLE
cout << “Please run this program again\n”;
break; }
}
return 0;
}
The break at the end of the default case might seem redun-
dant. After all, no other case statements execute by “falling
through” from the default case. It is a good habit to put a
break after the default case anyway. If you move the default
higher in the switch (it doesn’t have to be the last switch
option), you are more inclined to move the break with it
(where it is then needed).
3. To show the importance of using break statements in each
case expression, here is the same beeping program without
any break statements.
// Filename: C15BEEP4.CPP
// Incorrectly beeps using a switch.
#include <iostream.h>
317
Chapter 15 ♦ The switch and goto Statements
318
C++ By
EXAMPLE
// Filename: C15SALE.CPP
// Prints daily, weekly, and monthly sales totals.
#include <iostream.h>
#include <stdio.h>
main()
{
float daily=2343.34; // Later, these figures
float weekly=13432.65; // come from a disk file
float monthly=43468.97; // instead of being assigned
// as they are here.
char ans;
int day; // Day value to trigger correct case.
switch (day)
{ case (6): printf(“The monthly total is %.2f \n”,
monthly);
case (5): printf(“The weekly total is %.2f \n”,
weekly);
default: printf(“The daily total is %.2f \n”, daily);
}
return 0;
}
5. The order of the case statements is not fixed. You can rear-
range the statements to make them more efficient. If only
one or two cases are being selected most of the time, put
those cases near the top of the switch statement.
319
Chapter 15 ♦ The switch and goto Statements
// Filename: C15DEPT1.CPP
// Prints message depending on the department entered.
#include <iostream.h>
main()
{
char choice;
320
C++ By
EXAMPLE
break; }
}
return 0;
}
321
Chapter 15 ♦ The switch and goto Statements
322
C++ By
EXAMPLE
Examples
1. The following program has a problem that is a direct result
of the goto, but it is still one of the best illustrations of the
goto statement. The program consists of an endless loop (or an
infinite loop). The first three lines (after the opening brace)
execute, then the goto in the fourth line causes execution to
loop back to the beginning and repeat the first three lines.
The goto continues to do this until you press Ctrl-Break or
ask your system administrator to cancel the program.
Identify the program and include the input/output header file. You
want to print a message, but split it over three lines. You want the
message to keep repeating, so label the first line, then use a goto to
jump back to that line.
// Filename: C15GOTO1.CPP
// Program to show use of goto. This program ends
// only when the user presses Ctrl-Break.
#include <iostream.h>
main()
{
Again: cout << “This message \n”;
cout << “\t keeps repeating \n”;
cout << “\t\t over and over \n”;
return 0;
}
This message
keeps repeating
over and over
This message
keeps repeating
over and over
323
Chapter 15 ♦ The switch and goto Statements
This message
keeps repeating
over and over
This message
keeps repeating
over and over
This message
keeps repeating
over and over
This message
keeps repeating
over and over
This message
keeps repeating
over and over
This message
// Filename: C15GOTO2.CPP
// Program to show use of goto. This program ends
// only when the user presses Ctrl-Break.
#include <iostream.h>
main()
{
Again:
cout << “This message \n”;
cout << “\t keeps repeating \n”;
cout << “\t\t over and over \n”;
return 0;
}
324
C++ By
EXAMPLE
The line following the statement label is the one that ex-
ecutes next, after control is passed (by the goto) to the label.
Of course, these are silly examples. You probably don’t want
to write programs with infinite loops. The goto is a statement
best preceded with an if; this way the goto eventually stops
branching without intervention from the user.
3. The following program is one of the worst-written programs
ever! It is the epitome of spaghetti code! However, do your
best to follow it and understand its output. By understand-
ing the flow of this output, you can hone your understand-
ing of the goto. You might also appreciate the fact that the
rest of this book uses the goto only when needed to make the
program clearer.
// Filename: C15GOTO3.CPP
// This program demonstrates the overuse of goto.
#include <iostream.h>
main()
{
goto Here;
First:
cout << “A \n”;
goto Final;
There:
cout << “B \n”;
goto First;
Here:
cout << “C \n”;
goto There;
Final:
return 0;
}
325
Chapter 15 ♦ The switch and goto Statements
// Filename: C15GOTO4.CPP
// This program demonstrates the overuse of goto.
#include <iostream.h>
main()
{
goto Here;
First:
cout << “A \n”;
goto Final;
There:
cout << “B \n”;
goto First;
Here:
cout << “C \n”;
goto There;
Final:
return 0;
}
326
C++ By
EXAMPLE
Review Questions
The answers to the review questions are in Appendix B.
1. How does goto change the order in which a program nor-
mally executes?
2. What statement can substitute for an if-else-if construct?
3. Which statement almost always ends each case statement in
a switch?
4. True or false: The order of your case statements has no
bearing on the efficiency of your program.
5. Rewrite the following section of code using a switch
statement.
if (num == 1)
{ cout << “Alpha”; }
else if (num == 2)
{ cout << “Beta”; }
else if (num == 3)
{ cout << “Gamma”; }
else
{ cout << “Other”; }
Ask:
cout << “What is your first name? “;
cin >> name;
if ((name[0] < ‘A’) || (name[0] > ‘Z’))
{ goto Ask; } // Keep asking until the user
// enters a valid letter.
327
Chapter 15 ♦ The switch and goto Statements
Review Exercises
1. Write a program using the switch statement that asks users
for their age, then prints a message saying “You can vote!” if
they are 18, “You can adopt!” if they are 21, or “Are you
really that young?” for any other age.
2. Write a menu-driven program for your local TV cable com-
pany. Here is how to assess charges: If you are within 20
miles outside the city limits, you pay $12.00 per month; 21 to
30 miles outside the city limits, you pay $23.00 per month; 31
to 50 miles outside the city limits, you pay $34.00. No one
outside 50 miles receives the service. Prompt the users with
a menu for their residence’s distance from the city limits.
3. Write a program that calculates parking fees for a multilevel
parking garage. Ask whether the driver is in a car or a truck.
Charge the driver $2.00 for the first hour, $3.00 for the
second, and $5.00 for more than 2 hours. If it is a truck, add
$1.00 to the total fee. (Hint: Use one switch and one if state-
ment.)
4. Modify the previous parking problem so the charge depends
on the time of day the vehicle is parked. If the vehicle is
parked before 8 a.m., charge the fees in Exercise 3. If the
vehicle is parked after 8 a.m. and before 5 p.m., charge an
extra usage fee of 50 cents. If the vehicle is parked after 5
p.m., deduct 50 cents from the computed price. You must
prompt users for the starting time in a menu, as follows.
1. Before 8 a.m.
2. Before 5 p.m.
3. After 5 p.m.
Summary
You now have seen the switch statement and its options. With
it, you can improve the readability of a complicated if-else-if
selection. The switch is especially good when several outcomes are
possible, based on the user’s choice.
328
C++ By
EXAMPLE
329
Chapter 15 ♦ The switch and goto Statements
330
C++ By
16EXAMPLE
Writing C++
Functions
Computers never become bored. They perform the same input,
output, and computations your program requires—for as long as
you want them to do it. You can take advantage of their repetitive
natures by looking at your programs in a new way: as a series of
small routines that execute whenever you need them, however
many times you require.
This chapter approaches its subject a little differently than the
previous chapters do. It concentrates on teaching you to write your
own functions, which are modules of code that you execute and
control from the main() function. So far, the programs in this book
have consisted of a single long function called main(). As you learn
here, the main() function’s primary purpose is to control the execu-
tion of other functions that follow it.
This chapter introduces the following:
♦ The need for functions
♦ How to trace functions
♦ How to write functions
♦ How to call and return from functions
331
Chapter 16 ♦ Writing C++ Functions
Function Basics
When you approach an application that has to be programmed,
it is best not to sit down at the keyboard and start typing. Rather, first
think about the program and what it is supposed to do. One of the
best ways to attack a program is to start with the overall goal, then
divide this goal into several smaller tasks. You should never lose
sight of the overall goal, but think also of how individual pieces can
fit together to accomplish such a goal.
When you finally do sit down to begin coding the problem,
continue to think in terms of those pieces fitting together. Don’t
approach a program as if it were one giant problem; rather, continue
to write those small pieces individually.
This does not mean you must write separate programs to do
everything. You can keep individual pieces of the overall program
together—if you know how to write functions. Then you can use the
same functions in many different programs.
C++ programs C++ programs are not like BASIC or FORTRAN programs.
should consist of C++ was designed to force you to think in a modular, or subroutine-
many small
like, functional style. Good C++ programmers write programs that
functions.
consist of many small functions, even if their programs execute one
or more of these functions only once. Those functions work together
to produce a program quicker and easier than if the program had to
be written from scratch.
TIP: Rather than code one long program, write several smaller
routines, called functions. One of those functions must be
called main(). The main() function is always the first to execute.
It doesn’t have to be first in a program, but it usually is.
332
C++ By
EXAMPLE
main()
{
// :
// C++ code to retrieve a list of characters.
// :
// C++ code to alphabetize the characters.
// :
// C++ code to print the alphabetized list on-screen.
// :
return 0;
}
main()
{
getletters(); // Calls a function to retrieve the numbers.
alphabetize(); // Calls a function to alphabetize
// letters.
333
Chapter 16 ♦ Writing C++ Functions
getletters()
{
// :
// C++ code to get a list of characters.
// :
return 0; // Returns to main().
}
alphabetize()
{
// :
// C++ code to alphabetize the characters
// :
return 0; // Returns to main().
}
printletters()
{
// :
// C++ code to print the alphabetized list on-screen
// :
return 0; // Returns to main().
}
334
C++ By
EXAMPLE
The main() The first function called main() is what you previously used to
function is usually hold the entire program. From this point, in all but the smallest of
a calling function
that controls the
programs, main() simply controls other functions that do the work.
remainder of the These listings are not examples of real C++ programs; instead,
program. they are skeletons, or outlines, of programs. From these outlines, it
is easier to develop the actual full program. Before going to the
keyboard to write a program such as this, know that there are four
distinct sections: a primary function-calling main() function, a key-
board data-entry function, an alphabetizing function, and a print-
ing function.
Never lose sight of the original programming problem. (Using
the approach just described, you never will!) Look again at the main()
calling routine in the preceding program. Notice that you can glance
at main() and get a feel for the overall program, without the remain-
ing statements getting in the way. This is a good example of
structured, modular programming. A large programming problem
is broken into distinct, separate modules called functions, and each
function performs one primary job in a few C++ statements.
335
Chapter 16 ♦ Writing C++ Functions
All programs must The following listing shows you an example of a C++ function.
have a main() You can already tell quite a bit about this function. You know, for
function.
instance, that it isn’t a complete program because it has no main()
function. (All programs must have a main() function.) You know also
that the function name is calc_it because parentheses follow this
name. These parentheses happen to have something in them (you
learn more about this in Chapter 18). You know also that the body
of the function is enclosed in a block of braces. Inside that block is a
336
C++ By
EXAMPLE
smaller block, the body of a while loop. Finally, you recognize that the
return statement is the last line of the function.
calc_it(int n)
{
// Function to print the square of a number.
int square;
return 0;
}
TIP: Not all functions require a return statement for their last
line, but it is recommended that you always include one
because it helps to show your intention to return to the calling
function at that point. Later in the book, you learn that the
return is required in certain instances. For now, develop the
habit of including a return statement.
337
Chapter 16 ♦ Writing C++ Functions
// C16FUN1.CPP
// The following program illustrates function calls.
#include <stdio.h>
next_fun(); // Prototypes.
third_fun();
338
C++ By
EXAMPLE
return 0; // Control is returned to
//the operating system.
} // This brace concludes main().
339
Chapter 16 ♦ Writing C++ Functions
340
C++ By
EXAMPLE
Examples
1. Suppose you are writing a program that does the following.
First, it asks users for their departments. Then, if they are in
accounting, they receive the accounting department’s report.
If they are in engineering, they receive the engineering
department’s report. Finally, if they are in marketing, they
receive the marketing department’s report.
The skeleton of such a program follows. The code for main()
is shown in its entirety, but only a skeleton of the other
functions is shown. The switch statement is a perfect
function-calling statement for such multiple-choice
selections.
do
{ cout << “Choose your department from the “ <<
“following list\n”;
cout << “\t1. Accounting \n”;
cout << “\t2. Engineering \n”;
cout << “\t3. Marketing \n”;
cout << “What is your choice? “;
cin >> choice;
} while ((choice<1) || (choice>3)); // Ensure 1, 2,
// or 3 is chosen.
switch choice
{ case(1): { acct_report(); // Call accounting function.
341
Chapter 16 ♦ Writing C++ Functions
acct_report()
{
// :
// Accounting report code goes here.
// :
return 0;
}
eng_report()
{
// :
// Engineering report code goes here.
// :
return 0;
}
mtg_report()
{
// :
// Marketing report code goes here.
// :
return 0;
}
342
C++ By
EXAMPLE
do
{ menu_print(); // Call function to print the menu.
cin >> choice;
} while ((choice<1) || (choice>3)); // Ensure 1, 2,
// or 3 is chosen.
switch choice
{ case(1): { acct_report(); // Call accounting function.
break; } // Don’t fall through.
case(2): { eng_report(); // Call engineering function.
break; }
case(3): { mtg_report(); // Call marketing function.
break; }
}
return 0; // Program returns to the operating system
// when finished.
}
menu_print()
{
343
Chapter 16 ♦ Writing C++ Functions
acct_report()
{
// :
// Accounting report code goes here.
// :
return 0;
}
eng_report()
{
// :
// Engineering report code goes here.
// :
return 0;
}
mtg_report()
{
// :
// Marketing report code goes here.
// :
return 0;
}
344
C++ By
EXAMPLE
do
{ menu_print(); // Call function to print the menu.
cin >> choice;
} while ((choice<1) || (choice>3)); // Ensure 1, 2,
// or 3 is chosen.
switch choice
{ case(1): { acct_report(); // Call accounting function.
break; } // Don’t fall through.
case(2): { eng_report(); // Call engineering function.
break; }
case(3): { mtg_report(); // Call marketing function.
break; }
}
return 0; // Program returns to the operating system
// when finished.
}
//********************************************************
menu_print()
345
Chapter 16 ♦ Writing C++ Functions
{
cout << “Choose your department from the following"
"list\n”;
cout << “\t1. Accounting \n”;
cout << “\t2. Engineering \n”;
cout << “\t3. Marketing \n”;
cout << “What is your choice? “;
return 0; // Return to main().
}
//*********************************************************
acct_report()
{
// :
// Accounting report code goes here.
// :
return 0;
}
//*********************************************************
eng_report()
{
// :
// Engineering report code goes here.
// :
return 0;
}
//*********************************************************
mtg_report()
{
// :
// Marketing report code goes here.
// :
return 0;
}
346
C++ By
EXAMPLE
// Filename: C16FUN2.CPP
// Prints C++ is Fun! several times on-screen.
#include <iostream.h>
name_print();
reverse_print();
one_per_line();
main()
{
int ctr; // To control loops
//*********************************************************
name_print()
{
// Prints C++ is Fun! across a line, separated by tabs.
cout << “C++ is Fun!\tC++ is Fun!\tC++ is Fun!
\tC++ is Fun!\n”;
cout << “C++ i s F u n !\tC++ i s F u n ! “ <<
“\tC++ i s F u n !\n”;
347
Chapter 16 ♦ Writing C++ Functions
//*********************************************************
reverse_print()
{
// Prints several C++ is Fun! messages,
// in reverse, separated by tabs.
cout << “!nuF si ++C\t!nuF si ++C\t!nuF si ++C\t\n”;
//*********************************************************
one_per_line()
{
// Prints C++ is Fun! down the screen.
cout << “C++\n \ni\ns\n \nF\nu\nn\n!\n”;
return 0; // Returns to main()
}
348
C++ By
EXAMPLE
i
s
F
u
n
!
Review Questions
The answers to the review questions are in Appendix B.
1. True or false: A function should always include a return
statement as its last command.
2. What is the name of the first function executed in a C++
program?
3. Which is better: one long function or several smaller
functions? Why?
4. How do function names differ from variable names?
5. How can you use comments to help visually separate
functions?
6. What is wrong with the following program section?
calc_it()
{
cout << “Getting ready to calculate the square of 25 \n”;
sq_25()
{
cout << “The square of 25 is “ << (25*25);
return 0;
}
349
Chapter 16 ♦ Writing C++ Functions
Summary
You have now been exposed to truly structured programs.
Instead of typing a long program, you can break it into separate
functions. This method isolates your routines so surrounding code
doesn’t clutter your program and add confusion.
Functions introduce just a little more complexity, involving the
way variable values are recognized by the program’s functions. The
next chapter (Chapter 17, “Variable Scope”) shows you how vari-
ables are handled between functions, and helps strengthen your
structured programming skills.
350
Part IV
Variable Scope and
Modular Programming