C by Examples
C by Examples
EXAMPLE
C+ + By
Greg Perry
By
C++
Contents o
ii
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 books 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 books printing; the rightmost single-digit number, the
number of the books printing. For example, a printing code of 92-1 shows
that the first printing of the book occurred in 1992.
iii
EXAMPLE
C+ + By
Publisher
Lloyd Short
Publishing Manager
Joseph Wikert
Development Editor
Stacy Hiquet
Production Editor
Kezia Endsley
Copy Editor
Bryan Gambrel
Technical Editor
Tim Moore
Editorial Assistants
Rosemarie Graham
Melissa Keegan
Book Design
Scott Cook
Michele Laseau
Production Analyst
Mary Beth Wakefield
Cover Design
Jean Bisesi
Indexer
Johnna VanHoose
Production
Caroline Roop (Book Shepherd)
Jeff Baker, Paula Carroll,
Michelle Cleary, Brook Farling,
Kate Godfrey, Bob LaRoche,
Laurie Lee, Jay Lesandrini,
Cindy L. Phipps, Linda Seifert,
Phil Worthington
Composed in Palatino and MCPdigital typefaces by Prentice Hall Computer Publishing.
Screen reproductions in this book were created by means of the program Collage Plus
from Inner Media, Inc., Hollis, NH.
Contents o
iv
Dedic ation
Dr. Rick Burgess, you shaped my life. Good or bad, Im what I am
thanks to your help. I appreciate the many hours weve shared together.
G.M.P.
v
EXAMPLE
C+ + By
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.
Contents o
vi
vii
EXAMPLE
C+ + By
Ac knowledgments
Much thanks to Stacy Hiquet and Joseph Wikert at Prentice Hall
(Que) for trusting me completely with the direction and style of this
book. The rest of my editors: Kezia Endsley, Bryan Gambrel, and the
Technical Editor, Tim Moore, kept me on track so the readers can
have an accurate and readable text.
The Tulsa Junior College administration continues to be sup-
portive of my writing. More importantly, Diane Moore, head of our
Business Services Division, Tony Hirad, and Elaine Harris, are
friends who make teaching a joy and not a job.
As always, my beautiful bride Jayne, and my parents Glen and
Bettye Perry, are my closest daily companions. It is for them I work.
Trademark Ac knowledgments
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.
Contents o
viii
ix
EXAMPLE
C+ + By
Overview
I Introduc tion 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
II Using C++ Operators
8 Using C++ Math Operators and Precedence .......................... 163
9 Relational Operators ..................................................................185
10 Logical Operators .......................................................................207
11 Additional C++ Operators ........................................................ 221
III C++ Construc ts
12 The while Loop ...........................................................................245
13 The for Loop ................................................................................273
14 Other Loop Options ...................................................................295
15 The switch and goto Statements............................................... 311
16 Writing C++ Functions .............................................................. 331
IV Variable Sc ope and Modular
Programming
17 Variable Scope .............................................................................353
18 Passing Values ............................................................................379
19 Function Return Values and Prototypes ................................. 397
20 Default Arguments and Function Overloading..................... 415
V Charac ter Input /Output and
String Func tions
21 Device and Character Input/Output ....................................... 431
22 Character, String, and Numeric Functions ............................. 449
Contents o
x
VI Arrays and Pointers
23 Introducing Arrays .....................................................................473
24 Array Processing.........................................................................493
25 Multidimensional Arrays .......................................................... 519
26 Pointers ........................................................................................541
27 Pointers and Arrays ...................................................................557
VII Struc tures and File Input/Output
28 Structures .....................................................................................583
29 Arrays of Structures ...................................................................605
30 Sequential Files ...........................................................................625
31 Random-Access Files .................................................................645
32 Introduction to Object-Oriented Programming ..................... 661
VIII Referenc es
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
xi
EXAMPLE
C+ + By
Contents
Introduc tion ................................................... 1
Who Should Use This Book .................................................... 1
The Books 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 Introduc tion to C++
1 Welc ome to C++........................................... 11
What C++ Can Do for You........................................................ 12
The Background of C++ ............................................................ 15
C++ Compared with Other Languages................................... 16
C++ and Microcomputers ......................................................... 17
An Overview of Your Computer ............................................. 19
Hardware ................................................................................19
Software ...................................................................................29
Review Questions .......................................................................33
Summary .....................................................................................34
2 What Is a Program? ..................................... 35
Computer Programs ..................................................................36
Program Design ..........................................................................38
Using a Program Editor ............................................................. 40
Using a C++ Compiler ............................................................... 42
Running a Sample Program...................................................... 44
Handling Errors ..........................................................................46
Review Questions .......................................................................48
Summary .....................................................................................49
Contents o
xii
3 Your First C++ Program ............................... 51
Looking at a C++ Program........................................................ 52
The Format of a C++ Program ............................................. 53
Readability Is the Key............................................................ 54
Uppercase Versus Lowercase............................................... 55
Braces and main() ...................................................................56
Comments in C++ ..................................................................57
Explaining the Sample Program .............................................. 60
Review Questions .......................................................................66
Summary .....................................................................................67
4 Variables and Literals ................................. 69
Variables ......................................................................................70
Naming Variables ..................................................................70
Variable Types ........................................................................72
Declaring Variables................................................................73
Looking at Data Types .......................................................... 75
Assigning Values to Variables ............................................. 80
Literals..........................................................................................82
Assigning Integer Literals..................................................... 83
Assigning String Literals....................................................... 85
Assigning Character Literals ................................................ 89
Constant Variables .....................................................................94
Review Questions .......................................................................95
Review Exercises ........................................................................97
Summary .....................................................................................97
5 Charac ter Arrays and Strings ...................... 99
Character Arrays ......................................................................100
Character Arrays Versus Strings ............................................ 103
Review Questions .....................................................................110
Review Exercises ......................................................................111
Summary ...................................................................................111
6 Preproc essor Direc tives ............................ 113
Understanding Preprocessor Directives ............................... 114
The #include Directive ............................................................ 115
The #define Directive .............................................................. 120
xiii
EXAMPLE
C+ + By
Review Questions .....................................................................128
Review Exercises ......................................................................130
Summary ...................................................................................130
7 Simple Input/Output ................................... 133
The cout Operator ....................................................................134
Printing Strings.....................................................................134
The cin Operator ..................................................................144
printf() and scanf() ...................................................................149
The printf() Function................................................................149
Conversion Characters ............................................................ 151
The scanf() Function.................................................................154
Review Questions .....................................................................157
Review Exercises ......................................................................158
Summary ...................................................................................159
II Using C++ Operators
8 Using C++ Math Operators
and Prec edenc e ......................................... 163
C++s Primary Math Operators.............................................. 164
The Unary Operators ........................................................... 165
Division and Modulus......................................................... 167
The Order of Precedence ......................................................... 168
Using Parentheses ................................................................170
The Assignment Statements ................................................... 174
Multiple Assignments ......................................................... 175
Compound Assignments .................................................... 176
Mixing Data Types in Calculations ....................................... 178
Type Casting .........................................................................179
Review Questions .....................................................................182
Review Exercises ......................................................................183
Summary ...................................................................................184
9 Relational Operators ................................. 185
Defining Relational Operators................................................ 186
The if Statement ........................................................................189
The else Statement ....................................................................199
Contents o
xiv
Review Questions .....................................................................203
Review Exercises ......................................................................204
Summary ...................................................................................205
10 Logic al Operators ...................................... 207
Defining Logical Operators..................................................... 207
Logical Operators and Their Uses ......................................... 209
C++s Logical Efficiency...................................................... 211
Logical Operators and Their Precedence .............................. 216
Review Questions .....................................................................217
Review Exercises ......................................................................218
Summary ...................................................................................219
11 Additional C++ Operators .......................... 221
The Conditional Operator ....................................................... 222
The Increment and Decrement Operators ............................ 225
The sizeof Operator ..................................................................230
The Comma Operator .............................................................. 232
Bitwise Operators .....................................................................234
Bitwise Logical Operators................................................... 235
Review Questions .....................................................................242
Review Exercises ......................................................................243
Summary ...................................................................................243
III C++ Construc ts
12 The while Loop .......................................... 245
The while Statement.................................................................246
The Concept of Loops .............................................................. 247
The do-while Loop ...................................................................252
The if Loop Versus the while Loop........................................ 255
The exit() Function and break Statement .............................. 256
Counters and Totals .................................................................260
Producing Totals ..................................................................265
Review Questions .....................................................................268
Review Exercises ......................................................................269
Summary ...................................................................................270
xv
EXAMPLE
C+ + By
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 switc h and goto Statements .............. 311
The switch Statement ............................................................... 312
The goto Statement ...................................................................321
Review Questions .....................................................................327
Review Exercises ......................................................................328
Summary ...................................................................................328
16 Writing C++ Func tions ............................... 331
Function Basics .........................................................................332
Breaking Down Problems ....................................................... 333
More Function Basics ............................................................... 335
Calling and Returning Functions ........................................... 337
Review Questions .....................................................................349
Summary ...................................................................................350
IV Variable Sc ope and Modular Programming
17 Variable Sc ope .......................................... 353
Global Versus Local Variables................................................ 354
Defining Variable Scope...................................................... 355
Use Global Variables Sparingly ......................................... 362
The Need for Passing Variables ......................................... 363
Automatic Versus Static Variables......................................... 369
Contents o
xvi
Three Issues of Parameter Passing......................................... 374
Review Questions .....................................................................375
Review Exercises ......................................................................375
Summary ...................................................................................377
18 Passing Values .......................................... 379
Passing by Value (by Copy) .................................................... 379
Passing by Address (by Reference)........................................ 385
Variable Addresses .............................................................. 385
Sample Program...................................................................386
Passing Nonarrays by Address.......................................... 391
Review Questions .....................................................................394
Review Exercises ......................................................................395
Summary ...................................................................................396
19 Func tion Return Values and Prototypes ... 397
Function Return Values ........................................................... 398
Function Prototypes .................................................................405
Prototype for Safety ............................................................. 407
Prototype All Functions ...................................................... 407
Review Questions .....................................................................412
Review Exercises ......................................................................412
Summary ...................................................................................413
20 Default Arguments
and Func tion Overloading ......................... 415
Default Argument Lists ........................................................... 416
Multiple Default Arguments .................................................. 417
Overloaded Functions ............................................................. 420
Review Questions .....................................................................426
Review Exercises ......................................................................426
Summary ...................................................................................427
V Charac ter Input /Output
and String Func tions
21 Devic e and Charac ter Input/Output .......... 431
Stream and Character I/O ...................................................... 432
Standard Devices .................................................................434
Redirecting Devices from MS-DOS ................................... 435
xvii
EXAMPLE
C+ + By
Printing Formatted Output to the Printer............................. 436
Character I/O Functions ......................................................... 437
The get() and put() Functions............................................. 438
The getch() and putch() Functions .................................... 444
Review Questions .....................................................................446
Review Exercises ......................................................................447
Summary ...................................................................................448
22 Charac ter, String,
and Numeric Func tions ............................. 449
Character Functions .................................................................450
Character Testing Functions............................................... 450
Alphabetic and Digital Testing .......................................... 450
Special Character-Testing Functions ................................. 453
Character Conversion Functions ....................................... 453
String Functions ........................................................................455
Useful String Functions ....................................................... 456
String I/O Functions ........................................................... 456
Converting Strings to Numbers ......................................... 460
Numeric Functions ...................................................................461
Useful Mathematical Functions ......................................... 461
Trigonometric Functions..................................................... 464
Logarithmic Functions ........................................................ 465
Random-Number Processing ............................................. 465
Review Questions .....................................................................467
Review Exercises ......................................................................468
Summary ...................................................................................469
VI Arrays and Pointers
23 Introduc ing Arrays ..................................... 473
Array Basics...............................................................................474
Initializing Arrays ....................................................................479
Initializing Elements at Declaration Time ........................ 479
Initializing Elements in the Program ................................ 486
Review Questions .....................................................................491
Review Exercises ......................................................................491
Summary ...................................................................................492
Contents o
xviii
24 Array Proc essing ....................................... 493
Searching Arrays ......................................................................494
Searching for Values ................................................................496
Sorting Arrays ...........................................................................501
Advanced Referencing of Arrays........................................... 508
Review Questions .....................................................................515
Review Exercises ......................................................................516
Summary ...................................................................................517
25 Multidimensional Arrays ............................ 519
Multidimensional Array Basics .............................................. 520
Reserving Multidimensional Arrays ..................................... 522
Mapping Arrays to Memory................................................... 524
Defining Multidimensional Arrays ....................................... 526
Tables and for Loops ................................................................530
Review Questions .....................................................................537
Review Exercises ......................................................................538
Summary ...................................................................................538
26 Pointers ...................................................... 541
Introduction to Pointer Variables .......................................... 542
Declaring Pointers ................................................................543
Assigning Values to Pointers ............................................. 545
Pointers and Parameters ..................................................... 546
Arrays of Pointers.....................................................................551
Review Questions .....................................................................553
Summary ...................................................................................555
27 Pointers and Arrays ................................... 557
Array Names as Pointers......................................................... 558
Pointer Advantages ..................................................................560
Using Character Pointers ........................................................ 563
Pointer Arithmetic ....................................................................568
Arrays of Strings .......................................................................574
Review Questions .....................................................................578
Review Exercises ......................................................................579
Summary ...................................................................................580
xix
EXAMPLE
C+ + By
VII Struc tures and File Input/Output
28 Struc tures .................................................. 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 Struc tures .................................. 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-Ac c ess 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
Contents o
xx
32 Introduc tion to Objec t-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 Referenc es
A Memory Addressing, Binary,
and Hexadec imal Review .......................... 679
Computer Memory ..................................................................680
Memory and Disk Measurements ..................................... 680
Memory Addresses .............................................................. 681
Bits and Bytes ............................................................................682
The Order of Bits ......................................................................686
Binary Numbers .......................................................................686
Binary Arithmetic .....................................................................690
Binary Negative Numbers ...................................................... 692
Hexadecimal Numbers ............................................................ 695
Why Learn Hexadecimal? ....................................................... 697
How Binary and Addressing Relate to C++......................... 698
B Answers to Review Questions .................. 701
C ASCII Table ................................................ 719
D C++ Prec edenc e Table .............................. 729
E Keyword and Func tion Referenc e ............ 733
stdio.h ....................................................................................734
ctype.h....................................................................................734
string.h ...................................................................................735
math.h ....................................................................................735
stdlib.h ...................................................................................735
xxi
EXAMPLE
C+ + By
F The Mailing List Applic ation ..................... 737
Glossary ..................................................... 747
Index .......................................................... 761
Contents o
xxii
1
EXAMPLE
C+ + By
Introduc tion
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 Ques 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.
Who Should Use This Book
This book teaches at three levels: beginning, intermediate, and
advanced. Text and numerous examples are aimed at each level. If
you are new to C++, and even if you are new to computers, this book
attempts to put you at ease and gradually build your C++ program-
ming skills. If you are an expert at C++, this book provides a few
extras for you along the way.
Introduction o
2
The Books Philosophy
This book focuses on programming correctly in C++ by teaching
structured programming techniques and proper program design.
Emphasis is always placed on a programs readability rather than
tricks of the trade code examples. In this changing world, pro-
grams should be clear, properly structured, and well-documented,
and this book does not waver from the importance of this philos-
ophy.
This book teaches you C++ using a holistic approach. In addi-
tion to learning the mechanics of the language, you learn tips and
warnings, how to use C++ for different types of applications, and a
little of the history and interesting asides about the computing
industry.
Many other books build single applications, adding to them a
little at a time with each chapter. The chapters of this book are stand-
alone chapters, and show you complete programs that fully demon-
strate the commands discussed in the chapter. There is a program for
every level of reader, from beginning to advanced.
This book contains almost 200 sample program listings. These
programs show ways that you can use C++ for personal finance,
school and business record keeping, math and science, and general-
purpose applications that almost everybody with a computer can
use. This wide variety of programs show you that C++ is a very
powerful language that is easy to learn and use.
Appendix F, The Mailing List Application, is a complete
applicationmuch longer than any of the other programs in the
bookthat brings together your entire working knowledge of C++.
The application is a computerized mailing-list manager. Through-
out the chapters that come before the program, you learn how each
command in the program works. You can modify the program to
better suit your own needs. (The comments in the program suggest
changes you can make.)
Overview of This Book
This book is divided into eight parts. Part I introduces you to
the C++ environment, as well as introductory programming con-
cepts. Starting with Part II, the book presents the C++ programming
3
EXAMPLE
C+ + By
language commands and built-in functions. After mastering the
language, you can use the book as a handy reference. When you
need help with a specific C++ programming problem, turn to the
appropriate area that describes that part of the language to see
numerous examples of code.
To get an idea of the books layout, read the following descrip-
tion of each section of the book:
Part I: Introduc tion to C++
This section explains what C++ is by describing a brief history
of the C++ programming language and presenting an overview of
C++s advantages over other languages. This part describes your
computers hardware, how you develop your C++ programs, and
the steps you follow to enter and run programs. You begin to write
C++ programs in Chapter 3.
Part II: Using C++ Operators
This section teaches the entire set of C++ operators. The rich
assortment of operators (more than any other programming lan-
guage except APL) makes up for the fact that the C++ programming
language is very small. The operators and their order of precedence
are more important to C++ than most programming languages.
Part III: C++ Construc ts
C++ data processing is most powerful due to the looping,
comparison, and selection constructs that C++ offers. This part
shows you how to write programs flowing with control computa-
tions that produce accurate and readable code.
Part IV: Variable Sc ope and
Modular Programming
To support true structured programming techniques, C++
must allow for local and global variables, as well as offer several
Introduction o
4
ways to pass and return variables between functions. C++ is a very
strong structured language that attempts, if the programmer is
willing to listen to the language, to protect local variables by
making them visible only to the parts of the program that need them.
Part V: Charac ter Input/Output and
String Func tions
C++ contains no commands that perform input or output. To
make up for this apparent oversight, C++ compiler writers supply
several useful input and output functions. By separating input and
output functions from the language, C++ achieves better portability
between computers; if your program runs on one computer, it will
work on any other.
This part also describes several of the other built-in math,
character, and string functions available with C++. These functions
keep you from having to write your own routines to perform
common tasks.
Part VI: Arrays and Pointers
C++ offers single and multidimensional arrays that hold mul-
tiple occurrences of repeating data, but that do not require much
effort on your part to process.
Unlike many other programming languages, C++ also uses
pointer variables a great deal. Pointer variables and arrays work
together to give you flexible data storage that allow for easy sorting
and searching of data.
Part VII: Struc tures and File
Input/Output
Variables, arrays, and pointers are not enough to hold the types
of data that your programs require. Structures allow for more
powerful grouping of many different kinds of data into manageable
units.
Your computer would be too limiting if you could not store
data to the disk and retrieve that data back in your programs. Disk
5
EXAMPLE
C+ + By
files are required by most real world applications. This section
describes how C++ processes sequential and random-access files
and teaches the fundamental principles needed to effectively save
data to the disk. The last chapter in this section introduces object-
oriented programming and its use of classes.
Part VIII: Referenc es
This final section of the book includes a reference guide to the
ASCII table, the C++ precedence table, and to keywords and func-
tions in C++. Also in this section are the mailing list application and
the answers to the review questions.
Conventions Used in This
Book
The following typographic conventions are used in this book:
o Code lines, variables, and any text you see on-screen are in
monospace.
o Placeholders on format lines are in i t al i c monospace.
o Filenames are in regular text, all uppercase (CCDOUB.CPP).
o Optional parameters on format lines are enclosed in flat
brackets ([ ] ). You do not type the brackets when you
include these parameters.
o New terms, which are also found in the glossary, are in italic.
Index to the Ic ons
The following icons appear throughout this book:
Level 1 difficulty
Introduction o
6
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.
Margin Graphic s (Book Diagrams)
To help your understanding of C++ further, this book includes
numerous margin graphics. These margin graphics are similar to
flowcharts you have seen before. Both use standard symbols to
represent program logic. If you have heard of the adage A picture
is worth a thousand words, you will understand why it is easier to
look at the margin graphics and grasp the overall logic before
dissecting programs line-by-line.
7
EXAMPLE
C+ + By
Throughout this book, these margin graphics are used in two
places. Some graphics appear when a new command is introduced,
to explain how the command operates. Others appear when new
commands appear in sample programs for the first time.
The margin graphics do not provide complete, detailed expla-
nations of every statement in each program. They are simple instruc-
tions and provide an overview of the new statements in question.
The symbols used in the margin graphics, along with descriptions
of them, follow:
Terminal symbol
( {, }, Ret ur n. . . )
Assignment staement (t ot al =
t ot al + newval ue; ct r = ct r =
1; . . . )
Input/output
( scanf , pr i nt f . . . )
Calling a function
Small circle; loop begin
Large dot; begining and end
of I F- THEN, I F- THEN- ELSE,
and Swi t ch
Input/output of arrays;
assumes implied FOR loop(s)
needed to deal with array I/O
Comment bracket; used for
added info, such as name of a
function
Introduction o
8
The margin graphics, the program listings, the program com-
ments, and the program descriptions in the book provide many
vehicles for learning the C++ language!
Companion Disk Offer
If youd like to save yourself hours of tedious typing, use the
order form in the back of this book to order the companion disk for
C++ By Example. This disk contains the source code for all complete
programs and sample code in this book, as well as the mailing-list
application that appears in Appendix F. Additionally, the answers
to many of the review exercises are included on the disk.
Part I
Introduction to C++
11
EXAMPLE
C+ + By
1
Welc ome 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 bookstores 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.
Chapter 1 o W elcom e to C ++
12
What C++ Can Do for You
Imagine a language that makes your computer perform to your
personal specifications! Maybe you have looked for a program that
keeps track of your household budgetexactly as you preferbut
havent found one. Perhaps you want to track the records of a small
(or large) business with your computer, but you havent found a
program that prints reports exactly as youd like them. Possibly you
have thought of a new and innovative use for a computer and you
would like to implement your idea. C++ gives you the power to
develop all these uses for your computer.
If your computer could understand English, you would not
have to learn a programming language. But because it does not
understand English, you must learn to write instructions in a
language your computer recognizes. C++ is a powerful program-
ming language. Several companies have written different versions
of C++, but almost all C++ languages available today conform to the
AT&T standard. AT&T-compatible means the C++ language in ques-
tion conforms to the standard defined by the company that invented
the language, namely, American Telephone & Telegraph, Incorpo-
rated. AT&T realizes that C++ is still new and has not fully matured.
The good people there just completed the AT&T C++ 3.0 standard
to which software companies can conform. By developing a uniform
C++ language, AT&T helps ensure that programs you write today
will most likely be compatible with the C++ compilers of tomorrow.
NOTE: The AT&T C++ standard is only a suggestion. Software
companies do not have to follow the AT&T standard, although
most choose to do so. No typical computer standards commit-
tee has yet adopted a C++ standard language. The committees
are currently working on the issue, but they are probably
waiting for C++ to entrench the programming community
before settling on a standard.
Companies do not have to follow the AT&T C++ 3.0 standard.
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++.
C++ i s currentl y
defi ned by Ameri can
Tel ephone &
Tel egraph,
Incorporated, to
achi eve conformi ty
between versi ons
of C++.
C++ i s cal l ed a
better C than C.
13
EXAMPLE
C+ + By
AT&T developed C++ as an improved version of the C pro-
gramming language. C has been around since the 1970s and has
matured into a solid, extremely popular programming language.
ANSI, the American National Standards Institute, established a
standard C programming specification called ANSI C. If your C
compiler conforms to ANSI C, your program will work on any other
computer that also has ANSI C. This compatibility between comput-
ers is so important that AT&Ts C++ 3.0 standard includes almost
every element of the ANSI C, plus more. In fact, the ANSI C
committee often requires that a C++ feature be included in subse-
quent versions of C. For instance, function prototypes, a feature not
found in older versions of ANSI C, is now a requirement for
approval by the ANSI committee. Function prototypes did not exist
until AT&T required them in their early C++ specification.
C++ By Example teaches you to program in C++. All programs
conform to the AT&T C++ 2.1 standard. The differences between
AT&T 2.1 and 3.0 are relatively minor for beginning programmers.
As you progress in your programming skills, you will want to tackle
the more advanced aspects of C++ and Version 3.0 will come more
into play later. Whether you use a PC, a minicomputer, a mainframe,
or a supercomputer, the C++ language you learn here should work
on any that conform to AT&T C++ 2.1 and later.
There is a debate in the programming community as to whether
a person should learn C before C++ or learn only C++. Because C++
is termed a better C, many feel that C++ is an important language
in its own right and can be learned just as easily as C. Actually, C++
pundits state that C++ teaches better programming habits than the
plain, vanilla C. This book is aimed at the beginner programmer,
and the author feels that C++ is a great language with which to
begin. If you were to first learn C, you would have to unlearn a few
things when you moved to C++. This book attempts to use the C++
language elements that are better than C. If you are new to program-
ming, you learn C++ from the start. If you have a C background, you
learn that C++ overcomes many of Cs limitations.
When some people attempt to learn C++ (and C), even if they
are programmers in other computer languages, they find that
C++ can be cryptic and difficult to understand. This does not have
to be the case. When taught to write clear and concise C++ code in
an order that builds on fundamental programming concepts,
Chapter 1 o W elcom e to C ++
14
programmers find that C++ is no more difficult to learn or use than
any other programming language. Actually, after you start using it,
C++s modularity makes it even easier to use than most other
languages. Once you master the programming elements this book
teaches you, you will be ready for the advanced power for which
C++ was designedobject-oriented programming (OOP). The last
chapter of this book, Introduction to Object-Oriented Program-
ming, offers you the springboard to move to this exciting way of
writing programs.
Even if youve never programmed a computer before, you will
soon understand that programming in C++ is rewarding. Becoming
an expert programmer in C++or in any other computer lan-
guagetakes time and dedication. Nevertheless, you can start
writing simple programs with little effort. After you learn the
fundamentals of C++ programming, you can build on what you
learn and hone your skills as you write more powerful programs.
You also might see new uses for your computer and develop
programs others can use.
The importance of C++ cannot be overemphasized. Over the
years, several programming languages were designed to be the
only programming language you would ever need. PL/I was
heralded as such in the early 1960s. It turned out to be so large and
took so many system resources that it simply became another
language programmers used, along with COBOL, FORTRAN, and
many others. In the mid-1970s, Pascal was developed for smaller
computers. Microcomputers had just been invented, and the Pascal
language was small enough to fit in their limited memory space
while still offering advantages over many other languages. Pascal
became popular and is still used often today, but it never became the
answer for all programming tasks, and it failed at being the only
programming language you would ever need.
When the mass computer markets became familiar with C in
the late 1970s, C also was promoted as the only programming
language you would ever need. What has surprised so many
skeptics (including this author) is that C has practically fulfilled this
promise! An incredible number of programming shops have con-
verted to C. The appeal of Cs efficiency, combined with its portabil-
ity among computers, makes it the language of choice. Most of
15
EXAMPLE
C+ + By
The UNIX operati ng
system was wri tten
al most enti rel y i n C.
todays 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 todays business and industry.
The Bac kground of C++
Before you jump into C++, you might find it helpful to know a
little about the evolution of the C++ programming language. C++ is
so deeply rooted in C that you should first see where C began. Bell
Labs first developed the C programming language in the early
1970s, primarily so Bell programmers could write their UNIX oper-
ating system for a new DEC (Digital Equipment Corporation) com-
puter. Until that time, operating systems were written in assembly
language, which is tedious, time-consuming, and difficult to main-
tain. The Bell Labs people knew they needed a higher-level pro-
gramming language to implement their project quicker and create
code that was easier to maintain.
Because other high-level languages at the time (COBOL, FOR-
TRAN, PL/I, and Algol) were too slow for an operating systems
code, the Bell Labs programmers decided to write their own lan-
guage. They based their new language on Algol and BCPL. Algol is
still used in the European markets, but is not used much in America.
BCPL strongly influenced C, although it did not offer the various
data types that the makers of C required. After a few versions, these
Bell programmers developed a language that met their goals well. C
is efficient (it is sometimes called a high, low-level language due to
its speed of execution), flexible, and contains the proper language
elements that enable it to be maintained over time.
Chapter 1 o W elcom e to C ++
16
In the 1980s, Bjourn Stroustrup, working for AT&T, took the C
language to its next progression. Mr. Stroustrup added features to
compensate for some of the pitfalls C allowed and changed the way
programmers view programs by adding object-orientation to the
language. The object-orientation aspect of programming started in
other languages, such as Smalltalk. Mr. Stroustrup realized that C++
programmers needed the flexibility and modularity offered by a
true OOP programming language.
C++ Compared with Other
Languages
If you have programmed before, you should understand a little
about how C++ differs from other programming languages on the
market. C++ is efficient and has much stronger typing than its C
predecessor. C is known as a weakly typed language; variable data
types do not necessarily have to hold the same type of data. (Func-
tion prototyping and type casting help to alleviate this problem.)
For example, if you declare an integer variable and decide to
put a character value in it, C enables you to do so. The data might not
be in the format you expect, but C does its best. This is much different
from stronger-typed languages such as COBOL and Pascal.
If this discussion seems a little over your head at this point,
relax. The upcoming chapters will elaborate on these topics and
provide many examples.
C++ is a small, block-structured programming language. It has
fewer than 46 keywords. To compensate for its small vocabulary,
C++ has one of the largest assortment of operators such as +, - , and &&
(second only to APL). The large number of operators in C++ might
tempt programmers to write cryptic programs that have only a
small amount of code. As you learn throughout this book, however,
you will find that making the program more readable is more
important than saving some bytes. This book teaches you how to
use the C++ operators to their fullest extent, while maintaining
readable programs.
C++s large number of operators (almost equal to the number
of keywords) requires a more judicious use of an operator precedence
C++ requi res more
stri ngent data- type
checki ng than
does C.
17
EXAMPLE
C+ + By
table. Appendix D, C++ Precedence Table, includes the C++
operator precedence table. Unlike most other languages that have
only four or five levels of precedence, C++ has 15. As you learn C++,
you have to master each of these 15 levels. This is not as difficult as
it sounds, but its importance cannot be overstated.
C++ also has no input or output statements. You might want to
read that sentence again! C++ has no commands that perform input
or output. This is one of the most important reasons why C++ is
available on so many different computers. The I/O (input/output)
statements of most languages tie those languages to specific hard-
ware. BASIC, for instance, has almost twenty I/O commands
some of which write to the screen, to the printer, to a modem, and so
forth. If you write a BASIC program for a microcomputer, chances
are good that it cannot run on a mainframe without considerable
modification.
C++s input and output are performed through the abundant
use of operators and function calls. With every C++ compiler comes
a library of standard I/O functions. I/O functions are hardware
independent, because they work on any device and on any computer
that conform to the AT&T C++ standard.
To master C++ completely, you have to be more aware of your
computers hardware than most other languages would require you
to be. You certainly do not have to be a hardware expert, but
understanding the internal data representation makes C++ much
more usable and meaningful.
It also helps if you can become familiar with binary and
hexadecimal numbers. You might want to read Appendix A,
Memory Addressing, Binary, and Hexadecimal Review, for a
tutorial on these topics before you start to learn the C++ language.
If you do not want to learn these topics, you can still become a good
C++ programmer, but knowing what goes on under the hood
makes C++ more meaningful to you as you learn it.
C++ and Mic roc omputers
C was a relatively unknown language until it was placed on the
microcomputer. With the invention and growth of the microcom-
puter, C blossomed into a worldwide computer language. C++
Chapter 1 o W elcom e to C ++
18
extends that use on smaller computers. Most of readers of C++ By
Example are probably working on a microcomputer-based C++
system. If you are new to computers, this section will help you learn
how microcomputers were developed.
In the 1970s, NASA created the microchip, a tiny wafer of sili-
con that occupies a space smaller than a postage stamp. Computer
components were placed on these microchips, hence computers
required much less space than before. NASA produced these
smaller computers in response to their need to send rocket ships to
the moon with on-board computers. The computers on Earth could
not provide split-second accuracy for rockets because radio waves
took several seconds to travel between the Earth and the moon.
Through development, these microchips became small enough so
the computers could travel with a rocket and safely compute the
rockets trajectory.
The space program was not the only beneficiary of computer
miniaturization. Because microchips became the heart of the mi-
crocomputer, computers could now fit on desktops. These micro-
computers cost much less than their larger counterparts, so many
people started buying them. Thus, the home and small-business
computer market was born.
Today, microcomputers are typically called PCs from the wide-
spread use of the original IBM PC. The early PCs did not have the
memory capacity of the large computers used by government and
big business. Nevertheless, PC owners still needed a way to pro-
gram these machines. BASIC was the first programming language
used on PCs. Over the years, many other languages were ported
from larger computers to the PC. However, no language was as
successful as C in becoming the worldwide standard programming
language. C++ seems to be the next standard.
Before diving into C++, you might take a few moments to
familiarize yourself with some of the hardware and software com-
ponents of your PC. The next section, An Overview of Your
Computer, introduces you to computer components that C++
interacts with, such as the operating system, memory, disks, and
I/O devices. If you are already familiar with your computers
hardware and software, you might want to skip to Chapter 2, What
Is a Program?, and begin using C++.
19
EXAMPLE
C+ + By
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 computers
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.
System Unit
Keyboard
Mouse
Printer
Modem
Monitor
Figure 1.1. A typical PC system.
Disk Drives
Chapter 1 o W elcom e to C ++
20
The System Unit and Memory
The system unit is the large, box-shaped component of the
computer. This unit houses the PCs microprocessor. You might
hear the microprocessor called the CPU, or central processing unit.
The CPU acts like a traffic cop, directing the flow of information
throughout your computer system. The CPU is analogous also to the
human brain. When you use a computer, you are actually interact-
ing with its CPU. All the other hardware exists so the CPU can send
information to you (through the monitor or the printer), and you can
give instructions to the CPU (through the keyboard or the mouse).
The CPU also houses the computers internal memory. Al-
though the memory has several names, it is commonly referred to as
RAM (random-access memory). RAM is where the CPU looks for
software and data. When you run a C++ program, for example, you
are instructing your computers CPU to look in RAM for that
program and carry out its instructions. C++ uses RAM space when
it is loaded.
RAM is used for many things and is one of the most important
components of your computers hardware. Without RAM, your
computer would have no place for its instructions and data. The
amount of RAM can also affect the computers speed. In general, the
more RAM your computer has, the more work it can do and the
faster it can process data.
The amount of RAM is measured by the number of characters
it can hold. PCs generally hold approximately 640,000 characters of
RAM. A character in computer terminology is called a byte, and a
byte can be a letter, a number, or a special character such as an
exclamation point or a question mark. If your computer has 640,000
bytes of RAM, it can hold a total of 640,000 characters.
All the zeros following RAM measurements can become cum-
bersome. You often see the shortcut notation K (which comes from
the metric systems kilo, meaning 1000) in place of the last three
zeros. In computer terms, K means exactly 1024 bytes; but this
number is usually rounded to 1000 to make it easier to remember.
Therefore, 640K represents approximately 640,000 bytes of RAM.
For more information, see the sidebar titled The Power of Two.
The limitations of RAM are similar to the limitations of audio
cassette tapes. If a cassette is manufactured to hold 60 minutes of
A byte i s a si ngl e
character of memory.
21
EXAMPLE
C+ + By
music, it cannot hold 75 minutes of music. Likewise, the total
number of characters that compose your program, the C++ data, and
your computers system programs cannot exceed the RAMs limit
(unless you save some of the characters to disk).
You want as much RAM as possible to hold C++, data, and the
system programs. Generally, 640K is ample room for anything you
might want to do in C++. Computer RAM is relatively inexpensive,
so if your computer has less than 640K bytes of memory, you should
consider purchasing additional memory to increase the total RAM
to 640K. You can put more than 640K in most PCs. There are two
types of additional RAM: extended memory and expanded memory
(they both offer memory capacity greater than 640K). You can access
this extra RAM with some C++ systems, but most beginning C++
programmers have no need to worry about RAM beyond 640K.
The Power of Two
Although K means approximately 1000 bytes of memory, K
equates to 1024. Computers function using on and off states of
electricity. These are called binary states. At the computers
lowest level, it does nothing more than turn electricity on and
off with many millions of switches called transistors. Because
these switches have two possibilities, the total number of states
of these switchesand thus the total number of states of
electricityequals a number that is a power of 2.
The closest power of 2 to 1000 is 1024 (2 to the 10th power). The
inventors of computers designed memory so that it is always
added in kilobytes, or multiples of 1024 bytes at a time. There-
fore, if you add 128K of RAM to a computer, you are actually
adding a total of 131,072 bytes of RAM (128 times 1024 equals
131,072).
Because K actually means more than 1000, you always have a
little more memory than you bargained for! Even though your
computer might be rated at 640K, it actually holds more than
640,000 bytes (655,360 to be exact). See Appendix A, Memory
Addressing, Binary, and Hexadecimal Review, for a more
detailed discussion of memory.
Chapter 1 o W elcom e to C ++
22
The computer stores C++ programs to RAM as you write them.
If you have used a word processor before, you have used RAM. As
you type words in your word-processed documents, your words
appear on the video screen and also go to RAM for storage.
Despite its importance, RAM is only one type of memory in
your computer. RAM is volatile; when you turn the computer off, all
RAM is erased. Therefore, you must store the contents of RAM to a
nonvolatile, more permanent memory device (such as a disk) before
you turn off your computer. Otherwise, you lose your work.
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 disks 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 youre 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 RAMs 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
23
EXAMPLE
C+ + By
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.
Write-protect notch
Write-protect notch
Figure 1.2. 5 1/4-inch disk and 3 1/2-inch disk.
Before using a new box of disks, you have to format them
(unless you buy disks that are already formatted). Formatting
prepares the disks for use on your computer by writing a pattern of
paths, called tracks, where your data and programs are stored. Refer
to the operating system instruction manual for the correct format-
ting procedure.
Disk drives house the disks in your computer. Usually, the disk
drives are stored in your system unit. The hard disk is sealed inside
the hard disk drive, and you never remove it (except for repairs). In
general, the floppy disk drives also are contained in the system unit,
but you insert and remove these disks manually.
Disk drives have names. The computers first floppy disk drive
is called drive A. The second floppy disk drive, if you have one, is
called drive B. The first hard disk (many computers have only one)
is called drive C. If you have more than one hard disk, or if your hard
disk is logically divided into more than one, the others are named
drive D, drive E, and so on.
Label
Insert this side into drive
Insert this side into drive
Label
Chapter 1 o W elcom e to C ++
24
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.
25
EXAMPLE
C+ + By
The Printer
The printer provides a more permanent way of recording your
computers 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
Chapter 1 o W elcom e to C ++
26
message, you can press Esc to remove the help message from the
screen.
Spacebar
Shift Alt
Function keys
Shift
Slash (/)
Enter Control Escape Backslash (\) Backspace
Spacebar
Shift Alt
Function keys
Shift
Slash (/)
Control Tab Backslash (\) Enter Backspace Escape
Tab
Escape Function keys
Backslash (\)
Backspace
Enter
Shift
Spacebar
Control
Tab
Slash (/) Alt Shift
Figure 1.3. The various PC keyboards.
Numeric keypad
Numeric keypad
Numeric keypad
27
EXAMPLE
C+ + By
The group of numbers and arrows on the far right of the
keyboard is called the numeric keypad. People familiar with a 10-key
adding machine usually prefer to type numbers from the keypad
rather than from the top row of the alphabetic key section. The
numbers on the keypad work only when you press the NumLock
key. If you press NumLock a second time, you disable these number
keys and make the arrow keys work again. To prevent confusion,
many keyboards have separate arrow keys and a keypad used solely
for numbers.
The arrows help you move the cursor from one area of the
screen to another. To move the cursor toward the top of the screen,
you have to press the up arrow continuously. To move the cursor to
the right, you press the right-arrow, and so on. Do not confuse the
Backspace key with the left-arrow. Pressing Backspace moves the
cursor backward one character at a timeerasing everything as it
moves. The left-arrow simply moves the cursor backward, without
erasing.
The keys marked Insert and Delete (Ins and Del on some
keyboards) are useful for editing. Your C++ program editor prob-
ably takes advantage of these two keys. Insert and Delete work on
C++ programs in the same way they work on a word processors
text. If you do not have separate keys labeled Insert and Delete, you
probably have to press NumLock and use the keypad key 0 (for
Insert) and period (for Delete).
PgUp and PgDn are the keys to press when you want to scroll
the screen (that is, move your on-screen text either up or down).
Your screen acts like a camera that pans up and down your C++
programs. You can move the screen down your text by pressing
PgDn, and up by pressing PgUp. (Like Insert and Delete, you might
have to use the keypad for these operations.)
The keys labeled F1 through F12 (some keyboards go only to
F10) are called function keys. The function keys are located either
across the top of the alphabetic section or to the left of it. These keys
perform an advanced function, and when you press one of them,
you usually want to issue a complex command, such as searching for
a specific word in a program. The function keys in your C++
program, however, do not necessarily produce the same results as
they might in another program, such as a word processor. In other
words, function keys are application-specific.
Chapter 1 o W elcom e to C ++
28
CAUTION: Computer keyboards have a key for number 1, so
do not substitute the lowercase l to represent the number 1, as
you might on a typewriter. To C++, a 1 is different from the
letter l. You should be careful also to use 0 when you mean zero,
and O when you want the uppercase letter O.
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 PC modem enables your PC to communicate with other
computers over telephone lines. Some modems, called external
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.
A modem can be
used to communi -
cate between two
di stant computers.
29
EXAMPLE
C+ + By
A Modem by Any Other Name...
The term digital computer comes from the fact that your com-
puter operates on binary (on and off) digital impulses of
electricity. These digital states of electricity are perfect for your
computers equipment, but they cannot be sent over normal
telephone lines. Telephone signals are called analog signals,
which are much different from the binary digital signals in
your PC.
Therefore, before your computer can transmit data over a
telephone line, the information must be modulated (converted)
to analog signals. The receiving computer must have a way to
demodulate (convert back) those signals to digital.
The modem is the means by which computer signals are
modulated and demodulated from digital to analog and vice
versa. Thus, the name of the device that modulates and demodu-
lates these signals is modem.
Software
No matter how fast, large, and powerful your computers
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 computers disk and load it in
your computers 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.
Programs and Data
No doubt you have heard the phrase, data processing. This is
what computers actually do: they take data and manipulate it into
Chapter 1 o W elcom e to C ++
30
meaningful output. The meaningful output is called information.
Figure 1.4 shows the input-process-output model, which is the foun-
dation of everything that happens in your computer.
Figure 1.4. Data processing at its most elementary level.
In Chapter 2, What Is a Program?, you learn the mechanics of
programs. For now, you should know that the programs you write
in C++ process the data that you input in the programs. Both data
and programs compose the software. The hardware acts as a vehicle
to gather the input and produce the output. Without software,
computers would be worthless, just as an expensive stereo would be
useless without some way of playing music so you can hear it.
The input comes from input devices, such as keyboards, mo-
dems, and disk drives. The CPU processes the input and sends the
results to the output devices, such as the printer and the monitor. A
C++ payroll program might receive its input (the hours worked)
from the keyboard. It would instruct the CPU to calculate the payroll
amounts for each employee in the disk files. After processing the
payroll, the program could print the checks.
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 computers hardware,
including the monitor, keyboard, and printer.
Figure 1.5 illustrates the concept of DOS as the go-between
with your computers 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++ i s f un! on your printer takes many
computer instructions. However, you do not have to worry about all
31
EXAMPLE
C+ + By
those instructions. When your C++ program wants to print some-
thing, it tells DOS to print it. DOS always knows how to send
information to your printer, so it takes your C++ program requests
and does the work of routing that data to the printer.
Figure 1.5. DOS interfaces between hardware and software.
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).
Chapter 1 o W elcom e to C ++
32
NOTE: As mentioned, DOS always resides in RAM and is
loaded when you start the computer. This is done automati-
cally, so you can use your computer and program in C++
without worrying about how to transfer DOS to RAM. It is
important to remember that DOS always uses some of your
total RAM.
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
RAMseveral boxes stacked on top of each other. Each memory
location (each byte) has a unique address, just as everybodys 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.
Your operating system (whether you use MS-DOS, PC DOS,
DR DOS, or UNIX) takes part of the first few thousand bytes of
memory. The amount of RAM that DOS takes varies with each
computers configuration. When working in C++, the C++ system
sits on top of DOS, leaving you with the remainder of RAM for your
program and data. This explains why you might have a total of 512K
of RAM and still not have enough memory to run some programs
DOS is using some of the RAM for itself.
33
EXAMPLE
C+ + By
Review Questions
The answers to each chapters 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?
Chapter 1 o W elcom e to C ++
34
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.
35
EXAMPLE
C+ + By
2
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 programs 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
o The concept of programming
o The programs output
o Program design
o Using an editor
o Using a compiler
Chapter 2 o W hat Is a Program ?
36
o Typing and running a C++ program
o Handling errors
After you complete this chapter, you should be ready to learn
the C++ programming language elements in greater detail.
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.
NOTE: A program is a list of instructions that tells the computer
to do things.
Keep in mind that computers are only machines. Theyre not
smart; in fact, theyre quite the opposite! They dont do anything
until they are given detailed instructions. A word processor, for
example, is a program somebody wrotein a language such as
C++that tells your computer exactly how to behave when you
type words into it.
You are familiar with the concept of programming if you have
ever followed a recipe, which is a program, or a list of instructions,
telling you how to prepare a certain dish. A good recipe lists these
instructions in their proper order and with enough description so
you can carry out the directions successfully, without assuming
anything.
If you want your computer to help with your budget, keep
track of names and addresses, or compute your gas mileage, it needs
a program to tell it how to do those things. You can supply that
program in two ways: buy a program somebody else wrote, or write
the program yourself.
Writing the program yourself has a big advantage for many
applications: The program does exactly what you want it to do. If you
buy one that is already written, you have to adapt your needs to
those of the author of the program. This is where C++ comes into
37
EXAMPLE
C+ + By
play. With the C++ programming language (and a little studying),
you can make your computer carry out your own tasks precisely.
To give C++ programming instructions to your computer, you
need an editor and a C++ compiler. An editor is similar to a word
processor; it is a program that enables you to type a C++ program
into memory, make changes (such as moving, copying, inserting,
and deleting text), and save the program more permanently in a disk
file. After you use the editor to type the program, you must compile
it before you can run it.
The C++ programming language is called a compiled language.
You cannot write a C++ program and run it on your computer unless
you have a C++ compiler. This compiler takes your C++ language
instructions and translates them into a form that your computer can
read. A C++ compiler is the tool your computer uses to understand
the C++ language instructions in your programs. Many compilers
come with their own built-in editor. If yours does, you probably feel
that your C++ programming is more integrated.
To some beginning programmers, the process of compiling a
program before running it might seem like an added and meaning-
less step. If you know the BASIC programming language, you might
not have heard of a compiler or understand the need for one. Thats
because BASIC (also APL and some versions of other computer
languages) is not a compiled language, but an interpreted language.
Instead of translating the entire program into machine-readable
form (as a compiler does in one step), an interpreter translates each
program instructionthen executes itbefore translating the next
one. The difference between the two is subtle, but the bottom line is
not: Compilers produce much more efficient and faster-running
programs than interpreters do. This seemingly extra step of compil-
ing is worth the effort (and with todays compilers, there is not much
extra effort needed).
Because computers are machines that do not think, the instruc-
tions you write in C++ must be detailed. You cannot assume your
computer understands what to do if some instruction is not in your
program, or if you write an instruction that does not conform to C++
language requirements.
After you write and compile a C++ program, you have to run,
or execute, it. Otherwise, your computer would not know that you
Chapter 2 o W hat Is a Program ?
38
want it to follow the instructions in the program. Just as a cook must
follow a recipes instructions before making the dish, so too your
computer must execute a programs instructions before it can ac-
complish what you want it to do. When you run a program, you are
telling the computer to carry out your instructions.
The Program and Its Output
While you are programming, remember the difference be-
tween a program and its output. Your program contains only
the C++ instructions that you write, but the computer follows
your instructions only after you run the program.
Throughout this book, you often see a program listing (that is,
the C++ instructions in the program) followed by the results
that occur when you run the program. The results are the
output of the program, and they go to an output device such as
the screen, the printer, or a disk file.
Program Design
You must plan your programs before typing them into your
C++ editor. When builders construct houses, for example, they dont
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 programs output (what the user should see).
Desi gn your
programs before you
type them.
39
EXAMPLE
C+ + By
3. Break the problem into logical steps to achieve this output.
4. Write the program (using the editor).
5. Compile the program.
6. Test the program to assure it performs as you expect.
As you can see from this procedure, the typing of your program
occurs toward the end of your programming. This is important,
because you first have to plan how to tell the computer how to
perform each task.
Your computer can perform instructions only step-by-step.
You must assume that your computer has no previous knowledge
of the problem, so it is up to you to provide that knowledge, which,
after all, is what a good recipe does. It would be a useless recipe for
a cake if all it said was: Bake the cake. Why? Because this assumes
too much on the part of the baker. Even if you write the recipe in
step-by-step fashion, proper care must be taken (through planning)
to be sure the steps are in sequence. Wouldnt it be foolish also to
instruct a baker to put the ingredients into the oven before stirring
them?
This book adheres to the preceding programming procedure
throughout the book, as each program appears. Before you see the
actual program, the thought process required to write the program
appears. The goals of the program are presented first, then these
goals are broken into logical steps, and finally the program is
written.
Designing the program in advance guarantees that the entire
program structure is more accurate and keeps you from having to
make changes later. A builder, for example, knows that a room is
much harder to add after the house is built. If you do not properly
plan every step, it is going to take you longer to create the final,
working program. It is always more difficult to make major changes
after you write your program.
Planning and developing according to these six steps becomes
much more important as you write longer and more complicated
programs. Throughout this book, you learn helpful tips for program
design. Now its time to launch into C++, so you can experience the
satisfaction of typing your own program and seeing it run.
Chapter 2 o W hat Is a Program ?
40
Using a Program Editor
The instructions in your C++ program are called the source code.
You type source code into your computers memory by using your
program editor. After you type your C++ source code (your pro-
gram), you should save it to a disk file before compiling and running
the program. Most C++ compilers expect C++ source programs to be
stored in files with names ending in .CPP. For example, the follow-
ing are valid filenames for most C++ compilers:
MYPROG.CPP
SALESACT.CPP
EMPLYEE.CPP
ACCREC.CPP
Many C++ compilers include a built-in editor. Two of the most
popular C++ compilers (both conform to the AT&T C++ 2.1 stan-
dard and include their own extended language elements) are
Borlands C++ and Microsofts C/C++ 7.0 compilers. These two
programs run in fully integrated environments that relieve the
programmer from having to worry about finding a separate pro-
gram editor or learning many compiler-specific commands.
Figure 2.1 shows a Borland C++ screen. Across the top of the
screen (as with Microsoft C/C++ 7.0) is a menu that offers pull-
down editing, compiling, and running options. The middle of the
screen contains the body of the program editor, and this is the area
where the program goes. From this screen, you type, edit, compile,
and run your C++ source programs. Without an integrated environ-
ment, you would have to start an editor, type your program, save the
program to disk, exit the editor, run the compiler, and only then run
the compiled program from the operating system. With Borlands
C++ and Microsoft C/C++ 7.0, you simply type the program into the
editor, thenin one stepyou select the proper menu option that
compiles and runs the program.
41
EXAMPLE
C+ + By
Figure 2.1. Borland Turbo C++s integrated environment.
If you do not own an integrated environment such as Borland
C++ or Microsoft C/C++, you have to find a program editor. Word
processors can act as editors, but you have to learn how to save and
load files in a true ASCII text format. It is often easier to use an editor
than it is to make a word processor work like one.
On PCs, DOS Version 5 comes with a nice, full-screen editor
called EDIT. It offers menu-driven commands and full cursor-
control capabilities. EDIT is a simple program to use, and is a good
beginners program editor. Refer to your DOS manual or a good
book on DOS, such as MS-DOS 5 QuickStart (Que), for more infor-
mation on this program editor.
Another editor, called EDLIN, is available for earlier versions
of DOS. EDLIN is a line editor that does not allow full-screen cursor
control, and it requires you to learn some cryptic commands. The
advantage to learning EDLIN is that it is always included with all
PCs that use a release of DOS prior to Version 5.
Chapter 2 o W hat Is a Program ?
42
If you use a computer other than a PC, such as a UNIX-based
minicomputer or a mainframe, you have to determine which editors
are available. Most UNIX systems include the vi editor. If you
program on a UNIX operating system, it would be worth your time
to learn vi . It is to UNIX what EDLIN is to PC operating systems, and
is available on almost every UNIX computer in the world.
Mainframe users have other editors available, such as the ISPF
editor. You might have to check with your systems department to
find an editor accessible from your account.
NOTE: Because this book teaches the generic AT&T C++
standard programming language, no attempt is made to tie in
editor or compiler commandsthere are too many on the
market to cover them all in one book. As long as you write
programs specific to the AT&T C++, the tools you use to edit,
compile, and run those programs are secondary; your goal of
good programming is the result of whatever applications you
produce.
Using a C++ Compiler
After you type and edit your C++ programs source code, you
have to compile the program. The process you use to compile your
program depends on the version of C++ and the computer you are
using. Borland C++ and Microsoft C/C++ users need only press Alt-
R to compile and run their programs. When you compile programs
on most PCs, your compiler eventually produces an executable file
with a name beginning with the same name as the source code, but
ends with an .EXE file extension. For example, if your source
program is named GRADEAVG.CPP, the PC would produce a
compiled file called GRADEAVG.EXE, which you could execute at
the DOS prompt by typing the name gr adeavg.
43
EXAMPLE
C+ + By
NOTE: Each program in this book contains a comment that
specifies a recommended filename for the source program. You
do not have to follow the file-naming conventions used in this
book; the filenames are only suggestions. If you use a main-
frame, you have to follow the dataset-naming conventions set
up by your system administrator. Each program name in the
sample disk (see the order form at the back of the book) matches
the filenames of the program listings.
UNIX users might have to use the cf r ont compiler. Most cf r ont
compilers actually convert C++ code into regular C code. The C code
is then compiled by the systems 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 programs 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 compilers reference manuals
or to your companys 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,
Chapter 2 o W hat Is a Program ?
44
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.
Figure 2.2. Compiling C++ source code into an executable program.
Running a Sample Program
Before delving into the specifics of the C++ language, you
should take a few moments to become familiar with your editor and
C++ compiler. Starting with the next chapter, Your First C++
Program, you should put all your concentration into the C++
programming language and not worry about using a specific editor
or compiling environment.
45
EXAMPLE
C+ + By
Therefore, start your editor of choice and type Listing 2.1,
which follows, into your computer. Be as accurate as possiblea
single typing mistake could cause the C++ compiler to generate a
series of errors. You do not have to understand the programs
content at this point; the goal is to give you practice in using your
editor and compiler.
Listing 2.1. Practicing with the editor.
Comment the program with the program name.
Include the header file iostream.h so the output properly works.
Start of the mai n( ) function.
Define the BELL constant, which is the computers beep.
Initialize the integer variable ct r to 0.
Define the character array f name to hold 20 elements.
Print to the screen What i s your f i r st name?.
Accept a string from the keyboard.
Process a loop while the variable ct r is less than five.
Print the string accepted from the keyboard.
Increment the variable ct r by 1.
Print to the screen the character code that sounds the beep.
Return to the operating system.
/ / Fi l ename: C2FI RST. CPP
/ / Request s a name, pr i nt s t he name f i ve t i mes, and r i ngs a bel l .
#i ncl ude <i ost r eam. h>
mai n( )
{
const char BELL= \ a ; / / Const ant t hat r i ngs t he bel l
i nt ct r =0; / / I nt eger var i abl e t o count t hr ough l oop
char f name[ 20] ; / / Def i ne char act er ar r ay t o hol d name
cout << What i s your f i r st name? ; / / Pr ompt t he user
ci n >> f name; / / Get t he name f r omt he keyboar d
whi l e ( ct r < 5) / / Loop t o pr i nt t he name
Chapter 2 o W hat Is a Program ?
46
{ / / exact l y f i ve t i mes.
cout << f name << \ n;
ct r ++;
}
cout << BELL; / / Ri ng t he t er mi nal s bel l
r et ur n 0;
}
Be as accurate as possible. In most programming languages
and especially in C++the characters you type into a program must
be very accurate. In this sample C++ program, for instance, you see
parentheses, ( ) , brackets, [ ] , and braces, {}, but you cannot use them
interchangeably.
The comments (words following the two slashes, / / ) to the right
of some lines do not have to end in the same place that you see in the
listing. They can be as long or short as you need them to be.
However, you should familiarize yourself with your editor and
learn to space characters accurately so you can type this program
exactly as shown.
Compile the program and execute it. Granted, the first time you
do this you might have to check your reference manuals or contact
someone who already knows your C++ compiler. Do not worry
about damaging your computer: Nothing you do from the keyboard
can harm the physical computer. The worst thing you can do at this
point is erase portions of your compiler software or change the
compilers optionsall of which can be easily corrected by reload-
ing the compiler from its original source. (It is only remotely likely
that you would do anything like this, even if you are a beginner.)
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.
47
EXAMPLE
C+ + By
Figure 2.3. The compiler reporting a program error.
When you get an error message (or more than one), you must
return to the program editor and correct the error. If you dont
understand the error, you might have to check your reference
manual or scour your programs source code until you find the
offending code line.
Getting the Bugs Out
One of the first computers, owned by the military, refused to
print some important data one day. After its programmers
tried for many hours to find the problem in the program, a
programmer by the name of Grace Hopper decided to check
the printer.
She found a small moth lodged between two important wires.
When she removed the moth, the printer started working
perfectly (although the moth did not have the same luck).
Chapter 2 o W hat Is a Program ?
48
Grace Hopper was an admiral from the Navy and, although
she was responsible for developing many important computer
concepts (she was the author of the original COBOL language),
she might be best known for discovering the first computer
bug.
Ever since Admiral Hopper discovered that moth, errors in
computer programs have been known as computer bugs. When
you test your programs, you might have to debug themget the
bugs (errors) out by correcting your typing errors or changing
the logic so your program does exactly what you want it to do.
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 computers
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?
49
EXAMPLE
C+ + By
6. What filename extension do all C++ programs have?
7. Why is typing the program one of the last steps in the pro-
gramming process?
8. What does the term debug mean?
9. Why is it important to write programs that are compatible
with the AT&T C++?
10. True or false: You must link a program before compiling it.
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 programs 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.
Chapter 2 o W hat Is a Program ?
50
51
EXAMPLE
C+ + By
3
Your First C++
Program
This chapter introduces you to some important C++ language
commands and other elements. Before looking at the language more
specifically, many people like to walk through a few simple
programs to get an overall feel for what a C++ program involves.
This is done here. The rest of the book covers these commands and
elements more formally.
This chapter introduces the following topics:
o An overview of C++ programs and their structure
o Variables and literals
o Simple math operators
o Screen output format
This chapter introduces a few general tools you need to become
familiar with the C++ programming language. The rest of the book
concentrates on more specific areas of the actual language.
Chapter 3 o Your First C ++ Program
52
Looking at a C++ Program
Figure 3.1 shows the outline of a typical small C++ program.
No C++ commands are shown in the figure. Although there is much
more to a program than this outline implies, this is the general
format of the beginning examples in this book.
Figure 3.1. A skeleton outline of a simple C++ program.
To acquaint yourself with C++ programs as fast as possible,
you should begin to look at a program in its entirety. The following
is a listing of a simple example C++ program. It doesnt do much, but
it enables you to see the general format of C++ programming. The
next few sections cover elements from this and other programs. You
might not understand everything in this program, even after finish-
ing the chapter, but it is a good place to start.
/ / Fi l ename: C3FI RST. CPP
/ / I ni t i al C++ pr ogr amt hat demonst r at es t he C++ comment s
/ / and shows a f ew var i abl es and t hei r decl ar at i ons.
Program goes here
Preprocessor directives
go here
Function name
#i ncl ude <i ost r eam. h>
mai n( )
{
.
.
.
}
Block
53
EXAMPLE
C+ + By
#i ncl ude <i ost r eam. h>
mai n( )
{
i nt i , j ; / / These t hr ee l i nes decl ar e f our var i abl es.
char c;
f l oat x;
i = 4; / / i and j ar e bot h assi gned i nt eger l i t er al s.
j = i + 7;
c = A ; / / Al l char act er l i t er al s ar e
/ / encl osed i n si ngl e quot at i ons.
x = 9. 087; / / x r equi r es a f l oat i ng- poi nt val ue because i t
/ / was decl ar ed as a f l oat i ng- poi nt var i abl e.
x = x * 4. 5; / / Change what was i n x wi t h a f or mul a.
/ / Sends t he val ues of t he var i abl es t o t he scr een.
cout << i << , << j << , << c << , << x << \ n;
r et ur n 0; / / ALWAYS end pr ogr ams and f unct i ons wi t h r et ur n.
/ / The 0 r et ur ns t o t he oper at i ng syst emand
/ / usual l y i ndi cat es no er r or s occur r ed.
}
For now, familiarize yourself with this overall program. See if
you can understand any part or all of it. If you are new to program-
ming, you should know that the computer reads each line of the
program, starting with the first line and working its way down, until
it has completed all the instructions in the program. (Of course, you
first have to compile and link the program, as described in Chap-
ter 2, What Is a Program?.)
The output of this program is minimal: It simply displays four
values on-screen after performing some assignments and calcula-
tions of arbitrary values. Just concentrate on the general format at
this point.
The Format of a C++ Program
Unlike some other programming languages, such as COBOL,
C++ is a free-form language, meaning that programming statements
C++ i s a free- form
l anguage.
Chapter 3 o Your First C ++ Program
54
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:
/ / Fi l ename: C3FI RST. CPP I ni t i al C++ pr ogr amt hat demonst r at es
/ / t he C++ comment s and shows a f ew var i abl es and t hei r
/ / decl ar at i ons.
#i ncl ude <i ost r eam. h>
mai n( ) {i nt i , j ; / / These t hr ee l i nes decl ar e f our var i abl es.
char c; f l oat x; i =4; / / i and j ar e bot h assi gned i nt eger l i t er al s.
j =i +7; c= A ; / / Al l char act er l i t er al s ar e encl osed i n
/ / si ngl e quot at i ons.
x=9. 087; / / x r equi r es a f l oat i ng- poi nt val ue because i t was
/ / decl ar ed as a f l oat i ng- poi nt var i abl e.
x=x*4. 5; / / Change what was i n x wi t h a f or mul a.
/ / Sends t he val ues of t he var i abl es t o t he scr een.
cout <<i <<, <<j <<, <<c<<, <<x<<\ n; r et ur n 0; / / ALWAYS
/ / end pr ogr ams and f unct i ons wi t h r et ur n. The 0 r et ur ns t o
/ / t he oper at i ng syst emand usual l y i ndi cat es no er r or s occur r ed.
}
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.
Readability Is the Key
As long as programs do their job and produce correct output,
who cares how well they are written? Even in todays world of fast
computers and abundant memory and disk space, you should still
55
EXAMPLE
C+ + By
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 elses 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 readers
eye follow and recognize the next indented block.
Upperc ase Versus Lowerc as e
Your uppercase and lowercase letters are much more signifi-
cant in C++ than in most other programming languages. You can see
that most of C3FIRST.CPP is in lowercase. The entire C++ language
is in lowercase. For example, you must type the keywords i nt , char ,
and r et ur n in programs using lowercase characters. If you use
uppercase letters, your C++ compiler would produce many errors
and refuse to compile the program until you correct the errors.
Appendix E, Keyword and Function Reference, shows a list of
every command in the C++ programming language. You can see
that none of the commands have uppercase letters.
Many C++ programmers reserve uppercase characters for
some words and messages sent to the screen, printer, or disk file;
they use lowercase letters for almost everything else. There is,
however, one exception to this rule in Chapter 4, Variables and
Literals, dealing with the const keyword.
Use l owercase
abundantl y i n C++!
Chapter 3 o Your First C ++ Program
56
Brac es and mai n( )
All C++ programs require the following lines:
mai n( )
{
The statements that follow mai n( ) are executed first. The section
of a C++ program that begins with mai n( ) , 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
mai n( ) is always required and always the first function executed.
In the sample program shown here, almost the entire program
is mai n( ) because the matching closing brace that follows mai n( ) s
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, mai n( ) ,
and the entire function is a single block because there is only one
pair of braces.
All executable C++ statements must have a semicolon (; ) after
them so C++ is aware that the statement is ending. Because the
computer ignores all comments, do not put semicolons after your
comments. Notice that the lines containing mai n( ) 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.
Al l executabl e C++
statements must
end wi th a semi -
col on (; ).
A C++ bl ock i s
encl osed i n two
braces.
57
EXAMPLE
C+ + By
/ / Fi l ename: C3FI RST. CPP
/ / I ni t i al C++ pr ogr amt hat demonst r at es t he C++ comment s
/ / and shows a f ew var i abl es and t hei r decl ar at i ons.
#i ncl ude <i ost r eam. h>
mai n( )
{
i nt i , j ; / / These t hr ee l i nes decl ar e f our var i abl es.
char c;
f l oat x;
i = 4; / / i and j ar e bot h assi gned i nt eger l i t er al s.
j = i + 7;
c = A ; / / Al l char act er l i t er al s ar e
/ / encl osed i n si ngl e quot at i ons.
x = 9. 087; / / x r equi r es a f l oat i ng- poi nt val ue because i t
/ / was decl ar ed as a f l oat i ng- poi nt var i abl e.
x = x * 4. 5; / / Change what was i n x wi t h a f or mul a.
/ / Sends t he val ues of t he var i abl es t o t he scr een.
cout << i << , << j << , << c << , << x << \ n;
r et ur n 0; / / ALWAYS end pr ogr ams and f unct i ons wi t h r et ur n.
/ / The 0 r et ur ns t o t he oper at i ng syst emand
/ / usual l y i ndi cat es no er r or s occur r ed.
} End block
Body of program
Variable declarations
Begin block
Comments
Figure 3.2. The parts of the sample program.
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
programs instructions. Programmers, on the other hand, look at the
program listings, add new routines, change old ones, and update for
advancements in computer equipment.
Preprocessor directive
Chapter 3 o Your First C ++ Program
58
As explained earlier, the readability of a program is important
so you and other programmers can look through it easily. Neverthe-
less, no matter how clearly you write C++ programs, you can always
enhance their readability by adding comments throughout.
Comments are messages that you insert in your C++ programs,
explaining what is going on at that point in the program. For
example, if you write a payroll program, you might put a comment
before the check-printing routine that describes what is about to
happen. You never put C++ language statements inside a comment,
because a comment is a message for peoplenot computers. Your
C++ compiler ignores all comments in every program.
NOTE: C++ comments always begin with a / / symbol and end
at the end of the line.
Some programmers choose to comment several lines. Notice in
the sample program, C3FIRST.CPP, that the first three lines are
comment lines. The comments explain the filename and a little about
the program.
Comments also can share lines with other C++ commands. You
can see several comments sharing lines with commands in the
C3FIRST.CPP program. They explain what the individual lines do.
Use abundant comments, but remember who theyre for: people,
not computers. Use comments to help explain your code, but do not
overcomment. For example, even though you might not be familiar
with C++, the following statement is easy: It prints C++ By Ex-
ample on-screen.
cout << C++ By Exampl e; / / Pr i nt C++ By Exampl e on- scr een.
This comment is redundant and adds nothing to your under-
standing of the line of code. It would be much better, in this case, to
leave out the comment. If you find yourself almost repeating the
C++ code, leave out that particular comment. Not every line of a
C++ program should be commented. Comment only when code
lines need explainingin Englishto the people looking at your
program.
It does not matter if you use uppercase, lowercase, or a mixture
of both in your comments because C++ ignores them. Most C++
Comments tel l
peopl e what the
program i s doi ng.
59
EXAMPLE
C+ + By
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:
net pay = gr osspay - t axes; / * Comput e t ake- 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-
graminstead 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:
/ / The f ol l owi ng f ew l i nes dr aw a f ancy box ar ound
/ / a name, t hen di spl ay f l ashi ng dot s ar ound t he
/ / name l i ke a Hol l ywood movi e mar quee.
Chapter 3 o Your First C ++ Program
60
This would not tell C++ to do anything because a comment
is not a command, but it would make the next few lines of
code more understandable to you and others. The comment
explains in English, for people reading the program, exactly
what the program is getting ready to do.
2. You should also put the disk filename of the program in one
of the first comments. For example, in the C3FIRST.CPP
program shown earlier, the first line is the beginning of a
comment:
/ / Fi l ename: C3FI RST. CPP
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.
TIP: It might be a good idea to put your name at the top of a
program in a comment. If people have to modify your program
at a later date, they first might want to consult with you, as the
original programmer, before they change it.
Explaining the Sample
Program
Now that you have an overview of a C++ program, its struc-
ture, and its comments, the rest of this chapter walks you through
the entire sample program. Do not expect to become a C++ expert
just by completing this sectionthat is what the rest of the book is
for! For now, just sit back and follow this step-by-step description of
the program code.
61
EXAMPLE
C+ + By
As described earlier, this sample program contains several
comments. The first three lines of the program are comments:
/ / Fi l ename: C3FI RST. CPP
/ / I ni t i al C++ pr ogr amt hat demonst r at es t he C++ comment s
/ / and shows a f ew var i abl es and t hei r decl ar at i ons.
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 #i ncl ude is called a preprocessor
directive and is shown here:
#i ncl ude <i ost r eam. h>
This strange looking statement is not actually a C++ command, but
is a directive that instructs the C++ compiler to load a file from disk
into the middle of the current program. The only purpose for this
discussion is to ensure that the output generated with cout works
properly. Chapter 6, Preprocessor Directives, more fully explains
this directive.
The next two lines (following the blank separating line) are
shown here:
mai n( )
{
This begins the mai n( ) function. Basically, the mai n( ) functions
opening and closing braces enclose the body of this program and
mai n( ) s instructions that execute. C++ programs often contain more
than one function, but they always contain a function called mai n( ) .
The mai n( ) function does not have to be the first one, but it usually is.
The opening brace begins the first and only block of this program.
When a programmer compiles and runs this program, the
computer looks for mai n( ) and starts executing whatever instruction
follows mai n( ) s opening brace. Here are the three lines that follow:
i nt i , j ; / / These t hr ee l i nes decl ar e f our var i abl es.
char c;
f l oat x;
Chapter 3 o Your First C ++ Program
62
These three lines declare variables. A variable declaration describes
variables used in a block of code. Variable declarations describe the
programs data storage.
A C++ program processes data into meaningful results. All
C++ programs include the following:
o Commands
o Data
Data comprises variables and literals (sometimes called con-
stants). As the name implies, a variable is data that can change
(become variable) as the program runs. A literal remains the same.
In life, a variable might be your salary. It increases over time (if you
are lucky). A literal would be your first name or social security
number, because each remains with you throughout life and does
not (naturally) change.
Chapter 4, Variables and Literals, fully explains these con-
cepts. However, to give you an overview of the sample programs
elements, the following discussion explains variables and literals in
this program.
C++ enables you to use several kinds of literals. For now, you
simply have to understand that a C++ literal is any number, charac-
ter, word, or phrase. The following are all valid C++ literals:
5. 6
- 45
Q
Mar y
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 Mar y, requires double quotation marks.
63
EXAMPLE
C+ + By
Look for the literals in the sample program. You find these:
4
7
A
9. 087
4. 5
A variable is like a box inside your computer that holds
something. That something might be a number or a character. You
can have as many variables as needed to hold changing data. After
you define a variable, it keeps its value until you change it or define
it again.
Variables have names so you can tell them apart. You use the
assignment operator, the equal sign (=), to assign values to variables.
The following statement,
sal es=25000;
puts the literal value 25000 into the variable named sal es. In the
sample program, you find the following variables:
i
j
c
x
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.
Chapter 3 o Your First C ++ Program
64
i = 4; / / i and j ar e bot h assi gned i nt eger l i t er al s.
j = i + 7;
c = A ; / / Al l char act er l i t er al s ar e
/ / encl osed i n si ngl e quot at i ons.
x = 9. 087; / / x r equi r es a f l oat i ng- poi nt val ue because i t
/ / was decl ar ed as a f l oat i ng- poi nt var i abl e.
x = x * 4. 5; / / Change what was i n x wi t h a f or mul a.
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.
Table 3.1. The primary math operators.
Operator Meaning Example
+ Addition 4 + 5
Subtraction 7 2
* Multiplication 12 * 6
/ Division 48 / 12
The character literal A is assigned to the c variable. The number
9. 087 is assigned to the variable called x, then x is immediately
overwritten with a new value: itself (9. 087) multiplied by 4.5. This
helps illustrate why computer designers use an asterisk (*) for
multiplication and not a lowercase x as people generally do to
show multiplication; the computer would confuse the variable x
with the multiplication symbol, x, if both were allowed.
TIP: If mathematical operators are on the right side of the
equal sign, the program completes the math before assigning
the result to a variable.
65
EXAMPLE
C+ + By
The next line (after the comment) includes the following
specialand, at first, confusingstatement:
cout << i << , << j << , << c << , << x << \ n;
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
#i ncl ude file called iostream.h, and it sends output to the screen.
C++ also supports the pr i nt f ( ) function for formatted output.
You have seen one function already, mai n( ) , which is one for which
you write the code. The C++ programming designers have already
written the code for the pr i nt f function. At this point, you can think
of pr i nt f as a command that outputs values to the screen, but it is
actually a built-in function. Chapter 7, Simple Input/Output
describes the pr i nt f function in more detail.
NOTE: To differentiate pr i nt f from regular C++ commands,
parentheses are used after the name, as in pr i nt f ( ) . In C++, all
function names have parentheses following them. Sometimes
these parentheses have something between them, and some-
times they are blank.
The last two lines in the program are shown here:
r et ur n 0; / / ALWAYS end pr ogr ams and f unct i ons wi t h r et ur n.
}
Put a r et ur n
statement at the end
of each functi on.
Chapter 3 o Your First C ++ Program
66
The r et ur n command simply tells C++ that this function is
finished. C++ returns control to whatever was controlling the pro-
gram before it started running. In this case, because there was only
one function, control is returned either to DOS or to the C++ editing
environment. C++ requires a return value. Most C++ programmers
return a 0 (as this program does) to the operating system. Unless you
use operating-system return variables, you have little use for a
return value. Until you have to be more specific, always return a 0
from mai n( ) .
Actually, many r et ur n statements are optional. C++ would
know when it reached the end of the program without this state-
ment. It is a good programming practice, however, to put a r et ur n
statement at the end of every function, including mai n( ) . Because
some functions require a r et ur n statement (if you are returning
values), it is better to get in the habit of using them, rather than run
the risk of leaving one out when you really need it.
You will sometimes see parentheses around the r et ur n value,
as in:
r et ur n ( 0) ; / / ALWAYS end pr ogr ams and f unct i ons wi t h r et ur n.
The parentheses are unnecessary and sometimes lead begin-
ning C++ students into thinking that r et ur n is a built-in function.
However, the parentheses are recommended when you want to
return an expression. You read more about returning values in
Chapter 19, Function Return Values and Prototypes.
The closing brace after the r et ur n does two things in this
program. It signals the end of a block (begun earlier with the open-
ing brace), which is the end of the mai n( ) function, and it signals
the end of the 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?
67
EXAMPLE
C+ + By
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?
ci t y
9. What, if anything, is wrong with the following C++
statement?
RETURN;
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 programs 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.
Chapter 3 o Your First C ++ Program
68
69
EXAMPLE
C+ + By
4
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:
o The concepts of variables and literals
o The types of C++ variables and literals
o Special literals
o Constant variables
o Naming and using variables
o Declaring variables
o Assigning values to variables
Now that you have seen an overview of the C++ programming
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
Garbage i n, garbage
out!
Chapter 4 o Variables and Literals
70
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 computers 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.
o Each variable has a name.
o Each variable has a type.
o 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.
71
EXAMPLE
C+ + By
TIP: Spaces are not allowed in a variable name, so use the
underscore character to separate parts of the name.
The following list of variable names are all valid:
sal ar y aug91_sal es i i ndex_age amount
It is traditional to use lowercase letters for C++ variable names.
You do not have to follow this tradition, but you should know that
uppercase letters in variable names are different from lowercase
letters. For example, each of the following four variables is viewed
differently by your C++ compiler.
sal es Sal es SALES sALES
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.
Variables cannot have the same name as a C++ command or
function. Appendix E, Keyword and Function Reference, shows
a list of all C++ command and function names.
The following are invalid variable names:
81_sal es Aug91+Sal es MY AGE pr i nt f
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
t ot al _payr ol l is much more descriptive than using the variable
name XYZ34. Even though both names are valid, t ot al _payr ol l is
easier to remember and you have a good idea of what the
variable holds by looking at its name.
Do not gi ve vari abl es
the same name as a
command or bui l t- i n
functi on.
Chapter 4 o Variables and Literals
72
Variable Type s
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 variables value. A large
number of types are possible in C++. For now, the most important
types you should concentrate on are char , i nt , and f l oat . You can
append the prefix l ong to make some of them hold larger values than
they would otherwise hold. Using the unsi gned prefix enables them
to hold only positive numbers.
Table 4.1. Some C++ variable types.
Declaration Name Type
char Character
unsi gned char Unsigned character
si gned char Signed character (same as char )
i nt Integer
unsi gned i nt Unsigned integer
si gned i nt Signed integer (same as i nt )
shor t i nt Short integer
unsi gned shor t i nt Unsigned short integer
si gned shor t i nt Signed short integer (same as shor t i nt )
l ong Long integer
l ong i nt Long integer (same as l ong)
si gned l ong i nt Signed long integer (same as l ong i nt )
unsi gned l ong i nt Unsigned long integer
f l oat Floating-point
doubl e Double floating-point
l ong doubl e Long double floating-point
73
EXAMPLE
C+ + By
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.
Dec laring Variable s
There are two places you can declare a variable:
o Before the code that uses the variable
o Before a function name (such as before mai n( ) 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 mai n( ) 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.
mai n( )
{
i nt i , j ; / / These t hr ee l i nes decl ar e f our var i abl es.
char c;
f l oat x;
/ / The r est of pr ogr amf ol l ows.
This declares two integer variables named i and j . You have no
idea what is inside those variables, however. You generally cannot
assume a variable holds zeroor any other numberuntil you
assign it a value. The first line basically tells C++ the following:
I am going to use two integer variables somewhere in this
program. Be expecting them. I want them named i and j . When I
put a value into i or j , I ensure that the value is an integer.
Decl are al l vari abl es
i n a C++ program
before you use them.
Chapter 4 o Variables and Literals
74
Without such a declaration, you could not assign i or j a value
later. All variables must be declared before you use them. This does
not necessarily hold true in other programming languages, such as
BASIC, but it does for C++. You could declare each of these two
variables on its own line, as in the following code:
mai n( )
{
i nt i ;
i nt j ;
/ / The r est of pr ogr amf ol l ows.
You do not gain any readability by doing this, however. Most
C++ programmers prefer to declare variables of the same type on the
same line.
The second line in this example declares a character variable
called c. Only single characters should be placed there. Next, a
floating-point variable called x is declared.
Examples
1. Suppose you had to keep track of a persons 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:
mai n( )
{
char f i r st , mi ddl e, l ast ;
/ / The r est of pr ogr amf ol l ows.
This statement could go after the opening brace of mai n( ) . It
informs the rest of the program that you require these three
character variables.
2. You could declare these three variables also on three sepa-
rate lines, although it does not necessarily improve readabil-
ity to do so. This could be accomplished with:
75
EXAMPLE
C+ + By
mai n( )
{
char f i r st ;
char mi ddl e;
char l ast ;
/ / The r est of pr ogr amf ol l ows.
3. Suppose you want to keep track of a persons age and
weight. If you want to store these values as whole numbers,
they would probably go in integer variables. The following
statement would declare those variables:
mai n( )
{
i nt age, wei ght ;
/ / The r est of pr ogr amf ol l ows.
Looking at Data Type s
You might wonder why it is important to have so many
variable types. After all, a number is just a number. C++ has more
data types, however, than almost all other programming languages.
The variables type is critical, but choosing the type among the many
offerings is not as difficult as it might first seem.
The character variable is easy to understand. A character
variable can hold only a single character. You cannot put more than
a single character into a character variable.
NOTE: Unlike many other programming languages, C++
does not have a string variable. Also, you cannot hold more
than a single character in a C++ character variable. To store a
string of characters, you must use an aggregate variable type
that combines other fundamental types, such as an array.
Chapter 5, Character Arrays and Strings, explains this more
fully.
Integers hold whole numbers. Although mathematicians might
cringe at this definition, an integer is actually any number that does
Chapter 4 o Variables and Literals
76
not contain a decimal point. All the following expressions are
integers:
45 - 932 0 12 5421
Floating-point numbers contain decimal points. They are known
as real numbers to mathematicians. Any time you have to store a
salary, a temperature, or any other number that might have a
fractional part (a decimal portion), you must store it in a floating-
point variable. All the following expressions are floating-point
numbers, and any floating-point variable can hold them:
45. 12 - 2344. 5432 0. 00 . 04594
Sometimes you have to keep track of large numbers, and
sometimes you have to keep track of smaller numbers. Table 4.2
shows a list of ranges that each C++ variable type can hold.
CAUTION: All true AT&T C++ programmers know that
they cannot count on using the exact values in Table 4.2 on
every computer that uses C++. These ranges are typical on a
PC, but might be much different on another computer. Use this
table only as a guide.
Table 4.2. Typic al ranges that C++ variables hold.
Type Range*
char 128 to 127
unsi gned char 0 to 255
si gned char 128 to 127
i nt 32768 to 32767
unsi gned i nt 0 to 65535
si gned i nt 32768 to 32767
shor t i nt 32768 to 32767
unsi gned shor t i nt 0 to 65535
77
EXAMPLE
C+ + By
si gned shor t i nt 32768 to 32767
l ong i nt 2147483648 to 2147483647
si gned l ong i nt 2147483648 to 2147483647
f l oat 3.4E38 to 3.4E+38
doubl e 1.7E308 to 1.7E+308
l ong doubl e 3.4E4932 to 1.1E+4932
* Use this table only as a guide; different compilers and different computers can have different
ranges.
NOTE: The floating-point ranges in Table 4.2 are shown in
scientific notation. To determine the actual range, take the
number before the E (meaning Exponent) and multiply it by
10 raised to the power after the plus sign. For instance, a
floating-point number (type f l oat ) can contain a number as
small as 3.4
38
.
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 usuallybut not
alwaysthe case.
Do Not Over Type a Variable
If the long variable types hold larger numbers than the regular
ones, you might initially want to use long variables for all your
data. This would not be required in most cases, and would
probably slow your programs execution.
Type Range*
Chapter 4 o Variables and Literals
78
As Appendix A, Memory Addressing, Binary, and Hexadeci-
mal Review, describes, the more memory locations used by
data, the larger that data can be. However, every time your
computer has to access more storage for a single variable (as is
usually the case for long variables), it takes the CPU much
longer to access it, calculate with it, and store it.
Use the long variables only if you suspect your data might
overflow the typical data type ranges. Although the ranges
differ between computers, you should have an idea of whether
you numbers might exceed the computers storage ranges.
If you are working with extremely large (or extremely small
and fractional) numbers, you should consider using the long
variables.
Generally, all numeric variables should be signed (the default)
unless you know for certain that your data contain only positive
numbers. (Some values, such as age and distances, are always
positive.) By making a variable an unsigned variable, you gain a
little extra storage range (as explained in Appendix A, Memory
Addressing, Binary, and Hexadecimal Review). That range of
values must always be positive, however.
Obviously, you must be aware of what kinds of data your
variables hold. You certainly do not always know exactly what each
variable is holding, but you can have a general idea. For example, in
storing a persons age, you should realize that a long integer variable
would be a waste of space, because nobody can live to an age that
cant be stored by a regular integer.
At first, it might seem strange for Table 4.2 to state that
character variables can hold numeric values. In C++, integers and
character variables frequently can be used interchangeably. As
explained in Appendix A, Memory Addressing, Binary, and Hexa-
decimal Review, each ASCII table character has a unique number
that corresponds to its location in the table. If you store a number in
a character variable, C++ treats the data as if it were the ASCII
character that matched that number in the table. Conversely, you
can store character data in an integer variable. C++ finds that
79
EXAMPLE
C+ + By
characters ASCII number, and stores that number rather than the
character. Examples that help illustrate this appear later in the
chapter.
Designating Long, Unsigned, and Floating-Point Literals
When you type a number, C++ interprets its type as the
smallest type that can hold that number. For example, if you
print 63, C++ knows that this number fits into a signed integer
memory location. It does not treat the number as a long integer,
because 63 is not large enough to warrant a long integer literal
size.
However, you can append a suffix character to numeric literals
to override the default type. If you put an L at the end of an
integer, C++ interprets that integer as a long integer. The
number 63 is an integer literal, but the number 63L is a long
integer literal.
Assign the U suffix to designate an unsigned integer literal. The
number 63 is, by default, a signed integer literal. If you type 63U,
C++ treats it as an unsigned integer. The suffix UL indicates an
unsigned long literal.
C++ interprets all floating-point literals (numbers that contain
decimal points) as double floating-point literals (double float-
ing-point literals hold larger numbers than floating-point liter-
als). This process ensures the maximum accuracy in such
numbers. If you use the literal 6. 82, C++ treats it as a double
floating-point data type, even though it would fit in a regular
f l oat . You can append the floating-point suffix (F) or the long
double floating-point suffix (L) to literals that contain decimal
points to represent a floating-point literal or a long double
floating-point literal.
You may rarely use these suffixes, but if you have to assign a
literal value to an extended or unsigned variable, your literals
might be a little more accurate if you add U, L, UL, or F (their
lowercase equivalents work too) to their ends.
Chapter 4 o Variables and Literals
80
Assigning Values to Variable s
Now that you know about the C++ variable types, you are
ready to learn the specifics of assigning values to those variables.
You do this with the assignment statement. The equal sign (=) is used
for assigning values to variables. The format of the assignment
statement is
var i abl e=expr essi on;
The var i abl e is any variable that you declared earlier. The
expr essi on is any variable, literal, expression, or combination that
produces a resulting data type that is the same as the var i abl es data
type.
TIP: Think of the equal sign as a left-pointing arrow. Loosely,
the equal sign means you want to take the number, variable, or
expression on the right side of the equal sign and put it into the
variable on the left side of the equal sign.
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, sal ar y, and dependent s.
To declare these three variables, the first part of the mai n( )
function would look like this:
/ / Decl ar e and st or e t hr ee val ues.
mai n( )
{
i nt age;
f l oat sal ar y;
i nt dependent s;
81
EXAMPLE
C+ + By
Notice that you do not have to declare all integer variables
together. The next three statements assign values to the
variables.
age=32;
sal ar y=25000. 00;
dependent s=2;
/ / Rest of pr ogr amf ol l ows.
This example is not very long and doesnt do much, but it
illustrates the using and assigning of values to variables.
2. Do not put commas in values that you assign to variables.
Numeric literals should never contain commas. The follow-
ing statement is invalid:
sal ar y=25, 000. 00;
3. You can assign variables or mathematical expressions to
other variables. Suppose, earlier in a program, you stored
your tax rate in a variable called t ax_r at e, then decided to
use your tax rate for your spouses rate as well. At the
proper point in the program, you would code the following:
spouse_t ax_r at e = t ax_r at e;
(Adding spaces around the equal sign is acceptable to the
C++ compiler, but you do not have to do so.) At this point in
the program, the value in t ax_r at e is copied to a new variable
named spouse_t ax_r at e. The value in t ax_r at e is still there
after this line finishes. The variables were declared earlier in
the program.
If your spouses tax rate is 40 percent of yours, you can
assign an expression to the spouses variable, as in:
spouse_t ax_r at e = t ax_r at e * . 40;
Any of the four mathematical symbols you learned in the
previous chapter, as well as the additional ones you learn
later in the book, can be part of the expression you assign to
a variable.
Chapter 4 o Variables and Literals
82
4. If you want to assign character data to a character variable,
you must enclose the character in single quotation marks.
All C++ character literals must be enclosed in single quota-
tion marks.
The following section of a program declares three variables,
then assigns three initials to them. The initials are character
literals because they are enclosed in single quotation marks.
mai n( )
{
char f i r st , mi ddl e, l ast ;
f i r st = G ;
mi ddl e = M ;
l ast = P ;
/ / Rest of pr ogr amf ol l ows.
Because these are variables, you can reassign their values
later if the program warrants it.
CAUTION: Do not mix types. C enables programmers to do
this, but C++ does not. For instance, in the mi ddl e variable
presented in the previous example, you could not have stored
a floating-point literal:
mi ddl e = 345. 43244; / / You cannot do t hi s!
If you did so, mi ddl e would hold a strange value that would
seem to be meaningless. Make sure that values you assign to
variables match the variables 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
83
EXAMPLE
C+ + By
are numbers that contain a fractional portion (a decimal point with
an optional value to the right of the decimal point).
Assigning Integer Literals
You already know that an integer is any whole number without
a decimal point. C++ enables you to assign integer literals to vari-
ables, use integer literals for calculations, and print integer literals
using the cout operator.
A regular integer literal cannot begin with a leading 0. To C++,
the number 012 is not the number twelve. If you precede an integer
literal with a 0, C++ interprets it as an octal literal. An octal literal is
a base-8 number. The octal numbering system is not used much in
todays computer systems. The newer versions of C++ retain octal
capabilities for compatibility with previous versions.
A special integer in C++ that is still greatly used today is the
base-16, or hexadecimal, literal. Appendix A, Memory Addressing,
Binary, and Hexadecimal Review, describes the hexadecimal num-
bering system. If you want to represent a hexadecimal integer literal,
add the 0x prefix to it. The following numbers are hexadecimal
numbers:
0x10 0x2C4 0xFFFF 0X9
Notice that it does not matter if you use a lowercase or upper-
case letter x after the leading zero, or an uppercase or lowercase
hexadecimal digit (for hex numbers A through F). If you write
business-application programs in C++, you might think you never
have the need for using hexadecimal, and you might be correct. For
a complete understanding of C++ and your computer in general,
however, you should become a little familiar with the fundamentals
of hexadecimal numbers.
Table 4.3 shows a few integer literals represented in their
regular decimal, hexadecimal, and octal notations. Each row con-
tains the same number in all three bases.
An octal i nteger l i ter-
al contai ns a l eadi ng
0, and a hexadeci -
mal l i teral contai ns a
l eadi ng 0x.
Chapter 4 o Variables and Literals
84
Table 4.3. Integer literals represented in three
bases.
Decimal Hexadecimal Octal
(Base 10) (Base 16) (Base 8)
16 0x10 020
65536 0x10000 0100000
25 0x19 031
NOTE: Floating-point literals can begin with a leading zero,
for example, 0.7. They are properly interpreted by C++. Only
integers can be hexadecimal or octal literals.
Your Computers Word Size Is Important
If you write many system programs that use hexadecimal
numbers, you probably want to store those numbers in un-
signed variables. This keeps C++ from improperly interpreting
positive numbers as negative numbers.
For example, if your computer stores integers in 2-byte words
(as most PCs do), the hexadecimal literal 0xFFFF represents
either 1 or 65535, depending on how the sign bit is interpreted.
If you declared an unsigned integer, such as
unsi gned_i nt i _num= 0xFFFF;
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
i nt i _num= 0xFFFF; / * The wor d si gned i s opt i onal . */
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.
85
EXAMPLE
C+ + By
Assigning String Literals
One type of C++ literal, called the string literal, does not have a
matching variable. A string literal is always enclosed in double
quotation marks. Here are examples of string literals:
C++ Pr ogr ammi ng 123 4323 E. Oak Road x
Any string of characters between double quotation marks
even a single characteris considered to be a string literal. A single
space, a word, or a group of words between double quotation marks
are all C++ string literals.
If the string literal contains only numeric digits, it is not a
number; it is a string of numeric digits that you cannot use to
perform mathematics. You can perform math only on numbers, not
on string literals.
NOTE: A string literal is any character, digit, or group of
characters enclosed in double quotation marks. A character
literal is any character enclosed in single quotation marks.
The double quotation marks are never considered part of the
string literal. The double quotation marks surround the string and
simply inform your C++ compiler that the code is a string literal and
not another type of literal.
It is easy to print string literals. Simply put the string literals in
a cout statement. The following code prints a string literal to the
screen:
The following code prints the string literal, C++ By Exampl e.
cout << C++ By Exampl e;
Examples
1. The following program displays a simple message on-screen.
No variables are needed because no datum is stored or
calculated.
A stri ng l i teral i s
al ways encl osed i n
doubl e quotati on
marks.
Chapter 4 o Variables and Literals
86
/ / Fi l ename: C4ST1. CPP
/ / Di spl ay a st r i ng on- scr een.
#i ncl ude <i ost r eam. h>
mai n( )
{
cout << C++ pr ogr ammi ng i s f un! ;
r et ur n 0;
}
Remember to make the last line in your C++ program (be-
fore the closing brace) a r et ur n statement.
2. You probably want to label the output from your programs.
Do not print the value of a variable unless you also print a
string literal that describes that variable. The following
program computes sales tax for a sale and prints the tax.
Notice a message is printed first that tells the user what the
next number means.
/ / Fi l ename: C4ST2. CPP
/ / Comput e sal es t ax and di spl ay i t wi t h an appr opr i at e
message.
#i ncl ude <i ost r eam. h>
mai n( )
{
f l oat sal e, t ax;
f l oat t ax_r at e = . 08; / / Sal es t ax per cent age
/ / Det er mi ne t he amount of t he sal e.
sal e = 22. 54;
/ / Comput e t he sal es t ax.
t ax = sal e * t ax_r at e;
/ / Pr i nt t he r esul t s.
cout << The sal es t ax i s << t ax << \ n;
r et ur n 0;
}
87
EXAMPLE
C+ + By
Here is the output from the program:
The sal es t ax i s 1. 8032
You later learn how to print accurately to two decimal places
to make the cents appear properly.
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++ Pr ogr am looks like
in memory.
Figure 4.1. In memory, a string literal always ends with 0.
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++ Pr ogr am, for example, the com-
piler would recognize it as a string literal (from the double quotation
marks) and store the zero at the end.
Null zero
Chapter 4 o Variables and Literals
88
The zero is important to C++. It is called the string delimiter.
Without it, C++ would not know where the string literal ended in
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 am30.
Al l stri ng l i teral s end
i n a nul l zero (al so
cal l ed bi nary zero or
ASCII zero).
String-terminating zero
Figure 4.2. The bit pattern showing that a null zero and a character zero
are different.
Figure 4.2 shows how a string is stored in your computers
memory at the binary level. It is important for you to recognize that
the character 0, inside the number 30, is not the same zero (at the bit
level) as the string-terminating null zero. If it were, C++ would think
this string ended after the 3, which would be incorrect.
89
EXAMPLE
C+ + By
This is a fairly advanced concept, but you truly have to under-
stand it before continuing. If you are new to computers, reviewing
the material in Appendix A, Memory Addressing, Binary, and
Hexadecimal Review, will help you understand this concept.
String Lengths
Many times, your program has to know the length of a string.
This becomes critical when you learn how to accept string input
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 l onger st r i ng l i t er al
2. The following table shows some string literals and their
corresponding string lengths.
String Length
C 1
0" 21
Hel l o 5
0
30 or anges 10
Assigning Charac ter Literals
All C character literals should be enclosed in single quotation
marks. The single quotation marks are not part of the character, but
they serve to delimit the character. The following are valid C++
character literals:
w W C 7 * = . K
The l ength of a
stri ng l i teral does
not i ncl ude the nul l
bi nary zero.
Chapter 4 o Variables and Literals
90
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
R is a single character literal. It is one character long, because
all character literals (and variables) are one character long. R is a
string literal because it is delimited by double quotation marks. Its
length is also one, but it includes a null zero in memory so C++
knows where the string ends. Due to this difference, you cannot mix
character literals and character strings. Figure 4.3 shows how these
two literals are stored in memory.
Figure 4.3. The difference in memory between R as a character
literal and R as a string literal.
All the alphabetic, numeric, and special characters on your
keyboard can be character literals. Some characters, however, can-
not be represented with your keyboard. They include some of
the higher ASCII characters (such as the Spanish ). Because you do
not have keys for every character in the ASCII table, C++ enables you
to represent these characters by typing their ASCII hexadecimal
number inside single quotation marks.
For example, to store the Spanish in a variable, look up its
hexadecimal ASCII number from Appendix C, ASCII Table. You
find that it is A5. Add the prefix \ x to it and enclose it in single
quotation marks, so C++ will know to use the special character. You
could do that with the following code:
char sn= \ xA5' ; / / Put s t he Spani sh i nt o a var i abl e cal l ed sn.
91
EXAMPLE
C+ + By
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 accent ed a i s \ xA0
is a C++ string that is 18 characters, not 21 characters. C++ interprets
the \ xA0 character as the , just as it should.
CAUTION: If you are familiar with entering ASCII charac-
ters by typing their ASCII numbers with the Alt-keypad com-
bination, do not do this in your C++ programs. They might
work on your computer (not all C++ compilers support this),
but your program might not be portable to another computers
C++ compiler.
Any character preceded by a backslash, \ , (such as these have
been) is called an escape sequence, or escape character. Table 4.4 shows
some additional escape sequences that come in handy when you
want to print special characters.
TIP: Include \ n i n a cout if you want to skip to the next
line when printing your document.
Table 4.4. Spec ial C++ esc ape-sequenc e
c harac ters.
Escape Sequence Meaning
\ a Alarm (the terminals bell)
\ b Backspace
\ f Form feed (for the printer)
continues
Chapter 4 o Variables and Literals
92
\ n Newline (carriage return and line feed)
\ r Carriage return
\ t Tab
\ v Vertical tab
\ \ Backslash (\ )
\ ? Question mark
\ Single quotation mark
\ Double quotation mark
\ 000 Octal number
\ xhh Hexadecimal number
\ 0 Null zero (or binary zero)
Math with C++ Characters
Because C++ links characters so closely with their ASCII num-
bers, you can perform arithmetic on character data. The follow-
ing section of code,
char c;
c = T + 5; / / Add f i ve t o t he ASCI I char act er .
actually stores a Y in c. The ASCII value of the letter T is 84.
Adding 5 to 84 produces 89. Because the variable c is not an
integer variable, but is a character variable, C++ adds the ASCII
character for 89, not the actual number.
Conversely, you can store character literals in integer variables.
If you do, C++ stores the matching ASCII number for that
character. The following section of code
i nt i = P ;
Table 4.4. Continued.
Escape Sequence Meaning
93
EXAMPLE
C+ + By
does not put a letter P in i because i is not a character variable.
C++ assigns the number 80 in the variable because 80 is the
ASCII number for the letter P.
Examples
1. To print two names on two different lines, include the \ n
between them.
Print the name Har r y; drop the cursor down to a new line and
print Jer r y.
cout << Har r y\ nJ er r y;
When the program reaches this line, it prints
Har r y
J er r y
You also could separate the two names by appending more
of the cout operator, such as:
cout << Har r y << \ n << J er r y;
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.
/ / Fi l ename: C4BELL. CPP
/ / Ri ngs t he bel l
#i ncl ude <i ost r eam. h>
mai n( )
{
char bel l = \ a ;
cout << bel l ; / / No newl i ne needed her e.
r et ur n 0;
}
Chapter 4 o Variables and Literals
94
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 i nt days_of _week = 7;
C++ offers the const keyword as an improvement of the #def i ne
preprocessor directive that C uses. Although C++ supports #def i ne
as well, const enables you to specify constant values with specific
data types.
The const keyword is appropriate when you have data that
does not change. For example, the mathematical is a good candi-
date for a constant. If you accidently attempt to store a value in a
constant, C++ will let you know. Most C++ programmers choose to
type their constant names in uppercase characters to distinguish
them from regular variables. This is the one time when uppercase
reigns in C++.
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:
95
EXAMPLE
C+ + By
Comment for the program filename and description.
Declare a constant value for .
Declare variables for radius and area.
Compute and print the area for both radius values.
/ / Fi l ename: C4AREAC. CPP
/ / Comput es a ci r cl e wi t h r adi us of 5 and 20.
#i ncl ude <i ost r eam. h>
mai n( )
{
const f l oat PI =3. 14159;
f l oat r adi us = 5;
f l oat ar ea;
ar ea = r adi us * r adi us * PI ; / / Ci r cl e ar ea cal cul at i on
cout << The ar ea i s << ar ea << wi t h a r adi us of 5. \ n;
r adi us = 20; / / Comput e ar ea wi t h new r adi us.
ar ea = r adi us * r adi us * PI ;
cout << The ar ea i s << ar ea << wi t h a r adi us of 20. \ n;
r et ur n 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_sal es sal es_89 a- sal ar y
2. Which of the following literals are characters, strings, inte-
gers, and floating-point literals?
0 - 12. 0 2. 0 X X 65. 4 - 708 0
Chapter 4 o Variables and Literals
96
3. How many variables do the following statements declare,
and what are their types?
i nt i , j , k;
char c, d, e;
f l oat x=65. 43;
4. With what do all string literals end?
5. True or false: An unsigned variable can hold a larger value
than a signed variable.
6. How many characters of storage does the following literal
take?
\ x41
7. How is the following string stored at the bit level?
Or der 10 of t hem.
8. How is the following string (called a null string) stored at the
bit level? (Hint: The length is zero, but there is still a termi-
nating character.)