START~
NG OUT WITH Fr,o m Contr,o t Structures, through Objoects sixth edition
c++ Quick Reference c++ Data Types Data Type char unsigned char
Commonly Used Operators As signment Operators
Description
=
CbanK::ter
Assignment Combined addition/assignment Combined su btraction/assignment Combined multiplication/assignment Combined di vision/assignment Combined modulus/assignment
+..
Unsigned Character Integer
int Short integer short int short Same as short int unsigned short int Unsigned shon integer unsigned short Same as unsigned short int unsigned int Unsigned integer unsigned Same as unsigned int long i nt Long integer Same as long int long unsigned long int Unsigned long integer Sarneas unsigned long int unsigned long float Single precision floating point double precision floating point double long double Long double precision floating point
- ". *'"
1''''
Arithmetic Operators +
Addition Subtraction Multiplication Division Modulus (remainder)
..
1 %
Relational Operators <
Less than Less than or equal to Greater than Greater Ihall or equal 10 Equal to Not equal to
<> >'" -!;-
Logical Operators AND
Ii Ii
II
OR
I
NOT
Increment/Decrement
Forms of the 1f Statement Simple if i f (expression) statement; if/else i f ( expression)
++
Example i f (x < y) x++;
Conditional Operator 7:
For-m:
Example
expression ? expression ; expression Example:
i f (x < y)
x++;
,statement; else
lncrement Decrement
x '" a < b ? a : b; The sratement above works like:
else
statement;
if(3
x--;
g
'"
a;
e18e
x - b;
if/el se if
Example
i f (expression)
i f (x < y)
statement; else i f (expression) statement;
x++; else i f (x < z)
else
x--; else
y++;
statement;
To conditionally-execute more than one statement, enclose the statements in braces: Form Example if (expression) i f (x < y) (
The wbile Loop Form:
Example:
while (expression) statement;
while (x < 100)
while (expression) {
while (x < 100)
cout « (
.9tatement;
cout « X++i
statement; )
xo4o+ «
x
«
end1 ;
endl;
)
(
statement; statement;
I
x++; cout « )
x,
The do-wbile Loop Form:
Example:
do
do
statement,
Web Sites For tbe Sf1lrting Out with C++ Series aw.com/gaddisbooks For Addison-Wesley Computing aw.com/computing
cout «
x++ «
while (expres sion):
while (x < 100);
do
do {
{
endl;
statement; cout « x « end1; statement; x++ ; } while (expression) ; } while (x <: 100);
LOCATION OF VIDEO NOTES IN THE TEXT Chapter 1
Introducti on to Flowcharting, p. '9 Designing a Program with Pse udocode, p. 19 Designing the Account Balance Prog ram, p. 25 Predicting the Resu lt of Problem 33, p. 25
Chapter 2
Using cout, p. 33 Va riable Definitions, p. 39 Assig nmen t Statements and Simp le Math Exp ressions, p. 6 1 Solving the Restaurant Bi ll problem, p. 77
Chapter 3
Reading.lnput w ith cin, p. 83 Formatting Numbers w ith setprecision, p. 119 Writing Data to a Fi le, p. 144 Reading Data from a File, p. 145 Solving the Stadium Seat ing Problem, p. 156
Chapter 4
The i f Statement, p. 168 The if/else Statement, p. ' 81 The if/else i f Statement, p. 191 Solving the Time Calc ulator Problem, p. 239
Chapter 5
The while Loop, p. 254 The for Loop, p. 270 Solving the Ca lories Burned Problem, p. 299
Chapter 6
Functions and Arguments, p. 319 Value-Returni ng Functions, p. 332 Solving the Markup Problem, p. 375
Chapter 7
Accessing Array Elements with a l oop, p. 392 Passing an Array to a Function, p. 415 Solving the Chips and Salsa Problem, p. 457
ChapterS
The Binary Search, p. 470 The Select ion Sort, p. 485 Solving the Charge Account Validat ion Modification Proble m, p. 503
Chapter 9
Dynamically Allocating an Array, p. 535 Solving the getString Function Problem, p. 554
Chapter 10
Writing a C-String -Hand ling Function, p. 582 Usi ng the string Class, p. 588 Solving t he Backward String Problem, p. 602
VANWYLEN (
'Yiffi1J03 'mOWge)
CO
Hope College Holland, Michigan
LOCATION OF V IDEO NOTES IN THE TEXT Chapter 11
Creating a Structure, p. 611 Passing a Structure to a Function, p. 630 Solving the Wea ther Statistics Problem, p. 664
Chapter 12
Passing File Stream Objects to Functions, p. 683 Worki ng with Multiple Files, p_ 69S Solving the File En cryptio n Filte r Problem, p _725
Chapter 13
Writing a Class, p_ 736 Defining an Instance of a Class, p. 741 Solving the Employee Class Problem, p_ 816
. Chapter 14
Chapter 15
(continued)
-:"';' ."",
Operator Overloading, p. 843 Class Aggregation, p. 872 Solving the NumDays Problem, p_ 888
Redefining a Base Class Function in a Derived Class, p. 917 Polymorphism, p. 927
Solving the Employee and ProductionWorker Classes Problem, p. 960 Chapter 16
Throwing an Exception, p. 972 • T Handling an Exception, p. 973 Writing a Function Template, p_ 991 Storing Objects in a vector I p. 1011 Solving the Exception Project Problem, p_ 1025
Chapter 17
Appending a Node to a Linked List, p_ 1030 Inserting a Node in a Linked List, p. 10 37 Deleting a Node from a Linked List, p_ 1042 Sulvill~ the Mernber InSt!rlion by Pu~ition Pruult!HI, p. 1064
Chapter 18
Storing Objects in an STL stack, p. 1083 Storing Objects in an STL queue, p_ 1098 Solving the File Compare Problem, p. 1104
Chapter 19
Reducing a Problem w ith Recursion, p_ 1112 Solving the Recursive Multiplication Problem, p. 1141
Chapter 20
Inserting a Node in a Binary Tree, p_ 1150 Deleting a Node from a Binary Tree, p_ 11 56 Solving the Node Counter Problem, p. 1167
'''.~
'.
--
From Control Structures through Objects 6th Edition
Tony Gaddis ,
-
PEARSON
Addison
Wesley
BOSTon San Francisco New York London Toronto Sydney Tokyo Singapore Madrid Mexico City Mu nich Pans Cape "Iown Hong Kong Montrt"al
Executive Editor Editorial Assistant Senior Production Supervisor Text Designer Cover Designer Cover Jmage Media Producer Senior Media Buyer Marketing Manager Senior Mapufacturiug Buyer Production Services
M ichael H irsch Stephanie Sellinger Marilyn Lloyd Joyce Cosent~n o Wells Beth Paquin iStockphoto Bethany Tidd Ginny Michaud Christopher Kel ly Carol Melville Aptara, Inc.
Access the latest information about Addison-Wesley titles from our World Wide Web site: http:www.aw.comJcomputi ng Many of the designations llsed by manufactnrers and sellers to distinguish their products are claimed as trademarks . Where those designations appear in this book, and Addison-Wesley was aware of a trademark claim, the designations have been printed in initial caps or all caps. T he programs and applications presented in this book have been included for their instructional value. They have been tested with care but are not guaranteed for any particula r purpose. The publisher does not offer any warranty or representation, nor does it accept any liabilities with respect to the programs or applications. Library of Congress Cataloging-ill-Publication Data
..
Gaddis, Tony. Srarring out with C++ : from control structures through objects I Tony Gaddis. - 6th cd. p. em. Includes index. lSBN-13,978-0-321-54588-6 [SBN-l0, 0-321-54588-5 I . C++ (Compu ter program language) 1. Title.
QA76.73.CI53G332008 005.J3'3--dc22
2008008001 . Copyright
~
2009 Pearson Education, Inc.
All rights reserved. No part of this publication may be reproduced, stored in a retrieval system, or transmitted, in any form or by any means, electronic, mechanical, photocopying, recording, or otherwise, without the prior written permission of the publisher. l)rinted in the United Sta tes of America. For information on obtaining permission for use o f material in this work, please submit a written request to Pearson Education, inc., Rights and Contracts Departinellt, 501 Boylston Street, Suite 900, Boston, MA 02116, fax your request to 617-671-3447, or e-mad at http://www.pearsoned.com/legaVpermissions.htm.
ISBN n 978-0-321 -54588-6 ISBN 10, 0-321-54588 -5 23456789 IO-QWT-ll10 09 08
j
o '1
Preface
xiii
CHAPTER 1
Introduction to Computers and Programming
CHAPTER 2
Introduction to c++
CHAPTER 3
Expressions and Interactivity 83
CHAPTER 4
Making Decisions
CHAPTER 5
Looping
CHAPTER 6
Functions
CHAPTER 7
Arrays
CHAPTER 8
Searching and Sorting Arrays 467
CHAPTER 9
Pointers 507 Characters, Strings, and the string Class
CHAPTER 10 CHAPTER 11
1
29
163
249
307
387
559
CHAPTER 14
Structured Data 609 Advanced File Operations 673 Introduction to Classes 729 More About Classes 825
CHAPTER 15
Inheritance, Polymorphism, and Virtual Functions 895
CHAPTER 16
Exceptions, Templates, and the Standard Template Library (STL)
CHAPTER 17
Linked Lists
CHAPTER 18
Stacks and Queues
CHAPTER 19
Recursion
CHAPTER 20
Binary Tree.
CHAPTER 12 CHAPTER 13
1027 1067
1107 1145
Appendix A: Getting Started with Alice
1171
Appendix B: The ASCII Character Set 1199 Appendix C: Operator Precedence and Associativity Index
971
1203
1205
v
vi
Contents at a Glance
Student CD
Th e fo llowing appendices arc on the accompany ing Student CD. Appendix D: Introduction to Flowcharting
Appendix E: Using UML in Class Design Appendix F: Namespaces Appendix G: Writing Managed C++ Code for the .NET Framework
Append ix Appendix Appendix Appendix Appendix Appendix Appendix Appendix
H: Passing Command Line Arguments I: Header File and Library Function Reference ,: Binary Numbers and Bitwise Operations K: Multi-Source File Pro grams L: Stream Member Functions for Formatting M: Introduction to Microsoft Visual c ++ 2008 Express Edition N: Answers to Checkpoints 0 : Answers to Odd Numbered Review Questions
Table of Locat ion of Video Notes Preface CHAPTER 1
1.1 1.2
1.3 1.4 1.5 1.6 1.7 CHAPTER 2
2.1 2 .2 2.3 2.4 2.5 2.6 2.7 2.8 2.9 2.10 2.11 2.12 2.13 2.14 2. 15 2. 16 CHAPTER 3
3. 1 3.2 3.3
xiii
Introduction to Computers and Programming
1
Why Program? 1 Compmer Systems: Ha rdware and Software 2 Programs and Programming Languages 6 What Is a Program Made of? ]2 Input, Processing, and Output ] 6 The Programming Process 17 Procedural and Object-Oriented Programming 21 Introduction to C++
29
The Parts of a C++ Program 29 T he cout Object 33 The #include Directive 38 Variables and Literals 39 Identifiers 43 Integer Data T ypes 44 The char Data Type 49 Floating- Poim Data Types 54 The bool Data Type 57 Determining the Size of a Data Type 58 Variable Assignments and Initialization 59 Scope 60 Arithmetic Operators 61 Commems 67 Focus on Software Engineering: Programming Sty le 69 llYou Plan to Conti nue in Comp uter Science: Standa rd and Presra ndard C++ Expressions and Interactlvity
71
83
The cin Object 83 Mathematical Expressions 91 When You Mix Apples and Oranges: Type Co nversion
100
vii
viii
Contents
3.4 3.5 3.6 3.7 3.8 3.9 3.10 3.11 3.12 3.13 3.14 CHAPTER 4
4.1 4.2 4.3 4.4
4.5 4.6
4.7 4.8 4.9 4.10 4.11 4.12 4.13 4.14 4.15 4.16 CHAPTER 5
5.1 5.2 5.3 5.4 5.5 5.6 5.7 5.8 5.9
5.10 5.11 5.12 5.]3 CHAPTER 6
6.1
6.2
6.3
Overflow and Underflow 102 Type Casting 104 Named Constants 107 Mul tiple Assignment and Combined Assignment 1.12 Formatting Output 116 Fonnartcd Tnpur 125 Focus on Object-Oriented Programming: More About Member Functions More Mathematical Library Functions 131 Focus on Debugging: Hand Tracing a Program 135 Focus on Problem Solving: A Case Study 137 Introduction to File Input and Output 140
Making Decisions 163 Relational Operators 163 The if Statement 168 Flags 176 Expanding the if Statement 177 The if/else Statement 181 Nested if Statements 184 The if/else if Statement 191 Menus 195 Logical Operators 199 Check ing Numeric Ra nges with Logical Operators 206 Focus on Softwa re Engineering: Validating User Input 207 More About Variable Definitions and Scope 209 Comparing Suings 213 The Conditiona l Operator 218 The switch Statement 222 Testing for File Open Errors 231
Looping 249 The Increment and Decrement Operators 249 Introduction to Loops: The while Loop 254 Using the while Loop for input Validation 261 Counters 263 The do - while Loop 265 The for Loop 270 Keeping a Running Total 280 Sentinels 283 Using a Loop to Read Data from a Fi le 284 Focus on Software Engineering: Deciding Which Loop to Use Nested Loops 287 Breaking Out of a Loop 290 The continue Statement 292
Functions 307 Focus on Softvvare Engineering: Modular Programming Defining and Ca Uing Functions 309 Function Prototypes 317
307
287
130
• 6.4 6.5 6.6 6.7 6.8 6.9 6.10 6.11 6.12 6.13 6.14 6. 15 6.16
CHAPTER 7 7. 1 7.2 7.3 7.4 7.5 7.6 7.7 7.8
7.9 7. 10 7.11 7.12
CHAPTER 8 8.1 8.2 8.3 8.4 8.5
CHAPTER 9 9.1 9.2 9.3 9.4 9.5 9.6 9.7 9.8 9.9 9.10
Sending Data mta a Function 319 Pa ssi ng Dara by Value 324 Focus on Softv.rare Engineering: Us ing Function s in a Menu·Driven Program The return Statement 330 Returning a Value from a Function 332 Returning a Boolean Value 340 Local and Global Variables 342 Static Local Variables 350 Defau lt Arguments 353 Using Reference Variables as Parameters 356 Overloading Functions 362 Theexit() Function 366 Stubs and Drivers 369
Arrays 387 Arrays Hold Multiple Values 387 Accessing Array Elements 389 No Bounds Checking in C++ 396 Array Ini tia lization 399 Processing Array Contents 404 Focus on Software Engineering: Using Parall el Arrays Arrays as Function Arguments 41 5 Two-Dimensio nal Arrays 426
ix
Contents
412
Arrays of Strings 433 Arrays with Three or More Dimensions 435 Focus on Problem Solving and Progra m Design: A Case Study 437 1£ You Plan to Continue in Computer Science: Introducti on to the STL vector 439
Searching and Sorting Arrays 467 Focus on Software Engineering: Introduction to Search Algorithms 467 Focus on Pro blem Solving and Program Design: A Case Study 474 Focus on Software Engineering; Introduction to Sorring Algorithms 480 Focus on Problem Solving and Program Design: A Case Study 488 If You Pla n to Continue in Computer Science: Sorting and Searching vectors 496 Pointe rs 507 Getting the Address of a Variable 507 Pointer Variables 509 The Relationship Between Arrays and Pointers 516 Pointer Aritbmetic 520 Initializing Pointers 522 Comparing Pointers 523 Pointers as Functio n Parameters 525 Focus on Software Engineering: Dynamic M emory Allocation 534 Focus on Software Engineering: Returning Pointers from Functions 538 Focus on Problem So lving and Program Design: A Case Study 545
326
x
Contents
CHAPTER 10 10.1 10.2 10.3 lOA 10.5 10.6
10.7 10.8 CHAPTER 11 11.1 11.2 11.3 11.4
11.5 11.6 11.7 U.S 11.9 11.10 lUI
11.12
Characters, Strings, and the s tring Class 559 Character Testing 559 Character Case Conversion 563 Review of the Internal Storage of C-Strings 566 Library Functions for Working with C-Strings 569 StringINumeric Conversion Functions 577 Focus on Software Engineering: Writing Your Own C-String-Handling Functions 582 The c++ string Class 588 Focus on Problem Solving and Program Design: A Case Study Struct ure d Data 609 Abstract Data Types 609 Focus on Software Engineering: Combining Data into Structures 611
Accessing Struemre Members 614 Initializing a Structure 619 Arrays of Structures 623 Focus on Software Engineering: Nesred Structures 626 Structures as Function Arguments 630 Returning: a Structure from a Function 633 Pointers [0 Strucrures 636 Focus on Software Engineering: When to Use ., When to Use - >, and When to Use * 639 Unions 641 Enumerated Data Types 645
CHAPTER 12 12.1 12.2 12.3 12.4 12.5 12.6 12.7 ' 12.8 12.9 12.10
Adva nced File Operations 673 File Operations 673 Fi le Output Formatting 680 Passing File Stream Objects to Functions 683 More Detailed Error Tesring 685 Member Functions for Reading and Writing Files 688 Focus on Software Engineering: Working with Multiple Files Binary Files 696 Creating Records with Structures 702 Random-Access fi les 706 Opening a File for Both Input and Output 714
CHAPTER 13 13.1 13.2 13.3 13.4 13.5
Introduction to Classe s 729 Procedural and Object-Oriented Programming fntroduction to Classes 736 Defining an Instance of a Class 741 Why Have Private Members? 752
13.6 13.7 13.8 13.9
598
729
Focus on Software Engineer ing: Separating Class Specification from Implementation 753 Inline Member Functions 759 Constructors 762 Passing Arguments to Constructors 766 Destructors 774
695
• 13.10
13.11 13.12 13.13 .13.14 13.15 13.16
Contents
Overloading Consrrucwcs 778 Private Member Functions 782 Arrays of Objects 784 Focus on Problem Solving and Progra m Design: An OOP Case Study 788 Focus on Object-Oriented Programming: Creating an Abstract Array Data Type 795 Focus on Object-Oriented Design: The Unified Modeling Language (UML) 799 Focus on Object-O riented Design: Finding the Classes and Thei r Responsibilities 802
CHAPTER 14 14.1 14.2 14.3 14.4 14.5 14.6 14.7 14.8
More About Classe . 825 Instance and Static Members 825 Friends of Classes 833 Mcmberwise Assignment 838 Copy Constructors 839 Operator Overloading 843 Object Conversion 870 Aggregation 872 Focus on Object-Oriented Design: Class Collaborations
CHAPTER 15
Inheritance, Polymorphism, and Virtual Function. 895 What Is Inheritance? 895 Protected Members and Class Access 904 Constructors and Destructors in Base and Derived Classes 910 Redefining Base Class Functions 917 Class Hierarchies 921 Po lymorphism and VinuaJ Member Functions 927 Abstract Base Classes and Pure Virtual Functions 942 Multiple Inheritance 949
IS .1 15.2 15.3 1.').4
15 .5 15.6 15.7 15.8
CHAPTER 16 16.1 16.2 16.3 ]6.4 16.5
Exception., Template., a nd the Sta ndard Template Library (Sn) 9 71 Exceptions 971 Function Templates 990 Focus on Software Engineering: Where to Start When Defining Templates 996 Class Templates 997 Introduction to the Standard Template Library (STL) 1007
CHAPTER 17 Linked LI.t. 1027 17.1 Introduction to the Linked List ADT 17.2 . Linked List Operations 1029 17.3 A Linked List Template 1046 17.4 Variations ofthe Linked List 1058 17.5 The STL list Container 1059 CHAPTER 18 18.1 '18.2 18.3 18.4
878
1027
Stack. and Queue. 1067 Introduction to the Stack ADT 1067 Dynamic Stacks 1078 The STL stack Container 1083 Introduction to the Queue ADT 1085
xi
xli
Contents
18.5 18,6
CHAPTER 19 19.1 19,2 19,3 19.4 19,5 19,6 19,7 19.8 19.9 19.10
CHAPTER 20 20.1 20 .2 20.3
Dynamic Queues 1093 T he STL deque and queue Containers
1097
Recursion 1107 Introduction to Recursion 1107 Solving Problems with Recursion 1112 Focus on Problem Solving and Program Design: The Recursive ged Function 1119 Focus on Problem Solving and Program Design: Solving Recursively Defined Problems 1120 Focus on Problem Solving and Program Design: Recursive Linked List Operatio ns 1122 Foclis o n Problem Solving and Program Design: A Recursive Binary Search Function 1125 The Towers of Hanoi 1128 Focus on Problem Solving and Program Design: The-QuickSort Algorithm Exhaustive A1gorithms 1136 Focus on Software Engineering: Recursion vs. lteration 1138
1·131
Binary Trees 1145 Definition and Appl ications of Binary Trees 1145 Binary Search Tree Operations 1148 Template Considera tions for Binary Search Trees 1165 Appendix A: Getting Started with Allee 1171 Appendix B: The ASCII Character Set 1199 Appendix C: Operator Precedence and Associativity ·1203
Index Student CD
1205
The following appendices are on [he accompanying Studcm CD.
Appendix D: Introduction to Flowcharting Appendix E: Using UML
~n
Clan Design
Appendix F: Namespaces Appendix G: Writing Managed C++ Code for the .NET Framework Appendix H: Paning Command Line Arguments Appendix I: Header File and Library Function Reference Appendix J: Binary Numbers and Bitwise Operations Appendix K: Multi-Source File Programs Appendix l: Stream Member Functions for Formatting Appendix M: Introduction to Microsoft Visual C++ 2008 Express Edition Appendix N: Answers to Checkpoints
Appendix 0: Answers to Odd Numbered Review Questions
•
1 JO JLJ
DO Welcome to Starting Out with C++: From Comral Structures through Objects, 6th edition. This book is intended for use in a two-semester C++ programming sequence, o r a n
accelerated one-semester course. Srudents new to programming, as weJl as those with prior course work in other languages, will find this text beneficial. T he fundamental s of programming are covered for the nov ice, while the details, pitfalls, and nuances of the c++ language are explored in-depth for both the beginner and more experie nced student. The book is written with clear, easy-co-understand language and it covers all the necessary tOpiCS for a n introductory programmmg course. This text is rich in example programs that a re concise, practical, and real-world oriented, ensuring that the student nor on ly learns how to implement the features and constructs of C++, but why and when to use them.
Changes in the Sixth Edition This book 's pedagogy, organization, and clear writing style remain the same as in the preViOllS edition. Many improvements have been made, which are summarized here:
•
lmproved O rgani zatio n in Cha pter 4 The section cover ing the if/else i f statement has been simplified, and now appears immediately following the section on nes ted i f statements . These sections have been rewritten to highlight the SImilarities between an if/else i f statement and a nested if statement.
~.
New In the Spotlight Sectio ns Many of the chapters have new sections titled In the Spotlight. Each of these provides a programming problem and a detailed, step-by-step analys is showing the student how to so lve it.
~.
Online Video Notes An extensive series of online videos have been developed to accompany this text . T hroughout the book, video nOte icons alert the student to videos covering specific topics. Additionally, one Programming Challenge at the end of each chapter now has an accompanying video note explaining how to develop the problem's solution. The videos are available at http : //www.aw.com/gaddis/v i deonotes.
xiii
xiv
Preface
•
Additional Programming Problems Additional Programmi ng Challenge problems have been added ro mOst chapters. Several of these are simple games that will challenge and motivate students.
•
New Appendi x: Gening Starred with Alice Th is new appendix gives a qu ick introduction to Alice. Alice is free software that can be used to teach fundamental programming concepts using 3D graphics.
Organization of the Text This text teaches C++ in a step-by-step fa shion . Each <.: hapter covers a major set of topics and builds knowledge as th e student progresses through the book. Although the chapte rs can be easily taught in thcir existing sequence, some flexibility is prov idcd. The diagram shown in Figure P-l suggests possible sequences of instruction. Chapter J covers fundamental hardware, software, and programming concepts. You may choose to skip rhis chapter if the class has already mastered those topics. Chapters 2 through 7 cover basic C++ syntax, data types, expressions, selection structures, repetition structures, functions, and arrays. Each of these chapters bui lds on the previous chapter and should be covered in the order presented. After Chapter 7 has been covered, you may proceed ro Chapter 8, or jump to either Ch a pter 9 or Chapter 12. (If yo u jump to Chapter 12 at this point, you will need to postpone sections 12.7, 12.8, and 12.10 until Chapters 9 and 11 have been covered.) After Chapter 9 has been covered, either of Chapters 10 or 11 may be covered . After Chapter 11, you may cover Chapters 13 through 17 in seq uence. Next you can proceed to either Chapter 18 or Chapter 19. Finally, Chapter 20 may be cove red. T his text's approach starts with a firm founda tion in structured, procedural programming before delving fully into objeer-oriented programming and advanced data StruCtures.
Brief Overview of Each Chapter Chapter 1: Introduction to Computers and Programming Th is chapter provides an introduction to the field of computer science and covers the fundamentals of programming, problem solving, and software design. The components of programs, such as key words, variables, operato rs, and punctuation are covered. The tools of the trade, such as pseudocode, flow charts, and hie rarchy charts are also presenred.
Chapter 2: Introduction to C++ This chapter gets rhe student started in C++ by introducing data types, identifiers, variable declarations, constants, comments, program output, simple arithmetic operations, and Cstrings. Programmi ng sry le convent ions are introduced and good programming style is modeled here, as it is throughout the text. An optional seerion explains the difference berween ANSI standard and pre-standard C++ programs.
Preface
Figure P-l
Chapter 1 Introduction
Chapters 2-7 Basic Language Elements
I
I
Chapter 8 Searching And Sorting Arrays
Chapter 12 Advanced File Operations·
Chapter 9 Pointers
I
• A few subtopics in Chapter 12 requir e Chapters 9 and 11
I
Chapter 10 Characters, Strings, and the string Class
Chapte r 11 Structures
I Ch apter 13 Introduction to Classes
I Chapter 14 More About Classes
I
Chapter 15 Inheritance and Polymo rphism
I
Chapter 16 Exceptions. Templates, and STL
I Chapter 17 Linked Lists
I I
Chapter 18 Stacks and Queues
Chapter 19 Recursion
I Chapter 20 Binary Trees
xv
x vi
Preface
Chapter 3: Expressions and Interadivity In this chapter the student learns to write programs that input and handle numeric, character, and C-string data. The use of arithmetic operators and the creation of mathematical expressions are covered in greater detail, with emphasis on operator precedence. Debugging is introduced, w ith a section on hand tracing a program. Sections are also included on using sequenc.ial flies, o n simple output for matting, on data type co nversion and type casting, and on using library functions that work with numbe rs.
Chapter 4 : Making Decisions Here tbe student learns about relational operators, relational expressions and how to control the flow of a program with the if, if/else, and if/else i f statements. The conditiona l operator and the swi tch statement: arc also covered. Crucial applications of these constructs are covered, such as menu-driven programs and the validation of input:
Chapter 5 : Looping This chaptcr covers repetition control strllcrurcs. The while loop, do-while loop, and for loop arc taught, along with conunon use'> for these devices. Counters, accumulators, running totals, sentinels, and ocher application-related topics are discussed. A section on file VO discusses how to use a loop to read from a file until the end of the file is encoumered,
Chapter 6: Functions In th is chapter the student learns how and why to mod ularize programs, using both void and value return ing functions. Argument passing is covered , with emphasis on when arguments should be passed by va lue versus when t hey need to be passed by reference. Scope of variables is covered and sections are provided oIlloeal versus global variables and on static local variables. Overloaded functions arc also introduced and demonstrated.
Chapter 7: Arrays In this chaptcr the student learns to create and work with single and multidimensional arrays. Many examples of array processing are provided including examples illustrating how CO find the sum, average, highest and lowest values in an array and how to sum the rows, columns, and aU elements of a two-dimensional array. Programming techniques using parallel arrays are also demonstrated and the smdent is shown how co llse a data fi le as an input source to populate an array, STL vectors are introduced a,nd compared to arrays.
Chapter 8: Sorting and Searching Arrays Here t he stndent learns the basics of sorting arrays and searching for data stored in them. The chapter covers the Bubble Sort, Selection Sort, Linear Search, and Binary Search algorithms, There is-also a section on sorting and searchi ng STL vector objects.
Prefac.e
Chapter 9: Pointers This chapter explains how to use pointers. Poimers are compared to and contrasted with reference variables. Other topics include pointer arithmetic, initializa tion of pointers, rel ati onal comparison of pointers, pointers and arrays, poi nters and hmctions, dynamic memory allocation, and more.
Chapter 10: Characters, C-strlngs, and the Standard string Class Tills chapter foc uses on library funct ions that man ipulate or test characters or strings. A review of the interna l sto rage of C~strings is given. An extensive discussion of the sta ndard s tr ing class is also presented.
Chapter 11: Structured Data The srudent is introdu ced to abstract data rypes aod taught how to create them using strue· tures, unions, and enumerated data types. Discussions and examples include using pointers to structures, passing structure..;; to functions, and returning structures from functions.
Chapter 12: Advanced File Operations This chaprer covers seq uenti al access, random access, text, and binary fi les. The various modes for opening files are discussed, as well as the many methods for reading and writing file con tents. Advanced output formatting is also covered.
Chapter 13: Introduction to Classes
.
The srudenr now shifts focus to the object-oriented paradigm. This chapter covers the fundamental concepts of classes. Member varia bles and functions are discussed. The student lea rns abo llt private and public access specifications, and reasons to use each. The topics of constructors, overloaded constructo rs, and destructors are also presented. The chapte r presents a section modeling classes with UMl, and how to find the classes in a particular problem .
Chapter 14: More About Classes This chapter contin ues t~e study of classes. Static members, frien ds, memberwise assign~ ment, and copy constructors are discussed. The chapter also incl udes in~depth sections on operator overloading, object conversio n) and object aggregation. There is also a section on class colla bor.ations and the use of eRC cards.
Chapter 15: Inheritance and Polymorphism The study of classes continues in this ch apter with the subjects of inherita nce, polymor· phism, and virtual membet fu nctions. The topics covered include base and derived class constructors and destructors, virtual member functions, base class pointers, sta tic and dynamic binding, multiple inheritance, and class hierarchies.
xvii
xviii
Preface
Chapter 16: Exceptions, Templates, and the Standard Template Library (STL) The student learns [0 develop enhanced effOf trapping techniques using exceptions. Discussion then turns to functio n and class templates as a method for reusing code. Finally, the student is introduced to the containers, iterators, and algorithms offered by the Standard Template Library (STL).
Chapter 17: Linked Lists This chapter introduces concepts and techniques needed to work with lists. A linked list ADT is developed and the student is taught to code operations such as creating a linked Jist, appending a node, traversing the list, searching for a node, insening a node, deleting a node, and destroying a list. A linked list class template is also demonstrated.
Cha pter 18: Stacks and Queues In this chapter the student learns to create and use static and dynamic stacks and queues. The operations of stacks and queues are defined, and templates for each ADT are demonstrated.
Chapter 19: Recursion This chapter discusses recursion and its use in problem solving. A visual trace of recursive calls is provided and recursive applications are discussed. Many recursive algorithms are presented, including recursive functions for finding factorials, finding a greatest common denominator (GCD), performing a binary search, and sorting (QuickSort). The classic Towers of Hanoi example is also presented. For students who need more challenge, there is a section on exhaustive algorithms.
Chapter 20: Binary Trees This chapter covers the binary tree ADT, and demonstrates many binary tree operations. The student learns to traverse a tree, insert an element, delete an element, replace an element, test for an element, and destroy a tree.
Appendix A: Getting Started w ith Alice This appendix gives a quick introduction [0 Alice. AJice is free software that can be used to teach fundamenta l programming concepts using 3D graphics.
Appendix B: ASCII Character Set A list of [he ASCII and Extended ASCll characters and their codes.
Appendix C: Operator Precedence and Associativity A chart showing the C++ operators and their precedence.
,
Preface
The following appendices are on the accompanying Student CD
Appendix D: Introduction to Flowcharting A brief introduction to flowcharting. This tuto ri al discusses sequence, selection, case, repetition, and module structures.
Appendix E: Using UML in Class Design '~
This appendix shows the studenc how to use the Unified Modeling Language to design classes. Notation for showing access specification, data types, parameters, return values, overloaded functions, composition, and inheritance afC included.
Appendix F: Namespaces This appendix explains namespaces and their p urpose. Examples showing how to define a na mespace and access its members arc given .
Appendix G: Writing Managed C++ Code for the .NET Framework This appendix introdllces the student Microsoft's .NET environment.
to
the concepts surrounding managed C++ m
Appendix H: Passing Command Line Arguments Teaches the student how co write a C++ program that accepts arguments from the command line. This appendix will be usefu l to students working in a command line environment, such as Unix, LiulIX, or the \Vindows MS-DOS prompt console.
Appendix I: Header File and Library Function Reference This appendix provides a reference for the C++ library functions and header files discussed in the book.
Appendix ,: Binary Numbers and Bitwise Operations A guide to the C++ bitwise operators, as we ll as a tutorial on the intern al storage of integers.
Appendix K: Multl·Source File Programs Provides a tutorial on crcating programs that consist of multiple source files. Function header fi les, class specification files, and class impl ementation files arc discussed .
Appendix L: Stream Member Functions for Formatting Covers stream member functions for formatting such as setf.
Appendix M: Introduction to Microsoft Visual C++ 2008 Express Edition A tutorial on how to start a project in Microsoft Visual C++ 2008 Express Edition, compile a program, save source files, and more.
xix
xx
Preface
Appendix N: Answers to Checkpoints Students may (est their own progress by comparing their answers to the checkpoin t exercises against this appendix, The answers to a ll Checkpoints a re included.
Appendix 0 : Answers to Odd-Numbered Review Questions Another roo! that students can use ro gauge their progress.
Feature s of the Text Concept
Statements
Each major section of the text Starts with a concept sw tement. This statement summarizes the ideas of the section.
Example Programs
The (ex t has over 300 complete example programs, each designed ro highlight the topic currently be ing studied. In most cases, these are practical, real -world examples. Source code for these programs is provided so that students can fun the programs themselves.
Program Output
After each example program there is a sample of its screen output. This immediately shows the student how the program shou ld function.
In the Spot light
Each of (hese sections provides a programming problem and a dctailed, step by step analysis showing the studenr how to solve >t.
Video Notes
A se ries of on[me videos, developed specifically for this book, are availab[e for viewing at http : //www.aw.com/gaddis/ videonotes. Icons appear throughout the text alerring the student to videos about specific tOpics.
Checkpoints
Checkpoints are questions placed throughout each chapter as a self-test STUd y aid. Answers fat a[ 1 Checkpoint questions a re provided on the student CD so students can check how well they have learned a new topic.
Notes
Notes appear at appropriate places throughout the text. They are short explanations of interesting or often misunderstood points relevam to rhe topic at hand.
Warnings
Warnings are notcs that caution the studcnt about certain C++ features, programming techniques, or practices that can lead to malfunctioning programs or lost data.
Preface
Case Studies
Case studies that simulate real-world applications appear in many chapters throughout the rext, with complete code provided for each one on the student CD. These case studies are designed to highlight the major wpics of the chapter in which they appear.
Review Questions and Exercises
Each chapter presents a thorough and diverse set of review questions, such as fill-in-the-blank and short answer, that check the student's mastery of the basic material presented in the chapter. These are followed by exercises requiring problem solving and analysis, such as the Algorithm Workbench, Predict the Output, and Find the Errors sections. Answers to the odd numbered review questions and review exercises are provided on the student CD.
Programming Challenges
Each chapter offers a pool of programming exerc ises designed to solidify the student's know ledge of the topics currently being studied. In most cases the assignments present real-world problems to be solved. When applicable, these exe rcises inclu de input validation rules.
Group Projects
There are several group programming projects throughout the text, intended to be constructed by a team of students. One student might build the program's user inte rface, while another student writes the mathemat ical code, and another designs and implemems a class the program uses. This process is similar (Q the way many professional programs are written and encourages team work within the classroom.
Software Development Project: Serendipity Booksellers
T his is an on-going project that instructors can optiona lly assign to teams of students. It systematically develops a "real-world" softwa re package: a point-of-sale program for t he fic tlrious Serendipity Bookse llers organization. The Serendipity assignment for each chapter adds more func tionality ro the software, using constructs and techniques covered in that chapter. When complete, the program will act as a cash register, manage an invemory darabase, and prod uce a variety of reports.
C++ Quick Reference Guide
Fo r easy access, a quick reference guide to the C++ language is printed on the la st page of the book and the ins ide back cover.
xxi
x x ii
Preface
Supplements Student CD This CD includes: •
Borland Turbo c++ Explorer Edition
•
Answers co all Checkpoint questions (Appendix N)
•
Answers
•
Complete source codc for every program included in rhe book
•
Additional case studies, complete with source code
•
A full set of appendices (including several tu(Onals) that accompany the book
(0
all odd-numbered Review Questions and Exercises (Appendix 0)
If a CD did not come with your book or you can't locare your CD, you can access most of these items at http : //www . aw.com/cssupport/
Other CDs Upon Request Professors should cOntact their campus Addison-Wesley representative for the specific ISBN to order this book packaged with Microsoft Visual C++ 2008 Express Edition.
MyCodeMate-Your Own T.A. Just a Click Away Addison-Wesley's MyCodeMate is a book-specific Web resource that provides tutorial help and evaluation of student programs. Example programs throughout the book and selected Programming Challenges from every chapter have been integrated inro MyCodeMate. Using this tool , a student is able to write and compile programs from any computer with Internet access, and receive guidance and feedback on how to proceed and on how to address com piler error messages. InStructors can track each student's progress on Programming Challenges from the text or can develop projects of their OWll. A comp limentary subscription to MyCodeMate is offered when the access code is ordered in a package with a new copy of this text. Subscriptions can also be purchased online. For more information visit http:// www.mycodemate.com. or contact your campus Addison-Wesley representative .
Instructor Resources T he following supplements arc available to qualified instructors only: •
Answers
•
Solutions for all Programmmg Challenges in the text
•
PowerPoint presentation slides for every chapter
•
Computerized test bank
•
Answers
•
Solutions for all Srudenr Lab Manual programs
to
to
all Review Questions in the text
all Student Lab Manual questions
Visit the Addison-Wesley Instructor Resource Cenrer (http : //www . aw . com/ire) or send an email to
[email protected] information on how to access them.
•
Preface
Textbook Web site A Web site for the Starting Out with C++ series of books is located at the following URL: http://www.aw.com/gaddisbooks
Get this book the way you want it! This book is part of Pearson Education's custom database for Compurer Science textbooks. Use OUf online PubSelect system to select just the chapters you need from this, and other, Pearson Education CS textbooks. You can edit the sequence ro exactly match your course organization and teaching approach. Visit www . pearsoncustom . com/csfordetails.
Which Gaddis C++ book is right for you? The Starring Our with C++ Series includes three books, one of which is sure to fit your cou rse:
•
Starting Out with C+ +: From Control Structures through Objects (formerly called the "Standard VersIon");
• •
Starting Ollt with C++: Early Objects (fo rmerly called the" Alternate Version"); Starting Out with C++: Brief Version.
The following chart will help you determine which book is right for your co urse .
• FROM CONTROL STRUCTURES THROUGH OBJECTS • BRIEF VERSION
• EARLY OBJECTS
LATE INTRODUCTION OF OBJECTS Classes are introduced in Chapter 13 of the standard tcxt and Chapter 11 of thc brief text, after control structures, functions, arrays, and pointers. Advanced OOP tOpics, such as inheritance and polymorphism, are covered in the following rwo chapters.
EARlIER INTRODUCTION OF OBJECTS Classes are inrroduced in Chapter 7, after comrol srructures and functions, but before arrays and pointers. Their usc is then integrated into the remainder of the text. Advanced OOP topics, such as inheritance and polymorphism, are covered in Chapters 11 and 15.
USE OF C-STRINGS Null-terminated C-strings are used throughout, with the C++ string class covered briefly.
USE OF s t r ing OBJECTS Standa rd library str ing class objects are used throughout, with C-strings covered briefly.
INTRODUCTION OF DATA STRUCTURES AND RECURSION Linked lists, stacks and queues, and binary trees are introduced in the final chapters of the standard text. Recursion is covered after stacks and queues, but before binary trees. These copics are nOt covered in [he brief text, though it does have appendices dealing with linked lists and recursion.
INTRODUCTION OF DATA STRUCTURES AND RECURSION Linked lists, stacks and queues, and binary trees are inrroduced in the final chapters of the text, after the chapter on re<:ursion.
xxiii
xxiv
Preface
Acknowledgments There have been many helping hands in the development and p ublication of this text. We would like to [hank the following fac ulty reviewers for [heir helpful suggestions and expertise. Ahmad Abuhejleh U11iversity of Wisc011sin, River Falls
Royce Curtis Western Wisconsin Technical College
David Akins Ef Camino Col/ege
Joseph .l)cLibero Arizona State University
Steve Alla n Utah State University
Jeanne Douglas University of Vermont
Vicki Allan Utah State UnIVersity
Michael Dowell Augusta State U
Ka ren M. Arlien Bismark State College
Judy Etchison Southem Methodist University
Mary Astone Troy University
Dennis Fairclough Utah Valley State College
Tjaz A. Awan Savannah State University
Richard Flint North Central College
Robert Baird Salt Lake Community College
Ann Ford Florida Stare University
Don Biggersra ff Fayetteville Technical Community College
James Gifford University of Wisconsin, Stevens Point
Micbael Bolton Northeastern Oklahoma State University
Leon Gleiberman Touro College
Bill Brown Pikes Peak Community College
Ranette Halverson, Ph.D. Midwestem State University
Charles Cadenhead Richlmld Community College
Carol Hannahs University of Kentucky
Randall Campbell Momingside College
Dennis Heckman Portland Community College
Wayne Caruolo Red Rocks Community College
Ric He ishman
Carhi Chambley-Miller Aiken Tech1lical College
M ichael Hennessy University of Oregon
c.c. Chao Jacksonville State University
IJga H igbee Black Hawk College
Joseph Chao Bowling Green State University
Parricia H lOes Brookdale Community Col/ege
George Masoll University
Preface
Mike Holland Northern Virginia Community College
Lynne Q'H anlon Los Angeles Pierce College
Mary Hovik Lehigh Carbon Community College
Frank Paiano SOllthwestern Community College
Richard Hull Lenoir-Rhyne College
Theresa Park Texas State Technical College
Ch ris Kardaras North Central College
Mark Parker Shoreline Commlmity College
Willard Keeling Blue Ridge Community College
T ino Posiltico SUNY Farmingdale
A.J. Krygeris Ho uston Community College
Frederick Pratter Eastern Oregon University
Sheila Lancas[cr
Susan L Q uick Penn State University
Gadsden State Community College R ay Larson Inver Hills Community College
Alberto Ram o n
Jennifer Li Ohlone Col/ege
Sazlur Rasheed Sault College of Applied Arts and Technology
Norman H . Lieb ling San jacillto College
Farshad Ravanshad Bergen Commllnity College
Zhu-qu Lu University of Maine, Presque l sle
Dolly Sa mson Weber State University
H eidar Malki University of HOllston
Ruth Sa pir SUNY Farmingdale
Debbie Marhews J. Sargeant Reynolds
Jason Schatz City Col/ege of San Francisco
R ick Matzen Northeastern State University
Dr. Sung Shin
Robert McDona ld East Stroudsburg University
Sari Sid d ique University of Texas at Brownsville
James McGuffee Austin Community College
William Slater Collin COHllly Community College
Dean MelJas
Shep Smith line
Cerritos Col/ege
University of Minnesota
Lisa Milkowski Milwaukee School of Engineering
Caroline Sr. Clai re North Central College
M arguerite Nedreberg Youngstown State University
Kirk Stephens SOllthwestern Community College
Diablo Valley College
South Dakota State Univers ity
xxv
xx vi
Preface
Cherie Stevens South Florida Community College
Arisa K. Ude Richland College
Dale Suggs Campbell University
Perer van der Goes Rose State College
Mark Swanson Red Wing Technical College
Stewart Venit Californ ia State University, Los Angeles
M artha Til lman College of San Mateo
Judy Wa lters North Cell tral College
Ralph To mlinson Iowa State University
John H . Whipple Northamp ton Community College
David Topham Ohlone College
Aurelia Williams Norfo lk State University
Robert Tureman Patti D. Camp Community Col/ege
Vida Winans Illinois fnstift/le of Technology
First, I would like to thank my fam ily for their ma ny years of suppOrt, and my stude nts at Haywood Comm unity College for inspiring me (Q write student-friendly books. l owe a debt of gratitu de to everyo ne at Addison-Wesley who is parr of rbe ed irorial, production, and marketing team for this book. J am ve ry fortunate to have M ichael Hirsch as my editOr, guiding me th rough a ll pbases of development a nd production. 1 am also for tunate to work with C hris Kell y, Maril yn Lloyd , Stephanie Sellinger, Bethany Tidd, Joyce Wells, and Shelley C reager. This book would nor be possible wirhout your tircless work. You arc all great people ro work with!
Preface
About the Author Tony Gaddis is the principa l author of the Starting Out with series of textbooks . He has nearly twO decades of experience teaching computer science courses, primarily at Haywood Community College. Tony is a highly acclaimed instrucror who was previously selected as the North Carolina Community CoUege Teacher of the Year, and h.as received the Teaching Excellence award from the National Institute for Staff and Organizational Development. T he Starting Ollt With series includes introductory textbooks covering Programming Logic and Design, Alice, C++, Java TM, Microsoft® Visual Basic®, and Python, all publ ished by
Addison-Wesley.
x x vH
TOPICS 1 .1 1.2
Why Program? Computer Systems: Hardware
and Software Programs and Programming Languages
'.4 '.5
What Is a Program Made of? Input, Processing, and Output
1.6 1.7
The Programming Process Procedural and Object·Oriented Programming
Why Program 7 CONCEPT: Computers can do many different jobs because they are programm able. Every profession has tools that make its job easier to do. Carpenters use hammers, saws,
and measuring rapes . Mechanics use wrenches, screwdrivers, and ratchets. Electronics technicians lise probes, scopes, and meters. Some tools are unique and can be categorized
as belonging ro a single profession. For example, surgeons have certain tools that are designed specifically for surgica l operations. Those tools probably aren't used by an yone other than surgeons. T here are some tools, however, that are used in several professions. Screwdrivers, for instance, are used by mechanics, carpenters, and many others. The computer is a tool that is used by so many professions that it cannot be easily categorized. It can perform so many different jobs that it is perhaps the most versatile tool ever made. To the accoun tant, computers balance books, analyze profits and losses, and prepa re tax reports. To the factory worker, computen comrol manufaccuring machines and (rack production. To the mechanic, computers analyze the various systems in an automob ile and pinpoinr hard-to-find problems.
1
2
Chapter 1 Introduction to Com puters and Programming
What makes the computer so useful? Quite simply, the computer can do such a wide variety of tasks because it can be programmed. it is a machine specificaJly designed to foUow insrructioos.
Because of the computer's programmability, it doesn't belong to any single profession. Computers are designed to do whatever cask their programs, or software, tell them to do . Computer programmers do a very important job. They create software that transforms computers into the specialized tools of many trades . Without programmers, the users of computers
would have no software, and without software, computers would not be able to do anything. Computer programming is both an art and a science. It is an art because every aspect of a program should be carefully designed. Listed be low are a few of the thi.ngs char must be designed fo r any real-world computer program:
• •
The logical flow of the instructions The mathematical procedures
• • • •
The appearance of the screens The way information is presented to the Llse r The program's "user-friendl iness " Manuals and other fo rms of written documentation
There is also a scienrific, or engineering, side to programming. Because programs rarely work right the firs[ time they are written, a lac of testing, correction, and redesigning is required . This demands patience and persistence from the programmer. Writing software demands discipline as well. Programmers must learn special languages like C++ beca use
computers do not understand English or other human languages. Languages such as C++ have strict fules that muSt be carefully followed. Both the artistic a nd scientific nature of programming make writing compurer software like designing a car: Both cars and programs should be func tional, efficient, powerful, easy to use, and pleasing to look at.
Computer Systems: Hardware and Software systemS consist of sim ilar hardware dev ices and so ftwa re components. T his section provides an overview of standard computer hardware and software o rga nizatio n.
CONCEPT: All compute r
Hardware Hardware refers to the physical components that a compurer is made of. A computer, as we generally think of it, is not an individual device, but a syStem of devices. Like the instruments in a symphony orchestra, each device plays its own part. A typical computer sys tem consis ts of th e following m:ljo l' components:
1. The central processing unit (CPU) 2. Main memory
3. Secondary storage devices 4. Input devices 5. Output devices
1.2 Computer Systems: Hardware and Software
The organization of a computer system is depIcted in Figure] -1. Figure 1-1
-
Central Processing Unit
Output Devices
Inpu t Devices
-
Main Memory (RAM) •
,t
-
Secondary Storage Devices
The CPU
At the heart of a computer is its central processing tIIlit, or CPU. The CPU's job is co fe tch instructions, follow the instructions, and produce some result. Internally, the central processing unit consists of two parts: the cO/1trol tm it and the arithmetic and logic Im;t (ALU). T he control uni t coordinates all o f the computer's operations. It is responsible for determining where to get the next instruction and regulating the other ma jor components of the computer with control signals. The ari thmetic and logic unit, as its name suggests, is designed to perform mathematical operations. T he organization of the CPU is shown in Figure 1-2.
Figure 1-2 Central Processing Unit Arithmetic and LogiC Unit Result (Ou tput)
Instruction (Input)
• Control Unit
3
4
Chapter 1 Introduction to Computers and Programming
A program is a sequence of instructions stored in the computer's memory. When a com~ plIter is running a program, the C PU is engaged in a process known for mally as the fetchl
decode/execute cycle. The steps in (he ferch/decode/execute cycle are as follows: instruc ~
Fetch
The CPU's control unit fetches, from main memory. the next cion in the sequence of program inStrllctions.
Decode
T he Instr uction is encoded in the form of a number. T he control unit decodes the instruction and generates an electronic signal.
Execute
The signal is routed to the appropriate component of rhe computer (such as the ALU, a d isk drive, or some mher device). The signa l ca uses the co mponent to perform an operation .
These steps are repeated as long as there are instructions to perform.
Main Memory Commonly known as random-access memory, or RAM, the computer's mai n memory is a device that holds information. Specifically, RAM holds (he sequences of instructions in the programs thar afe ru n ning and the da ta those programs are usi ng. Memory is divided into sections, or celis, that eac h hold an equal amount of data. Each cell is made of eight "switches" that may be either on or off. A switch that is in rhe on pos ition usually represents the numbcr 1, wh ile a switch in thc off position usually represents the numbe r O. The computer stores data by setting the switches in a memo ry cell to a pattern thar representS a character of informatio n. Each of these switches is k nown as a bit, which sta nds for binary digit. Each cell, which is a collection of eight bits, is known as a byte. Each byte is assigned a unique n umber known as an address. The addresses are o rdered from lowest to highest. A byte is identified by its address in much rhe same way a post office box is identified by an address. Figure 1-3 shows a group of memory cells with their addresses. In the illustration, sam ple dara is stored in memory. The number 149 is srored in rhe cell with the add ress 16, and the number 72 is stored at address 23 .
Figure 1-3
.£J
f.'-I
f.'J
2l
~
f'J
2l
~
i'!J
~
~
~
1!3
~
~
~
11'1
nI
" f'iI
inI
§I
'"
f.'-I
f!J
.£J
~
~
~
IW
~
nI
RAM is usua lly a volarile type of memory, used only for temporary StOrage. When the computer is tu rned off, the contents of RAM are erased.
Secondary Storage Secondary storage is a rype of memory that can hold data for long periods of time--even when t here is no power to the compute r. ):rcqllently used progr~ms ~ re stored in secondary memory and loaded into main memory as needed . Important information, such as word processing documents, payroll dara, a nd inventory figures, is sa ved to secon dary storage as well.
'.2 Computer Systems: Hardware and Software
The most common type of secondary storage device is the disk drive. A disk drive stores data by magnetically encoding ie OntO a circular disk. Most computers have a disk drive mounted inside their case. External disk drives, which connect to one of the computer's communication pores, are also available. External disk d rives can be used to create backup copies of imporranr data or to move data to another computer. In addition to external disk drives, many types of devices have been created for copyi ng data, and for moving it to other computers. For many years floppy disk drives were popular. A floPPY disk drive records data onto a small floppy disk, which can be removed from the drive. The LIse of floppy disk drives has declined dramatically in recent years, in favor of superi or devices such as USB drives. USB drilles are sma ll devices rhat plug into the computer's USB (universal serial bus) porr, and appear to the system as a disk drive. USB d rives, which use flash memory to store data, are inexpensive, reliable, and small enough ro be carried in your pocket.
Optical devices such as rhe CD (compact disc) and the DVD (digita l versatile disc) arc also popular for data storage. Data is nor recorded magnetically on an optical disc, but is encoded as a series of pi ts on the disc su rface. CD and DVD drives lise a laser to detect rhe pits and rhus read the encoded data. Oprical di scs hold large amounts of data, and because recordable CD and DVD dr ives are now commonplace, they are good mediums for creating backup copies of data.
Input Devices Input is any information the computer collects from the outside world. The device that collects the information and sends it to the computer is called an iI/put device. Common input dev ices are the keyboard, mouse, scanner, digital camera. and microphone. Disk drives, CD/DVD drives, and USB drives can also be considered input devices because programs and information are retrieved from them and loaded into the computer's memory.
Out put Devices Output is any info rmation the computer sends to the outside world. It might be a sales report, a list of names, or a graphic image. The information is sent to an output device, wh ich formars and presents it. Common output devices are monirors, p rimers, and speakers. Output sem to a monitor is sometimes called "so[rcopy," while ourpllt sent ro a prinrer is called "hardcopy. " Disk drives, USB drives, and CDIDVD recorders can also be considered output devices beca use the CPU sends them information to be saved.
Software As previously mentioned, sofrware refers to the programs that run on a computer. There are two genera l categories of softwar e: operating systems and application software. An operating system is a set of programs thar ma nages (he comp uter's hardware devices and controls their processes. Operating systems fall into one of the followi ng caregon es.
Single tasking
A single tasking operating sysrem is capable of running only one program at a time. T he compu ter devotes all its hardwa re resources and CPU time to each program as it executes. MS-DOS is an examp le of a single ta sking operati ng system.
5
6
Chapter 1 Introduction to Computers and Programming
Multitasking
A multitask ing operating system is capable of run ning multiple programs at once. Thcough a technique called lime sharing, the syste m divides the alloca tion of hardware resources and the anention of the CPU among all the executing programs. UN1X, Windows XP, and Windows Vista are multitasking operating systems.
In add ition, operating systems fall into one of the foJl owi ng ca tego ries, which describe the number of users they can accommodate.
Single lIser
This type of system allows o nly o ne user to operate the comp uter at a time. MS-DOS and older versions of Windows are single user operating systems.
Multiuser
Multiuser systems allow several users to run programs and operate the computer at once. Most varia tions of the UNIX operating system are multiuser syste m s .
Applica tion software refers to programs that make the computer useful to the user. T hese programs solve specific problems or perform general operations that satisfy the needs of the user. Word processing, spreadsheet, and database progra ms are all examples of application softwa re.
~ Checkpoint 1.1
Why is the computer used by so ma ny differe nt people, in so m:tn y differellt professions?
1,2
List the five major hardwa re components of a computer system.
1. 3
Internally, the CPU consists of wha t two units?
1.4
Desc ribe the steps in the fetch/decode/execu te cycle.
1.5
What is a memory add ress? What is its purpose?
1.6 1.7
Explain why computers have both main memory and secon dary sto rage. What are the twO general ca tegories of software?
1.8
What is the difference between a single ta sk ing system and a multitasking system?
1.9
What is the difference between a single user system and a multiuser system?
Programs and Programming Languages CON C EPT: A program is a set of instructions a computer fo llows in order to perform a task, A programming language is a special language used to wrilc computer programs.
What Is a Program? Computers :l re designed to follow ;nstJ:ucrions_ A computer ptogr.:l m ill .:l set of instructions that tells the compmer how to solve a problem or perform a task. For exampl e, suppose we want th e comp urer ro calcu late someone's gross pa y. Here is a list of things the computer should do:
'.3 Programs and Programming languages
1. Disp lay a message on the screen asking " H ow many hours did you wor k?" 2. Wait for the user to eorer the number of hours worked. Once the llser enters a num-
ber, store it in memory.
3. Display a message on the screen asking "How much do you get paid per hour?" 4. Wait for the user to enter an hourly pay rate. Once the user enters a number, store it in memory.
5. Multiply the number of hours by the amount paid per houf, and StOre the result in memory. 6. Display a message on the screen that tells the amOllnt of money earned. The message must include rhe result of the calcula tion performed in Step 5. Collectively, these instructions are called an algorithm. An algorithm is a set of welldefined steps for performing a task o r solving a problem. Notice these steps are sequentially orde red. Step 1 shoul d be performed before Step 2, and so forth . It is important that these instructions be performed in their proper sequence. Although yo u and I might easily understand the instructions in the pay-calculating algorithm, it is nOt ready to be executed on a computer. A computer 's CPU can only process instructions that arc written in machine language. If you were ro look at a machine language program, yo u would see a stream of binary numbers (numbers consisting of o nly I s and Os). T he binary numbers form ma chine language instructions, which the CPU interprets as commands . Here is an example of what a machine language instruction m ight look like: 1011010000000101
As you can imagine, the process o f encoding an algorithm in machine language is very ted ious and difficult. In addi tion, each di fferen t type of CPU has its own machine language. If you wrote a machine language program fo r comp uter A and then wanted to r un it on computer S, which ha s a different type of CPU, you would have to rewrite the program in computer B's machine language . Programming languages, which use words instead of numbers, were invented to ease rhe task
of programming. A program can be wrirren in a programming language, such as C++, which is m uch easier to understand than machine language. Programmers save their programs in text files, and then use special software to convert their programs to machine language. Program 1-1 shows how the pay-calcu lating algorithm might be written in C++. T he " Program Output with Example Input" shows what the program will display on the screen when it is running. In the example, the user emers 10 for the number of hours worked and 15 for the hourly pay rate. The program displays the earnings, which a re $150. NOTE : The line numbers that are shown in Program '] -1 arc not part of the program . This book shows line numbers in all program listings to help point ou t specific parts of the program.
7
8
Chapter 1
Program
1
Introduction to Computers and Programming
1 ~1
II This program calculates the user's pay. iinclude
2 3
,
using namespace std;
5
int main ()
6 7
{
double hours, rate, paYi
•
II Get the number of hours worked .
9 10
cout « "How many hours did you work? "; c i n » hours;
11
12 13
1/ Get the hou rly pay rate. cout « "How much do you get paid per hour? "; cin » rate:
14 15
16
17
/1 Calculate the pay .
18 19
pay = hours * rate;
20
/1 Display the pay.
21 22 23
cout « "You have earned $" « return 0;
pay «
endl;
}
Program Output with Example Input Shown In Bold How many hours did you work? 10 [Enter] HOW much do you get paid per hour? 15 [Enter]
You have e arned $150
Programming Languages In a broad sense, there are two categori es of programming languages: low·level and high-level. A low -level language is close co the level of the computer, which means it resembles the numeric machine language of the computer more than the natural language of humans. The easiest languages for people to learn are high-leuel languages. They are called "high-level" because they are closer to the level of huma n-readability than computer-readability. Figure 104 illustrates the concept of language levels. Many high-level languages have been created. Table 1-1 lists a few of the well-known ones. In addition to the hIgh-level features necessary for writing applications such as payroll systems and inventory programs, C++ also has many low-level features. c++ is based on the C language, which was invented for purposes such as writing operating systems and compilers. Since C++ evolved from C, it carries an of C's low-leve l capabilities with it.
'.3 Programs and Progr1!lmming languages
Figure 1-4 High level (Close 10 human language)
Low level (machine language)
10100010 11101011
Table 1-1 Language BASIC
Description Begi nners All-purpose Symbolic In struction Cod e. A general programming language originally designed to be simple enough for beginners (0 learn.
FORTRAN Formula Translator. A language designed fo r programming complex mathematical algorithms. COBO L Common Business·Oriented Language. A language designed for business appl ica tions. Pascal A strllctured, general -purpose language designed primarily fo r tcaching programming. C A stfllcfllrcd, general-purpose language developed at Bell Laboratories. C offers both high-level and low-level features. C++ C# Java JavaScript Python Ruby VisuaJ Basic
Based on the C language, C++ offers object-oriented features not found in C. Also invented at Bell Laboratories. Pronounced "C sharp. " A language invented by Microsoft for developing applications based on the Microsoft .N ET platform. An object-oriented language invented at Sun Microsysrems. Java ma y be used to develop programs that run over the Imernet, in a Web browser. JavaScript can be used to write small programs that run in Web pages. Desp ite its name, JavaScript is nor reJared to Java. Python is a general purpose language created in the early 1990s. it has become popular in boch business and academic applications. Ruby is a general purpose language that was created in the 1990s. It is increasingly becoming a popular language for programs that run 011 Web servers. A Microsoft programming language and software development environment that allows programmers to quickly create Windows-based applications.
9
10
Chapter 1 (ntroduction to Computers and Programming
c++ is popular nOt on ly because of its
mixture of low- and high-level features, bur also because of its portability. This means th at a C++ program can be written on one type of co mputer and then fun o n many other types of systems. Th is usually requires the pcogram to be recompiled on each type of system, but rhe progra m itself may need little o r no change. NOTE: Programs wrinen fo r specific g raphical env ironments often req uire significant ch anges when moved to a differenr type of system . Examples of such graphical env ironments are Windows, the X-Window System , and the Mac OS X operating system.
Source Code, Object Code, and Executable Code When a C++ program is written, it must be typed inro rhe computer and saved to a fil e. A text editor, which is similar to a word processing program, is used for thi s task. The stare· ments written by the programmer a rc called source code, a nd the file thc}' arc saved in is called the source file. Afrer the source code is saved to a file, the process of translating it to machine language can begi n. During the first phase of this process, a program ca lled the preprocessor reads the source code. T he preprocessor searches fo r special lines that begi n with rhe t symbol. These lines contain commands that cause the preprocessor to modify the source code in some way. During the next phase the compiler steps through the preprocessed SOll rce codc, translating each source code inst.ruction into the appropriate machine language instruction. This process willll ncover any syntax errors that may be in the program. Syn· la x errors are illega l uses of key words, operators, punctuation, and other language elements. If the progra m IS free of syn tax errors, the co mp iler stores the transla ted machine language instructions, which are called object code, in an object file. Although an object file contains machine language instructions, it is nO( a complete pro· gram. Here is why; C++ is conveniently equipped with a library of prewritten code for performing common operations or sometimes-diffi cult tasks. For example, the library con tains hardware-specific code for displaying messages on the screen and reading input from the keyboard. It also provides routines for mathematical functions, sllch as calculati ng the square root of a number. This collection of code, ca lled the run-time library, is extensive. Programs almost al wa ys use some part of it. When rhe compil er generates an object fi le, however, it does not include machine code for any run-time library routi nes [he programmer might have used. During the last phase of the translation process, another program called th e linker combines the object file with the necessary library romines. Once the linker has fimshed with this step, an executable file is created. The execura ble file contains machine language instructions, or executable code, a nd is rcady to rlln on the computer. Figure 1-5 illustrates the process of translating a C++ source file into an executable file. The cnrire process of invoking the preprocessor, compiler, and linker can be initiated wirh a single action. For example, o n a Linux system, the following command causes the C++ program named hello _cpp CO be preprocessed, compiled, and link ed. T he executa ble code is stored in a file named hello. g++
-0
he l lo hello . cpp
1. 3 Programs and Programming l anguag es
Figure 1-5
Source Code
,
Source (ode Is entered with a text editor by the p'OfJrommer.
1
I
,
Rinclude using n ... Up.ce ltd;
Preprocessor
,
in t
".i"O CO"t«"Heiio IOorld\,,",
Modified Source Code
r eturn 0;
1 Compiler
I
U
Object Code
1
I
linker
1J
I bu"bbl .. Cod ..
.i"iet
Appendix G on the Student CD expla ins how comp il ing work s in .Net. Many development systems, pa rticularly those on persona l computers, have bltegrated development environments (TO Es). These envi ronments cons ist o f a text edi tor, compiler, debugger, and other util ities integra ted into a package with a single set of menus. Preprocessing, com piling, linki ng, and even execming a progra m is done with a si ngle cl ick of a bmron, or by selec(ing a si ngle item from a menll. Figure 1-6 shows a screen from the Microsoft Visual C++ IDE.
~
Checkpoint 1. 10 1.1 1 1. 12
What is an algorithm ? Why were computer program mi ng la nguages in vented? What is the diffe rence between a high-level la nguage and a low-level la nguage?
1.13
What does portability mean?
1. 14
Explain the operations carried out by the preprocessor, compiler, and linker.
1.15
Expla in wha t is stored in a source fil e, an object file, and an executa ble file.
1.1 6
Wha t is an integrated development envi ronment?
11
12
Chapter 1 Introduction to Computers and Programming
Figure 1-6 ': Grm.~Poly
:5J~ ~ . ~g"
, ,• " " " H
~§fE]
MicrO!oOftVlsu41 Ch (i;k>s.ign) · Prl I cpp'
!j/It~~~t""~
.l
!_~~
a..
• DeW;
I I Ge~ the n~r Q! h~~r. vork~d. cout « - Hov aacy hcur~ d~ d yeu weer?
ci.n »
h our" ,
I I Get COUt «
~
12
lS
eUI
»
hourly pay race.
- Holl :weh do .tAt e:
~OClU
gee p aid per hour? ";
:6:
17: u:
:~
"23,,
I I Calculate che pay . pay • hou r " • rate; II Ol",pla:.' che pay.
coue «
- You bavt e ar ned S-
«
pay
« eod1;
l-
Rltl';'Q.
CIC
n,IP
Reltb'y. P.MII
"'''CIa'' 0 ;
+.
Content
Co6e
. . - t;
.. \- \.. l,.. 1100'S
•
""" What Is a Program Made of? CON CE PT: There ace certain elements that are common to all programming languages.
Language Elements All programming languages have a few things in common . Table 1-2 lists the common elements you will find in almost every language.
Let's look at some specific parts of Program 1-1 (the pay-calculating program) to see examples of each element listed in the table above. For your convenience, Program 1-1 IS listed again.
1.4 What Is a Prog ram Made of?
Table 1-2 Language
Element Key Words
Description Words thar have a special meaning. Key words may only be used for their inrended purpose. Key words are also known as reserved words.
Progra mmer-Defined Words or names defined by the programmer. They are symbolic names that refer ro variables or programming routines . Operarors Operators perform operarions on one or more opcmnds. An operand is usual ly a piece of data, like a number.
Identifiers
Punctuation
Punctuation ch aracters that mark the beginning or ending of a statement, or
Syntax
separate items in a lise. Rules tbat must be followed when constructing a program. Syntax dictates how key words and ope rators may be used, and where punctuation symbols ml,lsr appear.
Program 1-1
1
II This program calculates the user's pay .
2
3
' include
5
intrnain()
6 7 8
{
•
double hours , rate, pay ;
9
II Get the number of hours worked . cout « "How many hours did you work? "; cin » hours ;
10
11 12
II Get the hourly pay rate . cout « "How much do you get paid per hour? "; cin » rate;
13 14 15 16
17 16
II Calculate the pay. pay - hours * rate;
19 20 21 22 23
II Display the pay. cout « "You have earned S" « re turn 0 ;
pay «
e ndl;
}
Key Words (Reserved Words) Three of C++'s key words appear on lines 3 and 5 : using, namespace, and into The word double, which appears on line 7, is also a C++ key word. These words, which are al wa ys written in lowercase, each have
13
14
Chapter 1
o o
Introduction to Computers and Programming
own names for ce([ain things in a program. Key words, however, are reserved and cannot be used for anything other than their designated purposes. Part of learning a progl'amming language is learning what the key words are, what they mean, and how to use them. NOTE: The !include statement in line 2 is a preprocessor directive.
NOTE: In C ++, key words arc written in al l lowercase.
Programmer-Defined Identifiers The words hours, rate, and pay that appear in the program on lines 7, 11 , 15, 18, and 21 arc programmer-defined identifiers. They afC nOt part of the C++ language but rather are names made up by the programmer. In this particular program, these are the names of variables . As you will learn later in this chapter, variables are the names of memory locations tha t may hold data.
Operators On line 18 the following code appears: pay
=
hours * rate ;
The = and:;' symbols arc both operators. They perform operations on pieces of data known as operands. Th e" operator multiplies irs two operands, which in this example are the variables hours and rate. The = symbol is called the assignment operator. Tt takes the value of the expression o n the right and stores it in the variable whose name appears on the left. In this example, the::: operator stores in the pay variable the result of the hours va riable multiplied by the rate variable. In other words, the statemen t says, "Make the pay variable equal to hours times rate, or " pay is assigned the value of hours rimes rate. n Punctuation
Notice that lines 3, 7, 10, 11, 14, 15, 18,21, and 22 all end with a semicolo n. A semicolon in C++ is similar to a period in English; It marks the end of a complete senrence (or statement, as it is called in programming jargon). Semico lons do not appear at the end of every line in a C++ program, however. There are rules that govern where semicolons are requi red and where they are not. Part of learning C++ is learning where to place semicolons and other punctuation symbols.
Lines and Statements Often, the contents of a program are thought of in terms of lines and statements. A "line" is JUSt that- a single line as it appears in the body of a program. Program 1-1 is shown wi th each of its lines numbered . M ost of the lines comain something meaningful; however, some of the lines a re empry. The blank lines are only there to make the program more readable .
1.4 What Is a Program Made of?
A statement is a complete instruction that causes the computer to perfo rm some action. Here is the sta tement that appears in line 10 of Progra m 1- 1: cout «
"How many hours did you work? ";
This starement causes the computer ro display the message " How many hours did you work?" on the screen. Statements can be a combination of key words, operators, and programmer-defined symbols. Statements often occupy only one line in a program , but some· times they are spread out over more than one line.
Variables A varia ble is a named storage location in the computer's memory for holding a piece of information. The information stored in varia bles may change while the program is running (hence the name " variable") . Notice that in Program 1-1 the words hours, rate, and pay appea r in several pl aces. All three of these are the names o f variables. The hours variable is used to store the number of hours the user has work ed. The rate variable Stores the user's hourly pay rate. The pay variable holds the result o f hours multiplied by rate, which is the user's gross pay.
o
NOTE : Notice the variables in Program 1-1 have names that reflect their purpose. In fact, it would be easy [Q guess what the va ri ables were used for just by reading their names. This is discussed further in Chapter 2.
Variables arc symbolic names that represent locations in the computer's random-access memory (RAM). When information is stored in a variabl e, it is actually s[Qred in RAM. Assume a program has a variable named l ength. Figure 1-7 illustrates the wa y the variable name represents a memory location. Figure 1-7
~ ~
f.'-I
~
2J
~
~
~
~
~
2J
~
lSI
~
!iJ
~
~
~
~
~
~
~
~
~
.1iI
~
~
~
~
~
72
\
\
length
In Figure 1-7, the variable length is holding th e value 72. The number 72 is actually stored in RAM at addtess 23, bur the name length symbolically represents this storage location. If it helps, you can think of a va riable as a box that holds informa tion. In Figure 1-7, the number 72 is stored in the box named length. Only one item ma y be stored in the box at any given rime. If [he program stores another value in the box, it will take the place of the number 72.
15
16
Chapter 1 Introduction to Computers and Programming
Variable Definitions In programming, there are two general types of data: num bers and cha racters. Num bers are used to perform mathema tica l operations and characte rs are used to print data on the screen or on paper.
Nume ric data can be categorized even further, For instance, the following are aU whole
numbers, or integers: 5 7
-129 32154
The fo ll owing arc real, or floating-point numbers: 3 . 14159 6 .7 1. 0002
When creating a va riable in a C++ program, you must know what type of data the pro -
gram will be storing in it. Look at line 7 of Program 1-1;
double hours , rate , paYi The wo rd double in this statement indica tes that rh e variables hours, rate, a nd pay will be used to hold double precision floating-poim nu mbers. This sta tement is called a variable definition . It is used to define one o r more variab les that will be used in the program, and TO indicate the type of data they will hold. The variable definition causes the variables to be created in memory, so all va r iables must be defined before rhey ca n be used. If you review the listing of Program '1-1, you will see that the va ri3ble definitions come before any other Statements using those variables.
()
NOTE : Progra mmers often use the term "variable decla ration" to mean the sa me thi ng as " variable definitio n." Strictly speaking, there is a difference between the two terms. A defin ition sta tement always ca uses a variable to be crea ted in memory. Some types of decla ration sta remenrs, however, do not ca use a variab le to be created in memory. YOLI will lea rn more about declarations later in this book.
Input, Processing, and Output CON C EPT: The three primary activities of a program are input, processing, and output. Computer programs typically perform a three-step process of gathering input, perfor mi ng some process on the information gathered, and then producing output. fnput is information a program collects from the outside world. It can be sent to the program from the user, who is entering data at the keyboard or using the mouse. It can also be read fro m disk files or hardware devices connected to the computer. Progcam 1-1 <1llows tJ\e user to enter two pieces
1.6 The Programming Process
of information: the number of hours worked and the hourly pay rare. Lines 11 and 15 use the cin (pronounced "see in ") object to perform these input operations: cin » cin »
hours; rate;
Once information is gathered from the outside world, a progra m usually processes it in some manner. In Program 1-1, the hours worked a nd ho urly pay rare are multiplied in line 18 and the result is assigned to the pa.y variable:
pay
~
hours * rate;
Output is information tha t a program sends to the outside world. It ca n be words or graphics disp layed on a screen, a report sent to the p rioter, data stored in a file, or info r-
marion sen t to any device connected to the computer. Lines la, 14, and 21 in Program 1-1 all perform ou tput: cout <<; "How ma ny hours did you work? " i cout « "How much do you get paid per hou r ? "; cout « "You have earned $ " « pay « endl;
These lines use the cout (pronounced "see ou t") o bj ect to display messages on the computer's screen. You will learn more details about the cin and cout objects in Chapter 2.
~ Checkpoint 1.17
Desc ribe the difference between a key word a nd a programmer-defi ned identifier.
1.1 8
Describe the difference between opera tors a nd punctuation symbols.
1. 19
Describe the difference between a program line and a statement.
1.20
Why are variab les called "vanable"?
1.21
What happens to a variable's currenr contents when a new value is scored there?
1.22
What mu st take place in a program before a variable is used? What are the three primary activities of a program?
1.23
The Programming Process CONCEPT: The programming process consists of severa l steps, which include design, crea tion, tes ting, and debugging activities.
Designing and Creating a Program Now that you have been introduced to what a program is, it's time to consider the process of crea ring a program. Quite ofren, when inexperienced students are given programming assignments, they have trouble getting started because they don't know what to do nrst. If you find yourself in th is dilemma, the steps listed in Figure 1-8 may help. These are the steps recom mended for the process of writing a progra m.
17
18
Chapter 1 Introduction to Computers and Programming
Figure 1-8
1,
Clearly define what the program is to do.
2. 3.
Visualize the program funning on the computer. Use design tools such as a hierarchy chari, flowcharts,
4.
Check the model for logical errors.
or pseudocode to create a model of the program. 5.
Type the COde, save it, and compile il.
6. 7. 8.
Correct any errors found during compilation. Repeal Steps 5 and 6 as many times as necessary. Aun the program with test data for input. Correct any errors found while running the program.
9.
Repeat Steps 5 through 8 as many times as necessary. Validate the results of the program.
T he steps listed in Figure 1-8 emphasize rhe importance of planning. J ust as there are good ways and bad ways to paint a house, there are good ways and bad ways to create a program. A good program always begins with planning.
With the pay-calculating program as our example, Jet's look at each of the steps in more detail. 1.
Clearly d efi ne w hat the program is to d o.
T his step requires that you identify the purpose of the program, the in for mation that is to be input, the processing that is ro take place, and the desired output. Let's examine each of these requirements for the example program:
Purpose
To calculate the user's gross pay.
Input
Number of hours worked, hourly pay rate.
Process
Multiply number of hours worked by hourly pay rate. The result is the user's gross pay. Display a message indicating the user's gross pay.
Output 2.
Visualize the program funn ing o n the computer.
Before you create a program on the computer, you should first create it in your mind. Step 2 is the visualization of the program. Try to imagine what the computer screen looks like while the program is run ning . If it helps, draw pictures of the screen, with sample input and omput, at va riOliS points in the program. For instance, here is the screen prod uced by the pay-calcu lating program: How many hours d id you work? 10 How much do you get paid per hour? 15 You have ea rned $150
In this step, you must put yourself in rhe shoes of the user. What messages shou ld the progra m display? What questions should it ask? By addressing these concerns, YOll will have already determined most of the program 's ou tpu t.
'.6 The Programming Process
3.
Use design tools sl1ch as a hi erarchy chart, flowcharts, or pseudocode to create a model of (h e program.
While planning a program, the programmer uses one or more design rools to create a model of the program. Three common design tools arc hierarchy charrs, flowcharts, and pseudocode. A hierarchy chart is a dia gra m that gra phically depicrs rhe structure of a program. It has boxes that represent each step in the program. The boxes are connected in a way that illustrates their relationship for the pay-calcu lating program.
one anot her. Figure 1-9 shows a hierarchy chart
to
Figure 1-9
Calculate Gross Pay
I
I Multiply Hours
Get Payroll Data
Worked by Pay Rate
from User
Display Gross Pay
I I
I
Read Number of Hours Worked
Read Hourly Pay Rate
A hierarchy chart begins with the overall task, and then refi nes it into smaller subtasks . Each of th e subtasks is then refined inro even smaller sets of subtasks, until each is small enough to be easi ly performed. For insrance, in Figure 1-9, the overall tas k "Calculate Gross Pay" is listed in rhe tOp-level box. That task is broken into three subrasks. T he first subtask, "Get Payroll Data from User," is broken further into two subrasks. This process of "divide and conquer" is known as top-down design.
A flowchart is a dlagcam that shows the logical flow of a program. It is a useful tool for planning each operation a program performs, and the order in which the operations are to OCCLlr. For marc information see Appendix D, Introduction to Flowcharting.
Pseudocode is a cross between hu man language and a programming language. Although Flowcharting the computer can't understand pseudocode, programmers often find it helpful to write an algorithm in a language that's "almost" a programming language, but still very simila r to natural language. For example, here is pseudocode that describes the pay-calcula ting program:
Introd uctio n 10
Get payroll data. CaICII/ate gross pay. Display gross pay. Designing a Progl'am with Pseudocode
Although the pseudocode above gives a broad view of th e program, it doesn't reveal all the program's derails. A more derailed version of the pseudocode follow s.
19
20
Chapter 1
Introduction to Computers and Programming
Display "H ow many hours did yotl work?", lnpllt hO~1T5.
Display "How much do you get paid per hour?", Input rate. Store the valHe of hOllrs times rate in the pay variab le. Display the value in the pay variable. Notice {he pseudocode contain s sta tements that look more li ke commands than the English statements that describe the algorithm in Section "1 .4 (What Is a Program Made of?). The pseudocode even names variables and describes mathematical operations.
4. Check the model for logical errors. Logical errors arc mistakes that cause the program to produce erroneous results. Once a hierarc hy chart, flowcha rt, or pseudocode model of the program is assembled, it should be checked fo r these errors . T he programmer shou ld trace through the charts Q( pseudocode, checking the logic of each step. If an error is foun d, the mod el ca n be corrected before the next step is attempted.
5. Type the code, save it, and compi le it. Once a model of the program (hierarchy chact, flowchart, oc pseudocode) ha s been created, checked, and corrected, the programmer is ready to write source code on the computer. The programmer saves the sou rce code to a file, and begins the process o f translating it to machine language. During this step the comp iler will find any syntax errors that may exist in the program . 6.
Correct any errors found during compil atio n. Repeat Seeps Sand 6 as many times as necessary.
If the compiler reports any errors, they must be corrected . Steps 5 and 6 mUSt be repeated un til the progra m is free of compile-time errors. 7.
Run the program with test data for inpur.
Once an execu table file is generated, the program is rea dy to be tested for run -time erro rs. A run-time error is a n error cha t occurs while the program is run ning. These a f C usually logical erro rs, such as marhema rical mistakes . Testing for ru n-time errors requires that the program be exec uted with sample data o ( sample input. T he sample data should be such thar rhe correct output can be predicted. If the program does not produce the co rrect output, a logical error is present in the program. 8.
Correct any run-rime errors fo und while running the program. Repeat Steps 5 through 8 as many times as necessary.
When run-time errors are fo und in a program, rhey must be corrected. YOll mUSt ide ntify the step where the error occurred and determine the cause. Desk-checking is a p rocess tha t can he lp loca te run-time errors. T he term desk-checking means the programmer stans rea ding the program, or a portion of the program, and steps through each Statement . A sheet of paper is often used in this process to jOt down the current COntents of aU variables a nd sketch what the screen looks like after eac h output operation. When a variable's contents cha nge, or information is displa yed on the screen, this is noted. By stepping through each statement, many errors can be loca ted a nd corrected . If a n error is a result of inco rrect logic (such as an improperly stated math formula), you mu st correer rhe sta rement or statements involved in the logic. If an error is due to an incomplete understa nding of the
'.7 Procedural and Ob;ect-Oriented Programming
program requirements, then you muse restate the program purpose and modify the hierarchy andlor f1.owcharts, pseudocode, and source code_ The program must then be saved, recompiled and retested . T his means Steps 5 though 8 must be repeated until the program rel iably produces satis facto ry results. 9.
Validate the resuhs of th e program.
When you believe you have correcred all rhe run-time errors, enrer rest data and determine whether the program solves the original problem .
What Is Software Engineering? The field of softwa re engineering encompasses the whole process of crafting computer software. It includes designing, writing, testing, debugging, documenting, modifying, and maintai ning complex softwa re development projects. Like tradi rional engineers, software engineers use a number of tools in their craft. H ere are a few exa mples: • • • • • •
Program spec ifications Cha rts and diagrams of screen output Hierarchy charts and fl owcha rts Pseudocode Examples of expected inpm and desired output Special sofrwa r~ designed for rest ing programs
Most commerciul software applicat ions arc very large. In many Instances one o r more teams of programmers, not a single individua l, develop them . h is imponant that the program requ irements be thoroughly analyzed and divided into sllbta sks that arc handled by individual teams, or individuals within a team. In Step 3 of the programming process, you were introduced to the hierarchy chart as a tool for top-down design . The subrasks that are idcmified in a top-down design can easily become modules, or separate componentS of a program. If the program is very large or complex, a team of software engineers can be aSSigned to work on the ind ivid ual modules. As the project develops, the modules are coo rdinated to finally become a single software application.
Procedural and Object-Oriented Programming CONCEPT: Procedural programming and object-oriented programming are two ways of thinking about software devel opment and program design. c ++ is a language that can be used fo r two methods o f writing compu ter programs: proce-
dural programming and object-oriented programming. This book is designed to reach yo u some of both. In procedural programming, the programmer constructs procedures (or functions, as they are called in C++). T he procedures are collections of programmi ng sraremems that perform a specific task . The procedures each contain rheir own variables and commonly share variables with orher procedLlres. This is illllsrrated by Figure 1-10.
21
22
Chapter 1
Introduction to Com puters and Programming
Figure 1-10 Program
PAOCEDUREA Variables Programming END OF PROCEDURE A PAOCEDURE B Variables Programming
END OF PROCEDURE B
Procedural programm ing is centered on the procedure, or function. Objec r-orienred programming (OOP), on the other hand, is centered on the object. An object is a programming element that conrains data and the procedures that operate on the data. It is a self-
contained unie. This is illustrated in Figure 1-11.
Figure 1-11
Program Objec t A
Object B
Object C
Variables
Variables
Variables
PAOCEDUAEA
PROCEDUAEA
END OF PROCEDURE A
Variables Programming END OF PROCEDURE A
PROCEDURE B Variables Programming END OF PROCEDURE B
PROCEDURE B Variables Programming END OF PROCEDURE B
Variables Programming
PROCEDURE A Variables Programming END OF PROCEDURE A
PROCEDURE B Variables Programming END OF PROCEDURE B
The objects comain, within themselves, both information and the ability ro manipulate the information. Operations a re carried out on the information in an object by sending the object a m essage. When an object receives a message instructing it ro perform some operation, it ca rries out t he instruction. As yOli study this text, you will enCounter many other
aspecrs of object-orienred programming.
~
Checkpoint 1.24 1.25
What four items should you idemify when denning what a program is to do? Whar does it mean to "visualize a program running"? Whar is rhe value of such an activity?
:I .26
What is a hiera rchy cha rt ?
1.27
Describe the process of desk-checking.
1.28
Describe what a compiler does with a program's source code.
Review Questiom and E.x.ercises
] .29
What is a run -time error?
1.30
I!: a !:yntax error (suc h as misspelling a key wQed) found by the compiler or when the program is running?
1.31
Whar is the purpose of res[jng a program with sample dara or input?
1.32
Briefly describe the difference between procedural and object-oriented programming.
Review Questions and Exercises Short Answer 1. Both main memory and seconda ry sto rage are types of memory. Describe the differ-
ence between the two. 2. What is the difference between operating system softwa re a nd application softwa re? 3. Indicate al l the categories that the following operating systems belong to.
System A
This system allows multiple users to run multiple programs simultaneousl y.
System B
Only one user may access the system at a rime, but multiple programs can be run simultaneously. Only one user may access the system at a time, and only onc program ca n be nm on the system at a time.
System C
4. Why must programs written in a high-Ievcllanguage be translated into machine language before they can be run? 5. Why is it easier to write a program in a high-level language than in machine language? 6. Explain the difference between an object file and an executable fil e. 7. What is the difference between a syntax error and a logical error?
Fill-in-the-Blank 8. Computers can do many diffcrem jobs because they ca n be _ _ __ 9. The job of the is to fetch instructions, carry out the operations com~ manded by the instructions, and produce some outcome or resultant information . 10. Jnternall y, the CPU consists of the _ _ _ _ and the _ _ __
11. A{n)
is an example of a secondary storage device.
12. The two general categories of software are
I
and _ _ __
I
13. A program is a set of _ _ __
14. Since computers can't be programmed in naturaf human language, algorithms must be written in a(n )
language.
1
15. _ _ _ _ is the only language computers rea~ly process.
16. _ _ _ _ languages are dose
to
the level of humans in terms of readability.
17. _ _ _ _ languages are close to the level of the computer. 18. A program's abi li ty to run on several different types of computer systems is called
24
Chapter 1 Introduction to Computers and Programming
19. Words that have special meaning in a programming language are called _ __ __ . 20. Words or names defined by the programmer afe caned _ _ __ 21. ___-,---_ are characters or symbols tha r perform operations on one or more
operands. 22.
characters Of symbols mark the beginning or ending of programming statements, or separate items in a list.
23. The ru les that must be followed when consrructing a program are called _ _ __ 24. A(n} _ _ _ _ is a named storage location. 25. A variable must be _ _ _ _ before it can be used in a program. 26. The three primary activities of a program are _____ _ _ __ .,and 27. _____ is information a program gathers from the outside world. 28. _____ is information a program sends to the outside world. 29. A(n) _____ is a diagram that graphica ll y Illustrates the structure of a program.
Algorithm Workbench Draw hierarchy charts or flowcharts that depict the programs described below. (See Appendix D for instructions on creating flowcharts. )
30. Available Credit The followi ng steps should be followed in a program that calculates a customer's avai lable credit:
1. Display the message "Enter the customer's maximum credit." 2.
Wait for the user to enter the customer's maximum credit.
Display the message "Enter the amount of credit used by the customer." 4 . Wait for the user to enter the customer's credit used. 3.
S.
Subtract t he Llsed credit from t he max;mllm c red it to get the customer's available
credit,
6. Display a message that shows the customer's available credit. 31. Sales Tax
Design a hierarchy chart or flowchart for a program that calculates the roral of a retail sale. The program should ask the user fo r: The retail price of the item being purchased The sa les tax rate
Once these items have been entered, the program shou ld calculate and display: The sales tax for the purchase The rotal ohhe sale
Review Questions and Exercises
32. Account 'Balance
De$igning Ihe Acc(l .. n t
Balance Program
Design a hierarchy chart or flowchart for a program that calculates the current balance in a savings accounC". The program mUSt ask the user for; T he starting balance The total dollar amou nt of deposits made The rota l dollar amount of withdrawals made T he monthly interest rate Once [he program calculates the current balance, it sho uld be displayed on the screen.
Predict the Result Questions 33-35 are programs expressed as English statements. What would each display on the screen if they were actual programs?
33 . The variable x starts with the value O. The variable y stans with the value 5. Add 1 to x.
Add 1 toy. Predicting the Result of Problem 33
Add x and y, and store the result in y. Display the value in y on the screen.
34. The variable j starts with the value 10. The variable k starts with the va lue 2. The variable 1 starts with the va lue 4. Store the val ue of j rimes k in j. Store the value of k times 1 in l. Add j and 1, and store the result in k. Display the value in k on t he screen. 35. The variable a stans with the value 1. The variable b starts with the va lue 10. The variab le c starts with the val ue 100. The variable x starts wi th the va lue O. Store the value of c times 3 in x. Add t he va lue of b times 6 to the value alrea dy in x. Add the value of a times 5 to the value already in x. Disp lay the value in x on the screen.
Find the Error 36. The following pseudocode algorithm has an error. The progra m is supposed to ask the user for the length and width of a rectangu lar room, and then disp lay the room's area. The program must multip ly the width by the length in order to determine the area. Find the error. area = width x length. Display ' What is the room's width?·. Input width. Display "What is the room's length? · . l1lPllt length.
Display area.
25
26
Chapter 1
Introduction to Computers and Programming
Serendipity Booksellers Software Development ProjectPart 1: Program Specifications Serendipity Booksellers is a small bookstore located in a shopping mall. They have a cashier stati.on equipped with a personal computer, The manager wants you to develop a point-aE-sale (POS) software package that will make the computeI' function as a cash register ilnd keep an inventory file. T he inventory file will be
• • • •
Calculate the roral of a sale, including sales tax When a book is purchased, subtract it from the sro re's inventory file Add, change, delete, and look up books in the inventory file Display various reports
At the end of each chapter you will be given assignments that build on the project by implementillg newly teamed features. At the end of the book, YOll will have designed and written a fully functional software package chat incorporates most of the topics covered in the text.
The Modules T he program wil l be organ ized into the following three modules: • • •
Cashier module Inventory Database module Report module
When the program funs) a menu will be displayed on the screen, which allows (he user co activate any of the modules. A discussion of each module follows.
The Cashier Module T he Cashier module allows the computer to act as a cas h register. T he user enters information for the books being purchased and the program calculates the sales tax and the total price. In addition, the books being purchased are automatically subtracted from the Invemor y Database.
The Inventory Database Module The Inventory Database will be a file conta ini ng a list of all the books in Serendipity's inventory. The follO\ving information for each book will be stored in the file:
Review Questions and Exercises
Field
Description
ISBN
This is the intern ational Standatd Book Number. It is a unique number assigned co each book by the publisher.
Title
The title of the book.
Author
The book's author.
Publisher
The company that publishes the book .
Date Added
The date the book was added to the inventory.
Quantity·On-Hand
The number of copies of the book in inventory.
Wholesale Cost
The price paid by Serendipity for each copy of the book ..
Retail Price
The price Serendipity is charging for each copy of the book.
The Inventory Database modu le will allow the user to look up information on any book in the file. add new books to the file, delete books, and change any information in the database.
The Report Module The Report module will ana lyze the information in the Invento ry Da tabase to produce any of the following repofts:
Inventory List.
A list of information on all books in the inventory.
Invelltory Wholesale Value. A list of the wholesale value of all books in the inventory and the total wholesale value of the inventory.
Inventory Retail Value. A list of the retail value of all books in the inventory and the total retail value of the inventory. List by Quantity. A list of all books in the invemory sorted by quantity on hand. The books with the greatest quantity on hand will be listed first. List by Cost. A list of all books in the inventory, sorted by wholesale cost. The books with the greatest wholesale cost will be listed first.
List by Age. A list of all books in the invencory, sorted by purchase date. The books that have been in the inventory longest will be listed first.
TOPICS 2.1 2.2 2.3 2.4 2.5
The Parts of a C++ Program The cout Object The 'include Directive Variables and Literals Identifiers
2.6 2.7
Integer Data Types The char Data Type
2.8
Floating-Point Data Types
2.9
The boo1 Data Type
2.10
Determining the Size
2.11
Variable Assignments and Initi;;llization
2.12 2. 13 2.14 2.15
Scope
2.16
Arithmetic Operators
Comments Focus on Software Engineering: Programming Style If You Plan to Continue
in Computer Science: Standard and Prestandard C++
of a Data Type
The Parts of a c++ Program CONCEPT: c++ programs ha ve parts and components that serve specific purposes.
Every C++ program has an anatomy. Unlike human anatomy, the parts of C++ programs are nor always in the sa me place. Neve rtheless, the pans are there and your first step in learning C++ is to learn what they are. We will begin by looking at Program 2-1 . Lec's examine the program line by line. Here's the first line: II A simple c++ program
The I I marks the beginning of a comme1lt. The compiler ignores everything from the double slash to the end of the line. That means you can type anything you W3nr 011 that line and the compiler will never complain ! Although comments are not required, they are very important to programmers. Most programs are much more complicated than the example in Program 2-1, and commenrs help explain what's going on. 29
30
Chapter 2 Introduction to C++
Progra m 2-1 1 2
II A simple c+ + program 'include
3
using namespace std ;
4 5 6
intmain()
{ cout «
7 8 9
"Progranuning is great fun!";
return 0; }
The olltpur of the program is shown be low. This is what appears on the screen when the program runs. Pro gra m Output Programming is g r eat fun!
Lin e 2 looks like this: iinclude
Because this line starts w ith a #, it is ca lled a preprocessor directive. The preprocessor rcads your program before j( is compiled and on ly executes those lines begi nning with a # symbol. Think of the preprocessor as a program that "sets up" your source code for the compiler. The tinclude directive causes the preprocessor to include the contents of a nother file in the program. T he word inside the brackets, i ostream, is the name of rhe fi le that is ro be included. The iostream file conrains code that allows a CH program to display output on the screen and read input from the keyboard. Because this program uses cout to display screen ourput, the iostream file must be included. T he contents of the iostream file a r e included in the program a t t h e p oi m t he 'include st
file is called a header file. so it should be included at the head, or top, of the program . Line 3 reads:
using namespace std ; Programs usually contain several items with unique names. In this chapter you will learn to create variables. In Chapter 6 you will learn to create functions. In Cha pter 13 yo u will lea rn to create obj ects. Variables, functions, and objects are examples of program entities that must have names . C++ uses namespaces to o rganize the n ames of program entities. The statement using names pace std ; declares rhat rhe program will be accessing enti ti es whose names are parr of the namespace called std. (Yes, even namespaces have names. ) The reason the program needs access to the std namespace is because every name created by the iostream file is part of that namespace. In order for a program to use the entities III iostream, it must have access to the std namcspacc.
Line 5 re.:ds : int main()
This ma rks the beginning of a function. A {unction can be thought of as a group of one or more programming statements that collectively has a name. The name of this function is
2.1 The Parts of a C++ Program
main, and the set of parentheses that follows the name indicate that it is a function. The word int stands for "integer." It indicates that the function sends an imeger value back to the operating system when it is finished executing. Although most C++ programs have more than onc funerion, every C++ p rogram must have a function called main. it is the starti ng point of the program. If you are ever reading someone else's c++ program and want to find where it starts, just look for the function named main.
()
NOTE: C++ is a case-sensitive language. That means it regards uppercase letters as being enrirely different characte rs {han theif lowercase counterparts. In C++, the name of the function main must be wrincn in all lowercase letrers. C++ doesn't sec "Main" the same
as "main," or "INT" the same as "int." This is true for all the C++ key words. Line 6 contains a si ogle, solitary chanlCter:
This is called a left-brace, or an opening brace, and it is associated with the beginning of rhe funceion main. All the s(aremelHs that make up a function are enclosed in a set of braces . If you look at rhe (hird line down from the opening brace you'll see the closing brace. Everything between the two braces is rhe contents of the function mai n.
CD
WARNING! Make sure
YOll
have a closing brace for every o pening brace in
your program! Afrer the opening brace cout «
YOll
see the following statement in line 7:
"programming is great fun!";
To put it simply, this line di splays a message on rhe screen. You wi ll read more about cout and the « operator later in this chapter. The message "Programming is great fun !" is printed without the quotation marks. In programming terms, the group of characte rs inside the quotation marks is called a string literal or strillg constant.
()
NOTE: T his is the only line in the program that causes anything to be printed on the screen . The other lines, like #include and int main ( ), are necessary for the framewor k of your program, but they do not cause any screen output. Rcmembcr, a program is a set of instructions for the com puter. If something is to be displayed on rhe screen, you must use a programming statement for that purpose. At the end of the line is a semicolon. Just as a period marks the end of a sentence, a semi colon marks the end of a complete statement in C++. Com ments are ignored by the compi ler, so the semIColon isn't required at the end of a comment. Preprocessor directives, like *include statemenrs, simply end at the end of the line and never require semicolons. The beginning of a function, like iot main ( ), is nor a complete statement, so you don't place a semicolon {here either.
31
32
Chapter 2 Introduction to
c++
It might seem that the (ules for where to put a semicolon are not clear at all. Rather than worry about it now, just concentrate on learning the pans of a program. You'll soon get a
feel for where
YOli
should and should not use semicolons.
Line 8 (eads;
return 0; T his sends the integer value 0 back to the ope rating system upon the program's rion . T he value 0 usually indicates that a program executed successfully.
comple~
Line 9 contains the closing brace:
This brace marks the end of the main functio n. Since main is the only function in this program, it also marks the end of the program . In the sample program you encountered several sets of special characters . Table 2- 1 p ro vides a 5ho[[ summa ry of how they were used .
Table 2-1
Special Characters
C haracter Na me II Double slash i Pou nd sign
Description Marks the beginning of a comment. Marks the beginning of a preprocessor directive.
< >
Opening and closing brackets
Encloses a filename when used with the h nc l ude directive.
( )
Openi ng and closing parentheses Opening and closing braces
Used in naming a function, as in int main{) Encloses a group of statements, such as the con rems of a function .
~
Opening and dosing quotation marks
Encloses a string of characters, such as a message that is to be printed on the screen.
Semicolon
Marks the end of a complete programming statement.
Checkpoint 2.1
T he following C++ program will not compile because the lines have been mixed up. int mai n ()
II A crazy mixed up program return 0 ; 'include cout «
"In 1492 Columbus sailed the ocean blue." ;
(
using names pace std;
2.2 The cout Object
When the lines are properly a rranged the program should display the foHawi ng on the screen : I n 1492 Columbus sai l ed the ocean blue . Rearra nge the Jines in rhe correct order. Test the program by enreri ng it on the compUTer, compiling it, and running it.
IIIIIIII
2.2
The cout Object CONCEPT: Usc the cout object to d ispla y informati o n o n the co mputer's screen. In this section you will [earn to write programs that prod li c e OLttPllt on the screen. The simplest type of scree n o utpLlt chat a program can display IS console output, which is merely plain tex t. The word con sole is an old computer rerm. It comes from the days
when a computer operator interacted wirb the system by eypi ng on a terminal. The terminal, which consIsted of a simp le screen and key boa rd, was known as the cOllso/e. On modern computers, running gra phical operating systems such as Windows or Mac OS X, conso le o urput is uSllally displayed in a window sllch as the one shown in Figure 2-l. In C++ you lise the cout object to produce consol e output. (You can think of the word cout as meaning console o utp ut. ) Figure 2-1
A Console Window
cout is classified as a stream object, which mea ns it works with streams of data. To print a message on the screen, you send a stream of characters to cout o Let's look at line 7 from Program 2-1; cout « U~i " B eout:
"Programming is great fun!" ;
Notice that the« operator is used [Q send the string " Programming is great fu n! " to couto When the « symbol is used this way, it is called the stream insertion operator. The item immediately to the eight o f the openn o r is sem to cout and then displayed on the screen.
33
34
Chapter 2
In troduc tion to C++
The srream inserrion operator is always wrirrcn as twO less-rhan signs with no space between them. Because you arc using it to send a stream of data to the cout object} you can think of the stream insertion ope rator as an arrow that must point rowa rd couto This is illustrated in Figure 2-2. Program 2-2 is another way to write the same program.
Figure 2-2 cout «
"prograrMIing is great fun!" ;
Think of the stream insertion operator as an arrow that pOints toward coul. cout ___ "PrograllUTli n g is great fun!";
Program 2· 2
1
II A simple c++ program
2
tinclude
3
using namespace std;
4 5
in t main()
6
{
7
cout «
8
return 0:
9
" P r ogramming is " «
"great fun!";
}
Program Output Programming is great fun !
As you can see, t he stream- insertio n operaror can be used to send more than one ircm to couto The OUtput of this program is identical to chat of Program 2-1. Program 2-3 shows yet another way to accomplish the same thing.
Program 2 -3
1
II A simple c++ program
2
#include
3
,
using namespace std;
5
int main ( )
6
{
cout « "Programming is ., cout « "great fun!"; return 0;
7 8
9
10
i
}
Program Output
Programming is great fun ! An important concept to understand about Program 2-3 is tha t, although the Output is broken up inro two progra m mi ng statements, this program will still dIsplay the message
2.2 The cout Object
on a single line. Unless you specify otherwise, the information you send to cout is displayed in a continuous strea m. Sometimes this can produce less-than-desirable results. Program 2-4 is an example. The layo ut of the actual output looks nothing like the arra ngement of th e strings in the source code. First, notice there is no space displayed between the words "sellers" and "during," or between "June:" and "Computer." cout displays messages exactly as they arc sent. jf spaces a re to be displayed, they must appear in the strings. Program 2-4 1 2
II An unruly printing program iinclude
3
using namespace std ;
4 5 6
int main() {
9
cout « cout « cout «
10
cout «
"Coffee" ;
11
cout «
"Aspirin";
7 8
12
13
"The following items were top sellers" ; "during the month of June:"; "Computer games";
return 0 ;
}
Program Output
The following items were top sellersduring the month of June :Computer game sCoff eeAspirin
Second, even though the output is broken into five lines in the source code, it comes out as one long line of output. Because the output is too long to fit on one line on the screen, it wraps around to a second line when displayed. The
reaSOD
the output comes out as one
long line is because cout does nOt start a new line unless told to do so. There are two ways to instruct cout to stare a new line. The first is to send cout a stream manipulator ca lled endl (which is pronounced "end-line" o r "end -L "). Program 2-5 is an examp le. Program 2-5 1
1/ A well-adjusted printing program
2
#include
3
using namespace std;
4 5
6 7
int main() { cout « "The following items were top sellers" «
8
cout «
9
cout « cout « "Coffee" « endl ; cout « "Aspirin" « e ndl; return 0 ;
10 11
12 13
"during the month of J une : " « "Computer games" « end l;
endl;
endl;
)
(program output continues)
3S
Chapter 2
36
Program 2-5
Introduction to CH
(continued)
Program Output
The following items were top sellers during the month of June : computer games Coffee Aspirin
~
NOTE: The last character in endl is the lowercase lener L,
1I0t
the number one .
V~----------------------~ Every rime cout encou nters an endl strea m ma n ipulator it advances the Olltput to the beginning of the next line for subsequent printing. The manipulator ca n be inserted anywhere in the stream of characters sent to cout, olltside the double quotes. T he following
st(l temen ts show an example. cout <:< "My pets are" « cout « endl « "cat" «
endl « endl «
"dog"; "bird" «
endl;
Another way to cause cout to go ro a new line is to insert an escape sequence in the string itsel f. An escape seq uence starts with the backs lash character (\), and is followed by one o r more control cha racters. It a ll ows YOLl to control the way output is displayed by embed ding commands wi rhin the string itself. Progr:lrll 2-6 is an example.
Program 2-6
-
2
J 4 5 6
II Yet another well-adjusted printing program 'include using namespace std; int main() {
cout « "The following items were top sellers\n"; cout « "during the month of June :\n" ; cout « "Computer games\nCoffee"; cout « "\nAspirin\n" ; retu rn 0;
7 8 9
10 l' 2
}
Program Output
The followi ng items were top sellers during the month of June: computer games Coffee Aspirin
The newline escape sequence is \n, When cout encounters \n in a string, it doesn 't print it o'n the scr een , but interprets it as a special comm[]nd to advance t h e
Ulltput
CUI'sor
[0
t he
next line, You have probably noticed insening tht, escape sequence requi res less typing than inserting end!' Tha t's why many programmers prefer it.
2.2 The cout Object
A common mistake made by beginning C++ students is to use a forward slash (I) insread of a backs lash (\) when trying to write an escape sequence. This will nor work . For example, look at the following code. I I Error! cout « "Four ScorelnAnd seve n/nYears ago./n":
In this code, the progra mmer accidentally wrotc In when he or she meant to write \ n. The cout object will simply displa y the /n characters on the screen. This code will display the followi ng output: Four Score/nAnd se ven/nYears ago . /n
Another co mmon mistake is to forger to pur [he \n inside qu ota tion marks. For example, the following code wil l nOt compile. II Error! This code will not compile. cout « cout «
"Good" « \n ; "Morning'· « \n:
T his code will result in an error because the \n sequences arc not inside quotation marks. We can cor rect th e code by placing the \n sequences inside the stri ng literals, as shown here: II This will work . cout « cout «
"Good\n" : "Morning\n" i
There are many escape sequences in C++. T hey give you the ability to exerc ise greater conrrol over the way informarion is output by your program. Table 2-2 lists a few of them.
Table 2-2 Common Escape Sequences Escape Seq uence
Name
Description
\n
Newline
\t \b
Horizontal tab Alarm Backspace
Causes Causes Causes Causes
\r
Return
Causes the cursor to go to the beginning of the current line, not the next lin e.
\\
Backslash
Ca uses a backslash
\
Single quote
Causes a single quotation mark to be printed. Causes a double quotation ma rk to be printed.
\a
\
. .
CD
D ouble quote
the cursor to go to the next iine for subsequent printing. the cursor to skip over to the next tab stop. the computer to beep. the cursor to back up, or move left one posi tion.
to
be printed .
WAR N IN G! When llsing escape seq uences, do not put a space between the backslash and the control character.
37
38
Chapter 2
Introduction to C++
The #include Directive CONCEPT: Th e #i nclude directi ve causes the contents of another file [0 be inserted into the program . Now is a sood time to expand our discussion o f the Hnclude directive. The followi ng
line has appeared near the top of every example program. tinclude
The header file iostream m ust be included in any program that uses the cout object. This is beca use cout ]s not part of the "co re" of the C++ language. Specifically, it is pan of the it/put-outpll t stream library. The header file, iostream, conta ins informa cion describi ng iostream objects. Without it, rhe compiler will not know how to properly compile a progra m that lIses couto
Preprocessor di recnves are not C++ statemenrs. They are commands CO the preprocessor, wh ich runs p rior to the compiler (hence the name "preprocessor"). T he preprocessor's job is to set programs up in a wa y that makes life easier for the progra mmer. For example, a ny program that uses the cout object must contain the extensive setup information found in iostre am. T he programmer could type all this information into the progra m, but it would be tOO time consuming. An alternative would be to use an editor to "cur and paste " the information into the program, bur that would quickly become tiri ng as well. The solution is to let the preprocessor insert the contents of iostream automatically.
CD
WARNING! Do not put semicolon s at the end of processor directives . Beca use p reprocessor di rectives are not C++ statements, they do not require sem icolons . In man y cases a n error wiU resu lt from a preprocessor directive termina ted with a semicolon.
An hnclude directive must always contai n [he na me of a file. T he preprocessor inserts the entire contents of the file into the program a t the point it encounters the linclude directive. The compiler doesn't actual ly see the linclude directive . Instead it sees the code that wa s inserted by the preprocessor, just as if the programmer had typed it there. The code contained in header fi les is C++ code. Typicall y it describes complex objects like couto Later you wi!llearn to create your own header files.
Checkpoint 2.2
The followi ng c++ prograrri will nor compile because the lines have been mixed up. cout « cout «
"Success\n" i ,. Success \n\n " i
int main()
cout «
"Success";
)
using namespace std; II I t' s a mad, mad program
2.4 Variables and literals
'include cout « "success\n": {
return 0: When the lines are properly a rranged rhe program should display the following on rhe screen: Program Output Success success Success
Success Rearrange the lines in the correct o rder. Test the program by entering it on the computer, compi ling it, and running it. 2.3
Srudy the following program and show what it will print on the screen . II The Works of Wolfgang 'include
using names pace std : int main() (
cout « "The works of wolfgang\ninClude the fallowing": cout « "\nThe Turkish March" « endl: cout « "and Symphony No . 40 ": cout « "in G minor . " « endl; return 0 ; )
2.4
On paper, write a program that will display your name on the first line, your street address on the second line, yollC city, state, and ZiP code on the third line, and you r telephone number on the fourth line. Place a comment with raday's date at the top of the program. Test your program by emering, compiling, and running it.
Variables and Literals CONCEPT: Variabl es represent storage locations in th e computer's memory. Lilerals arc consta nt values that arc assigned to variables.
As you discovered in Chapter 1, variables allow you to srore and work with data in the compu ter's memory. They provide an "interface" to RAM . Part of the job of programming is to determine how m .. " y variables a program will need and what types of information they will hold. l)rogram 2-7 is an example of a C++ program with a variable. Take a look at line 7: int number;
This is called a variable definition. lt [eils the compiler the variable's name and the type of Variable data it will hold. This line indIcates the variable's name is number. The word int stands Definitions [or inrcger, so number will only be used to hold integer numbers. Later in this chapter you will learn all the types of data that C++ allows .
39
40
Chapter 2 Introduction to
c++
Program 2-7
1
/1 This program has a variable.
2 J 4
linclude
using namespace std;
~
int main()
6
{
7
int number;
B 9
number = 5;
"The value in number is " «
10
cout «
11 12
return 0;
number «
endl;
Program Output
The value in number is 5
o
NOTE : You must have a definition for every variable you intend to use in a program. In C++, variable definitions can appear at a ny paim in th e program. Later in (his chapter, and throughout the book, you will learn the best places to define vari ables. Notice that variable definitions end with a semicolon. Now look at line 9: number = 5 ;
This is caUed an assigllment. The equal sign is an aperatQ( that copies [he value on irs right (5) into the variable named on irs left (number). After this line executes, number will be set to 5. NOTE : This line does nor print anything on the computer's screen. h rllns silently
behind the scenes, sroring a value in RAM. Look at line 10. cout «
"The va l ue in number is " «
number «
endl;
Th e second item sent co cout is the variable name number. When yo u send a variable name to cout it prints the variable's contents. Notice there a re no quotation marks aro und numbe.L Look a t what happens in Prog(am 2-8. Program 2-8 1 2 3 4 5 6 7 8
II This program has a variable. #include using names pace std i int main{) { int number ; (program continues)
2.4 Variables and Literals
Program 2 -8
number 5; cout « "The va lue in number is .. « return 0 ;
9
10 11
12
(continued)
~number"
«
endl;
)
Program Output
The value in number is number When double quotation marks are placed around the word number it becomes a string literal , and is no longer a variable name. When suing literals are sent to cout they are printed exactly as they appear inside the quotation marks . You 've probably noticed by now that the endl stream manipulator has no quotation marks arou nd it, for the same reason.
Sometimes a Number Isn't a Number As shown in Program 2 -8, juSt placing quotation marks around a vari:lblc name changes
the program's results . In fact, plac ing double quotation marks around anything that is not intended to be a string literal will create an crror of some type. For example, in Program 2-8 the num ber 5 was assigned to the va riable number. It would have been incorrect to perform the assignment this way: number"" "5" ; In this line, 5 is no longer an imeger, bu r a stri ng li teral. Because number was defined as an integer variable, you can only stOre inrege rs in it. The integer 5 and the string literal "5" are not the same thing. The fact that numbers can be represented as strings frequently con fu ses students who are new to programming. J USt remember that strings are intended for humans to read. They are to be printed on computer screens or paper. Numbers, however, are intended primarily for mathematical operations. You cannot pe rform math on strings. Before numbers can be displayed on the screen, they mUSt first be converted to strings. (Fortunately, cout bandies the conversion automatically when you send a number to it.)
Literals A variable is called a "variable" because its value may be changed. A literal, on the other hand, is a value that does nor change during the program's execlltion. Program 2-9 contains both literals and a variable. Program 2-9
1 2
3
II This program has literals and a variable. 'include using namespace std ;
4
5
int main()
6
{
41
42
Chapter 2 Introduction to C++
Program 2-9 7
(co ntinued)
int apples ;
8 9 10
apples cout «
11
return 0 ;
12
= 20i "Today we sold" «
apples «
" bushels of apples . \0";
}
Program Output Today we sold 20 bushels o f apples .
Of course, the variable is apples. It is defined as an integer. Table 2-3 lists the literals found in the program.
Table 2-3 Literal
Type of Literal
20
"Today we sold "
Integer literal Stung literal
"bushels of apples.\n"
Srring literal
o
Intege r literal
What are literals lIsed for? As you can see fcom this program, they arc commonly used to
srore known values in varia bles and display messages on the sc reen or a printout. NOTE: Literals are also called constants. ( ) ~----------------------~
~
Checkpoint 2.5
Examine the follo wing program.
IJ This program us es variables and li terals . l inc lude using namespace std j iot main() {
int little j int big; little = 2; big = 2000; cout « ""The l i t t le number is cout « ""The big number is "" « return 0 ;
little « endl ; big « endli
«
List all the variables and literals th at appear in the program. 2.6
What will the foll o wing program display on the screen?
iinclude
us ing names pace stdi
2.5 Identifiers
i nt ma in ( ) (
int number;
number'" 712; cout « "The value is " « return 0;
"number" «
end l ;
)
Identifiers CONCEPT: Choose variable names that indicate what the variables are used for.
An identifier is a programmer-defined name that represents some element of a program . Variable names are examples of identifiers. You may choose your own variable names in C ++, as long as you do not use any of the C++ key words. The key words make up the "core" of the language and ha ve speCific putposes. Table 2-4 shows a complete list of the C++ key words. Note tha t they are all lowercase .
Table 2-4
The C++ Key Words continue default de l ete
a nd
and_eq asm
auto bitand bitor bool break case catch ch a r cl a ss compl const canst cast
do
double dynamic_ cast else enum explicit export e xt ern false float f or
friend
goto if
in1ine int long mutable namespace new not not_ eq
operator or
or_eq pri vate protected
public reg i ster r ein t erpre t_cast ret urn short signed sizeof static static c as t struct switch template this throw true
t ry
typede£ typeid type name union unsigned us ing virtual void volatile wchar t while xor xor _eq
You sho uld always choose names fo r your variables that give an indication of what the vanables ace used for. Y Oll may be tempted to define va riables with names like this: int
x;
The rather nondescript name, x, gives no clue as to the variable's purpose. H ere is a better example. i nt i temsOrde red j
The name itemsOrdered gives an}'one reading the program an idea of the variable's use. This way of coding helps produce self-documenting programs, which means you get an understanding of wha t the program is doing JUSt by readmg its code. Because real-world programs usually have thousands of Jines, it is imporrant that they be as self-documenting as possible.
44
Chapter 2
Introduction to C++
You probably have noticed the mo([ure of uppercase and lowercase letters In the name itemsOrdered . Although all of C++'s key words must be written in lowercase, you may
LIse uppercase letTers in variable names. The reason the 0 in itemsOrdered is capitalized is to improve readability. Normally "i tems ordered " is t wO words . Unfortunately you ca nnot have spaces in a vari able name, so the two words must be combined into one . When "i tems" and "ord ered" are sruck together yo u get a variable defi nition like thi s:
io t i temsorderedi Ca pitalization of the first Jetter of the second word a nd succeeding words ma kes itemsOrdered eas ier to rcad . It should be mentioned tbat this style of cod ing is not required. You are free to usc all lowercase letfers, a ll uppercase letrers, or any combinati on of both. to fact, some programmers use the underscore character ro separa te words in a variable name, as in the following. i nt items_orde red;
Legal Identifiers Rega rdless o f which Style you adopt, be consistent and make you r varia bl e names as sensi~ ble as poss ible. Here are some specific rules [hat must be followed with all identifie rs. •
• •
The first cha racter must be o ne of the letters a t hrough z, A th rough Z , or an undersco re character C). After the first cha racter you may use [he letters a through z or A through Z, rhe digi ts through 9, or unde rscores. Uppercase and lowercase characters are distinct. Th is means ItemsOrdered IS not the same as itemsordered.
a
Tab le 2-5 lists variable names and tells whether each is legal or illegal in C++ . Tab le 2 -5
Some Variable Names
Va riabl e Name
lega l or Ulega l?
dayO fW eek
Lega l.
3dG raph
Illega l. Variable names cann ot begin with a digit.
_ employee_ num
Lega l.
June1997
Legal. 1I1ega1. Variable names may only usc lerrers, digits, or underscores.
Mix turet3
Integer Data Types CONCEPT: T here are many d ifferem types of data. Variables ate cl assified according to their data type, w hi ch determi nes the kind of informat ion that may be srorcd in them. Integer variables can only ho ld whole numbers.
Computer programs co llect pieces o f da ta from [he real world and manipulate them 1Il vario us ways. There are many different types of data. Tn the realm of numeric information,
2.6 Integer Data Types for example, there a re whole numbers and fractional numbers. There are negativc num¥ bers and positive numbers. And there are numbers so largc, and others so smaJl, that [hey don't even have a name. Then there is textual information. Names and addresses, for instance, a re stored as groups of characters. When YO Li write a program you must d ece c¥ min e what types of information it will be likely ro encounter.
If you are writing a program to calculate the number of miles to a distant star, you'll need variables that can hold very large numbers. If you are designing software to record micro¥ scopic dimensions, you' ll need to store very small and precise numbers. Additionally, if you are writing a program that must perform thousands of intensive calculations, yOll'll want vari¥ abIes that can be processed quickly. T he data type of a variable determines all of these factors. Although C++ offers many data types, in the very broadest sense there are only two: numeric and character. Numeric da ta types arc broken into two additional categories: integer and Aoating poinr. Integers arc w hole numbers like 12, 157, -34, and 2. Floating p oint numbers have a decimal poim, like 23.7, 189.0231, and 0.987. Additiona lly, the integer and floating point data types are broken into even more cl assifications . Before we discuss the character data type, let's ca refully exa mine the var iations of numeric data. Your primary considerarions for selecting a numeric data type are: • • • •
The largest and smallest numbers that may be stored in the variable How much memory the variable uses Whether the variable stores signed or unsigned numbers The numbe r of deci mal places of p recision the variable has
T he size of a variable is the number of bytes of memory it uses. Typically, the larger a varia ble is, the greater the range it can hold. Table 2¥6 shows the C++ integer data types with thei r typical sizes and ranges.
NOTE : The data type sizes and ranges shown in Table 2-6 are typical on many systems. Depending o n your operating system, the sizes and ranges may be differenr.
Table 2-6
Integer Data Types, Sizes. and Ranges
Da ta Type
Size
Range
shor t
2 bytes
unsigned short
2 bytes
int
4 bytes 4 bytes
- 32,768 CO +32,767 oto +65,535 -2,147,483,648 to +2,147,483,647 o to 4,294,967,295 -2,147,483,648 to +2,14 7,483,64 7
unsigned int long unsigned l ong
4 bytes 4 bytes
Here are some examples of variable definitions: int days; unsigned speed; short month ; unsigned short amount; long deficit ; unsigned long insects;
o to 4,294,967,29 5
45
Chapter 2
46
Introduction to C++
Unsigned da ra types can only store nonnegative values. T hey can be llsed when you know your program will not encounter negative values. For example, variables that hold ages or
weights would rarely hold numbers less than O. NOTE: An unsigned iot va riable can also b e defined using on ly the word unsigned. For example, the following variable definitions are equivalent. unsigned iot days; unsigned days ;
Notice in Table 2-6 thar the iot and long clara types have the same sizes and ranges, and that the unsigned iot data type has the same size and range as the unsigned long data type. This is not always (rue because the size of integers is dependent on the type of system yOll a rc using. Here arc the only gua rantees : • • • • •
Integers are at kast as big as short integers. Long integers are at least as big as imegers. Unsigned short integers are the Same size as short integers. Unsigned integers are rhe same size as integers. Unsigned long integers are rhe same size as long integers .
Later In this chapter you will lea rn to use the sizeof operator to determine how large all the data types are on your compute r. As mentioned before, variables are defined by staring the data type key word followed by the name of the variable. In Program 2-10 an integer, an unsigned integer, and a long integer have been defined.
Program 2-10 1 2 J
II This program has variables of several of the integer types . 'include using namespace stdi
4
5
int main()
6 7 S 9
{ int checking; unsigned int miles; long days ;
10 11 12 13 14 15
checking - -20; miles = 4276; days = 189000 ; cout « "We have made a long journey of " « cout « " miles . \n" j
16
cout «
17 IS 19 20
cout « "\nAbout " « days « " days ago Columbus cout « "stood o n this spot. \n" i return 0 ; )
miles;
"Our checking account balance is " « checking ; " j
2.6 Integer Data Types
Program Output
We have made a long journey of 4276 miles . Our checking account balance is -20
About 189 000 days ago Columbus stood on this spot . In mosr programs you will need more than one variable of any given data type. If a program llses two integers, length and wid th, they could be defined separately, like this: int length; int width;
It is easier, however, to combine borh variable definitions on one line:
int length, width; You can define seve ral variables of the same type like this, simply separating their names with commas. Program 2-1 1 ill ustra tes this. Program 2·11 1
II This program shows three variables defined on the same line .
2
,
'include
3
using namespace std;
5
int main()
6
(
, 7
int floors , rooms, suites ;
9
floors = 15 ; rooms = 300 : suites = 30; cout « "The Crande Hotel has" « floors « cout « "with" « rooms « " rooms and" « cout«" su ites . \n" ; return 0 ;
10 11 12
13 14 15 16
" floora\n";
suites;
)
Program Output
The Grande Hotel has 15 floors
with 300 rooms a nd 30 suites .
Integer and Long Integer Literals Look at lines 9, 10,and 11 in Program 2-11: floors = 15; rooms '" 300; suites = 30;
Each of th ese !ines contains an inreger literal. In C++, integer literals are normally stored in memory just as an into On a system that uses 2 byte integers and 4 byte longs, the literal 50000 is too large to be stored as an int, so it is stored as a long .
47
Chapter 2 Introduction to C++
One of the pleas ing characteristi cs of the C++ language is chat it allows you to control almost every aspect of your program. If yOll need to ch:lIlge the W:ly something is stored in memory, rhe rools are provided to do that. For example, what if you are in a situation where you have an integer literal, but you need it to be stored in memory as a long integer? (Resr assured, this is a siwarion that docs arise.} C++ allows yo u (0 force an integer lite ral to be srored as a long integer by pla cing the Jetter L at rhe en d of the number. Here is an example: 32L
On a comporer that uses 2-byte integers and 4-byte long integers, this literal will lise 4 bytes. T his is ca lled a lon g integer litera l. NOTE: You ca n use either an uppercase or lowercase L. The lowercase I looks (00 much like the number 1, so you should always use the uppercase L.
If You Plan to Continue in Computer Science: Hexadecimal and Octal Literals Programmers commonly express values in numbering systems other than decimal (or base 10). Hexadecimal (base 16) and octal (base 8) are popular because they make certain programming tasks more convenient than decimal numbers do. By default, C++ assumes thar all integer literals arc expressed in decimal. You express hexadecimal numbers by placing Ox in front of them. (T his is zero-x, not oh-x. ) Here is how the hexadecimal number F4 would be expressed in C++: OxF4
Octal numbers must be preceded by a 0 (zero, not oh). For example, the octal 3 1 would be written 031
NOTE : You will not be writing programs for some time that require this type of manipulation. It is important, howevel~ tha t you understand this material. Good programmers should develop (he skills for reading other people's source code. You may find yourself reading programs that usc items like long integer, hexadecimal, or octa l literals.
Checkpoint 2.7
Which of the following are ill egal va riable names, and why? x 99bottles july97 theSalesFigureForFiscalYear98 rod
grade_report 2 .8
Is the variable name Sales the sa me as sales? Why or why not?
2.7 The char Data Type
2.9
Refer to the dara types listed in Table 2-6 for rhese questions .
A} If a variable needs to hold numbers in the range 32 to 6,000, what data type would be best? B) If a variable needs to hoJd numbers in the range -40,000 to +40,000, what data type would be best? C) Which of the following literals uses more memory? 20 or 20L 2.10
On any computer, which data type llses more memOry, an integer or an uns igned intege r?
The char Data Type You might be wondering why there isn't a 1· byre integer dara eypc. Actually there is. It is called [he char data type, which gets its name from the word "character." As ItS name suggests, it is pIlmari Iy for storing characters, but strictly speaking, it is an integer data type.
<:)
NOTE: On some systems the char data type is largec than 1 byte.
T he reason an imeger data type is used to store characters is because characters are internally represented by numbers. Each printable character, as well as many nonprintable cha racrers, is assigned a unique number. The most commonly used method for encoding characters is ASCn, which stands for the American Standard Code for Information interchange. (There are other codes, such as EBCDIC, which is used by many IBM mainframes.) When a character is stored in memory, it is actuall y the numeric code that is stored. When the computee is instructed to print the value On the screen, it displays the character that corresponds with rhe numeric code. You may want to refer to Appcndix B, which shows the ASCII character set. Notice that the number 65 is the code for A, 66 is the code for B, and so on. Program 2- ·12 demonstrates that when you work with characters, you arc actually working with numbers. Program 2-12 1
2 3 4 5 6 7
II This program demonstrates the close relationship between II characters and integers. 'include using names pace std ;
int main() char letter;
8 9 10
letter = 65; cout « letter « letter = 66 ; cout « letter « return 0 ;
11
12
13
14 15
endl; endl;
)
(program output continues)
49
so
Chapter 2
Program 2-12
Introduction to C++
(continued)
Program Output A
8
Figure 2-3 illustrates that when characters. such as A, B, and C, arc stOred in memory, it is rcally the numbers 65, 66, and 67 that are stored.
Character Literals Although Program 2 -1 2 nicely illustrates the way characters are represented by numbers,
it isn't necessary to work with the ASCil codes themselves. Program 2-13 is another ver-
sion that works that sa me way. Figure 2-3
is stored in memory as
Program 2-13 assigns character literals to the variable letter. Any time a program works
with a character, it internally works with the code that represents that character, so th is program is still assigning the va lues 65 and 66 to letter.
Program 2-13 1 2 3
"
II This program uses character literals. Unclude using namespace std;
5
int maine l
6
{
char letter ;
7 B 9
letter = 'A' ; caut « l etter « letter = '8' ; caut « letter « return 0 ,
10 11
12 l3 14
}
Program Output A 8
endl; endl;
2.7 The char Data Type
Notice in lines 9 and 11 that the character literals are enclosed in single qumarion marks . it is imporrant that you do nOt confuse character litera ls with string literals, which are enclosed in double quotation marks. String literals cannot be assigned to standard char variables, because of the way string literals are srared internally. Strings are a series of characters stored in consecutive memory locations. The problem with strings is that they can be virtually any length. This means that there must be some way for the program to know how long the sering is. In C++ an extra byte is appended to the end of most strings. In this last byte, the number is stored . This null terminator or mill character marks the end of the string. Strings that are stored in memory in rhis fashion, with the null terminator appended to their end, are called C-stritlgs . They are called C-strings because this storage technique was initially used in the C progra mmi ng language.
a
Don't confuse the nuU term inator with the character '0', If you look at Appendix B, you will see that ASCII code 48 corresponds to the character '0', whereas the null terminator is the same as the ASCII code O. If you wall( to print the character on the screen, you use ASCII code 48. If yOll want to mark the end of a string, however, yOll use ASCII code O.
a
Let's look at an example of how a string is stored in memory. Figure 2-4 depicts the way the string "Sebastian" would be stored.
s
e
b
a
s
a
n
\0
First, notice the q uota tion marks are nor stored with the string. T hey are simply a way of marking the beginning and end of the string in your source code. Second, notice the very last byte of the string. It contai ns the null terminator, which is represented by the \0 character. The addition of rhis last byte means that although the string "Sebastian" is 9 cha racters long, it occupies 10 bytes of memory. T he null terminatOr is another example of something that sits quietly in the backgrou nd. It doesn'r prim on the screen when YOll display a string, bm nevertheless, it is there silenrly doing its job.
<:)
NOTE: C++ automatically places the null termi nator at the end of string literals.
Now let's compare the way a string and a char are stored . Suppose you have the literals 'A' and "A" in a program. Figure 2-5 depicts thei r internal storage. Figure 2-5 .A' is stored as
"A" is slored as
A
\0
51
52
Chapter 2 Introduction to C++
As you can sec, 'A' is a I -by te clement and "A" is a 2-byte element. Since characters are really scored as ASCII codes, Figure 2-6 shows what is actually being srored in memory. Figure 2-6 'A' is stored as
~A"
is slored as
65
65
o
Because char variables are onl y large enough to hold one character, you cannot assign string lirerals to them. For example, the following code defines a char va riable named le tter. The character literal' A' ca n be assigned to the va riable, hut the string literal" A" cannot. char letter ; lette r
= 'A';
letter'" "A" ;
II This wil l work. II This will not work!
YOli are probably wondering what kind of variable is used to hold st rings in C++. You mUSt define a variable that is made of severall -byte elements, enough for the en tire string and irs null terminator, We will discuss rhis in Chaprer 3,
One final [Opic about characters should be discussed, You have learned that some strings look like a single character but rea ll y aren't, It is also possible to have a character that looks like a string. A good example is the newline cha racter, \ n. Although it is represented by two characters, a slash and an n, it is in ternally represented as one character. In fact, all escape sequences, internall y, are just 1 byte. Prognlm 2-14 shows the lIse of \n as a character literal, enclosed in single quotation marks, Jf yOll refer to the ASCll chart in Appen d ix H, yOll will sec cha r Ascn code 10 is the linefeed character. Th is is the code C++ uses for the newline cha racter. Program 2 - 14
1 2 3 4 5
6
II This program uses character l iterals. 'include using namespace std; int main() {
char l etter;
7 8
9 10 11 12 13
14
letter - 'A'; cout « letter« letter = 'B' ;
'\n';
cout «
'\n';
letter«
return 0 ; }
2.7 The char Data Type
Program Output A B
Let's rev iew some important points regarding characters and strings: • • • • • • •
Pnntable characters are Internally represented by numeric codes . Most computers use ASCII codes for this purpose . Characters normally occupy a singl e byte of memory. Strings are consecutive sequences of characrers thar occupy consecutive bytes of memory. C-strings always have a null terminator at rhe end. This macks the end of the string. Character li terals are enclosed in single quotation macks. String literals are enclosed in double quotation marks. Escape sequences are stored internally as a single character.
~ Checkpoint 2.11
What are rhe ASCII codes for the following characters? (Refer to Appendix B) C
F W
2.1 2
Which of the following is a character literal?
'.'
"B
2.13
U
Assuming the char dara type uses 1 byte of memory, how many bytes do rhe fol-
lowing literals lIse? 'Q' "Q"
"Sales" '\n'
2.14
Write a program that has the following character variables: first, middle, and last. Store your i~itia l s in these variables <'nd then display them on the screen.
2.15
What is wrong with the fo llowing program? 'include using namespace std; int ma inj) {
char letter; letter = "Z"; ceut « letter « return 0; )
endl;
53
54
Chapter 2
Introduction to c++
Floating-Point Data Types CONCEPT: Floating-point data types are used to define variables that can hold rea l numbers.
Whole numbers are not adequate for many jobs. If you afC writing a program that works with dollar amountS or precise measurements, you need a data type that allows fractio nal values. In programming terms, these arc called floating-point numbers. Jnrernally. f1oating-polm numbers are stored in a manner similar to scientific notation. Take the number 47,281.97. Tn scientific notation rhis number is 4.728197 x 10 4 , (10 4 is
equa l to 10,000, and 4.728197 x 10,000 is 47,281.97.) The first part of the number, 4.728197, is called the mantissa. The mancissa is multiplied by a power of ten. Compmcrs typically use E notation to represent noaring-point values. In E notation, the number 47,281.97 would be 4.728197E4 . The part of the number before the E is the mantissa, and the part after the E is the power of 10. When a floating point number is stored in memory, it is stored as the mantissa and the power of 10. Table 2-7 shows other numbe rs represented in scientific and E nQ[ation.
Table 2-7
Floating Point Representations
Decimal No tation
Scientific Nota tion 10 2
247.91
0.00072 2,900,000
E Notation
2.4 791 x 7.2 x 10--4
2.4791E2
2.9 x106
2 . 9E6
7.2E- 4
In C++ there are three data types that can represent floating-po int numbers. They are float double long double The float data type is considered single precision. The double data type is usually twicc as big as float, so it is considered double precision . As you've probably gucssed, the long double is intended ro be larger than the double. Of course, the exact sizes of these data types are dependent on the computer you are using. The only guarantees are :
• •
A double is at least as big as a float. A long double is at least as big as a double.
Tabl e 2-8 shows the sizes and ranges of floating-poi nt data types usua!ly found on PCs. Table 2-8
Floating Point Data Types on pes
Data Type
Key Word
Description
Single precision
float
Double preciSion
double
Long double precision
long double*
4 bytes. Numbers between ~ 3 .4 E-38 and ~3.4E38 8 bytes. Numbers between ~1.7E-308 and ~1.7E308 8 bytes. Numbers berween : 1:1.7£·308 and ... 1.7E308
"Some compilers
US"
10 bytes fo r long doubles. This allows a range of :3.4E-4932 to ::t: 1.1£4832
2.B Floating-Pain t Data Types
You will notice there are no unsigned floating point data types . On all machines, variab le.s o( the. float., double, and long double data types can score positive or negarive numbers.
Floating Point Literals Floating point literals may be expressed in a variety of ways. As shown in Program 2-15, E notation is one method. When you are writing numbers that are extremely large or extremely small, this will probably be the easiest way. E notation numbers may be ex pressed with a n uppercase E or a lowercase e. Norice thar in the source code the litera ls were written as 1.4 95979E11 and 1.989E30, bu t the program printed them as 1.49598e+ 0] 1 and 1.98ge+30. The twO sets of numbers arc equ ivalent. (The pl us sign III front of the exponem is also o ptiona L) In Chapter 3 you will learn to control the way cout displays E notation numbers. Program 2 -15 1
2 3 4 5 6
II This p rogram uses floating point data types . 'include using namespace std; int main() (
7 8
f loat distance ; double mass ;
9 distance ~ 1 . 495979El1 ; mass = 1.989E30; cout « " The Sun is " « distance « " meters away. \n" ; cout « " The Sun\ 's mass is " « mass « " k ilograms . \n" ; return 0 ;
10 11 12
13 14 15
)
Program Output The Sun is 1. 49598e+Oll meters away . The Sun ' s mass is 1 . 98ge+030 kilograms .
You can also express floating-point li terals in decimal notation. T he literal 1.495979£11 cou ld have been written as 149597900 000 . 00
Obviously the E nora rion is more convenient for lengthy num bers, bur for numbers like 47.39, decimal n.otation is preferable ro 4.739E l. All of the following floating~point lite rals a re equivalent: 1. 4 959Ell 1.495gell 1. 49 59£+11
l.495ge+11 149590000000.00
S6
Chapter 2
Introduction to C++
Floating-point lirerals are normally stored in memory as doubles. BLIt remember, C+ . provides tools for handling just about any situation . Just in C35e you need to force a literal to be stored as a float, you ca n append the letter F or (to the end of it. For example, the following literals wo uld be scored as floats: 1.2F 45 . 907£
NOTE : Beca use floating-point literals ace normally sto red in memory as doubles) many compilers issue a warning message when you assign a f1oating-poim literal to a float va riable. For example, assuming num is a float, the following Statement might ca use the compi ler to generate a warning message: num = 14.725 ;
Yo u can sup press the warning message by appending the f suffix literal, as shown below:
to
the floating -point
num = 14. 725f;
If you want to force a value the following examples:
to
be srored as a long double, append an Lor 1
to
it, as in
l034.56L 89.21
The compiler won't confuse these with long integers because they have decimal points . (Remember, the lowercase L looks so much like rhe number 1 that you should always use the uppercase L when suffixing literals.)
Assigning Floating-Point Values to Integer Variables When a float ing-point value is assigned to an integer variable, the fractional parr of the value (the parr after the decimal point) is discarded . For example, look at the following code. int number; number -
7 . 5;
II Assi9ns 7 to number
This code attempts to assign the floating· poi nt value 7.5 to thc integer variable number. As a result, the va lu e 7 will be assigned to number, with the fractional part discarded. Whcn part of a value is discarded, it is said to be truncated. Assign ing a floaring-poim variable to an integer variable has rhe same eHecr. For example, look at the following code . int i ; float f; f 7.5; i = f;
II Assigns 7 to i .
2.9 The bool Data Type
When rhe float variable f is assigned to the int variab le i, the value being assigned (7.5 ) is mmcatcd. Afte r this code exeCUtes i will hold rhe va lue 7 and f will hold the value 7.5. NOTE: When a floating -point val ue is truncated, it is not rounded. Assigning the value
7.9 to an int variable will result in the value 7 be ing s(Q red in the variable.
CD
WARNING! Floating-poim variables can hold a much larger ra nge of values than integer variables can. If a fl oaring-poinr value is being stored in an inreger variable, and
the whole parr of the value (the part before the decimal poim) is toO large for the intege r variable, an invalid value will be stored in the integer variable.
The bool Data Type CONCEPT: Boolean va riables are set to either t rue or false . Expressions that have a true Of f a l se val ue a re called Boolean expressions, named in ho nor of English mathema ticia n George Boo le (1815-1864). The bool data type allows you to create small integer variables that are suitable for hold · ing true or false val ues. Program 2-16 demonstrates the definition and ass ign ment of a bool va riable.
Program 2-16 1
1/ Th i s program demonstrates bool ean variables .
2 3
iinclude using namespace std;
4
5
i nt main()
6
{
7
bool bool Value ;
a 9 10 IJ 12 13
boolVa l ue = true ; rout « boolvalue « boolValue = false; cout « boolvalue « return 0;
endl ; end l;
14
Program Output 1
o As YO ll can see from the program output, the value true is represented in memory by the number 1, and false is represenred by O. You will not be using bool vari a bles unri l Chapter 4, however, so just remember (hey arc useful for evalua ting conditions that are either {[ue or false.
57
58
Chapter 2 Introduction to C++
Determining the Size of a Data Type CONe EPT: T he s iz eof operator may be used to determine the size of a data type on
allY system. Chapter 1 di scussed the portability of the C++ language. As you have seen in this chapter,
one of the problems of portability is the lack of common sizes of data types on all machines. If you are not sure what the sizes of data types are on your computer, C++ provides a way to find ou t.
A special operator called sizeof will report the number of bytes of memory used by any data type or variable. Program 2-17 illustrates its use. The first line that uses the operato r is line 10: cout «
"The size of an integer is " «
sizeof(int);
T he name of the data type Or variable is placed inside the parentheses that follow the ope rator. The operator "returns" the number of bytes used by that item. This operator ca n be invoked anywhere you can use an unsigned integer, incl uding in mathematical operations.
Program 2 -17 1 2
II This program determines the size of i ntegers, long II intege r s, and long doubles .
J
'include using names pace std ;
4 5
• 7
int main ( ) {
8
long double
9 10 L
cout « cout « cout « cout « cout « cout « return
12 lJ
I." 15
17
apple;
"The s~ze of an integer is " « sizeof(int); " bytes.\n"; "The size of a long integer is " « sizeof ( long) ; " bytes . \n"; "An apple can be eaten in " « sizeof (apple) ; bytes ! \n" ;
o,•
)
Program Output The size of an integer is 4 bytes .
The size of a long integer is 4 bytes . An apple can be eaten in 8 bytes!
2.11 Variable Assignments and Initialization
Checkpoint 2.16
Ycs or No: Is there an unsigned floating point data type? If so, what is it?
2.17
How would [he following number in scientific noration be represenred in E notation? 6.31
2.18
X
10 17
Write a program that defines an integer variable named age and a float variable named weight. Swre you r age and weight, as litera ls, in the variables. The progra m should display these values on the screen in a manner similar to the following: Program Output
My age is 26 and my weIght is 180 pounds. (Feel free to lie to the computer about your age and your wcightit'll nevcr know !)
Variable Assignments and Initialization CONCEPT: An assignmenl oper:lIion assigns, or co pi es, a value into a variable. \V'hen a va lue is assigned to a va riable as pan of rh e va riabl e's definition, it is
called an initialization. As you have already seen in several exa mples, a va lu e is :,;tored in a variable with an assignment statemel1t. For example, the following statement copies the value 12 into the variable unitsSold . unitsSold - 12; The = symbol is ca lled the assignment operator. OperatOrs perform operations on data. The data that operators work with are called operands. The assignment operator has twO opera nd s. In the previous state ment, the operand s are unitSSold and 12. In an assignment statement, C++ requires the name of the variable receiving the assignment to appear on the left side of the operator. The following statement is incorrect. 12 ,. unitSSol d;
II Incorrectl
In C++ terminology, the operand on the left si de of the = symbol must be an lvalue. It is called an lvalue because it is a value that may appear on the left side of an assignment operator. An Ivalue is someth mg that identifies a place in memory whose contents may be changed. Most of the time this will be a variable name. The operand on the right side of the == symbol must be an rvallie. An rvalue is any expression that has a value . The assign ment srarement takes the value of the rval ue and putS it in the memory location of the object identified by the Ivalue.
59
60
Chapter 2
Introduction to C++
You may also assign values to variables as parr of the definition. This is called initialization. Program 2·18 shows how it is done.
Program
2~ 18
3
II This program shows variable initialization. ,include usi ng namespace std j
5 6
iot main() (
1 2
, 7
iot mo nth
B 9 10 11
= 2.
days
cout « "Month" « retu rn 0 ;
=
28 i
month «
" has" «
days «
" days. \ n";
)
Program Output
Month 2 has 28 days.
As you can see, this simplifies the program and reduces the number of statements that mu st be t yped by the programmer. H ere arc examples of oth er definition sra tements that perform initialization.
doub le interestRate
= 12.9:
char stockade = '0'; long custome rN um = 459L;
Of COllrse, there are alw ays variations on a theme. C++ allows you to define several variables and only in itialize some of them. Here is an example of such a definition: int flightNum - 89 , travelTime , departure - 10, distance ;
The variable flightNum is initialized to 89 and departure is initialized to 10. T he variables tr avelTime and distance remain uninitializcd.
2.12
~
Scope CONCEPT: A variable's scop e is t he part of th e p rogra m t hat has access to the variable. Every variable has a scope. The scope of a variable is the part of the program where the variable may be used. The rules that define a va riable's sco pe arc co mplex, a nd you will only be introduced to the concept here. In other sections of the book we will revisir this topic a nd expand on it. Th e fi rst rule of scope' you sho uld learn is tha t a variable ca nnm be used in a ny parr of the progra rn before the del1n ilion. Progra rn 2-19 iJ!u stratcs tbis.
2.13 Arithmetic Operators
Program 2-19 1
II This program can't find its variab l e.
2 3
fiinclude using namespace std ;
4
5
int main()
6
{
7
cout «
value; II ERROR ! value not defined yet !
8
9 10
int value return OJ
=
100;
11
T he program wi ll not work because line 7 attempts [0 send the contents of the variable value fO cout before the variable is defined. The compiler reads you r program from fOp ro bonom. If it encounters a statement that uses a variable before the variable is defined, an error will resuir. To correct the program, the variable definirion must be pur before any statement thar uses it.
Arithmetic Operators CONCEPT: There are ma ny operators fo r manipulating numeri c va lu es an d performing arithmetic opera tions. c++ offer s a multitude of o perators for manipu lati ng data. Generally, there are three types of operators: Hnary, binary, and temary. T hese terms refl ect the number of operands an operato r requi res.
Un ary operators o nly require a si ngle operand . For exam ple, consider the following expreSSIOn: -5 Assigruuent StatcmeOls and Of course, we understand this represents the value negative five. The literal
5 is preceded by the min us sign. T he minus sign, when used this way, is called the negatioll ope,·ator. Expressions Since it only requires one operand, it is a unary operator.
Simple Ma th
Bi nary operato rs work wit h two operands . The assignment operator is in this category. Terna ry operators, as yo u may have guessed) require three operan ds. C++ only has one ternary ope rator, which will be d iscussed in Chapter 4. Arithmetic operations are very common in programming. Table 2-9 shows the common arithmetic operators in C++.
61
62
Chapter 2
Introduction to
c++
Table 2-9 Fundamental Arithmetic Operators Operator
Meaning
Type
Examp le
+
Addition
Binary
total = cost + tax;
Subtraction
Binary
cost = total
•
Multiplication
Binary
tax
/
Division Modulus
Binary
salePrice remainder
,
Binary
= cost
•
- taxi rate; original / 2 ;
va lue
•
3;
Each of these o perators works as you probab ly expecr. T he addition operator recurns the sum of its twO operands. In the following assignment statement, the variable amount will be assigned the va lue 12: amount
=
4 + 8;
The subtraction operatOr returns the value of its right operand subtracted from its left operand. This statement will assign the value 98 w temperature:
temperature
= 112 -
14;
The multiplication operator returns the product of its two operands. In the following Statemem, markUp is assigned the value 3: markUp
= 12 *
0.25 i
The division operator reHlms the quotient of its left operand di vided by its right operand. In the next statement, points is assigned the value 5:
points = 100 I 20;
CD
WARNING! When both operands of a division statement a re integers, the statement will perform integer division . This means the result of the division will be an integer as well. If there is a remaindet, it will be discarded. For example, in the following sratemenr, parts is assigned the value 5: parts'" 17 / 3;
This may seem lik e an annoyance, bur it ca n actually be useful in some programs. Remember, C++ gives you the (Ools to so lve just about any problem! If you want to make sure a statement, like the one shown above, performs regular division, express one of the numbers as a floating point. H ere is an example: parts = 17 . 0 I 3 :
In the sta temem above, sin ce 17.0 is interpreted as a floating poim number, the division operation will return a floating point number. The result of the division is 5.66667.
2.13 Arithmetic Operalors
The modulu s operator, which on ly works with integer operands, returns the remainder of an integer division. The following statement assigns 2 to left Over: leftOver = 17 % 3 i
In Chaprer 3 you wi!) learn how ro use rhese operators in more complex mathematical for. mu\as. For now we will concentrate on their basic usage. For example, SlIppose we need to wri re a program that ca lculates and d isplays an employee's toral wages for the week. T he regular hou rs for the work week are 40, and a ny hours worked over 40 arC considered ove rtime. The employee earns $18.25 per hour for regular hours, and $27.78 per hour for overtime hours. The employee has worked 50 hOUTS this week. The following pseudocode algorithm shows the program's logic.
Regular wages = base pay rate x regular hOllrs Ollertime wages = ollertime pay rate x ollertime hours Total wages = regular wages + overtime wages Display the total wages Program 2·20 shows the C++ code for the program . Program 2· 20 1
2 3 4
5 6 7
8 9 10 11 12
"
II This program calculates hourly wages , i ncl uding overtime . ' include using names pace std; int main () { double regularwages, basePayRate = 18.25, regularHours = 40.0, overtimewages , overtimePayRate = 27 . 78 , o vertimeHours = 10 , t otalWage s ;
II II II II II II II
To hold regu lar wages Base pay rate Hours worked less overtime To hold overtime wages Overtime pay rate Overtime hours worked To hold tota l wages
14 15 16 17
II Calculate the regular wages . regularWages ~ basePayRate * regu l ar Hours i
18 19
II Calculate the ove r time wages. overtimeWages = overt ime PayRate * overtimeHours ;
20
21
II Calculate the total wages. total Wages regu larWages + overtimeWages;
22 23 24
II Display the total wages.
25
cout « "Wages for this week are $" « totalWages «
26
return 0 ;
21
)
Program Output
Wage3 for thi3 weeK are $1007.6
endl;
63
64
Chapter 2
1ntroduction to (+ ...
Let's take a closer look at the program . As mentioned in the comments, th ere 3re variables
for regular wages, base pay rare, regular hours worked, overtime wages, overtime pa y rare, overrime hours worked, and total wages. He re is line 16, which multiplies basePay Ra t e times regularHours an d stores the result in regularwages:
regularwages
basePayRate * regularHours;
~
H ere is line 19, which multiplies QvertimePayRate times ove rtimeHours a nd stores the result in ove rtimewag es:
overtimeWages
~
over t imepayRate * overtimeHours ;
Line 22 adds the regular wages and [he oven ime wages and srores the result in totalWages :
tota!wages
= regu larWages
+ over t imeWa ges ;
L ine 25 dis plays the message o n the screen re porting the week's wages.
In the Spotlight: Calculating Percentages and Discounts Determining pe rcentages is a common calc ula t ion in compute r programming. Although t he % symbol is used in general mathe matics to indicate a percentage, most programming languages (including C++) do nOt use the % symbol for this purpo~e. Tn a pjogram, you have to convert a percentage to a floatin g-point number, just as you would if 'You were
using a calculator. For example, 50 be written as 0.02 .
per~ent
would be written as 0.5 and 2
pe rce~t
would
Let's look at an example. Suppose you earn $6,000 per month and you are allowed to contribute a portion of your gross monthl y pa y to a re tireme nt plan. You wa nt t o determine the a mount of your pay that wi ll go into the plan if yo'u contribute 5 percent, 7 percent, or 10 percent of your gross wages. To make this determination you write the
program shown in Program 2-21. Program 2-21 1
II This program calculates the amount of pay that
2 3
/1 will be contributed to a retirement plan i f 5%, II 7% , or 10% of monthly pay is withheld . 'include using namespace stdi
4 5' 6
, 7
9 1Q 11 12 13
int main() { II Variables to hold the monthly pay and the 1/ amount of contribution. double monthlyPay ~ 60 00 .0, contribut~on; II Calculate and display a 5% contribution .
2.13 -Arithmetic Operators
I.
contribution = monthlypay 1< 0 . 05; cout « "5 percent is $" « contribution
·1' 15
«
" per month. \ n";
17
II Calculate and display a 7% contribution .
18
I.
cont;ribution = monthlyPay * 0',07; cout « "7 percent is $" « contribution « " per month. \ 0";
20 21 22
II Calculate and display a 10% contribution. contribution ~ monthlyPay * 0.1; cout « "10 percent is $" « contribution « .. per month . \0" ;
43 24
25 2. 27
28 2'
return OJ )
Program Output 5 percent is $300 per month.
7 percent is S420 per month . 10 percent is $600 per month.
Line 11 defines two variables: monthlyPay .and contribution . The monthlyPay vari· able, which is ini(i al~zed with the va lue 6000.0, holds rhe amounr of your monthly pay. The contribution va riable wilI hold the amount of a contriburion to the retirement plan. The statements in lines 14 through 16 calc ulate and display 5 percent of the monthly pay. The calcu lation is done in line 14, where the mo nt hlyPay var i ~ble is multiplied by 0.05. The result is assigned to the contrib~tion variable, which is then displa yed in line 15. Sim ilar steps are taken in Lines 18 through 21, which calcu late and display 7 pe rcent of the monthly pay, and lines 24 through 26, which calculate and display 10 percent of the monthly pay.
Calculating a Percentage Discount Another common calculation is determining a percentage discount. For example, sup pose a retail business sells an item ~hat is regularly priced at $59.95, and is planning co have a sale where th e item's price will be reduced by 20 percent. You have been asked co·write a program to calculate the sa le price of the item. To determine the sale price you perform two calculations: • •
First, YOll get rhe amount of the discount, which is 20 percent of the item's regular price. Second , you su'btract the discount amou nt from the item 's regu la r price. This gives you the sa le price.
Program 2-22 shows how this is done in C++.
65
Chapter 2
66
Introduction to C++
Program 2-22 1 II This program calculates the sale price of an item
2 II that is regularly priced at $59.95, with a 20 percent 3 II discount subtracted .
4 'include 5 using namespace std;
. 6
7 int main()
{
9 10
11
II Variables to hold the regular price, the II amount of a discount, and the sale price . double regularprice = 59 . 95, discount , saleprice;
12 IJ 14 15
II Calculate the amount of a 20% discount . discount m regularPrice * 0.2;
16 17
II calculate the sale price by subtracting the 1/ discount from the regular price.
18
sale Price
~
regularPrice - discount;
19 2~
21
22 23 14 25
/1 Display the results. cout « "Regular price: $" « regularErice « endl; cout « "Discount amount: $" « discount « endl; cout « "Sale price: $" « salePrice « endl; return 0;
Program Output
Regular price: $59.95 Discount amount: $11 . 99 Sale price: $47 . 96 Line 11 defines three variables. The regularPrice variable holds the item's regular price, and is initialized with the value 59.95. T he discount variable will hold the amounr of the discount once it is calculated. The salePrice variable will hold the item's sa le price. Line 14 calculates the amount of the 20 percent discount by multiplying regularPrice by 0.2. The result is stored in the discount va riable. Line 18 calculates the sale price by subtracting discount from regularPrice. The result is stored in the salePrice variable. The cout statements in lines 21 through 23 display the item's' regular price, the amount of ~he discount, and the sa le price.
~ Checkpoint 2. 19
Is the following assignment statement valid or invalid? If it is invalid, why? 72 - amount;
2. 14 Commen ts
2.20
How would you consolidate the following defini rions inro one starement? int x '" 7 i int y 16 : int z '" 28 ;
2.21
What is wrong with the following program? How would yo u corren it? *include using namespace std ; int main() {
number"'" 62 . 7; double number ; cout « numbe r « retur n 0 ;
e nd1 i
)
2.22
Is the following an example of integer division or floating-point division? What value will be stored in portion? portion
~
70 / 3 ;
Comments CONCEPT: Comm ents are notes of explanation (hat docllmem lines or sections of a program. Comments arc part of the program, but the compiler ignores them. They are intended for people who may be rcading [he source code. It may surprise yOll that one of the most important p arts of a program has absol utely no impact on the way it runs. In fact, the compiler ignores this pan of a program . Of course,
I'm speaking of the comments. As a beginning programmer, you might be resistanr to the idea of libera lly writi ng com ments in your programs. After all, it ca n seem more productive to write code that actually does some thing! Ir is crucial, however, rhat you develop the ha bit of thoroughly annOtating your code wi th descriptive comments. It might take extra time now, but it will al most cerrainly save time in the futuce. Imagine writing a program of medium comp lexity wit h abo ut 8,000 to 10,000 lines of C++ code. Once you have written [he code and satisfacrorily debugged it, you happily pur it away and move on to the next project. Ten months later you are asked to make a mo di ~ fication to the program (or worse, track down and fix an elusive bug). You open the file [ha t contains your soutce code and stare at thousands of statements that now make nO sense at al l. If only you had left some notes to you rself explaining rhe program's code. Of course it's roo late now. All that's Ide to do is decide what will take less time: figu ring out t he old program or completely rewriting it !
T his scena rio might sou nd extreme, but it's one you don't wa nt to happen to yOll . Real world programs arc big and complex. Thoroughly documented code will make your life eas~ ier, not ro mention the mhe!" programmers who may have ro read your code in the future.
67
68
Chapter 2
Introduction to C++
Single-line Comments You have already seen one way to place commelHS in a C++ program. You simply place twO forward slashes (//) where you want the comment to begin. The compiler ignores everything from (hat point to the end of the line. Program 1-23 shows that comments may be placed liberally through om a program.
Program 2 -23 2
II PROGRAM : P~YROLL . CPP II Written by Herbert Dorfmann
3
1/ This program calculates company payroll
4
II Last modificat i on : 8/20/2008
~
5
iinclude
6
using namespace std;
7 8 9 10
int main() { double payRate i
II Holds the hourly pay rate
double hours; // Holds the hours worked lot employNumber; /I Holds t he employee number
11
12
{[he remainder of this program is left
Ollt.}
Tn addit ion to telling who w rote the program and describing rhe pu rpose of variables, comments can also be used to expl ain complex procedures in your code.
Multi-Line Comments T he second rype of comment in C++ is the multi-line comment. Multi-line comments start with /* (3 forward slash followe d by an asterisk) and end with .. / (an asterisk followed by a forward slash). Everything between these markers is ignored. Program 2-24 illustrates how multi-line commems may be used. Notice rhat a mu lti -line comment starts in li ne 1 with the /1< symbol, and it ends in line 6 with the" / symbol. Program 2-24 1
/*
2
PROGRAM : PAYROLL.CPP
3 4 5
Written by Herbert Dorfmann This program calculates company pay roll Last modi f ication : S/20/200S
6
-/
7
B 'include 9 using names pace std ; 10
2.15 Focus on Software Engineering: Programming Style
11
12 13 14 15
int main() { double payRate ; 1/ Holds the hourly pay rate double hours; 1/ Holds the hours worked int employNumberi II Holds the employee number
([he remainder of this program is left Ollt.) Un like a comment starred with I I, a multi-line comment can span several lines. T his makes it more convenient to write large blocks of comments because you do not have to mark every li ne. Consequently, the multi -line comment is inconven ient for writing singleline comments beca use you must type both a beginning and ending comment symbol.
()
NOTE: Many programmers use a combination of single-line comments and muh i-l ine comments in [h ei r progra ms. Convenience usua lly dictates which style to use.
Remember the following adv ice when using multi-line comments: • •
Be careful not to reverSe the beginn ing symbol with the ending symbol. Be sure not to forget the ending symbol.
Both of these mistakes can be difficult to track down, and will prevent the program from compiling correctly.
Focus on Software Engineering: Programming Style CONCEPT: Programming style refers to the way a programmer uses identifiers, spaces, tabs, blank lin es, and punctuation characters to visually arrange a program's source code. Th ese are some, but not all , of rh e elements of programming style.
Tn Chapter 1 yO ll learned that syntax rules govern the way a language may be used. The sy ntax rules of C++ dictate how and where to place key words, semicolons, commas, braces, and other components of the language. T he compiler's job is to check for syntax errors and, if there are none, generate object code. When the compi ler reads a program it processes it as one long strea m of characters. The compiler doesn't care that each statement is on a separate line, or that spaces sepa rate operators from operands . Humans, on the other hand, find it difficul t to read programs that aren't wr itten in a visually pleasing manner. Consider Program 2-25 fo r example.
69
70
Chapter 2 Introduction to C++
Program 2 -25
1 2 3 4 5
' incl ude using namespace std i int main(){double share s=220 . 0: double avgPrice=14.67;cQut«"There were "«s hares « " shares sold at $"«avgPrice«" per share. 'n" ; return OJ }
Program Output
There were 220 shares sold at $14 . 67 per share. Although the program is sy ntactically correct (it doesn't violate any ru les of C++), it is very difficult to read. The same program is shown in Program 2-26, written in a more rea-
sonable style. Program 2-26 1 2 3
II This example is much more readable t han Program 2- 25 . 'include using namespace std;
4
5
lnt
6
{
main()
7
double share s'" 220.0:
B
double avgPrice
= 14.67:
9 10
cout «
"There were
11
cout «
avgPr i ce «
12
return 0;
shares « " s hares sold at per share.\n" ;
«
~"i
13
Program Output
There were 220 shares sold at $14.67 per share. Programming sty le refers to the way source code is visually arranged. Ideally, it is a consistent method of pu tti ng spaces and indentions in a program so visual cues are created. T hese cues quickly tell a program mer important information about a program. For example, notice in Program 2 -26 that inside the functio n main's braces each line is indented. It is a common C++ style to indent all the lines inside a set of braces. You will also notice the bla nk line between the va riable definitions and the cout statements . T his is intended to visually separate the definitions from the executable statements . NOTE : Although you are free to develop your own style. you should adhere to common programming practices. By doing so, yOll wil l write programs that visua ll y make sense to other programmers.
Another aspect of programming style is how to handle statements that are too long to fit on one line. Because C++ is a free-flowing language, it is usually possible to spread a statement over several lines. F 01' example, here is a cout statement that uses five lines:
2.16 If You Plan to Continue in Computer Science: Standard and Prestandard
cout «
« « « «
c++
"The Fahrenheit temperature i s " fahrenheit " and the Celsius temperature is celsius endl ;
T his statement will work just as if it were typed on one line. Here is an example o f variable definitions treated similarly: int fahrenheit, celsius kelvin; f
There are many other issues related to programm ing style. They will be presented throughout the book.
If You Plan to Continue in Computer Science: Standard and Prestandard C++ CONCEPT:
c++ programs written before th e language became standardized ma y appea r slightl y di fferent from programs written toda y.
c++ is now a standardized programming language, but it hasn't always been. The lan-
guage has evolved over the years and, as a result, there is a "newer style" and an "older style" of writing C++ code. The newer style is the way programs are written with standard CH, while the older style is the way programs were typically written using prestandard C++. Although the differences between the older and newer sryles are subtle, it is important that you recognJze them. When you go to work as a computer science professional , it is likely that you will see programs written in the older style. It is also possible that your workplace's programming tools only support the older conventions, and you may need to write programs using the older style.
Older Style Header Files In older style C++, all header files end with the ".h" extension. For example, in a prestandard C++ program the statemenr that includes the iostream. h header file is written as: jinclude
Absence of using namespace stdi Anorher difference between the newer and older sryles is that older style programs typicall y do not use the using namespace stdi statement. In fact , some older compile rs do
nor support namespaces at all, and will produce an error message if a program has that statement.
71
72
Chapter 2
Introduction to C++
An Older Style Program To illustrate these differences, look at the program below. It is a modification of Program 2·1, written in the older style. 1/ A simple c++ program 'include int main() {
cout « "Progranuning is great fun!"; return 0;
Most standard c++ compil ers support programs written in the older style. Presrandard compilers, however, may nOt support programs written in the newer style.
Review Questions and Exercises Short Answer 1. How many operands does each of the following types of operators require?
unary Binary Ternary
2. How may the float variables temp, weight, and age be defined in one statement ?
3. How may the int variables months, days, and years be defined in one statement, with months initialized to 2 and years initialized to 3? 4. Write assignment statements that perform the foHowing operations with the variables a, b, and c. A) Adds 2 to eo a nd stores the result in h.
B) Multiplies
b
times 4 and stores the resu lt in a.
C) Divides a by 3.14 and srores the result in b.
D) Subtracts 8 from b and stores the resule in a. E) Stores the value 27 in a. F) Srores the character 'K' in c. G) Stores the ASCII code for 'B' in c. 5. Is the following comment written using single-line or multi-line comment symbols? 1* This program was written by M. A. Codewriter*1
6. Is the following comment written using single-line or multi-line comment symbols? II This program was written by M. A. Codewriter
7. Mod ify the following program so it prints two blank lines between each line of text. 'include using namespace stdi
Review Questions and Exercises
int main,) (
couto « HTwo mandolins like creat.ures in the" : cout « "dark" ; c out « "Creating t he agony of ecstasy . " ; cout « - George Barker" ; r eturn 0 ; )
8. What will the fo ll owing programs print on the screen?
A) t i nclude usi ng namespace std; int main () {
int f reeze = 32, boil = 2 12 ; freeze - 0; boil '" 100; cout « f r eeze « end I « boil « return 0;
endl ;
)
B)
hnclude usi ng names pace std ; iot ma i n ( ) {
int x '" 0, y = 2; x = y * 4; cout « x « endl « r e turn 0;
y «
endl ;
)
C) t include usi ng n amespace std ;
int mai n( ) {
cout « "1 am the incredible"; cout « "computing\ nmachine "; cout « " \ nand 1 will\namaze\n" ; cout « "you . " ; return 0; )
0 ) 'inc l ude using namespace std; int main() {
cout « "Be careful \n"; c out « "This mi ght/n be a trick " i cout « "question \n " ; return 0 ;
73
74
Chapter 2
E)
Introduction to c++
tinclude
using namespace stdi int main () {
int a, x
23;
a - x % 2; cout «
x «
endl «
a «
endl;
return 0; )
Multiple Choice 9. Every complere sta tement ends with a
AI
period
BI
t symbol
C) semicolon
01 ending
brace
10. Which of the following statements is correct?
AI BI
'include (iostream) 'include {iostream}
C) tinclude
0 ) linclude [iostream] E) All 01 the above 11. Every CH program must have a
AI BI
cout statement. function main.
C) tinclude statement.
0) All of the above 12. Preprocessor directives begin with a
AI , BI C) <
DI • E) None of the above
13. The lollow;ng data 72 ' A'
"Hello World" 2.8712
Review Questions and Exercises
arc all examples of A) Variables
B)
Literals or conStants
C) Strings
DJ None of the above 14. A gro up of statements, such as the contents of a function, is enclosed in A} Braces {} B)
Parentheses ()
C) Brackets <>
D) All of the above will do ]5. Which of the following are not valid assignment statements? (Circle all that apply.) A) total::;: 9; B) 72 '" amount;
C) profit - 129
D) letter " 'W';
16. Wh ich of the following are not valid cout statements? (Circle all thar apply.) A) cout « B)
"Hello World" ;
cout«
a nice day"\n;
"Have
C) cout < value; D) cout «
Programming is great fun;
17. Assume w = 5, x = 4, y = 8, and z = 2. What value will be stored in result in each of the fo llowing statements? x + y;
A) resu l t
B)
result =
,
•
2;
C) result = y I x; y D) result
E)
result
- " - • w
2;
18. How would each of the following numbers be represented in E notatio n? A) 3 . 287 x 10 6
B)
-978.65 x 10 12
C) 7 . 65491 X 10- 3
D)
-58710 . 23 x: 10- 4
19. The negation operator is
AI
Unary
B) Binary C) Ternary
D) None of the ahave
75
76
Chapter 2
Inlroduction to C++
20. When do preprocessor directives execute? A) Before the compiler compiles your program B) After the compiler compiles your program
C) At the same time as the compiler compiles your program D) None of the above True or False
21. T
F
A variable must be defined before it can be used.
22. T
F
Variable names may begin with a number.
23. T
F
Variable names may be up
24. T
F
A left brace in a C+ ... program should always be followed by a right brace later in the program.
to
31 characters long.
Algorithm Workbench 25. Convert the following pseudocode to
c++ code.
Be sute to defioe the appropriate
variables. Store 20 in rhe speed variable. Store 10 in the time variable. Multiply speed by time and store the result in the distance variable. Display the contents of the distance variable. 26. Convert the following pseudocode to C++ code. Be sure to define the appropriate variables.
Store 172.5 in the force variable. Swre 27.5 in the area variable. Divide area by force and store the result in the pressure variable. Display the contents of the pressure variable. Find the Error 27. There are a number of syntax errors in the follow ing program. Locate as many as you can. */ What's wron g with this program? /*
'include iostream using narnespace std; int inain(); )
int a, b, c\\ Three integers
a : 3 b
=4
c '" a +
b
Cout < MThe value of c is %d" < C; return 0; {
Review Questions and ExerCises
Programming Challenges 1. Sum of Two Numbers Write a program that stores the integers 62 and 99 in variables, and stores the sum o f these two in a variable named total. 2. Sales Prediction The East Coast sa les division of a company genera tes 62 percent of rotal sales. Based on that percentage, write a program that will predict how much the East Coast div ision will generate if [he compan y has $4.6 mill ion in sa les this year. 3. Sales Tax Write a program that will compute the rotal sales tax on a $52 pllrchase. Assume the state sales tax is 4 percent and the county sales tax is 2 percent. 4 . Restaurant Bill
Solving the Res taurant Bill problem
Write a program that computes the tax and tip on a restaurant bi ll for a patron wi th a $44.50 meal charge. The tax shou ld be 6.75 percent of the mea l cost. The tip should be 15 percent of the total after adding the tax. Display the meal cOSt, tax arnounc, tip amount, and total bill on the screen. 5.
~verage
of Values
To get the average of a series of va lues, you add the values up and then divide the sum by the number of values. Write a program that stores the following values in five different variables: 28, 32, 37, 24, and 33. The program should first calculate the sum of these five variables and Store the cesu\r in a separate vaciable named sum. Then, the progl"am should divide the sum va riable by 5 to get the average. Display the average on the screen.
~~L-T__IP__: _u_s_e_t_h_e_d_O_U_b_'_e_d_,_ta__ty_p_c_f_o_,_,_II_v_a_'_ia_b_le_'_i_n_t_h_i'_p_ '_o_g_t_am __. __________________-" 6. Annual Pay Suppose an employee gets paid every two weeks and earns $1700.00 each pay period. in a year the employee gets paid 26 times. Write a program that defines the following variables: payAmou nt
T his variable will hold the amOunt of pay the employee earns each pay pe riod. initial ize the variable with 1700.0.
payperiods This varia ble will hold the number of pay periods in a year. Inirialize the variable with 26. annual Pay This variable will hold the emp loyee's total annual pay, which wi ll be cal culated. The program shou ld calculate the employee's tara 1 annua l pay by multiplying t he employee's pay amount by the number of pay periods in a yea r, and stote the result in the annualPay variable. Display the total annual pay on the screen. 7. Ocean Levels Assuming the ocean's level is currently rising at about 1.5 mil limeters per yea r, write a program that displays: •
The number of mi llimeters higher than the current level that the ocean's level will be in 5 years
77
78
Chapter 2
•
•
Introduction to C++
The number of millimeters higher than the current leve! that the ocean's level will be in 7 years T he number of millimeters higher than the current level that the ocean's level will be in 10 years
8. Total Purchase A customer in a store is purchasing five items. The prices of the five items are: Price Price ]'rice Price Price
of item o f item of item of item of item
1 == $12.95 2 == $24.95
3 "" $6.95 4 = $14.95 5 = $3.95
Write a program that holds the prices of rhe five items In five variables. Display each item's p rice, the subtora i of the sale, the amount of sales ta x, and the total. Ass ume t he sa les tax is 6%. 9. Cyborg Data Type Sizes
YOli have been given a job as a progra mmer on a Cybo rg supercomputer. In order to accomplish some calcu larions. you need to know how many bytes rhe foHowing da ta types use: char, int, float, a nd double. You do not have any manua ls, so you can 't look th is information up. Write a C++ program that will determi ne the amOllnt of memory used by these types and d isplay the information on the screen. 10. Miles per Ga llon A car holds 12 gallons of gasoline and can travel 350 mi les before refueling. Write a program chat ca lculates the number of miles per gallon the car gets. Display the result on the screen.
Hint: Use the following formula to calculate miles per ga llon (MPG); MPG = Mi les Driven I Gallons of Gas Used
11. Distance per Ta nk of Gas
A car with a 20-ga llon gas tank avera ges 21.5 miles per gallon w hen driven in [Own and 26.8 m iles per gallon w hen driven o n the highway. Write a program that calculares and displays the d istance the car can cravel on aile tank of gas when driven in town and when driven on the highway. Hint: The follow ing formula ca n be used to ca lculate the d istance: Distance = Number of Gallons x Average Miles per Gallon
12. Land Calculation One acre of land is equi valent to 4 3,560 square feet. Write a program that calcula tes the number of acres in a rract of land with 389.767 square feet . 13 . CLrcu it Board Price An electron ics company sells circuit boards at a 40 percent prahr. Wrire a program lhat will calculate t h e selli ng pri~c o f a circu it board thar cosrs $ 12.67. Display the result on the screen.
Review Questions and Exercises
14. Personal Information Write a program that displays the following pieces of information, each on a separate line: Your name Your address, with city, state, and ZIP code Your telephone num ber Your college major Use only a single cout statement to display all of th is information. 15. Triangle Pattern
Write a program that d ispla ys the following pattern on the screen:
...• ***** ****** *
16. Diamond Pattern
Write a progra m that displa ys the following pattern:
...•
.......... . •••• * ...• *****
17. Stock Commission Kathryn bought 600 shares of stock at a price of $21.77 per share. She must pay her stock broker a 2 percent commission for the transaction. Write a program that calculates and displays the fol lowing: • • •
The amount paid for the stock alone (without the commission) The amount o f the commission The tota l amount paid (for the stock plus the commission)
18. Energy Drink Consumption A soft drink company recendy surveyed 12,467 of its customers and found that
approximately 14 percent of those surveyed purchase one or more energy drinks per week. Of those customers who purchase energy drinks, approximately 64 percent of them prefer citrus flavored energy drinks. Write a program that displays the following: • •
The approximate number of customers in the survey who purchase one or more energy drinks per week The approximate number of customers in [he survey who prefer citrus fl avored energy drinks
7'
80
Chapter 2 Introduction to
c++
Serendipity Booksellers Software Development ProjectPart 2: A Problem-Solving Exercise Screen Design For this chapter 's ass ignment, you are to write programs that display the main screens used in the project. The SCreens have already been designed, so your primary task is to write the C++ code that displays them. For testing purposes you will c reate a separate
program for each screen. (1n late r chapters you w ill merge these into one program.)
Here is a list of the programs you should have after completing the assignment for this chapter: mainmenu.cpp
cashier.cpp invrnenu.cpp bookinfo.cpp reports.cpp
Assignments 1. Create the Main Menu Screen. Create a program called mainmenu. cpp. It should display the following screen:
Serendipity Boo ksellers
Main Menu
1. Cashier Module 2. Inventory Database Module 3. Report Module 4. Exit Ente r Your Choice :
.
Review Questions and Exercises
2. Create the Cashier Screen . Creare a program called cashier . cpp. Ie should display the following screen;
Serendipity Booksellers Date: Qty
ISBN
-
Title
Price
Total
Subtotal Tax Total
Thank You for Shopping at Serendipity!
3. Create the Inventory Database M enu Screen. Create a program called invrnenu . cpp. It shou ld display the following screen:
Serendipity BookSellers Inventory Database
1. Look Up a Book 2. Add a Book ~ . Edit a B.ook's Record 4. Delete a Book 5. Return to the Main Menu
Enter Your Choice:
I
Chapter 2 Introduction to C++
4. Create the Book Information Screen. Create a program called book info . cpp. It shou ld display the following screen:
Serendipity Booksellers Book Informallon
' ISBN:
Tille: Author: Publisher: Date Added : Quantity·Onpt:!and : Wholesale Cost: Retail Price:
5. Create the Reports Menu Screen. Create a program called reports. cpp. It should display the following screen:
Seren~ipity
Booksellers Reports
1. Inventory Listing Inventory Wholesale Value
?
3. Inventory Retail Value 4. listing by Quantity 5. Listing by Cost 6, Listing by Age 7. Return to the Main Menu Enter Your Choice:
TOPICS 3.1 3.2 3.3
The cin Object
3.4 3.5 3.6 3. 7
Overflow and Underflow
3.8
3.9
Mathematical Expressions When You Mix Apples and Oranges: Type Conversion
3.10 Focus on Object-Oriented
3. 11
Type Casting Named Constants
3.12
Multiple A!;signment and Combined Assignment
3.13
Formatting Output Formatted Input
3.14
Programming: More About Member functions More Mathematical library Functions Focus on Debugging: Hand Tracing
a Program Focus on Problem Solving: A Case Study Introduction to File Input and Output
The c in Object CON C E PT: T he cin object can be used
read data typed at the keyboard.
So far you have written programs with built-in data. Without giving the user an oPPOrtUnity to enter his or her own data, you have initia lized the variables with the necessary starting values. These types of programs are limited ro perfo rming their task with only a single set of starting data. If you decide to change the initial value of any variable, the program must be modified and recompiled.
-
Readi ng input
with
(Q
cin
In reality, most programs ask for values that will be assigned to variables. This means the program does not have ro be mod ified if the user wams to run it several times with differem sets of d ata. For example, a program that calculates payroll for a small business might ask the user to enter the name of the employee, the hours worked, and the hourl y pay rate. When the paycheck for that employee has been printed, program could stan over again and ask for the na me, hours worked, and hou rl y pay rate of the next employee.
me
83
84
Chapter 3 Expressions and Interact;vity
Just as cout is C++'s standard output object, cin is the standard input object. It reads input from the console (or keyboard) as shown in Program 3- 1.. Program 3-1 1 2 3
II This program asks the user to ente r the length and width of II a rectangle. It ca l culates the r ectangle's area and displays II the value on the screen.
4
'include
5 6
usi ng namespace std ;
7 8
lot main() { iot length, width, area;
9 10
12
cout « cout «
13 14 15
cout « "What is the length of the rectangle? "; cin » length ; cout « "What is the width o f the rectangle? ";
16 17
cin » width: area = length
18 19
cout « return
l:I.
20
"This program calculates the area of a "; "rectangle. \n" ;
* width:
"The area o f the rectangle is " «
area «
" . \n" i
OJ
}
Program Output with Example Input Shown in Bold
This program calculates the area of a rectangle . What is the length of the rectangle? 10 [Enter] What is the width of the rectangle ? 20 [Enter] The area of the rectangle is 200. Instead of calculating the area of one rectangle, this program can be used to gct the area of any rectangle. The values that are stored in the length and width variables are entered by th~ user when th ~ program is running. Look at lines 13 and 14 : cout « "What is the length of the rectangle? cin » length ;
"j
In line 13, the cout object is used to display the question "What is the length of the rectangle?" This question is known as a prompt, and it tells the user what data he or she should corer. Your program should always display a prompt before it uses cin to read input. T his way, the user will know that he or she must type a value at the keyboa rd. Line 14 uses the cin object to read a va lue from the keyboard. T he » symbol is the stream extraction operator. Ir gets characters from the strea m object On its left and scores [hem in the variable whose name appears on its right. In this line, characters arc taken from the cin object (which gets them from [he keyboard) and are stored in the length varia ble. Gathering input from the user is norma lly a two-step p rocess: 1. Use [he cout objec[ ro di splay a pl"Ompt on the screen.
2. Use the cin object to read a value from the keyboard.
3. 1 The cin Object
The prompt should ask the user a question, or tell the use r to enter a specific value. For example. the code we just examined from Program 3-1 displays thc foHow ing prompt:
what is the length of the rectangle? When the uscr sees this prompt, he or she knows to enter the rectangle's length. After the prompt is displayed, the program uses the cin object to read a value from the keyboard and store the value in the length variable. Notice that the « and» o perators appear to point in the direction that data is flowing. In a statement that uses the cout object, the« operator always points toward couto Thi s indicates that data is fl ow ing from a variable or a literal to the cout object. In a statement that uses the cin object, the» operaror always points toward the va ri able that is rece iving the value. This indica tes that data is flowing fro m cin to a variable. This is illustrated in Figure 3-l.
Fig ure 3-1 cou t cin
« "Wh at i s » le n gt h :
the le ng th of t h e rec t angle?
H .
Think ol lhe « and » operators as arrows that point in
the direction that data is flowing.
cou t ......- " Wha t i s th e le ngth o f t he r ec t a ngl e? "; ci n
-)0-
leng t h ;
The cin object callses a program to wait until data is typed at rhe keyboard and the [Enter] key is pressed. No other lines in the program wil l be executed until cin gets irs in put. cin automaticall y converts the data read from the keyboa rd to the data type of the vari· able used to Store it. If the user types 10, it is read as the charac ters ' I ' and '0'. cin is smart enough to know this will have to be converted to an int value before it is stored in the length variable. cin is also smart enough [Q know a value like 10.7 cannor be scored in an integcr va riable. If the u...er cnters a floating~point value for an integer variable, cin will not read the part of the number after the decimal point . ./"\
NOTE: You must include the iostrearn file in any program that llses c i n.
V~----------------------~
Entering Multiple Values The dn object may be used to gather mulripl e values at once. Look at Program 3-2, which is a modified version of Program 3-1. Line 15 waits for the user to enter two values. The first is assigned ro length and the second to width. cin »
length »
width;
8.
Chapter 3
86
E/tpressions and Interactivity
Program 3·2 1 2 3 4 5
6 7 8 9
II This program asks the user to enter the length and width of 1/ a rectangle . It calculates the rectangle's area and displays /1 the value on the screen. ' include using names pace std; int main() { iot length, width,
area;
10
cout « cout « cout «
11 12
13 14
"This program calculates the area of a "i "rectangle.\n" ;
"Enter the length a nd width of the rectangle ";
cout « "separated by a space. \n" ; cin » length » width ;
15 16
area
17
cout «
18 19
return 0 ;
= length
*
width ;
"The area of the rectangle is .. «
area «
endl;
}
Program Output with Example Input Shown In Bold This program calculates the area of a rectangle . Enter the length and width of the rectangle separated by a space . 10 20 [Enter] The area of the rectangle is 200
In the example output, the user entered 10 and 20, so 10 is stored in length and 20 is stored in width. Notice the user separates the numbers by spaces as they are emered. This is how do knows where each number begi ns and ends. Il doesn't matter how many spaces are entered between the individual numbers. For example. the user could have entered 10
20
~
NOTE : The [Enter] key is pressed after the last number IS entered. V~----------------------~
cin will also read multiple values of different data types. Th is is shown in Program 3-3. Program 3-3 1 2 3
4 5
II This program demonstrates ho w cin can read multiple values
II of different data types. tinclude using narnespace std;
3.1 The cin Object
6 7 B 9 10 II 12
13 14
15 16 17 18
int mai n ()
f int whole; double f ractional ; char letter; cout « nEnter an integer, a double, and a character : " ; cin » whole » fractional » letter; cout « "Whole : " « whole « endl ; cout « "Fractional : " « frac t ional « endl ; cout « "Letter : " « letter « endl ; return 0 ;
Program Output with Example Input Shown In Bold Enter an integer, a double, and a character : 45.7 b [Ente r) Whole : 4 Fractiona l: 5.7 Letter : b As you can see in the example Output, the values are stored in their respective va riables. Bur what if the user had responded in the following way?
Enter an integer, a double, and a cha r acter : 5 .74 b [Enter] When the user types values at rhe keyboard, those values arC first Stored in an area of memory known as the keyboard buffer. So, when the user enters the values 5.7, 4, and b, they are stored in the keyboard buffer as shown in F igure 3-2.
Figure 3 -2 Keyboard buffer
,
b
I[Enterll
t
cin begins reading here. When the user presses the Enter key, cin reads t he value 5 into the variable whole . It does not read the deCimal point because whole IS an integer vanable. Next it reads.7 and stores that value in the double variable fractional. The space is skipped and 4 is the nex t value read . It is scored as a character in the variable letter. Because this cin statement reads on ly three values, the b is left in the keyboard buffer. So, in this situation the program wou ld have stored 5 in whole, 0.7 in fractional, and the chamcter '4 ' in letter . It is important t hat the use r enters values in the correct o rder.
87
Chapter 3
88
Expressions and Interactivity
Reading Strings The cin ob ject can read a srring as input and store it in memory as a C-string. C-strings are commonly srored in character arrays. In this sect ion we will briefly touch on the topic of character arrays so you can perform some basic operations with C-strings. An array is like a group of vari ables with a single name, located together in memory. Here is an example of a character array definition:
char company[12Ji The num ber inside the brackets indicates rhe size of the array. The name of the array is company. and it is large enough to hold 12 cha ra cters . Remember, however, that
C-strings have the null termi nator at the end, so this array is large enough to hold a C-string that is 11 characters long. NOTE : If a character array is intended to ho ld strings, it must be at least one character larger than the largest string that will be stored in it. This extra character is for rhe null terminator.
Program 3-4 shows how cin may be used to read a string into a character array. Program 3-4 1
2 3 4
II This program demonstrates how cin can read a string into II a character array. tinc1ude using namespace std;
5
6 7
int main() {
8
char name[21];
9
cout « "What is your name? "; c in » name; cout « "Good morning " « name « return 0;
10 11
12 13 14
endl ;
)
Program Output with Example Input Shown In Bold What is your name? Charlie [Enter] Good morning Charlie Let's examine the array definition in line 8: char name[21};
The name of the array is name and it is la rge enough to hold 21 cha racters. The null terminator at the end of a C-string is a characte r, so the longest string that may be stored in this array is 20 characters.
3.1 The cin Object
CD
WARNING! The user can ente r a string larger than the array can hold. If rhis happens, the string will overflow the array's boundaries and destroy other dara in memory.
Norice in lines 11 and 12 for rhe brackets and rhe size indicaror name are left our. cin »
cout «
name;
"Good morning " «
name «
endl:
When reading a string into an array, yo u use the name of rhe array only, You would not get the desired result if you wrOte these Jines as: cin»
cout «
name(2l1;
// I ncorrect!
"Good morning " «
name [211 «
endl;
I IIncorrect !
Program 3-5 shows another example of using character arrays in a program.
Program 3-5 1
2 3 4
II This program reads two strings into two character arrays. 'include using narnespace std;
5
int main()
6
{
7 8 9
char first[l6],
cout « "Enter your first and last name s and I will\n": cout « "reverse them.\n"; cin » first » last; cout « last « ", " « first « endl ; return 0 i
10 11
12 13 14
last(l6];
}
Program Output with Example Input Shown In Bold Enter your first and last names and I will reverse them.
Johnny Jones (Enter] Jones, Johnny
The arrays first and last are large enough to hold strings of 15 characrers. Line 11 reads a string into each array: cin »
first »
last:
Just as before, spaces separate the
twO
items.
/ ' \ NOTE : If you wish the user to enter a string that has spaces in it, you cannot use this ~L-_in_p_"_t_m_'_t_h_o_d_o_L_'_t'_r_u_'_t_hi_s_c_h_a_p_t'_t_y_o_"_w __il_I_le_a_rn__h_o_w_t_o_a_c_c_o_m_p_l_is_h_t_h_is_o__________--"
89
90
Chapler 3 Expressions and Interactivity
~ Checkpoint 3.1
What header file must be incl uded in p rograms using dn?
3 .2
Wnat type of vari.able is used to ho\d a C-stIing?
3.3
Write a definition sta tement for a character array named customer . It should be large enollgh to hold a string 52 c haracters in length .
3 .4
TRUE or FALSE: cin requires the user to press the [Enter] key when finished
entering dara . 3.5
Assume value is an integer variable. If the user en ters 3.14 in response to the followmg programmlllg sta teme nt, what w ill be srored in value? cin » value; AI 3. 14
BI 3 C) 0 0 ) Nothing. An error message is displayed. 3.6
A program has the follo w ing variable definitions . l ong miles;
int feet; float inches;
Write one dn statement that reads a value into each of these variables. 3.7
The following program will nm , but the user will have difficulty und erstanding what ro do. How would you improve the program? II Th is program mUltiplies two numbers and disp l ays t h e re sult .
jinclude using names pace std ; int main() {
double first,
second, product:
cin » first » seco nd; product = first * second; cout « p r oduct; return 0 ; }
3.8
Examme th e following program. 'include using namespace std;
int main!) {
c har name[2l]; cout « "What i s your name? " ; ein » name; cout « "Hello « name « endli retu r n 0 ;
3.2 Mathematical E.xpressions
If Jill runs this program and encers her full name, Jill Birkenstock, what will be displayed on the screen? How ca n the program be improved?
3.9
Complere [he following program skeleton so it asks for the user's weight (in pounds) and displays the equivalenc weight in kilograms. 'include using namespace std; int main() {
double pounds, kilograms; II Write code here that prompts the user II to enter his or her weight and reads II the input into the pounds variable.
II The following line does the conversion. kilograms = pounds I 2. 2; II Write code here that displays the user's weight I I in kilograms. return 0; )
Mathematical Expressions CONCEPT; c++ allows you to constru ct complex mathematical expressions using multiple operators and grouping symbols. In Chapter 2 you were introduced to the basic mathematical operatOrs, which are used to
build ma rhemacical expressions. An expression is a programming starement char has a va lue. Usua lly, an expression consists of an operator and its operands. Look at the follow· ing statement: sum
= 21
+ 3;
Since 21 + 3 has a val ue, it is an expression. Its value, 24, is stored in the va riable sum. Expressions do not have to be in the form of mathematical operations. In the following statement, 3 is an expression .
number'" 3;
Here are some programming statements where the variable resu1 t is being assigned the val ue of an expression: result result result result result result
=
•
,x;, 15 I
22
•
3,
number ;
= sizeof (int) ; = a + b + c;
91
92
Chapter 3 Expressions and Interactivity
In each of these statements, a number, variable name, or ma thematical ex pression appears on the right side of the" symbol. A value is obtained from each of these and stored in the variable result. These are all examples of a variable being ass igned the value of an expression.
Program 3-6 shows how mathematical expressions can be used with the cout object.
Program 3-6 1 2
/1 This program asks the user to e nter the numerator II and denominator of a fraction and it displays the
3
II decimal value.
4
5 6 7 8
'include
int main()
9
{
using names pace std;
10
double numerator, de nominator;
11
12 13
cout « COllt «
14 15 16 17 18 19 20
cout « "Enter the numerator : " : cin » numerator; cout « "Enter the denominator: " ; cin » de nominator: cout « "The decima l value is "i cout « (numerator / denominator) « return 0;
21
"This program shows the decimal value of "; "a fraction . \n";
endl;
)
Program Output with Example Input Shown In Bold This progr am shows the decimal value of a frac tion . Enter the numerator : J [Ent er] Ente r t he denominator : 16 [Enter) The decimal value is 0 . 1875 T he cout object will disp la y the value of any lega l expression in C++. In Program 3· 6, the value of rhe expressio n numerator I denominator is displayed.
()
NOTE: The example input for Program 3-6 shows [he user enteri ng 3 and 16. Since these values are ass igned to double va riables, rhey are stored as rhe double val ues 3.0 and 16.0.
()
NOTE : When sending an expression that consists of an opera[Qr to cout. it is always a good idea to put parentheses around the cxp rcs~ion. Some advanced operators will yield
unexpected resul ts otherw ise.
3.2 Mathematical Expressions
Operator Precedence It is possible to build mathematical expressions with several operators. The following statement assigns the sum of 17, x, 21, and y to the variable answer. answer
= 17
+ x + 21 + y;
Some expressions are not that straightforward, however. Consider the following statement: outcome
= 12
+ 6 I 3;
What value wil! be stored in outcome? 6 is used as an operand for both the addition and div ision operators. outcome co uld be assigned either 6 or 14, depending on whether the addition operation or the division operation takes place first. The answer is 14 because the divis ion operator has higher precedence than the add ition operator. Mathematical expressions are evaluated from left to right. When two operators share an operand, the opera tor with the highest precedence wo rks first . Multiplication and div ision have higher precedence tha n addition and subtraction, so the statement above works like this: A) 6 is divided by 3, yielding a result of 2 B) 12 is added to 2, yield ing a result of 14 It could be diagrammed in the following way:
outcome outcome outcome
= 12
+ 6 I 3 \ I 2 12 +
= 14
Table 3-1 shows the precedence of the arithmetic operators. The operators at the top of the table have higher precedence than the ones below them.
Table 3-1 Prec::edence of Arithmetic Operators (Highest to Lowest) (unary negation) • I , +
The multiplication, division, and mod ulus operators have the same precedence. This is also true of the addition and subtraction operators. Table 3-2 shows some expressions WiTh their values.
Table 3-2
Some Simple Expressions and Their Values
Ex pression
Value
5 + 2 * 4 10 I 2 -
8
13 3
2
+ 12 * 2 - 4
28 4
4+17%2 - 1 6
3
*
2 + 7
1
6
93
94
Chapter 3 Expressions and Interactivity
Associativity An operatOr's associativity is either left to right) or right to left. If two operators sharing an operand have the same precedence, they work according to their associativity. Table 3-3 lists the associativity of the arithmetic operatOrs. As an example, look at the fo llowing expression: 5 -
3 + 2
Borh the - a nd + operators in [his expression have the same precedence, and they have left to right associativity. $0, the ope rators will work from left to right. T his expression is the same as: «5-3)+2)
H ere is another example: 12 I 6
* 4
Beca use the I and>} operators have the same precedence, and they have left to right aSSOciativity, they will work from left to right. This expression is the same as: ((12/6)""4)
Table 3· 3
Assodatlvlty of Arithmetic Operators
Operamr
Associativity
(una ry negation) -
Righr to left
•
Left to right Left to right
I
•
+
Grouping with Parentheses Parts of a mathematical expression may be grouped with pa rentheses to force some operations to be perfo rmed before mhers. In the following sta tement, the sum of a of- b is divided by 4 . result = (a + b) / 4;
Withour the pa rentheses, however, b woul d be divided by 4 and the result added to a . Table 3-4 shows more ex press ions and their va lues,
Table 3·4
More Simple Expressions and Their Values
Expression (5 + 2 )
•
Value 4
28
10 I (5 - 3) 8 + 12 ,.. (6 - 2) + 17) ,
" - 3) (6
•
2 -
5 56
1
0
(2 + 7) I 3
9
3.2 Mathematical Expressions
Converting Algebraic Expressions to Programming Statements In algebra it is not always necessary to use an operator for multiplication. C++, however, requires an operatOr for any mathematical opera tion. Table 3-5 shows some algebraic expressions that perform multiplication and the equivalent C++ expressions .
Table 3-5 Algebraic and c++ Multiplication Expressions Algebraic Expression
Operatio n
C++ Equiva lent
68
6 times B
6
(3)(12 )
3
times 12 4 times x times y
4xy
B
3
• •
4
•
x • y
12
When convening some algebraic expressions to C++, you may have to insert parentheses that do not appear in the algebraic expression. For example, look at the following expression:
x
= a+b c
To convert this to a C++ statemen t, a + b will have to be enclosed in parentheses: x = (a
+ b) I Ci
Table 3-6 shows more algebraic expressions and their C++ equivalents.
Table 3-6 Algebraic and c++ Expressions Algebraic Ex pression
c ++ Expression
Y = 3~ 2
y_x/2· Jj
z = 3bc + 4
z=J·b · c+4j
a =
3x + 2
a= (J '" x+Z) / (4 '" a- l)
4a - 1
No Exponents Please! Unlike many programming languages, C++ does not have an exponent operator. Raising a number to a power requires the use of a library (Imelion . The C++ library isn't a place where you check our books, but a collection of specia lized func tions. Think of a library function as a "routine" that performs a specific operation. One of the libra ry functions is called pow, and its purpose is to ra ise a number to a power. Here is an example of how it's used: area = pow(4.0, 2 . 0) ;
This statement comains a call ro the pow function . The numbers inside the paremheses arc arguments. Arguments are data being sem to the function. The pow function always raises the first argument ro the powe r of the second a rgumenr. 1n this example, 4 is raised to the power of 2. The result is returned from the function and used in the statement where the function call appears. In this case, the value 16 is returned from pow and assigned to the variable area. This is illustrated ;n Figure 3-3.
95
96
Chapter 3
Expressions and Interactivity
Figure 3·3
/f
arguments
area = -00---- pow(4 . 0, 2 . 0) 16 . 0 return value
The statement area = pow (4.0, 2. 0 ) is equiva lent to the following alge braic sta tement: area
=4 2
H ere is another examp le of a statement using the pow functio n. It assigns 3 rim es 6 3 to x: X"
3 * p o w(6. 0 , 3 . 0) ;
And the following statement displays the value of 5 raised to the power of 4: cout «
pow(S.O, 4.0);
It might be helpful to think of pow as a "black box" that you plug two numbers inco, and that then sends a third number om, The nu mber that co mes out has the value of the firs t number raised to the power of the second number, as illustra ted in Figure 3-4:
Argumenl1
x -
Argument 2
y _
pow function L -_ _ _---'
There are some guidelines that should be fo llo wed when the pow functio n is used . First,
tbe program mUSt incl ude the cmath header fi le. Second, the arguments that you pass to the pow function should be doubles. Third, the variable used to store pow's return value shou ld be defined as a double, For example, in the foll owing statement the variable area should be a double: area
= pow(4 , 0,
2 . 0);
Program 3 -7 solves a simple a lge braic problem . It asks the user to enrer the radius o f a circle a nd then calcula tes the area of the ci rcle. The formula is
Area = n r2 which is expressed in the program as
area
= 3.14159 * powtradius,
2.0) :
3.2 Mathematical Expressions
Program } _7
1 2
5
II This program calculates the area of a circle. II The formula for the area of a circle is pi times II the radius squared . pi is 3 . 14159. 'include linclude II needed for pow function
6
using names pace std;
3
7
8
9 10 11
int main()
{
double area, radius; cout « "This program calculates the area of a circle . \n" ; cout « "What is the radius of the circle? "; cin » radius; area = 3.14159 * pow(radius, 2 . 0} ; cout « "The area is " « area « endl: return 0;
12
13 14 15 16 17 1B
)
Program Output with Example Input Sh.own in Bold
This program calculates the area of a circle. What is the radius of the circle? 10 (Enter] The area is 314.159
NOTE: Program 3-7 is presented as a demonstration of the pow function. In reality, there is no reason to use the pow functio n in such a simple operation. The math statement could just as easily be written as area
= 3.14159
* radius * rad i us ;
The pow function is useful, however, in operations that involve larger exponents.
In the Spotlight: Calculating an Average Determining the average of a group of values is a simple calculation: You add all of the va lues and then divide the sum by the numqer of values. Altho~gh this is a stra ightforward caJculation, it is easy to make 'a mistake when writing 'a program that calculates an average: For example., let's.assume !hat a, b, and c are double variables. Each of the variables holds a value 'and we want to calculate the average of those values. If we are careless, we might vil:ire a staremem such as the following to perform the calculation:
average
=a
+ b + c I 3.0;
Can you see the error in this ~tatement? When it executes, the division will take place first. The value in c vvill be divided by.) . 0, :1nd then tho rcsu"tt will be ndde-d. to the sum of a . + b. That is not the correct way to calculate an average. To correcr this error we need to put parentheses around a + b 0+- c, as shown h ~re:
average
=
(~
+ b + C) I 3 . 0;
97
Chapter 3 Expressions and Interactivity
98.
Let's step through the process of writing a program that ca lculates an average. Suppose you have taken three tests in your computer science class, and you want to write a program that will display the average of the test scores. Here is the algori thm in pseudocode: Get the first test score.
Get the secol1d test score. Get the third test score. Calculate the average by adding the three test scores and dividing the sum by 3. Display the average.
In the nrst th ree steps we prompt the user to enter three rest scores. Let's say we store those test scores in the double va riables testl, test2, and test3. Then in the fourth step we calc ulate the average of the three test scores. We wi ll use the following statement to perform -the calcula tion and Sto re the resul t in the average variable, which is a double : average;; (testl + test2 + test3)' I 3.0; The last step is to display the average. Program 3·8 shows the program.
Program 3-8 1 II This program calculates the average 2 II of three -test scores . 3 ,include 4 'include 5 using namespace std; 6 7 int main()
B { 9 10 11
12 13 14
IS 16
p
,. 18
20
·21
22 23 -l4 25
double testl, testl, test3; double average;
II Get cout « cin » cout « cin » cout « cin »
II To hold 'the scores /I To hold the average
the three test scores . "Enter the first test score : "i te stl ; "Enter the second test score: "; testl ; "Enter the third test score: "i test3 ;
II Calculate the average of the scores. average = (testl + test2 + test3) I 3.0i II Display the average. cout « "The average score is: " « return 0;
26 ) Program Output with Example Input Shown In Bold
Enter the first test score: 90 [Enter] Enter the second test score: 80 [Ente r] Enter the third test score: 100 [Enter] The average score is 90
average «
endli
3.2 Mathematical Expressions
~ Checkpoint 3.10
Complete the table below by writing the value of each expression in the "Val ue" co lu mn.
Value
Expression 6 + 3 * 5 12 / 2 - 4 9+14*2-6 5 + 19 % 3 - 1 (6+2)*3 14/(11-4) 9+12*(8-3) (6+17)%2-1 (9 - 3) * (6 + 9 )
3. 11
Write C++ expressions for the following algebraic expressions:
y
6x
a
2b + 4 c
Y = x g =
2
x+2 Z
Y=
X
Z
3.12
I 3
2
2 2
Study the follo wing program and complete the table. 'i nc lude H nclude usi ng names pace std,
int main () {
double value l, value2, va lue3 ; cout «
"Enter a
numbe r :
";
ci n » valuel; value2 : 2 * pow(value1, 2. 0) ; value3 = 3 + value2 / 2 - 1; cout « value3 « endl; retu rn 0 ; }
If the User Enters ... 2 5
4. 3 6
The Program Will Display Wha t Number (Stored in value3 )?
99
Chapter 3 Expressions and Interactivity
100
3.13
Complete the following program skeleton so it displays the volume of a cylindrical fuel tank. The fo rmula for the volume of a cylinder is Volume = 1t?-h where 7t is 3.1415 9 r is the radius of the tan k h is the height of the tank .include 'include
using namespace std ; int main() (
double volume, radius, height; cout «
"This program will tell you the volume of\n"i
cout « cout «
" a cylinder - shaped fuel tank . \n"; "How tall is the tank? ";
cin :»
cout «
cin »
height;
"What is the radius of the tank? Hi
radius ;
II You must complete the program . )
When You Mix Apples and Oranges: Type Conversion CONCEPT: When a n operator's o pera nds are of different da ta types, c++ will automatically convert them to th e same data type. This can affect the results of mathema tical expressions.
If an
int is multiplied by a float, what data type wi ll the result be? What if a double is div ided by an unsigned int? Is t here any way of p redict ing w h at will happen in these
insea nces? T he answer is yes. C++ follows a set of rules when perform ing mathematical operations o n variables of differenr data types. It's helpful to understand these rules to prevent subrle errors from creeping into your programs. JUSt like o fficers in the mil itary, data types are ra nked. O ne data type outranks another if
it can hold a larger number. For example, a float outranks an into Table 3-7 lists the data types in order o f their ra nk, from highesr ro [owesr. Table 3-7
Data Type Ranking
long double double
float unsigned long
long unsigned int int
3.3 When You Mix Apples and Oranges: Type Conversion
One exception to the ranking in Table 3-7 is when an int and a long are the same size.ln thar case, an unsigned int outranks long because it can hold a higher value. When c++ is working with an operaror, it strives to convert the operands to the same type . This automatic conversion is known as type coercion. When a value is convened to a higher data type, it is said to be promoted. To demote a value means co convert it to a lower dara type. Let's look at the specific rules that govern the eval uation of mathematical expressIons. Ru le 1: ch.;lrs, shorts, and unsigned shorts are automatically promoted ro Int. You will notice that ch.;lr, short, and unsigned short do not appear in Table 3-7. That's beca use anytime they are used in a mathematical expression, they are automatically promoted to an into The only exception to this rule is when an unsigned short holds a value larger than can be held by an int. T his can happen on systems where shorts are the same size as ints. Tn this case, the unsigned short is promoted to unsigned into Rule 2: When an operator works with two values of diffe rent da ta types, the lowerranking va lue is promoted to the type of the higher-rank ing value. In the following exp ression, assume that years is an int and interestRate is a float:
years • interestRate Before the multiplication takes place, years wil! be prommed to a float. Rule 3: When the fina l value of an exp ression is assigned to a variable, it will be converted to the da ta type of that variable. In the following statement, assume that area is a long int, while lengt h and width are both ints: area - length * width; Since length and width are borh intS, they will not be converted to any other data type. The resu lt of the multiplication, however, will be converted co long so it can be stored in area. Watch out for situations where an expression to an integer variable. H ere is an example:
re~ults
in a fractional val ue being assigned
int x, y '" 4 ; float z = 2. 7: x = y * z;
In the expression y * z, y wi ll be promoted to float and 10.8 will result from the multi. p lication. Since x is an integer, however, 10.8 will be truncated and 10 will be stored in X .
Integer Division When you divide an integer by another integer in CH, the result is always an integer. If tbere is a remainder, it will be disca rded. For example, in (he following code, parts is assigned the value 2.0: double parts: parts'" 15 / 6;
101
102
Chapter 3 Expressions and Interactivity
Even though 15 divided by 6 is really 2.5, the.5 parr of the resule is discarded because we are dividing an integer by an integer. It doesn't maner chat parts is declared as a double because the fractional part of the resu lt is discarded before the assignment takes place. In order for a div ision operation to recurn a floating-point va lue, at least onc of the operands must be of a floating-point data type. For example, the previous code could be wrinen as: double parts i parts = 15.0 I 6;
In t his code the literal value 15.0 is interpreted as a f1oa ting-poine number, so (he division operation will return a floating-point number. The value 2.5 will be assigned to parts.
Overflow and Underflow CONCEPT: When a variable is assigned a value that is too large or too small in range for that variable's data type, the variable overflows or underflows.
Trouble can arise when a variable is being assigned a value tha t is too large for its type. Here is a Statement where a, b, and c are all short integers: a '" b *
Ci
If band c are set to values large enough, the mu ltiplication will prod uce a number tOO big to be stored in a . To prepa re for rhis, a shoul d have been defined as an int, or a long
into When a variable is assigned a num ber th at is tOo large fo r its data type, it overflows. Likewise, assigning a value that is tOO small for a varia ble causes it to underflow. Program 3-9 shows what happens when an integer overflows or underflows. (The output shown is from a system with two-byte shorr integers.)
Program 3-9 2
1
II This program demonstrates integer overflow and underflow. 'include
3
using namespace std ;
4 5
int main{)
6
{
7 S 9 10 11
II testVar is initialized with the maximum value for a short. short testVar ~ 32767; II Display testVar. cout « testVar « endl;
12 13 14
15 16
II Add 1 to testVar to make it overf l ow . T 1; endl;
testvar = testvar cout « testVar «
3.4 Overflow and Underflow
17
// Subtract 1 from testVar to make it underflow. testVar = testVar - Ii cout « testVar « endlj return Oi
18 19 20 21
)
Program Output
32767
-32768 32767
Typically, when an integer overflows, irs conrenrs wrap aro und ro rhar data type's lowest possible value. In Program 3-9, testVar wrapped around from 32,767 to -32,768 when 1 was added to it. When 1 wa s subtracted from testVar, it underflowed, which caused its contents to wrap back around to 32,767. No warning or error message is given, so be careful when working with numbers dose ro the maximum or minimum range of an integer. If an overflow or underflow occurs, the program will use the inco rrect number, and therefore produce incorrect results. When floating-poim va riab les overflow or underflow, rhe resu lts depend upon how rhe compiler is configured. Your system may produce programs that do any of the follow ing: • •
Produces an incorrect result and cominues running. Prinrs an error message and immediately stops when either fl oating point overflow or llDderflow occurs. Prints an error message and immediately stopS when floaring point overflow occurs, but stOres a 0 in the variable when it underflows. Gives you a choice of behaviors when overflow or underflow occurs.
• •
Yo u can find our how your system reacts by compiling and running Program 3-10. Program 3-10
1 2 3 4
1/ This program can be used to see how your system handles II float in g point overflow and under f low.
tinclude using namespace stdj
5
6 7 8
int main() { f loat test ;
9
10
test
11
cout «
l2 13
test - 2.0e-38 / 2.0e38; 1/ Should underflow test. cout « test « endl;
2 _Oe38 " 1000 j test «
return 0:
14 15
=
)
//
Should overflow test-
endl;
103
Chapter 3
104
Expressions and Interactivity
Type Casting CONCEPT: Type cas ting allows yo u to perform ma nu al data type conversion.
A type cast expression lets you manually promote or demote a val ue. The general format of a type cast expression is static_cast(Valuej
where Value is a variable or lireral value that you wish
[0
convert and
DdtdType
is the data
type you wish to convert Value roo Here is an example of coue that uses a type cast expresSion:
double number = 3 . 7; int val:
val
=
static_cast( nurnberJ ;
This code defines twO varia bles: number, a double, and va l , an into The type cast expression in the third statement returns a copy of the value in number, converred [0 an int o When a double is conven ed to an int, the fractional part is truncated so this statement stores 3 in val. The original value in number is not changed, however. Type cast expressions are useful in situations where C++ will n ot perform the desired conversion automatically. Program 3-11 shows an example where a type cast expression is used to prevent integer division from taking place. The statement that uses the type cast expression is perMo nth - static_cast<double>(books) / months:
Program 3-11 1 2 3 4 5 6 7 8 9
II This program uses a type cast to avoid integer division . 'include using namespace std; int main() ( int books ; lnt months; double perHonth ;
II Number o f books to read II Number of months spent reading II Average number of books per month
10 11 12 13
cout « "How many books do you plan to read? " ; cin » books; cout « "How many months will it take you to read them? " ;
14
cin » months ;
15 16 17 18
perMonth ~ static_ cast<double>(books) I months ; cout « "That is " « perMonth « " books per month.\n"; return 0; }
3.5 Type Casting
Program Output with Example Input Shown in Bold How many books do you plan to read? 30 [Enter] How many months will i t take you to read them? 7 [Enter] That is 4 . 28571 books per month. The variable books is an integer, but its value is converted ro a double before the division takes place. Withou t the type cast expression in line 15, integer division would have been performed resulting in an incorrect answer.
CD
WARN I NG! In Program 3-1 1, the foJ1owing statement would still have resulred in integer division :
perMonth : static_cast<double>tbooks I months); The result of the expression book s I months is 4. When 4 is converted to a double, it is 4.0. To prevent the integer d ivision from taking place, one of the ope rands should be converted to a double prior to the d iv ision operatio n. This forces c++ [Q automatically conven rhe value of the other operand to a double. Program 3·12 further demonstrates tbe type cast expression .
Program 3· 12 1
2 3
4
II This program uses a type cast expression to print a character II from a number. #include using namespace std;
5 6
7
8
int main ( ) ( lnt number
= 65;
9
10 11 12 13 14 15 16 17
II Display t he value of the number variable . cout « number « end1;
II Displ ay the value of numbe r converted to II the c har data type. cout « static_ cast(number) « endl j return 0;
Program Output 65 A
Let's take a closer look at this program . In line 8 the int variable number is initial ized with the value 65. In line 11., number is sent co cout, causing 65 CO be displayed. In line 15, a type cast expression is used to convert the value in number to the char data type.
105
106
Chapter 3 Expressions and Interactivity
Reca ll from Chapter 2 tha t characters are srored in memory as integer ASCII codes. The number 65 is the Ascn code for the letter 'A', so [his statement ca uses the lette r 'N to be
di sp layed. NOTE : C++ prov ides several different type cast expressions. static~ cast is the most ( ) L-_c_o_m_n_'_O_fl_ly__u_s_e d__t_y_p _e _c_. _st__ex_p_ r_e_s_s_iO_fl_,_S_o_'_v_e_w__il_l _p_ri_'n_ a_ r_i_ly__u_se__it_i_n_ t_h_i_s_b_o_o_k_. __________~
If You Plan to Continue In Computer Science: C-Style and Prestandard Type Cast Expressions c++ also su pportS two olde r methods of creating type cast expressions: the C-style form and the prestan dard C++ form. The C-style cast is the name of a da ta type enclosed in parentheses, preceding the value that is to be converted : For example, the followin g sta tement converts rhe value in n umber to an into val = (int ) number ;
Th e following statemenr shows another example. perMonth
=
(double)books / months;
In chis statement the va lue in the books variable is convened to a doub le before the div i· sion takes place.
T he presrandard C++ fo rm of the type cast expression appears as a data type name followed by a value inside a set of parentheses. Here is an example: val
= in t( number);
The type caS[ in thi s statement returns a copy of the va lue in number , convened to an i nto Here is another example: perMonth = double(books) / months;
Although the static_cast expression is preferab le to either the C-sryle or the prestandard C++ form of the type cast expression, you will probably see code in the wo rkplace tha t uses these older styles .
~
Checkpoint 3. 14
Assume the following variable definitions: iot a
m
5 , b _ 12;
double x - 3.4 , z - 9.1;
What are the values of the followi ng expressions?
AI
b / a
B) x ,. a
C)
static_cast<double>(b / a)
D) static_ cast<doub l e>(bl I a E)
b /
static_ cast<double > (a)
F)
static_cast<doub l e>( b) / static_ cast<double> (a)
G)
b I static_cast(x)
3.6 Named Constants
H)
static_cast(x) * static_cast(z)
I)
static_cast{x * z)
Jl Gtatic
cast<double>(stat~c_cast(x l
*
static_cast(z)
3. 15
Complete the following p rogram skeleton so it asks rhe user to enter a character. Score the character in the variable letter. Use a type cast expression with the varia bl e in a cout statement co disp lay the character's ASCII code on the screen. 'include using namespace std; int ma in() {
char letter; Finish this program as specified above . return 0; II II
)
3.16
What will t he fo llowing program display? tinclude using names pace std; int main() {
int integer l , integer2; double result; integer 1 '" 19; integer2 = 2; result = integerl / integer2j cout « result « endl; result - static_cast<double>(integerl) / integer2; cout « result « endl; result'" static cast<double>(integer1 I integer2); cout « result endl; return 0;
«
)
Named Constants CONCEPT: Literals m ay be given n ames that symbolica lly represent them in a p rogra m.
In Chapter 2 you learned about numbers and strings being expressed as litera ls. For example, the following statement contains t he numeric literal 0.1 29: newAmount
=
balance * 0.129;
107
108
Chapter 3 Expressions and Interactivity
Lel's assume this statement appea rs in a banking program that calculates data penaining to loans. In such a program, twO potential problems arise. First, it is not clear to anyone other than the original programmer what 0.129 is. It appears to be ao interest rate, but in some situatio ns there are fees associated with loan payments. How can the purpose of this statement be determ ined without painstakingly checking the rest of the program? T he second p roblem occurs if this number is used in other calculations throughout the program and must be cha nged periodica lly. Assumi ng the number is an inreresr rate, what if the rare changes from 12.9 percem ro 13.2 percent? The programmer will have to search through the soul'ce code for every occurrence of the number. Both of these problems can be addressed by usi ng named constants. A named constant is like a variable, bu t its content is read-only, and cannor be changed while the p rogram is running. Here is a definition of a named constant: const double INTEREST_RATE
=
0.129;
It looks just like a regular variable defi nition except that the word const appears before the data type name, and the name of rhe variable is written in all uppercase cha ra cters. The key word const is a qual ifier that tells the comp iler to make the variable read -only. Its va lue wi ll remain constant t hroughout the program's execution. It is not requ ired that the variable name be written in all uppercase characters, bur many programmers prefer to write them th is way so they are easily distinguishable from regular variable names.
An initialization value mUSt be given when defining a variable with the const qualifier, or an error will result when the program is compiled. A compiler error will also resul t if there are any statements in the program that attempt to change the value of a named consrant. An advantage of usi ng named constants is that they make programs more self-documenting. T he follow ing statement newAmount
a
balance * 0.129;
can be changed to read newAmount
= balance
* INTEREST_RATE;
A new programmer can read the second statement and know what is happening. It is ev ident tha t balance is being multiplied by the interest rate. Another advantage ro this approach is that widespread changes ca n easily be made to the program. Let's say the interest rate appears in a dozen different statements through our the program. When the rate changes, the initia lization value in the definition of the named constant is the on ly vatue that needs to be modified. tf rhe rate increases to 13.2% the defi nition is changed to the following: const double INTEREST_RATE
~
0. 1 32;
The program is then ready to be recompiled. Every Statement th at uses will then use the new val ue.
INTEREST RATE
It is also useful ro define named constan ts fo r common values chat a re difficult to remember. For example, Program 3-7 calculated the area of a circle. The num ber 3.14159 is used fo r pi in the formula. This value could easily be defined as a named constant, as shown in Program 3-13.
3.6 Named Constants
Program 3-13 1 2
3 4
5 6
II This program calculates the area of a circle. II The formula for the area of a circle is PI times II the radius squared . PI is 3.14159. iinclude II needed for pow function #include using names pace std;
7
8
int main()
9
{
10 11
canst double PI = 3.14159; double area, radius;
12
13 14 15 16 17 18 19
cout « "This program calculates the area of a circle.\n"; cout « "What is the radius of the circle? "; cin » radius ; area = PI * pow(radius, 2.0); cout « "The area is " « area « endl; return 0; ) Earlier in ch is chapter you saw how to create a char array for the purpose of holding a C-string. It is a common practice to use a named constant to indicate the array's size. H ere is an example: canst int SIZE ~ 21; char name [SIZE J i This practice can make the program easier to maintain. When we sto re the size of the array in a named constant, we can use the named constant rather than a literal number in any statement that must refer to the size of (he array. Then, if we ever need to change the array's size, we need only to change the ini tialization value of the named constant.
If You Plan to Continue in Computer Science: The #define Directive The older C-style method of creating named constants is with the 'define preprocessor directive. Although it is preferable (Q use the const modifier, there are programs with the ' define directive still in use. In addition, Chapter 13 teaches ocher uses of the ' define directive, so it is important to understand . In Chapter 2 you learned that the 'include directive causes the preprocessor to include rhe contents of another file in you r program. Program 3-14 shows how the preprocessor can be used to create a named conStant.
Program 3-14 1 II This program calculates the area of a circle. 2 II The formula for the area of a circle is PI times 3 II the radius squared. PI is 3.1459. 4 5
*include finclude II needed for pow function (program continues)
109
Chapter 3 Expressions and Interactivity
110
Program )·14 6
(continued)
using namespace stdi
7
8 9
10 11
'define PI 3 . 14159
lnt main() {
12
double area, radius;
13 14
cout « "This program calculates the area of a circle . \n"; cout « "What is the radius of the circle? "; cin » radius ; area m PI • pow{radius, 2 . 0); cout « "The area is " « area « endl; return 0 ;
15 16 17 18 19 20
)
Remember, the preprocessor scans your program before it is compiled. It looks for directives, which arc lines that begin with [he' symbol. Preprocessor directives cause you r source code to be modified prior to being comp iled. The i-define directive in line 8 reads 'define PI 3.14159
The word PI is a named constant and 3.14159 is irs value. Anytime PI is used in the pro· gram, it will be replaced by the va lue 3.1 415 9. Line 17, which reads area; PI
*
pow(radius, 2.0);
wil l be modified by the preprocessor to read area; 3.14159 * pow(radius, 2.0);
If there had been a line that read
cout «
PI «
endl ;
it wou ld have been modified to read
cout «
3.14159 «
endl;
It is important to realize the difference between const variables and constants created
with the fdef i ne directive. const varia bits are defined like regular variables. They have a dara rype and a specific storage Jocarion in memory. They are like regular variables in every way except that you can not change their va lue while the program is running. Conscams created with the 'define di rective, however, are not variables at all, but text substiturions. Each occurrence of the named constant in your source code is removed and the value of the constant is written in its place. Be careful not to put a semicolon at the cnd of a f define directive. T he semicolon will actua ll y become part of the va lue of the constant. If the !define directive in line 8 of Program 3-14 had read like this: 'define PI 3.14159; The mathematical statement area
~
PI
*
powfradius, 2 . 0);
3.6 Named Constants
would have been modified to read area: 3 . 14159 ; * pow(radiu5, 2.0) ;
Because of the semicolon, rhe preprocessor would have created a syntax error in the sta tement above and the compiler would have given an errot message when trying to process this state ment.
o
NOTE : tdefine directives are intended for the preprocessor and C++ statements are
intended for the compiler. T he preprocessor does nO[ look for sem icolons to terminate directives.
Checkpoint 3.17
Write statements using the canst qualifier to create named constants for the fol -
lowing literal values: Literal Va lue
Description
2.71828 5.256E5 32 .2
Euler's number (known in mathematics as e) N umber of minutes in a year The gravitational acce leration constant (in feet pe r second 2 ) The gravitational acceleration constant (i n meters per second 2 ) Number of meters in a mile
9.8
1609 3.18
Write idefine directives for the ljteral values listed in Question 3.17.
3.19
Assuming the user enters 6 in response to the question, what will the following program display on the screen? 'include usi ng namespace std : j define GREETINGl "This program calculates the number " 'defi ne GREETING2 "of candy pieces sold." #define QUESTION "How many jars of candy have you sold? fdefi ne RESULTS "The number of pieces sold : " 'define YOUR COJ>.lMISSION "Candy pieces you get for commission : 'define COMMISSION RATE . 20 iot main() (
canst int PER JAR int jars, pieces; double commission;
1860;
cout « GREETINGl; cout « GREETING2 « endl; cout « QUESTION, cin » jars; pieces - jars * PER JAR; cout « RESULTS « pieces « endl; commission = pieces * COMM I SSION_RATE ; cout « YOUR_COMMISSION « commission «
return 0; )
endl,
111
112
Chapter 3 Expressions and Interactivity
Com plete the followmg program skeleton so it properly converts a speed entered in miles per hour to feet per second. One mile per hour is 1.467 feet per second. (Hint: To convert a value in miles per hom to feet per second, multiply it by 1.467.)
3.20
linclude
usi ng names pace std; int main() {
1/ Define a named con stant named CONVERSION II with the value 1.467 . double milesPerHour, feetPerSecond; cout « "This prog ram convert s miles per hour to\n"; cout « "feet per second . \n" ; cout « "Enter a speed in MPH; "j cin » milesPerHour; /1 Calculate feet per second. /1 One mile per hour equals 1 .467 feet per second.
cout « « return
"That is " « feet Per Second " feet per second. \n" i OJ
}
Multiple Assignment and Combined Assignment CONCEPT: Mu ltiple assignment means to assign the same value ro several variables with one statement. c++ allows you to assign a value to multiple variables at oncc. If a program has several variables, such as a, b, c, and d, and each va riable needs to be assigned a value, such as
, 2, the following statement may be const ructed: a
c
= b =
~
d
~
12i
T he value 12 will be assigned to each variable listed in the statement. 0:-
Combined Assignment Operators Quire often, programs have assignment sta tementS of the following form: number
~
number + Ii
The expression on the right side of the assignment operator gives the value of number plus 1. The result is then assigned to number, replacing the value that was previously stored there. Effectively, this Statement adds 1 to number. In a similar fash ion, the fo llowing sta tement subtracts 5 from number . number
= number
-
5;
.. The assignment operatOr works from right ro left. 12 is first assigned to d, then to c, then to b, then to a.
113
3.7 Multiple Assignment and Combined Assignment
If you have never seen th is type of statement before, it might cause some initial confusion because the same vari.able name appears on both sides of the assif,nment operator. Table 3-8 shows other examples of statements w ritten this way.
Table J -8
(Assume x "" 6)
Statement
What It Does
x - x + 4;
Adds 4 to x
x x x
x
-= • -= , •
Va lue o f x After the Statement
x ·
3 ,'
Subtracts 3 from x
x
10;
x /
2 ,'
Multiplies x by 10 Divides x by 2 Ma kes x the remainder of x 14
x
10 3
60 3 2
These types of operations are very com mon in programming. For convenience, C++ offers a special set of operators designed spec ifically fo r these jobs. Table 3-9 shows the combined assignment operators. also known as compound operators. and arithmetic assign-
ment operators. Table 3·9 Operator
Example Usage
Equivalent to
+.
X +-
5;
x
2;
Y = Y
Y
'= /=
,=
-=
.
x + 5 ,'
, =,
z *-= 10; a I=- b;
a
c %= 3;
c = c
=a
2 ,'
•
10;
/ b,
•
3 ,'
As you can see, the combined assignment operators do not requi re the programmer to ty pe rhe variable name twice. Also, they give a clear indication of what is happen ing in the statement. Program 3-15 uses combined assignment operators.
Program 3·15 1 2 3 4
5 6 7
// This program tracks the inventory of three widget stores /1 that opened at the same time . Each store started with the // same number of widgets in inventory . By subtracting the II number of widgets each store has sold from its inventory, II the current inventory can be calculated. !include using namespace std;
8 9
10 11
12 13 14
15
int main ( ) {
int beglnv, sold, storel, store2 , store3 ;
Seginning Number of Store 1 ' s Store 2's II Store 3's
II // II II
inventory for all stores widgets sold inventory inventory inventory
16
17 18
// Get the beginning inventory for all the stores. COllt « "One week ago, 3 new widget stores opened\n";
(program continues)
·''-1 4
Chapter 3
Program 3-1 S
(continued)
cout « "at the same time with the same beginning\n"; cout « "inventory . What was the beginning inventory? cin » beglnv;
"
20 21 22 23
"j
II Set each store's inventory . storel ~ store2 = store3 E beglnv ;
24
25 2.
II Get the number o f widgets sold at store 1. cout « " How many widgets has store 1 sold? "; cin » sold; storel -= sold; 1/ Adjust store 1'5 inventory.
27
28 29
30 31
/1 Get the number o f widgets sold at store 2 . cout « "How many widgets has store 2 sold? "; cin » sold; store2 -= sold ; /1 Adjust store 2's inventory .
32 33
34 3s
/1 Get the number of widgets sold at store 3 . cout « "How many widgets has store 3 sold? " j cin » sold; store3 - = sold; II Adjust store 3'g inventory.
36 37
38 3' 40 41
II Display each store's current inventory . caut « "\nThe current inventory of each store : \n" ; « storel « endl; cout « "Store 1 , « stare2 « endl ; cout « "Store 2 , « store3 « endl, cout « "Store 3 , return 0 ,
42
43 44 4S 46
47
hpressions and \nterac.ti'Jity
)
Program Output with Example Input Shown In Bold One week ago, 3 new widget stor es opened
at the same time with the same beginning inventory . What was the beginning inventory? 100 [Enter] How many widgets has store 1 sold? 2S [Enter] How many widgets has store 2 sold? 15 (Enter] How many widgets has s t ore 3 sold? 4S [Enter] The c urrent inventory o f each store : Store I : 75 Store 2 : 85 Store 3 : 55 Mo re elaborate statements may be expressed with the combi ned assignment o perators. Here is an example: result *= a + 5;
In this statement, result is multiplied by the sum of a + 5, When constructing such statemen ts, you must realize the precedence of the combi ned assignment operaro rs is lower tha n that of the regular math operators. Th e statement above is equ ivalent to result - result
«
(a
~
5) ;
3.7 Multiple Assignment and Combined Assignment
which is different fro m result"" result
* a + Si
Table 3-10 shows other examples of such statements and their assignment statement equivalencies.
Table 3-10 Equivalent to
Exam ple Usage K + ..,
b + 5;
x - x +( b+5)i
, ,
z *'" 10 - c; a /= b + c; c %- d - 3;
~
y
y
y-=a *2 ;
~
(a
•
( 10
*
2) ;
-
c) ;
a " a I (b + c) ; c = c (d - 3) ;
•
Checkpoint 3 .21
Write a mul tiple assignment statement that assigns 0 su btota l , tax, and shipping.
3.22
Write Statements using combined assignment operators to perform the following: A) Add 6 to x.
B) Subtract 4 from amount. C) Multipl y y by 4.
D) Divide total by
27.
StOre in x the remainder of x divided by 7. F) Addy * S(Ox. G) Subtract discount rimes 4 from total. H ) Multiply increase by salesRep times 5. I) Div ide profit by shares minus 1000.
E)
3,23
What will the following program display? 'i nclude using namespace std; int main() (
int unus, duo, tres; unus '" duo unus += 4; duo *= 2;
=
tres
= 5;
tree - = 4; unus I:::::. 3; duo += tres;
cout «
unus «
cout « cout «
duo «
tres «
return 0: )
endl; endl;
endl;
to
the variables total,
115
U6
Chapter 3 Expressions and Interactivity
Formatting Output CONCEPT: T be cout object provides ways to form at data as it is being displayed. This affects th e way data appears o n the screen. The same data can be prin ted or displayed in several different ways. For example, all of the fol lowing numbers have the same value, although they look different: 720 720.0 720 . 00000000 7 . 2e+ 2 +720 . 0
T he way a val ue is printed is called its formatting. The cout object has a standard way of formatt ing variables of each data type. Sometimes, however, you need more control over the way data is displayed. Consider Program 3-16, fo r example, which displays three rows of numbers with spaces between each one. Program 3-16 1 2
. 3 4 5
7 8
II This program displays three rows of numbers . iinclude using namespace std ; i nt main() { int num1 '"" 2897, num2 num4 -
num7
9
34, 390,
num3 837 , 5, numS - 7, num6 = 1623. num8 '=' 3456, num9 = 12;
10
11
II Display the fi r st row of numbers cout « numl « " « num2 « "
12 13
I. 14
15
«
num3 «
end1 ;
II Display the second row of numbers cout « num4 « " « num5 « " «
num6 «
endl;
num9 «
endl;
II Display the third row of numbers « num8 « .. cout « num7 « " return 0;
17 18
19
20
«
}
Program Output 2897 5 837 34 390
7
1623 3456
12
Unfortunately, the numbers do not line up in columns. T his is because some of the numbers, such as 5 and 7, occupy one position on the screen, while others occupy twO or three positions. cout uses JUSt the number of spaces needed to prim each number.
3.8 Formatting Output
To remedy this, cout offers a way of specifying the minimum number of spaces to usc fo r each number. A Stream ma nipulator, setw, can be used to establish print fields of a specified width. Here is an example of how it is used: value = 23; cout « setw(5) «
value;
The number inside the parentheses after the word setw specifies the field width for the value immediatel y followin g it. The field width is the minimum number of character positions, or spaces, on the screen to print the value in. In the example above, the number 23 will be dis played in a fie ld of 5 spaces. Since 23 on ly occupies 2 positions on the screen, 3 bbnk spaces will be printed before it. To further clarify how (his works, look at the following statements: value = 23; cout « "(H «
setw(5) «
value «
")";
This will cause the following output: 23)
Notice that the number occupies the last two pos itions in the field . Since the number did not use the entire field, cout filled the extra 3 positions with blank spaces. Because the number appears on the right side of the fie ld with blank spaces "padding" it in front , it is said to be right-;tlstified. Program 3-17 shows how the numbers in Program 3·16 can be primed in columns that line up perfectly by using setw. Program 3· 17
4
II This program displays three r ows of numbers_ 'inc lude 'include II Required for setw using namespace std;
5 6
int main( )
7
(
1 2 3
int numl = 2897, num2 = 5, num3 = 837, num6 num4 = 34, numS = 7, 1G 23, num7 390 , numS 3456, num9 12 ;
8 9 10
-
11
12
-
II Display the first row o f numbers cout « setw(6) « num1 « setw(6) « num2 « setw(G) « num3 « endlj
13
14 15
II Display th e second row of numbers cout « setw(6) « num4 « setw{G) « num5 « setw(6) « num6 « endli
16 17
18 19 ~o
JI
21 22 23
cout «
"
Oigp~ay
«
th e
third row of numbo r o
setw(6) « num7 « num8 « setw(6j «
setw(6) num9 « endl;
return OJ )
(program output conlinuel)
117
Chapter 3 Expressions and Interactivily
118
Program
3 ~ 17
(continued)
Program Output
2897
5
837
34 390
7 3456
1623 12
By printi ng each number in a field of 6 positions, they are displayed in perfect columns.
NOTE: A new header file, ioman ip, is included in Program 3-17. 1£ muSt be used in any ()
L-_p_'_o_g_'a_m __,_h_a_'_u_'_e_s_'_e_t_w_"____________________________------------------------~
Notice how a setw manipu laror is used with each value because setw only establishes a field width for the value immediatel y following it. After that value is pri n ted, cout goes back (0 its default method of pr inting. You might wonder what will happen if the number is roo la rge to fir in th e field, as in the
following statement: value" 18397; cout « setw(2) «
value;
In cases like this, cout will prim the entire number. setw only specifies the minimum number of positions in the prim field. Any number larger than the minimum will cause cout to override the setw value. may specify the field width of any type of data. Program 3· 18 shows setw being used with an integer, a floatin g-point number, and a srring. YOll
Program 3-18 1 2 3
4
5
II This program demonstrates the setw manipulator being II used with values of various data types .
'include 'include using namespace std;
6 7
8
9 10 11
12
int main() { int intValue - 3928; double doubleVa1ue = 91.5; canst int ARRAY_SIZE _ 14, char cStringvalue[ARRAY_SIZEI - "John J. Smith";
13 14
cout « "( " « cout « " ( " « cout « " ( " « return 0;
15 16 17
18
)
setw(5) « intValue « ")" « endl; setw(S) « doubleValue « "J" « endl; setw(16) «
cStringValue «
")'. «
endl;
3.8 Formatting Output
Program Output ( 3928)
(
91.5) John J. Smith ) P rogram 3-18 can be used to ill ustrate the following points: • The field w idth of a floating -poi nt number includes a pos ition for the decimal point. • T he field width of a string indudes all characte rs in the stri ng, including spaces. • The values printed in the field are right-justified by defau lt. T his means they are aligned with the right side of the print field, and any blanks that m ust be used to pad it are inserted in front of the va lue .
The setprecision Manipulator Formatting Numbets with .etpr .. .,i.ion
Floating-point values may be rounded to a number of signi{icarlt digits, or precisiol1, which is the total number of digits that appear before and after the decimal point. You can control the number of significant digits w ith w h ich floating-point val ues are displayed by llsing the setprecision manipulator. Program 3-19 shows the results of a division operation displayed with different numbers of significam digits.
Program 3-19 1 2 3
4 5
II This program demonstrates how setprecision rounds a II floating point value. linclude 'include using names pace std:
6
7
i nt Illain()
8
( double quotient , number 1
9
10
quot ient = number 1 I number2; cout « quotient « endl ; cout « setprecision(5) « quotient cout « setprecision(4) « quotient cout « setprecision(3) « quotient cout « setprecision( 2) « quotient cout « setprec is ion ( 1 ) « quotient return 0,
11
12 13 1<
15
16
17 18 19
)
Program Output 4.91877
4 . 91BB 4. 91 9
' .~1
U
"
= 132 . 364,
number2
« « « «
«
endl; endl; endl ; endl; e ndl;
26 . 91 ;
11 9
120
Chapter 3 Expressions and Interactivity
The first value is displayed in line 12 without the setprecision manipulator. (By default) the system in the illustration displays floating-point values with 6 sign ificant digits.) The subseq uent cout statements print the same value, but rounded co 5, 4, 3, 2, and 1 signifl' cant digits. If the value of a number is expressed in fewer digits of precision than specified by setprecision, the manipulator will have no effect. In the following statements, the value of dollars only has four d igits of precision, so rhe number printed by both cout statements is 24.51. double dollars: 24 . 51; cout « dollars « endl;
cout «
setprecision(5) «
dollars «
endl;
II Displays 24.51 II Displays 24 . 5 1
Table 3·11 shows how setprecision affecrs the way various values are displayed. Table 3-11 Number
M anipula tor
Value Displayed
28.92786
setprecision (3 )
28.9
21
setpreci. .. i.on (5)
21
109.5
setprecision (4)
109.5
34 .28596
setprecision(2)
3.
Unlike field width, the precision setting remai ns in effect unti l it is changed to some other value. As with all formatting manipu lators, you must include the header file iomanip to use setprecision . Program 3·20 shows how t he setw and setprecision manipu lators may be combined to fully comro l the way float ing point n umbers arc dis played.
Prog ram 3-20 1 2 3 4 5
II This program asks for sales figures f or 3 days. The total II sales are calculated and displayed in a table . 'include 'include using names pace std ;
6 7
intmain()
8
{
9 10 11 12 13
,.
15
16 17
"
l~
20
double day1, day2, day3, total;
II Get cout « cin » cout « cin » cout « c,n »
the sa l es for each day. "Enter the sales for day 1 : "; dayl; "Enter the sales for day 2 , "-, day2j
.
"Enter the sales for day 3 , " , day3;
II Calculate the total sales. total = day 1 + day2 + day3;
3.8 Formatting Output
21 22 23 2.
II Display the sal es figures . cout « "\nSales Figures\n" i cout « " ----- - - ------\n" ; cout « set precision (5) ; c out « "Day 1 , " « setw(8) « cout « "Day 2 , " « setw (8 ) « « s e tw{ 8) « cout « "Day 3 , « setw( 8) « cout « "Total. return O·,
25 26
27 28
29 30 31
dayl « endl; day2 « endl; day3 « endl; total « end l ;
}
Program Output with Example Enter the sales for day 1 : Enter the sales for day 2 : Enter the sales for day 3:
Input Shown In Bold 321 .57 [Enter] 269.62 [Enter] 307.77 [Enter]
Sales Figures Day 1. Day 2: Day 3; Total:
32 1. 57
269.62 307.77
898.96
The fixed Manipulator The setprecision man ipu lator can som etimes s urprise you in an undesirable way. W hen the precision of a number is set to a lower value, numbe rs tend to be pr imed in scientific
notation. For example, here is the o utput of Program 3-20 with larger numbers being IOput: Program 3-20 Program Output with Example Enter the sales for day l : Enter the sales for day 2 : Enter the sales for day 3:
Input Shown In Bold 145678.99 [Enter] 205614_85 [Enter] 198645.22 [Enter]
Sales Figures Day 1 : Day 2: Day 3: Total:
1 . 4568e+OOS 2.0S61e+OOS
1.9865e+OOS 5.4994e+OOS
Another strea m man ipulator, fixed, forces cout to print the digits in fixed-point nolation, or decimal. Program 3-21 shows how the fixed manipulator is used.
121
122
Chapter 3 Expressions and lnteractivity
Program 3- 21 1 2
3 4 5 6 7 8 9 10
/I This program asks for sales figures for 3 days . The t otal /I sales are calculated and displayed in a table . #include llinclude
using namespace std; i nt main( ) (
double day!, d ay2, day), total; II Get the sales for each day . cout « "Enter the sales fo r day 1 , " cin » dayl; cout « "Enter the sales fo r day cin » day2 ; cout « "Enter the sales for day 3 , .,
11
12
.,
,, . ,.
13 14 15
16 17 18
c in »
19 20
II Calculate the total sales. dayl + day2 + day3; total
.,
day3;
:0
21
II Display the sales figures . cout « "\nSales Figures\n" i cout « ,, ------- - --- - - \n" ;
22 23
24
cout « cout « cout « cout « cout «
25
26 27 28 29 30 31
setpre c i sion(2 ) « f i xed; « setw( 8) « dayl « "Day 1 , 2 , « setw( 8) « day2 « "Day 3 , « "Day s e t w( 8) « day3 «
"Total: r eturn 0;
«
setw( 8)
endl;
endl; endl;
« tota l « endl;
)
Program Output with Example Input Shown in Bold Enter the sales for day 1 : 1321.87 (Enter] Enter the sales for day 2 : 1869.26 [Enter] Enter the sales for day 3: 1403.77 [Enter]
Sales Figures Day 1 : Day 2 :
Day 3 : Total :
1321.87 1869.26 1403.77 4594.90
The statement in line 25 uses the fixed manipulator: cout «
setprecision(2) «
fixed;
When the fixed manipulator is used, all floating poim numbers thar are su bsequently printed will be displayed in fixed point notation, with the number of digits to the right o f the decimal point specified by the setprecision manipulator.
3.B
Formattin9 Output
When the fixed and setprecision ma nipulators are used together, the va lue specified by the setpr ecision manipulator wi ll be the number of digits to appear after the decimal poin t, nOt the number of signHicam digits. For exa mp le, look at the following code. double x = 123.4567; cout « setprecision(2) «
fixed «
x «
endl;
Because the fixed manipulator is used, the setprecision manipulatOr wi ll cause the number to be displayed with twO digits after the decimal point. The value will be displayed as 123.46.
The showpoint Manipulator By default, f1oati ng-poim numbers are not displayed with trailing zeroes, and f1oatingpoint numbers that do not have a fractional part are not displayed with a decima l point. For example,look at the following code. doubl e x = 123 . 4, Y = 456.0; cout « setprecision(6) « x « cout « y « endl;
endl ;
The cout statements will produce the following Output. 123 .4 456
Although six significant digits are specified for both numbers, neither num ber is displayed with trailing zeroes. If we wam the numbers padded with traili ng zeroes, we must use [he showpoint manip ula tor as shown in the following code. double x = 123.4, Y = 456.0; cout « setprecision(6) « showpoint « cout « y « endl;
x «
end1;
These cout statements will produce the followi ng output. 123.400 456.000 ~
NOTE : With most compilers, trailing zeroes arc displayed when the setprecision and
~ L-_f_i_x_e_d__m_a_n_i_p_u_la_,_o_,_s_a_re__u_se_d__r_o_ge_'_h_e_'________________________________________--'
The left and right Manipulators Normally output is right justified. For example, look at the following code.
-
double x - 146.789, Y 24.2, , « « setw( 10) x« endl; cout « endl ; cout « setw(10) « y cout « setw(10) « , « endl:
= 1.
783;
1 23
Chapter 3 Expressions and Interactivity
12.
Each of the variables, x, Y. and the cout statements is
2,
is displayed in a pr ine field o f 10 spaces. The output of
14 6.789 24.2 1 . 783
Notice that each value is right-justified, or aligned to the right of irs print field. You ca n cause the val ues to be left-justified by using the left manipu lator, as shown in the following code. dou b le x
=
146 . 789 , Y = 24 . 2, Z = 1 .783 ;
left « setw(lO) « x « setw(lO) « y « endl; setw{lO) « z « e ndl;
cout « cout « cout «
endl;
The output of these cout statements is 146.789 24 . 2 1. 783
In th is case, the numbers are alig ned fO the left of their prim fields. The left manipulator rema ins in effect until yO LI use the right manipulator, which causes all subsequent output to be righe-j ustified. Table 3-12 su mmari:t:es the mani pulators we have discussed.
Table 3-12 Stream M anipul ator
Descriptio n
setw(n)
Establishes a print field of n spaces.
fixed
D isplays float ing-point numbers in fixed poinr notation.
showpoint setprecision (n)
Causes a decimal point and trailing zeroes to be displayed, even if there is no fractio nal part. Sets the pl-ecision of floating-point numbers.
left
Causes su bseq uent output to be left justified.
right
Causes subsequent output to be right just ified.
~ Checkpoint 3.24
Write cout statements with stJ:ea m manipulators that perform the follow ing: A) Display the number 34.789 in a held of nine spaces wit h two decimal places of precision. B) Display the number 7.0 in a held of five spaces with three decima l places o f precISion. The decimal poi nt and any trailing zeroes should be displayed. C) Display the number S.789e+ 12 in fixed point not3cio n. D) Display the number 67 left justified in a field of seven spaces.
3.9 Formatted Input
3.25
Th e following program will nOt compile because the lines have been mixed up. 'include )
cout « person « endl; char person{ 151 = "Wolfgang Smith"; int main() cout « person « endl; (
'include return 0 ; cout <<: left; using namespace std; cout « setw(20): cout « right:
When the lines are properly arranged the program should display the following: wolfgang Smith Wolfgang Smith
Rearrange the lines in the correct order. Test the program by entering it on the compU[er, compiling it, and running it. 3.26
The following program skeleton asks for an angle in degrees and converts it to radians. The formatting of the fi nal output is left w you . 'include 'include U$in9 namespace
s~d;
int main() (
canst double PI = 3 . 14159; double degrees, radians; cout « "Enter an angle in degrees and I wil l convert it\n" : cout « "to radians for you: "i cin » degrees; radians = degrees • PI I 180: II Display the value in rad ians left justified, in fixed II point notation, with 4 places of prec ision, i n a field II 5 spaces wide, making sure the dec i mal point is always II displayed . return 0; )
Formatted Input CONCEPT: T hc cin object provides ways of controllin g string and character input.
The cin object has formatting tools similar to those of couto For instance, an input field width may be set with the setw manipulator. T his is most helpful when cin is readin~ a string and :5toriflg it in a char;;tctcr a rray. You may recall that ci.n has no .wa y of know l ~S how large rhe array is. If [he user types more characte rs [han the array will hold, cin will
126
Chapter 3
Expressions and Interactivity
store (he string in the array anyway, overwriting wha tever is in memory next to the :ncay. This type of error is known as a buffer overrun, and can lead w serious prob lems if not prevented. An input field width solves this problem by tethng cin bow many characters to
read. Here is a sta temenr defi ni ng an array of 10 characters and a cin statement reading no more characters than the array will hold: char word[ 10 1 ;
cin »
setw(lO) »
word;
The field width specified is 10. cin will read one character less than th is, leaving room for the null character at the end. Program 3-22 ill ustra tes the use of the setw mani pu lator with cin.
Program 3-22 II This program uses setw with the cin object. 2
'include
3 4
iinclude using namespace s t d;
5 6 7
int main() {
a
canst int SIZE: 5; char word[SIZE]i
9 10 11 12 13
cout « "Enter a word : " ; cin » setw(SIZE) » word;
14
return 0;
15
cout «
"You entered " «
word «
endl ;
)
Program Output with Example Input Shown In Bold Enter a word: Eureka [Enter] You entered Eure In (his program, cin on ly reads 4 characters into the word array. Without the field width, cin would have written the entire word "Eureka" into the array, overflowing it. Figure 3-5 ill ustrates the way memory wou ld have been affected by this. The shaded area is the 5 bytes of memory used by the array. The word "Eureka" with its null terminator would spill over into the adjacent memory. Anything that was stored there would be destroyed.
Figure 3-S
, I• I I k
Beginning of word array, 5 characters.
a
\0
Next item in memory. Overwritten with 'a' and null character.
3.9 Formatted Input
There are two important points to remember about the wa y cin handles field widths: • •
The field width only pertains to the very next item entered by the user. cin stops reading input when it encou nters a whitespace characte r. Whitespace characters include the [E.nter] key, space, and tab.
Reading a " Line" of Input dn provides a member funct ion to read a string contai ning spaces. The fun ction is called getline, and its purpose is to read an entire "line" of text, until the [Enter] key is pressed. Here is an example of how it is used: cin . getline(sentence, 20) ; The get line func tion takes twO arguments separated by a comma. The first argument is the name of the array that the string is to be stored in. In the statement above, the name of the array is sentenc e. T he second argument is the size of the array. cin will read up to one character less than th is number, leav ing room for the null term inator. T his eliminates the need for using the setw manipulator. The statement above wil l read up to 19 characters and the null terminator will automatically be placed in the array, after the last character. Program 3·23 shows the getline member fu nction bei ng used to read a sentence of up to 80 characters. Program 3·23 1
II This program demonstrates ci n' s getline member function.
2
#include using namespace std;
3 4
5
int main()
6
7
const int SIZE = 81 ; char sentence[SIzEJ;
8 9 10 11
cout « "Enter a s e ntence: n; cin.getline(sentence, SIZE) ; cout « "You entered " « sentence « return 0 ;
12 13 14
endl;
}
Program Output with Example Input Shown In Bold Enter a sentence : To be, or not to be, that Is the questfon . (E.nter] You entered To be, or not to be, that is the question.
Reading a Character Sometimes you want to read only a single cha racter of input. For example, some programs dis pl.ay a menu of items for the user to choose from. Often the select ions will be denoted by the letters A, S, C, and so fo rth. The user chooses an item from the menu by typing a character. The simplest way to read a Single character is with the» operator, as shown in the following code.
127
Chapter 3 Expressions and Interactivity
128
II Define a character variable. char chi cout « "Type a character and press Enter : "; cin »chi 1/ Read a character. cout « "You entered " « ch « endl;
If the user types the character A and presses Enter. cin will store the character 'A' in the variable ch. Remember, dn is smart enough to know the data type of the va ri able it is storing da ta into. Since ch is a char variable, it wil l only store the single cha racter 'A' there. If ch had been a char array, cin would have stored the string "A" -with its null terminator there.
Using cin . get A limiting cha racteristic of the» operator w ith char variables
IS
tha t it requires a charac-
ter to be ente red and it ignores all lead ing whitespace characters. T his mea ns the program will nor conrinue past the cin statemenr unril some character other than the spacebar, the tab key, or the (Enter] key has been pressed. (T he [Enter) key must still be pressed after (he characrer has been typed.) Programs [hat ask the user ro "press the enter key to continue" cannot use the» operator to read only the pressi ng of the [Enter] key. In those situations anQ[her of do's member funct ions, get, beco mes useful. The get funcrion reads a single character including any whitespace cha racter. H ere is an examp le: char ch i /1 Define a character variable. cout « "Type a character and press Enter : "; cin.get(ch) ; II Read a character. cout « "You entered " « ch « endl;
1f the user types the character A and presses Enter, the cin . get function will store the character 'A' in the variable ch. If the user simply presses the Enter key, the cin.ge t function wi ll store the newline c haracter ('\n') in the variable ch . Program 3-24 shows the func tion being lIsed to pause a program. Program 3-24
1 2 3 4
II This program demonstrates cin.get .
'include using namespace std ;
,
int main()
7
char
5
{ Chi
8
9 10 11 12 13
cout « "This program has paused. Press Enter to continue ."; cin.get(ch); cout « "Thank you! " « end1; return 0 ; )
Program Output
This program has paused. Press Enter to continue. [Enter] Thank you!
3.9 Formatted Input
The only difference between the get function and the >:> operaror is rhar get reads the first cha racter typed, even if it is a space, tab, or the [Enter] key.
Mixing dn »and cin. get Mixing cin. get with cin » can cause an annoying and hard-to-find problem. For example, look at the following statements: char Chi // Define a character variable. int number ; // Define an integer variable . cout « "Enter a number ; .. i cin » number; /1 Read an integer. cout « "Enter a character ; "i cin.get(ch) i 1/ Read a character . cout « "Thank You!\n"; These statements may allow the user to enter a number, but not a character. It will appear tha t the cin . get statement is skipped. This happens because both cin »and dn. get read the user's keystrokes from the keyboard buffer. After the user enters a number, in response ro the first prompt, he or she presses the Enter key. Pressing the Enter key causes a newline character ('\11') to be srored in the keyboard buffer. For example, suppose the user enters 100 and presses Enter. The input will be stored in the keyboard buffer as shown in Figure 3-6. Figure 3-6
Keyboard buffer
I
1
t
I
0
I
0
I[En'er)I
cin begins reading here. When the cin »statement reads data from the keyboard buffer, it stops reading at the newline character that was generated by the Enter key. This newline character is left in the keyboard buffer. That means the first characrer read by cin.get will be the newline character. So, the cin. get starement will read only the newline character left in the keyboard buffer, and it will appear that the cin . get statement did nOt execute. You can remedy this situation by using the cin . ignore function, described in the following section .
Using cin. ignore To solve the problem previously described, rhe cin. ignore member func tion can be used. cin. ignore tells the cin object to skip characters in the keyboard buffer. Here is its general form: cin.ignore(n, c) ; The arguments shown in the parentheses are optional. If they are used, n is an integer and c is a character. They tell cin to sk ip n number of characters, or until the character c is encountered. For example, the following statement causes cin to skip the next 20 characters, or until a newline is encountered, whichever comes first: cin. ignore (20, . \n . ) ;
129
130
Chapter 3 Expressions and lnteractivity
If no arguments arc used, cin will only skip the very next character. Here's an examp le: cin . ignore();
The previous statcmems that mix cin » and cin.get can be repaired by inserting a cin. ignore statement after the cin » statement: II Define a character variable .
char chi
int number; II Define an integer variable . cout « "Enter a number : "; cin » number; II Read an integer .
cin. ignore ( ) i
cout «
II Skip the newline character.
"Enter a character:
~;
cin.get(ch)i cout «
/1 Read a character. "Thank You!" « endl ;
Focus on Object-Oriented Programming: More About Member Functions CONCEPT: A member functio n is a procedure, written in C++ code, [hal is part of an object. A member fun ction causes the object it is a member of to perform an action.
The concept of object-oriented programming (OO P) was introduced in Chapter 1, Section 1. 7 (Procedura{ and Object-Oriented Programming). Recall from that seaion that objects are programming elements conta ining both data and procedures that operate on the data. The packaging together of data and the dara 's related procedures within an object is known as encapsulation. In C++, the proced ures that are part of an object are known as member (I/nctions. They are called member fun ctions because they are func tions that are membe rs of, or belong to, an object. The use of member functions simplifies programming and red uces CHars. Anywhere an ob ject is used, it contains not only data, but also the correct algorithms and operations for working with the data. If you are the user of an object (as you are the user of cout and dn) you do not need fa write your own code ro manipulate the object's data. AU that is necessary is that you learn tbe object's member functions and how to use them. In this chapter you have used the following member fu nctions of the cin object:
• • •
getline get
ignore
Calling an object's member function causes the object to perform some o perati on. For exa mple, calli ng cin's getline member function causes cin to read a line o f input from the keyboard .
3.11 More Mathematical l ibrary Functjons
In OOP terminology, calling a member func tion is also described as passing a message to the object. For example, you can thin k of the following statement as sending a message to the cin object, instructing it to read a character from the keyboard and then store the characrer in rhe ch variable. cin.get(ch)i All of ci n's member funct ions are written in C++ code. In Chapter 13 you wil l learn to
design your own objects, complete with member functions.
More Mathematical Library Functions CONCEPT: The C++ runtime library p rovides severa l fun ctions for pe rforming
complex mathemati cal operations. Earlier in this chapter you learned to use the pow function to raise a number to a power. The c ..... library has numerous other functi ons that per form specialized mathematical operations. These functions are useful in scientific and special-purpose programs. Table 3-13 shows several of these, each o f which requires the cmath header file. Table 3-13
Function abs
Example y : abs(X)i
cos
Y
exp
y = exp (x) ;
fmod
y =
fmod (x, z);
log
y
log(x) i
10g10
Y
loglO(x) ;
sin
y - sin(x) ;
sqrt
y -
tan
y = tan(x) ;
= cos(xl;
sqrt(x) ;
Description Returns the absolute value of the argument. The argument and the return value are integers. Returns the cos ine of the argument. The argument should be an angle expressed in radians. The retu rn type and the argument are doubles . Compures the exponential func tion of the argument, which is x. The return type and the argument are doubles. Returns, as a double, the rema inder of the fi rst argument divided by the second argument. Works like the modulus apera[Qr, bur [he arguments are doubles. (The modulus operator only wo rks with integers.) Ta ke care not to pass zero as the second argume nt. Doing so wou ld cause division by zero. Returns the natural logarithm of the argument. The return (ype and the argument are doubles. Returns the base-IO logarithm of the argument. The return type and the argument are doubles.
Returns the sine of the argument. The argument should be an angle expressed in radians. The recurn type and the argu ment are doubles. Returns the square root of t he argument. The re t urn type and argument are doubles . Returns the tangent of the acgument. The argument should be an angle expressed in radians. The return type and the argument are doubles.
13]
132
Chapter 3 Expressions and lnteractivity
Each of these functions is as simp le to use as the pow function. The following program segment demonstrates the sqrt function, which returns the square rOOt of a number; cout « "Enter a number: "; cin » flum; s = sqrt(num) i
cout «
"The square root of " «
num «
" is " «
S «
endlj
Here is the output of the program segment, with 25 as the number emeeed by the user: Enter a number: 25 The square root of 25 is 5
Program 3-25 shows the sqrt function being used to find the hypotenuse of a right triangle. The program uses the following formu la, taken from the Pythagorean theorem:
In the form ula, c is the length of the hypotenuse, and a and bare rhe lengths of the other sides of the triangle.
Program 3-25 2 3
1
II This program asks for the lengths of the two sides of a II right triangle . The length of the hypotenuse is then II calculated and disp layed.
4 5 6 7
'include 'include /1 For setprecision 'include // For the sqrt and pow funct ions using names pace stdj
8
9 10
int main() {
11
double a, b,
12 13
.,
" ,. cout « "Enter the length of side » cin cout « "Enter the length of side b, , cin » b·, c = sqrt(pow{
.,
14 15
16 17 l8 19 20
21
Ci
...
...,
)
Program Output with Example Input Shown In Bold Enter the length of side a: 5.0 [Enter] Enter the length of side b: 12.0 [Enter]
The length of the hypotenuse is 13
The following sta tement, taken from Program of the squares of rhe rriangle's rwo sides: c
=
3~25,
sqrt(pow{a , 2 . 0) + pow(b , 2.0);
calc ulates the square roar of the sum
3.11 More Mathematical Library Functions
Notice chat the following mathematical expression is used as the sqrt function's argument: pow(a, 2.0) + pow(b, 2 . 0)
This expression calls the pow function twice: once to calculate th e square of a and again to calculate the square of b. T hese two squares arc then added together, and the sum is sent to [he sqrt function.
Random Numbers Some programming techniques require the use of randomly generated numbers. The C++ library has a function, rand(), for this purpose. (rand( ) requires the header file cstdlib}. The number returned by the function is an into Here is an example of its usage: y
:0
rand();
After this statement executes, the variable y will contain a ran dom number. In actuality, the numbers produced by rand( lare pseudorandom. The function llses an algorithm that produces the same sequence of numbers each time the program is repeated on the same system. For example, suppose the following sta tements are executed. cout « cout « cout «
rand() « rand() « rand() «
endl; end1; end1;
The three numbers displayed will appear to be random, but each time the program runs, the same three values will be generated. In order to randomize the results of rand ( l, the srand() function must be used. srand() accepts an unsigned int argument, which acts as a seed val ue fo r the algorithm. By specifying different seed values, rand() will generare different sequences of random numbers. A common practice for getting uniq ue seed values is to ca ll the time function, which is part of the standard library. The time function recurns the number of seconds that have elapsed since midnighr, Janua ry 1, 1970. The time function requires the ctime header file, and you pass 0 as an argument ro the funct ion. Program 3-26 demonstrates . The program should generate three differen t random numbers each time it is executed. Program 3-26
1 2 3 4 5
II This program demonstrates random numbers .
li nc lude 'include II For rand and srand iinclude II For the time function using names pace stdi
6
7 int main() B { 9 II Get the system time_ 10 unsigned seed time ( O) ; :0
11
12 13
II Seed the random number generator .
srand(seed);
14
(program continues)
133
134
Chapter 3
Expressions and Interactivity
Program 3-26
(continued)
/ I Display three random numbers . cout « rand ( ) « endl; cout « rand() « endl; cout « rand( ) « endl;
IS 16 17
18
return
19 20
o·,
)
Program Output 23861 20884
21941 NOTE : If you wish to limit the range of the random number, use the following formu la.
y
~
1 + rand() % maxRange;
The maxRange va lue is the upper limit of the range. For example, if you wish to generate a random number in the range of 1 through 100, lise the fo llowing sta tement. y - 1 + rand() % 100:
This is how the sta tement works: Look at the following expression. rand() % 100
Assuming rand( ) returns 37894, the val ue of the expression above is 94. That is because 37894 divided by 100 is 378 with a remainder of 94. (The modulus operator returns the remainder.) But, what if rand() returns a number that is evenly div isible by lOa, such as SOD? The expression above will rew rn a O. If we want a number in the range 1 - 100, we must add 1 to the resu lt. That is why we use the expression 1 + rand() % 100.
~ Checkpoint 3.27
Write a short description of each of the fo llowing func tions: cos
log
sin
exp
10g10
sqrt
ta n Assume the va riables ang1el and angle2 hold angles stored in radians. Write a statement that adds the sine of anglel ro the cosine of angle2, and srores the result in the va riable x. fmod
3.28
3.29
3.30
pow
To find the cube root (the third root) of a number, raise it to the power of lh. To find the fourth rOOt of a number, raise it to the power of 1/4. Write a statement that will find the fifth root of the variable x and store the resu lt in the variab le y. The cosecant o f t he a nSI\! a is 1 sina
3. 12 Focus on Debugging: Hand Tracing a Program
Write (I stMcmenr thar calculates the cosecant of rhe angle stored in the variable a, and sTores it in the variable y.
Focus on Debugging: Hand Tracing a Program Hand tracing is a debugging process where you pretend that you are the computer executing a program. You step through each of the program's statements one by one. As you look aT a statement, you tecord the contents that each variable will have afrer rhe statement executes. This process is often helpful in finding mathematical mistakes and other logic errors.
To hand trace a program you conStruCt a chart with a column fo r each. variable. The rows in the charr correspond to the lines in the program. For example, Program 3-27 is shown with a hand trace charr. The program uses the following four variables: nurnl, num2, num3, and avg. Notice that t he hand trace chart has a column for each variable and a row for each line of code in function main. Program 3-21 1 II This program asks for three numbers, then 2 II displays the average of the numbers. 3 'include
4 using namespace std: 5 int main() numl
6 {
7
double num1, num2, num3, avgi
8
cout«
9
cin»
num3
avg
"Enter the first number; "; num1;
10
cout «
11
cin »
12
cout «
13
cin»
14
avg
15
cout «
16
return 0i
~
num2
"Enter the second number ; ": num2; "Enter the third number : ";
num3: num1 + num2 + num3
I 3:
"The average is .. «
avg «
endl;
17 }
This program, which asks the user to enter three numbers and then displays the average of the numbers, has a bug. It does nor display the correct average. The output of a sample session with the program follows.
135
Chapter 3 Expressions and Interactivity
136
Program Output wIth bample Input Shown In Bold Enter the first number : 10 [Enter] Enter the second number : 20 [Enter] Enter the third number: 30 [Enter] The average is 40
The correct average of 10, 20, and 30 is 20, not 40. To find the error we wi ll hand [[ace the program. To hand trace this program , you step through each statement, observi ng the opera tion that is taki ng place, and then record the contents o f the variables after the sta tement executes . After the hand trace is complete, the cha rr will appear as follow s. We have written question marks in the chan where we do not know the contents of a va ria ble.
(with hand trace chart filled)
Program 3 -27
1 II This program asks for three 2 II displays the average o f the
numbers, then numbers .
3 'include
4 using na me space std; 5 int main ( )
nurn!
6 { 7
double nurnl , num2, nurn3, avg;
e
cout «
9
cin »
"Enter the first number:
,
. ..
nurn! ;
10
cout «
11
ci n »
12
cout «
13
ci n »
14
avg
15
cout «
16
return 0,
17
1
nurn2 ; "Enter the th ird number :
.....
nurn3;
• nurn l + num2 + nurn3 I 3, "The average is
.
«
avg
«
endl;
, ,
nurn3
avg
,
,
,
,
,
,
,
, ,
10
, ,
10
20
10
20
,
'0
20
30
10
20
30
.0
20
30
10
"Enter the second number : " ;
nurn2
,
,
, I
40 40
)
Do you see the error? By exa mi ning the statement that performs the math operation in
line 14, we find a mistake. The division operation rakes place before the addition operations, so we must rewrite that statement as
avg
=
(nurnl + num2 + nurn3) I 3;
H and t raci ng is a simpl e process that focuses yo ur a ttention on each statement in a program . Often this helps you locate errors that arc not obvious .
3.13 Focus on Problem
Solvjn~j:
A Case Study
Focus on Problem Solving: A Case Study General Crates, Inc. builds custom-designed wooden crares. Wi th materia ls and labor, it cOSts GCl $0.23 per cubic foot to bu ild a crate. In turn, they charge their customers $0.50 per cubic foot fo r the cra te. You have been asked to write a program that calculates the volume (in cubic feet), cost, cUStomer price, and profit of any crate GCI builds.
Variables Table 3-14 shows the variab les needed.
Table 3-14 Variable length
Description A doubl e variable to ho ld the length of the crate, whic h is input by the user.
width
A double variable to hold the width of the crate, which is input by the user.
hei g ht
A double variable to hold the height of the crate, which is input by the user. A double variable to ho ld the volume of the crate. The va lue stored in this variable is
vol ume
calculated. cost
A double va ria ble to ho ld the cost of bu ilding the crate. The value stored in this variable
is calculated. A double variable to hold the amount charged to the customer for the crate. The va lue sto red in this va riable is calcu lated. A double variable to hold the profit Gel makes from the crate. The va lue stored in this variable is calculated.
charge profit
Program Design T he program must perform the following general steps: 1. Ask the user to enter the dimensions of the crate (the crate's length, width, and height). 2. Calc ula te the crate's vo lume, the cost of bui lding t he crate, the customer's charge, and
[he profk made.
3. Display the data calcu lated in Step 2. A general hierarchy chart for this program is shown in Figure 3-7.
Figure 3-7 Calculale CraIe Volume, Cost, Price, and Profit.
I Gel Crate Dimensions.
Calculate Volume, Cost, Customer Charge. and Profit.
Display Calculated Data.
137
138
Chapter 3
Expressions and Interactivity
The "Get Crate Dimensions" step is shown in greater derail in Figure 3-8. Figure 3-8
Get Crate Dimensions.
I Get length.
Get Width.
Get Height.
T he "Calcula te Volume, COSt, Customer Charge, and Pront " step is shown in greater detai l in Figure 3-9. Figure 3-9 Calculate Volume, Cost,
Customer Charge, and Profit.
Calculate the Crate's Volume.
Calculate the Crate's Cost.
Calculate the Customer Charge.
Calculate the Prolil Made.
The "Display Calculated Dam" step is shown in greater derail in Figure 3-10. Figure 3-10
Display Calculated Data.
Display Ihe
Display the
Crate's Volume.
Crate's Cost.
Display the Customer Charge.
Pseudocode for the program is as follows:
Ask the user to input the crate ' s length. Ask the user to input the crate's width. Ask the user to input the crate ' s heigh t . calculate the crate's volume. Calculate the cost of building the crate . Calculate the customer's charge for the crate . Calcula~e
Display
~he
~he
profi~
made from
crate's volume .
~he
c ra~ e .
Display the Prolit Made.
3.13 Focus on Problem Solving: A Case Study
Display the cost of building the crate . Display the customer's charge for the crate . Display the profit made from the crate.
Calculations The following formulas will be used to calcula te the crate's volume, cost, charge, and profit: volume = length " width " height cOSt =volume" 0.23 charge:: volume " O.S profit = charge - COSt
The Program The last step is to expand the pseudocode into the final program, which Program 3-28.
IS
shown in
Program 3 -28
II II 3 II 4 II 1 2
5 6 7
,
This program is used by General Crates, Inc. to calculate the volume, cost, customer charge, and profit of a crate of any size. It calculates this data from user input, which consists of the dimensions of the crate. jinclude j include using namespace std;
6
10 11 12 13 14 15
16 i7 18
19 20
int main() {
double length, width, height, volume, cost, charge, profit;
The The The The The Th. II The
/I II /I II II II
crate's length crate ' s width crate ' s height volume of the crate cost to build the crate customer charge for the crate prof it made on the crate
II Set the desired output formatting for numbers. cout « setprecision(2) « fixed « showpoint;
21
22 23 24 25 26 27 28 29 30
/1 Prompt the user for the crate's length, width, and he ight cout « "Enter the dimensions of the crate (in fe et) : \n"; cout « "Length: n: cin » length; cout « "Width: "; cin » width; cout « "Height: " ; cin » he igh t;
(program continues)
139
140
Chapter 3
Expressions and Interactivity
Program )·28
(continued)
31
II calculate the crate's volume, the cost to produce it,
32
II the charge to the customer, and the profit.
33 34
volume
~
length * width * height ;
35
cost = volume * 0.23; charge = volume * 0.5:
36
profit
=
charge - cost;
37
38
II Display the calculated data .
39 40
cout cout cout cout cout
41 42 43 44
45
« « « «
"The volume of the crate is "i volume « " cubic feet . \n" ; "Cost to build: $" « cost « end!: "Charge to customer : $ " « charge « $" « profit « end l ;
endl;
« " Profit: return 0;
)
Program Output with Example Input Shown In Bold Enter the dimensions of the crate (in fee t ): Length: 10 [Enter] Width : 8 [Enter] Height: 4 [Enter]
The volume of the crate is 320.00 cubic feet. Cos t to build : $73 . 60 charge to c ustomer : $160.00 Profit: $86.40
Program Output with Different Example Input Shown In Bold Enter the dimensions of the crate ( in feet): Length: 12.5 [Enter] Width: 10.5 [Enter] Height : 8 [Enter] The volume of the crate is 1050.00 cubic feet . Cost to build : $241 . 50 Charge to customer: $525.00 Profit: $283.50
Introduction to File Input and Output CONCEPT: T his section discusses simple techniques [0 write input and output operations with files. The programs you have written so far require you to re-enter data each time the progr am runs. This is becaust: the data stored in RAM d isappears o nce the program stops r u nning or the computer is shut down. If a program is to retain data between the times it runs, it must have a way of saving it. Data is saved in a file, which is usually stored on a computer's disk. Once the data is saved in a file, it will remain there after the program stOps running. The data ca n then be retrieved and used at a later time.
3.14 Introduction to File Input and Output
There are always three steps thar must be taken when a file is used by a program! 1. The file must be opened. If the fi le does nor yet exist, opening it means creating it. 2. Data is then saved to the file, read from the file, or both. 3. When the program is finished using the file, the file must be closed.
When a program is actively working with data, the data is located in random-access memory, usually in variables. When data is written into a file, it is copied from the varia bles. This is illustrated in Figure 3-11.
Figure 3-11 Writing data to a file Variables X
[ 10 [ 25 [ 40 [
:~:_t
I
y
25
z
40 r---------~
Data is copied from variables into the fife.
When data is read from a file, it is copied from the file into variables. Figure 3-12 iIIustrares this.
Figure 3-12 Reading data from a tile Variables
x
G
y
@J
z
B
Data is copied from the file into variables.
Setting Up a Program for File Input/Output Just as cin and cout require the iostream fi le to be included in the program, C++ file access requires another header file. The file fstream contains all the declarations necessa ry for file operations. It is included with the following statement: 'include
The next step in setting up a program to perform file lfO is to define one or more file stream ob;ects. They are ca lled "stream " objects because a file can be thought of as a srceam of data. File stream o bj ects work very much like th e cin and oout objects. A stream of data may be sent to CQut, which ca uses values to be disp layed on [he screen.
141
142
Chapter 3 Expressions and lnteractivity
A stream of data may be read from the keyboard by cin, and stOred in variables. Likew ise, strea ms of da ta may be sent ro a file stream object, which writes the data to a file. Data th at is read from a fi le flows from a file st rea m object into other variables. The fstre1'l.m header fi\e defines the data types o f stream, ifstream, an d £s\;ream. Before a c++ program can work with a file, it must define an object of onc of these dara types.
The object will be "li nk ed" with an actu al file on the compu ter's disk, and the operati ons tha r may be performed on the fi le depend on which of these three data types you pick for the file stream object. Table 3-15Iis(5 and describes rhe file Stream data types.
Table 3-15 File Stream Data Typc of s t r eam
Descriprion Ou tput fi le strea m. Th is data type can be used to create file s and write data to them. With the of stream data type, data may only be copied from variables to the file, but not vice versa.
ifstream
Input file stream. T his daea type can be used to o pen existing files and read daea from them into memory. With the ifstream data type, data may on ly be copied from the file into va ria bles, not bm vice versa .
fstream
File stream. This data type can be used to cteate files, write data to them, a nd read data from them. With the fstream data type, data may be copied from variables into a file, or from a file into va ria bles .
O
NOTE: In this section we only discllss the of stream and i fstream types. The fstream type is covered in Chapter 12. ~--------------------~
Here are example statemenrs that define of stream and ifstream objects: of stream out pu tFile; ifstream inputFile The statements above defi ne the objects output File a nd inputFile. outputFile is of the of stream type, so data can be written to any file associated with it. inputF i le is of the i fst ream type, so data ca n be read from any fil e it is associated with.
Opening a File Before data can be written to or read from a file, the fi le must be opened . Outside of the c++ program, a file is identified by its name. Inside a C++ program, however, a fil e Stream
object identi fies a file. The object a nd the fil e na me are li nked when the file is opened. Files are opened through the open member fun ction of a file stream object. Assu me inputFile is an ifstream object, defined as: ifstream inputFile; For example, the following statement uses i nputFi le to open a file named customer.dat: input File . open("customer.dat"};
3.14 Introduction to File Input and Output
The argumenr to rhe open function in this sratement is the name of the fi le. T his links the file customer.dat with the stream object inputFile. Until inputFile is associated with anothe r fi le, any opera tions performed with it will be carried out on the file customer . dat. (Remember, ifstream objects can only perform input operations with files. This means data may only be read from the customer . dat file using the inputFile stream object. ) Often, when openi ng a file, you will need to specify its location as well as its name. For exam· pie, on a Windows system the follow ing statement opens the fi le c : \data \inventory. dat: ollt putFile . open ("C : \ \data \ \i nventory .dat" ) In this statemem, the file c : \data\inventory.dat is opened and linked with output File. ~ NOTE: Notice t he use of two backslashes in the file's path. As men tioned before in this ~L-_t_'__ x t,_t_w_o__b_a_c_k_'I_'_'_h_, , __"_" __ n_" _d_,_d__tO__t,_p_t_,_,_e_n_ t _o_n_, _b_"_c_k_,_I,_,_h_;_n_,__, _t,_;n_g__I;_t,_t_,_I_. ________--'
You may also use a character array as an argument to the open function. For example, the following program segment defines an ifstream object and a 20·element character array. The user is asked to cnter the name of the file, which is passed to the open function. i f stream inputF:ilej char' fileName [2'0 I ; cou t « "Enter l~he
name of the file : cin » filenamel; inputFile . open dfileName) i
" j
The previolls examples have shown you how ro define a file stream object and then use the open member funcrion lto open a file. It is possible to define a file stream object and open a file in one statement. Jicre is an example: if stream i nputF;ile ( "customer .dat" ) ; This statement defines an ifstream object named inputFile and opens the customer . dat
file.
Closing a File T he opposite of opening a file is closing it. Although a program's fi les are automatica ll y closed when the progrfm shu ts down, it is a good programmi ng practice to write statements that close them . Here are two reasons a program should cl ose files when it is fin ished using them: •
Most operating systems temporarily store data in a file buffer before it is weinen ro a file . A fi le buffer is a small "holding section" of memory that file- bound data is first written ro. When the buffer is filled, all the data stored there is written to the file. T his t~chnique improves the system's perfo rmance. Closing a fi le causes any unsaved data that may still be held in a buffer to be saved to its file. T his means the dat~ will be in [he file if you need to read it later in the same program.
143
Chapter 3 Expressions and Interactivity
144
•
Some operating systems limit the number of files that may be open at one time. When a program closes fil es that are no longer being used, it will n Ot deplete more of the operating system's resources than necessa ry.
Calling the file strea m object's close member funct ion closes a fi le. Here is an example: QutputFile.close();
Writing Data to a File You alread y know how to use t he strea m insertion operator «<) w ith the cout o bject to
write data to t he screen . It can a lso be used with fil e stream objects to write data to a file.
Assuming outputFile is a file stream object, the fo llowing statement demonstrates using the « operator £0 write a string to a file: outputFile «
"I love c+ + programming";
This statement writes (he string " I love C++ programming" ro (he fi le assoc ia ted with o utputFi l e . As you ca n see, the stateme nt looks like a cout statement, except the file strea m object name replaces couto H ere is a statement that writes both a suing a nd t he contem s of a variable to a file: Writing Data to a File
outputFile «
"Price: " «
price:
The statement above writes the strea m o f data ro outputFile exactl y as cout would write it to th e screen. Program 3-29 demonstrates openi ng a fil e, writing da ta to the fi le, and closing t he fi le. Progr am 3-29
1 2
3 4 5 6
,
II This program writes data to a file. ' include 'include using namespace std:
int main () (
8 9
of stre am outputF ile: output File .open( "demofile. txt" ) ;
10
11
cout «
" Now writing dat a to the file. \n" ;
,
12
II Write output File outputFile output File output File
13
"
15 16
"
great names to the file « "Bach\n" i « "Beethoven \n" : « "Mozart\n" ; « "Schubert\n" ;
18
19
II Close the file outputFile.c lose(); cout«"Oone . \n return 0 ;
20 21 22 23
h
}
;
3.14 Introduction to File Input and Output
Program Screen Output Now writing data to the file. Done. Output to File demo file . txt Bach Beethoven Mozart Schubert
Reading Data from a File The» operator nOt on ly reads user input from the cin object, but it can also read data from a file. Assuming inFile is a fi le stream object, the following statement shows the» operato r read ing data {rom the file into the variable name: inFile » in Program
name;
3 ~29,
,
the pIe demofile.txt was created and the following list of names was
stored there.
-
Bach
Beethoven Mozart Schubert
Reading Data
from a File
Program 3-30 demonso/ates the use of the» operator to read the names from the file and store them in a variablf
Program
3 ~ 30
1
II This program reads dtta from a file.
2
'include linclude using namespace std;
3 4 5 6
int main () { B ifstream inFile; 9 canst int SIZE = 81 ; 10 char name[SIZE]; 7
11
12 13
inFile.open("demofile.txt"); cout « "Reading dat~ from the file. \n\n";
14 15
inFile »
16
cout «
17
name; name « endl;,
II Read name 1 from the file
/1 Display name 1 (program continues)
145
Chapter 3 Expressions and lnteractivity
146
Program 3-30
,.
inFile »
18
24 25
2. 27 28 2. 30
e ndl;
II Read name 2 from the file II Display name 2
inFile » name; cout « name « endl;
II Read name 3 from the file II Display name 3
inFile »
II Read name 4 from the file II Display name 4
cout «
20 21 22 23
(continued)
cout «
name; name «
name; name
«
endl;
inFile.close() ; cout « "\nDone.\n"; return 0;
II Close t he file
)
Program Screen Output Reading data from the file . Bach
Beethoven Mozart Schubert
Done . Data is read from files in a seq uential man ner. When a file is first opened, the file stream object's read position is at the first byte of the file. The fi rst read operation extracts data starting at the first byte . As data is read, the file stream o bject's read position advances
through the file. When the :» operawr extracts data from a file, it expects to read pieces of dara that are sepa ra[ed by whirespace characters (spaces, tabs, Ot new lines). In Progtam 3-30, the following statement reads a stri ng from the fil e: inFile »
name;
In the statement above, the» operator extracts a string because name is a character array.
Figure 3-13 shows the fi rst 5 bytes in the file: Figure 3· 13 h
\n
The» operator w ill extract all of the cha racters up to the newline, so " Sach" is the first string read from the file. After "Bach" is extracted, the file stream object will be positioned
so the following read operation would extract the string "Beethoven." This procedure is followed until all fou r strings have been read from the flle. Sometimes, when a prog(am has a substantial amount of inpu t, it is preferable to read the input fcom a file instea d of the keyboard. For example, consider Program 3-3 1. It reads the length and width of five rectangles from a file and displays the area of each rectangle on the screen.
3.14 Introduction to File Input and Output
Program 3-31
1 2 3
4
I I This pr ogram reads
r~ctangle
dimensions from a file.
'include 'include using namespace stdi
5
6
7 8 9 10
i nt mai n ( ) {
ifstream inFilej lnt length , width, area; inFi1e. open ( "dimensi
11 12
13 14 15 16 17 18 19 20 21
22 23
24 25 26
27 28
29 30
II Process rectangle 1 inFile » length; inFile » width; a r ea = l ength * wi dtni cout « "Area of rec~angle 1: " «
area «
endl;
II Process rectangle 2 inFi1e » length; inFi le » width: area = length * width; c o ut « "Area of rectangle 2: " «
area «
endl;
II Process rectangle 3 inFile » length; inFile » width; area = length * width; cout « "Area of rectangle 3 : " «
area «
endl;
1/ Process rectangle 4 inFile » length; inFi le » width; area = length * width; cout « "Area of rec t angle 4: " «
area «
endl;
II Process rectangle 5 inFile » length: infile » width: area = length * widt~; cout « "Area of rec}angle 5: " «
area «
endl;
31
32 33 34
J5 36 37 38
39 40 41 42 43
II Close the file inFile . c1ose(); cout« "\nDone. \ n"; return 0;
44 45 46 47
48
}
147
148
Chapter 3
Expressions and Interact;vity
Before this program is executed, the fi le dimensions. txt must be created with a text editor (such as Windows Notepad) . H ere is an example of the file's contents: 10 2 5 7 18 9
6 20 8 3
Notice that the program first reads a value into length, and then reads a val ue into width. It then multiplies length by width to get the rectangle's area . $0, these file con-
tems specify [he followi ng dimensions: Rectangle
"
length
10, width = 2
Rectangle 2, length 5, width = 7 Rectangle 3, length 18, width = 9 Rectangle 4 , length = 6 , width = 20 Rectangle 5, l ength = 8, width = 3
The program's output follows,
Program 3-31 Program Output
Reading dimensions of 5 rectangles from the file. Area Area Area Area
of of of of
rectangle 20 rectangle 2, 35 rectangle 3, 162 rectangle 4, 120
"
Are. of rectangle 5, 24
Done.
Review Questions and Exercises Short Answer 1. Assuming (he array description is defined as follows: char description{ 4 0];
A) How many characters total can the array hold? B) What is the length of (he largest string that may be stored in the array? C) Will the following cin statement automatically stop reading input when the array
is filled? cin »
description;
2. Write a definition statement for a cha racter array la rge enough to hold any of the fol lowing strings: " Billy Bob's Pizza "
"Downtown Auto Supplies" "Betty Smith School of Architecture" "ABC Cabinet Company"
Review Questions and Exercises
3. Assllme the arra y name is defined as follows: char
name[2S] ;
A) Using a stream manipulatOr, write a cin Statement that will read a string into name, bllt will read no more cha racters than name can hold. B) Using the getline member function, write a cin statement that will read a string into name, but lwill read no more characters than name can hold. 4. Assume that the following varia bles are defined: int age; double pay; char section;
Write a single cin statement that will read input into each of these varia bles.
5. ~hat h~ader files r ust be included in the following program? ~nt
ma~n()
{
double cout « cout «
amou~t =
89 . 7; showpoint « fixe d; setJ (8) « amount «
endl;
return 0; 1
}
6. Write a definition statement for a character array named city. It should be large enough to hold a string 30 characters in length. 7. Assume the fo llow' ng preprocessor directive appears in a program: ,define SIZE 12
How will the prepfocessor rewrite the following lines? I
A)
* unitCost; B) cout« setJ(SIZE) « 98.7; I C) cout « SIZE; pr ice = SIZB
8. Complete the fo Uotng table by writing the value of each expression in the Value column,
I
Expression 28 I 4 - 2 6 + 12 * 2 - 8 4 + B * 2 6+17%3-2 2
+
22
l 1
*
(8 + 7)
Value
(9 -
•
2
1)
(16+7)%2-1 12/(10-6)
(19 - 3)
*
(2
2) I 4
149
150
Chapter 3 Expressions and Interactivity
9. Write C++ expressions for the following algebraic expressions: a = 12x
z=5x+14y+6k y = x
g=
,
h + 12 4k
c =
10. Assume a program has the following variable definitions;
iot units; float mass; double weight; and the fo llowing statement: weight
=
mass * units;
Which automatic data type conversion will take place?
A) mass is demoted to an iot, units remains an int, and the result of mass an into
1<
units is
B) units is promoted to a float, mass rema ins a float, and the result of mass
1<
units is a float.
C) units is promoted to a float , mass remains a float, and the resu lt of mass ... uni ts is a double.
11. Assume a program has the following variable definitions: int a, b = 2;
float c = 4.2;
and the following statement: a = b '" C;
What value will be stored in a? A) 8.4
B) 8 C) 0
D) None of the above 12. Assume that qty and salesReps are both integers. Use a type cast express ion to rewrite the follow ing statement so it will no longer perform integer division. unitsEach
= qty
/ salesRepsj
Review Questions and Exercises
13. Rewrite the following variable definition so the variable is a named constant. int rate:
14. Complete the following table by writing statements with combined assignment operators in the right-hand column. The statements shou ld be equivalent to the statements in the left-hand column. Statements with Assignment Operator
Statements with Combined Assignment Operator
x "" x + 5;
total = total + subtotal: dist '" dist / rep; ppl ppl" period: inv inv shrinkage; num '" num \ 2;
15. Write a multiple assignment statement that can be used instead of the following group of assignment statements: east
= 1:
west = 1;
north = Itol,lth -
1; 1;
16. Write a cout statement so the variable divSales is displayed in a field of 8 spaces) in fixed point notation, with a precision of 2 decimal places. The decimal point should always be displayed. 17. Write a cout statement so the variable totalAge is displayed in a field of 12 spaces, in fixed point notation, with a precision of 4 decimal places. 18. Write a cout statement so the variable population is displayed in a field of 12 spaces, left-justified, with a precision of 8 decimal places. The decimal point should always be displayed.
FIII-in-the-Blank 19. The _____ Iibraty function returns the cosine of an angle. 20. The
library function returns the sine of an angle.
21. The
library funct ion returns the tangent of an angle.
22. The
library function cecums the exponential function of a number.
23. The
library function returns the remainder of a floating point division.
24. The
library function returns the natural logarithm of a number.
25. The
library function returns the base-IO logarithm of a number.
26. The _____ Iibral"y function returns the value of a number raised to a power.
27. The _ _ _ _ library function returns the square roOt of a number. 28. The
file must be included in a program that uses the mathematical functions.
ISl
152
Chapter 3 Expressions and lnteractivity
Algorithm Workbench 29. A retai l store grants irs customers a maximum amount of credit. Each customer's available credit is his or her maximum amount of credit minus the amOullt uf credit used. Write a pseudocode algorithm for a program that asks for a custome r's maximum amOunt of credit and amount of credit used. The program should then display the customer's available credit. After you write the pseudocode algo rithm, convert it to a complete C++ program. 30. Write a pseudocode algorithm for a program that calculates the rota I of a retail sale. The program should ask for rhe amount of the sale and the sales tax rate. The sales rax rare should be entered as a floati ng-point number. For exampl~, if the sar~s tax rare is 6 percent, the user should ente r 0.06. The program should display the amounr of sales tax and the total of the sale. After you write the pseudocode algorithm, convert it to a complete C++ program.
Find the Errors Each of rhe following programs has some errors. Locate as many as yOll ca n. 31. using namespace std; int main () {
double number!, number2, sum: Cout « "Enter a number: "; Cin « number!; Cout « "Enter another number: ": Cin <:<: number2; numberl + number2 - sum; Cout "The Bum of the two numbers is " « return 0 ;
sum
)
32. 'include using namespace std; int main() {
iot numberl , number2; float quotient; cout « "Enter two numbers and I will divide\n": cout « "the first by the second for you.\nn; cin » numberl, number2; quotient = float<static_cast>(numberl) / number2; cout « quotient return 0; )
33. Hnclude ; using namespace std ; int maine) {
const int numberl, number2, product:
Review Questions and Exercises
cout « ~Enter two numbers and I will multiply\n cout « Mthem for you . \n M: cin » numberl » number2; product - numberl * number2; cout « product return 0; )
34. 'include ; using namespace std ; main int number!, number2; cout « "Enter two numbers and I will multiply\n" cout « "them by 50 for you . \n" cin » numberl » number2; number l =* 50; number2 =* 50; cout « numberl « « number2; return 0; M
M
)
35. 'include ; using namespace std , main {
double number, half; eout « "Enter a number and I will divide it\n" cout « "in half for you . \n" cin » number! ; half =/ 2;
cout « fixedpoint « return 0;
showpoint «
half «
endl;
)
36. finclude ; using names pace std ; int main() {
char name, go; cout « MEnter your name: "; ein » setw(20);
cin . getline » cout « ~Hi " « cout "Press the ein » go ;
return 0; )
name ; name « end!; key to end this progr.e.m.";
ENTER
H
;
153
154
Chapter 3 Expressions and Interactivity
Predict the Output What will each of the following programs display? (Some shou ld be hand traced, and require a calcularor.)
37. (Assume the user enters 38700. Use a calculator.) tinclude using names pace std : int main ( ) (
double salary, monthly :
cout « "What is your annual sal ary? ": cin » salary ; monthly - static_cast(salary) I 12; cout « ~You r monthly wages arc " « monthly « return 0; )
38. tinclude using namespace std; int main{) (
lon g x, y, Z;
x ,. y ,. Z : 4; x += 2: y -= 1; z *- 3: cout « x « " return 0;
H
«
y «
• " «
z «
endl;
)
39. 'include using namespace std :
'defi ne WHO "Columbus " 'define DI D "sailed" 'define WHAT "the ocean blue . " iot main() {
canst int WHEN = 1492; cout « "In " « WHEN«
« DID « return 0;
.... «
.. « WHO « WHAT « endl;
}
40. (Assume the user enters George Washington .) 'include 'include using namespace std; int main( 1
" ..
endl;
Review Questions and Exercises
const in SIZE - 20; char userlnput[SIZE]i cout « "What is your narne? "; cin » setw(SIZE) » userlnput; cout « MHello .. « userInput « return 0:
endl;
}
41 . (Ass ume the user enters George Washington. ) tinclude 'include using namespace std; int main() {
canst in SIZE = 20: char userlnput{SIZE): cout « "What is your name ? ": cin.getline(uSerInput, SIZE): cout « "Hello " « userInput « return 0:
endl;
}
42. (Assume the user enters 36720152. Use a calculator.) 'include tinclude using namespace std; int main() {
long seconds; double minutes, hours, days, months, years: cout « "Enter the number of seconds that have\n": cout « "elapsed s ince some time in the past and\n": cout « "I will tell you how many minutes, hours, \n" ; cout « "days, months, and years have passed: .. ; cin » seconds i minu~es
-
seconds /
60;
hours = minutes / 60: days = hours / 24; years - days / 365: months = years * 12; cout « setprecision(4) « fixed « showpoint « right; cout « "Minutes: " « setw(6) « minutes « endl: cout « ·'Hours: ~ « setw( 6) « hours « endl; cout « "Days: " « setw{6) « days « endl ; cout "<"< "Monthe ; " <"< setw(6) « months « endl; cout « "Years; .. « setw(6) « years « endl: return 0: }
ISS
156
Chapter 3 Expressions and Interactivity
Programming Challenges 1. Miles per Gallon Write a program that calculates a car's gas mileage. The program should ask the user
to enter the number of gallons of gas the car can hold, and the number of miles it can be driven on a full tank. It should then display the number of miles that may be driven
per gallon 01 gas. 2. Stadium Seating
Solving the Stadium Scating Problem
There are three seati ng categories at a stadi um. For a softball game, Class A seats cost $15 , Class B seats cost $12, and Class C seats cost $9. Write a program that asks how many tickets for each class of seats were sold, then displays the amount of income generated from ticket sales. Format your dollar amount in fixed-point noration, with two decimal places of precision, and be sure the decimal point is always displayed.
3. Test Average Write a program that asks for five test scores. The program should calcu late the average test score and display it. The number displayed should be formatte d in fixed-point notation, with one dec ima l point of precision. 4. Average Rainfall
Write a program that calcu lates the average rainfall for three months. The program should ask the user to enter the name of each month, such as June or july, and the amount of rain (in inches) that fe ll each month. The program should display a message similar to the follow ing: The average rainfall for j une, j uly, and August is 6.72 inches. 5. Box Office
A movie theater on ly keeps a percentage of the revenue earned from ticket sales. The remainder goes to the mov ie distributor. Write a program that calculates a theater's gross and net box office profit for a night. The program should ask for the name of the movie, and how many adult and ch ild tickets were sold. (The price of an adult ticket is $6.00 and a chi ld's ticket is $3.00.) It shou ld display a report similar to Movie Name: Adult Tickets Sold:
Child Tickets Sold, Gross Box Office Profit: Net Box Office Profit: Amount Paid to Distributor;
"Wheels of Fury" 382 127 $ 2673.00 $ 534.60 $ 2138.40
~L-_N_O __T_E_'__A_ss_'_'m_ '__rh_,_ r_h_, _' _r '_r_k_' _' _PS__2_O_p_c_r,_c_fl_r_o_l _r_h__ , g_ro_s_s_b_o_x_o_ f_fi_,_,_p_ro _ fi_r_. __________~
6. How Many Widgets? The Yukon Widger Company manufactures widgets that weigh 9.2 pounds each. Write a program that calculates how many widgers are stacked on a pallet, based on the total weight of the pallet. The program shou ld ask the user how much the paller weighs by itself and with the widgets stacked on it. It should then calculate and display the number of widgets stacked on the pallet.
Review Questions and Exercises
7. How Many Calories? A bag of cookies holds 40 cookies. The calorie information on the bag claims that
there are 10 "servings" in the bag and rhat a serving equals 300 calories. Write a program that asks the user to inp ut how many cookies he or she actually ate and then reports how many total calories were consumed.
8. How Much Insuran ce?
Ma ny fi nancia l experts advise that properry owners should insure their homes or buildings for at least 80 percent of the amount it would cost to replace the structure. Write a progra m that asks the user to enter the replacement cost of a building and rhen displays the minimum amount of insurance he or she sho uld buy for the property. 9. Automobil e Costs Write a program thar as ks the user to enter the monthly cOSts for the following expenses incurred from operating hi s or her automobile: loan payment, insurance, gas, oil, tires, and maintenance. The program should then display the cotal month ly cost of these expenses, and the total annual cost of these expenses.
10. Celsius to Fahrenheit Write a program that converts Celsius tem pera tu res to Fahrenheit temperatures. T he form ula is 9 F=-C+32
5
F is the Fahrenheit temperature and C is the Celsius temperature.
11. Currency Write a program that will convert U.S . dol lar amounts to Japa nese Yen and to Euros . To get the most up-to-date exc han ge rates, sea rch the Internet using the term "cu rrency exchange rare". Tf you cannot find the most recent exchange rares, use t he following:
1 Dollar = 113.22 Yen 1 Dollar:= 0.6936 Euros Format your currency amou nts in fixed-point notation, with precis ion, and be sure the decimal point is always displayed.
twO
decimal places of
12. Monthly Sales Tax A retail company mUSt file a monrhly sales tax report listing the sales fo r the month and the amount of sales tax collected. Write a program that asks for the month, the year, and the total amount collected at the cash register (that is, sales plus sales tax). Assume che stace sales tax is 4 percent and the county sales tax is 2 percent. If the total amo unt colkcttd is known and the tota l sa les tax is 6 percent, [he amOllnt of product sa les may be calcul ated as:
157
158
Chapter 3 Expressions and Interactivity
S is the product sales and T is the tOral income (product sales plus sales tax).
The program should display a report similar to Month: October Total Collected:
$ 26572.89
Sa les: County Sales Tax:
$ 25068.76 $ 501. 38 $ 1002 . 75
State Sales Tax: Total Sales Tax:
$
1504.13
13. Property Tax A counry collects property taxes on the assessment value of property, which is 60 percent of the property's actual value. If an acre of land is valued at $10,000, its assessment value is $6,000. The property [ax is then 64¢ for each S100 of the assessment value. The tax for the acre assessed at $6,000 will be $38.40. Write a program that asks for the actual value of a piece of property and displays the assessment value and property tax.
14. Senior Citizen Property Tax Madison County provides a $5,000 homeowner exemption for its senior citizens. For example, if a senior's house is va lued at $158,000 its assessed va lue would be $94,800, as explained above. However, he would only pay tax on $89,800. At last year's tax rate of $2.64 for each $100 of assessed va lue, the property tax would be $2,370.72. In addition to the tax break, senior citizens are allowed to pay their prop' erty tax in four equal payments. The quarterly payment due on this property would be $592.68. Write a program that asks the user to input the actual value of a piece of property and the current tax rate for each $100 of assessed value. The program should then calcu late and report how much annual property tax a senior homeowner will be charged for this property and what the quarterly tax bill will be. 15 . Math Tutor Write a program that can be used as a math tutor for a young student. The program shou ld display two random numbers to be added, such as
247 + 129
The program should then pause while the student works on the problem. When the student is ready to check the answer, he or she can press a key and the program will display the correct solution:
247 + 129
376 16. Interest Earned
Assuming there are no deposits other than the original investment, the balance in a savings account after one year may be calculated as Amount = principal
*
1 + R~te ) (
T
Review Questions and Exercises
Pri.ncipal is the balance in the savings account, Rate is the interest rate, and T is the number of times the interest is compounded during a yea r (T is 4 if the interest is compounded quarterly).
Write a program thac asks for che principal, the inrerest rare, and the number of times rhe interest is compounded. It should display a report similar to Interest Rate : Times Compounded: principal: Interest: Amount in savings :
4.25% 12 $ 1000 . 00 $ 43.34 $ 1043.34
17. Monthly Payments The monthly payment on a loan may be calculated by the following formula: Payment = Rate" (l+Ratet • L
,
«1 + Rate) - 1)
Rate is the monthly interest rate, which is the annual interest rate divided by 12. (12% annua l interest would be 1 percent monthly interest.) N is the number of payments and L is the amount of the loan. Write a program that asks for these values and displays a report simila r to Loan Amount: Monthly Interest Rate: Number of Payments; Monthly Payment : Amount Paid Back : Interest Paid:
$ 10000.00 l%
36
332.14 $ $ 11957 . 15 $ 1957.15
18. Pizza Pi Joe's Pizza Palace needs a program to calculate the number of slices a pizza of any size can be divided into. The program should perform the following steps: A) Ask the user for the diameter of the pizza in inches. B) Calculate the number of slices that may be taken from a pizza of that size.
C) Displa y a message telling the number of slices.
To calculate the number of slices that may be taken from the pizza, you muSt know the fo llowing facts: • • •
Each slice sho uld have an area of 14.125 inches. To calculate the number of slices, simply divide the area of the pizza by 14.125. The area of the pizza is calcu lated with this formula:
Area = 1t,-l
O
NOTE: 1t is the Greek letter pi. 3.14159 can be used as its va lue . The variable r is the
radius of {he pizza. Divide the diameter by 2 to get the radius. ~~~~~~~~~~~~~
159
160
Chapter 3 Expressions and Interactivity
Make sure the output of the program displays the number of slices in fixed point notation, rounded to one decimal pl ace of precision. Use a named constant for pi.
19. How Many Pizzas? Modify the program you wrote in Programming Challenge 18 (Pizza Pi) so that it repons the number of piz.z.as you need to buy for a party if e:Jch person nttending is expected (0 eat an average of four slices. The progra m should ask the user for the num ber o f people who will be at the party and for the diameter of the pizzas to be ordered. It should then calculate and display the number of pizzas to purchase.
20. Angle Calcu lator Write a program that asks the user for an angle, entered in radians. The program should then display the sine, cosi ne, and tangent of the angle. (Use the sin, cos, and tan library functions to determine these values.) The output should be displayed in fixed-point notation, rounded to fou r decima l places of precision. 21. Saving Numbers to a File For this assignment you will write two programs: Program 1
Program 2
Write a program thar asks the user to enter five numbers. Use a floating-point data type to hold the numbers. T he program should create a fil e and save all five numbers to the file. Write a program that opens the file crea ted by Program 1, reads the five numbers, and displa ys them. The program should also calculate and disp lay the sum of the fi ve numbers.
22. Monthly Sales Tax Modification Modify the program you wrote for Programmi ng Challenge 12 (Month ly Sales Tax) so it writes its outpllt to a file instead of the screen. 23. Average Rainfall Modification Modify the program you wrote for Programming Challenge 4 (Average Rainfall) so it reads its input from a fil e instead of the keyboard . 24. Stock Transaction Program Last Ill.ooth Joe purchased some stock in Acme Software, Inc. Here are the deta ils of the purchase: • • •
The number of shares that Joe purchased was 1,000. When J oe purchased the stock, he paid $32.87 per share. Joe paid his stock broker a comm ission tha t amounted to 2% of the amount he pa id for the srock.
Two weeks later Joe sold the stock. Here are the deta ils of the sale: • • •
The number of shares tha t Joe sold was 1,000. He sold the stock for $33.92 per share. He paid his stock broker another commiSSion that amounted amount he received for the stock.
to
2 % of the
Review Que!>tiom, and Exercises
Write a program that displays the foHow ing information: • • • • •
The amount of money Joe paid for the stock. The amount of commission Joe paid his broker when he bought the stock. The amount that Joe sold the stock for. The amount of commission Joe paid his broker when he sold the stock. Display the amount of profit that Joe made after selhng his stock and paying the two commissions to his broker. (If the amount of profit that your program displays is a negative number, then Joe lost money on the transaction.)
25. Word Game Write a program that plays a word game with the user. The program should ask the user to emer the following:
• • •
• •
• •
His at her name His or her age The name of a city The name of a college A profession A type of animal A pet's name
After the user has entered these items, the program should display the following Story, inserting the user's input into the appropriate locations; There once was a person named NAME who lived in CITro At the age of AGK, NAH£ went to college at COLLBOB. NAME graduated and went to work as a PRO'KSSION . Then, NAHB adopted a(n) ANIHAL named PKTNAHK. They both lived happily ever after !
Serendipity Booksellers Software Development ProJectPart 3 : A Problem-Solving Exercise 1. The Main Menu Modify the mainmenu . cpp program so it lets the user enter a choice from the menu. The choice will be a number in the range of 1 through 4, so it can be stored in either an int or char variable. 2. The Cashier Module You are ready to add some of the point-of-sale functionality to the project. Currently, the cashier . cpp program displays a simulated sa les slip without any sale information. Modify this program so that prior to displaying the simulated sales slip. it asks for the following data: • • • •
The date. Expect the user to enter a date in the form MMlDDfYY. This should be entered as a string and stored in a char array_ The quantity of the book being purchased. Store this number in an integer variable. The ISBN number of the book being purchased. The ISBN number is a string that contains numbers and hyphens . Use a char array to store it. The tide of the book. Store the book title in a char array.
161
Chapter 3
Expressions and lnteractivity
•
The unit price of the book. Store this number in a float variable.
Here is an example of what the screen might look lik e:
Serendipity Booksellers ' Ca$hier Module Date: 3/31/06 . Quantity of ~ook: 2 ISBN : 0-333·90123-8
.
Title~
History of Scotland
Prjc~:
19.95
Once this data is entered, the program should calculate the merchandise total (multiply quantity by price), and a 6 percent sales tax. The program shou ld then display the simulated sales slip. Here is an example:
Sere.ntlipity Booksellers Date: 3/31/06
.Qty ISBN
2
Title .
0-333-90123-8 History of Scotland Subtotal
Priclj
Total
$ 19.95 ' $' 39.90 . S 39.90
Tax
$ 2.39
Total
$ 42.29
. Thank You for Shopping at Serendipity!
The dollar amounts should all be displayed in fields of six spaces with two decimal places of precision. They should always be displayed in fixed-point notation and the ~ecimal point should always appear.
3. The Inventory Database Menu Modify the invrnenu. cpp program so it lets the user enter a choice from the menu. The choice will be a number in the range of 1 through 5, so it can be stored in either an int or char variable. 4. The Reports Menu
Modify [he reports .cpp program so it lees the user enter a choice from the menu. The choice will be a number in the range of 1 through 7, so it can be stored in either an int or char variable.
JO
o
Relational Operators
4 .1 4.2 4.3 4 .4 4 .5 4.6 4.7 4.8 49 4.10
4. 11
The i f Statement
Focus on Software Engineering: Validating User Input More About Variable Definitions
Flags Expanding the if Statement
4. 12
The if/else Statement
4.13 Com paring Strings 4.14 The Conditional Operator 4. 15 The switch Statement 4.16 Testing for File Open Errors
Nested i f Statements The if/else i f Statement Menus
and Scope
logical Operators Checking Numeric Ranges with Logical Operators
Relational Operators CON C EPT: Relational operators allow you lO compare numeri c and char values and determine whether onc is greater than, less than, equal to, or not equa l to a no ther.
So far, the programs you have wrinen follow this simple scheme: •
Gather input from the user.
• •
Perform one or more calcula tions. Disp lay the results on the screen.
Computers are good at perfo rming calcularions, bur they are also quite adept at compar' ing values to determine if one is greater than, less than, or equal to the other. These types 163
164
Chapter 4
Making Decisions
o f operations a re va luable fo r tasks such as examining sales figures, determining profit a nd loss, check ing a number to ensure it is within an acceptable range, and valida ting the inp ut given by a user. Numeric data is compared in C++ by using rel ational operatOrs. Each relational operaror determi nes whether a specific relations hip exists between tvlO values . Fo r exam ple, the greater-than operator (» determi nes if a value is grea ter than another, The equality operator (=:::) determ ines if two values are equal. Table 4-1 lists all o f C++'s relational operators.
Table 4 -1 Relational Operators
Meaning Greater than Less than Greater th an or equa l to Less tha n or equal to Equa l to Not equal to
1=
All of the relatio nal operators arc bina ry, w hich means they use two operands. H ere is an example of an exp ression using the greater-than operator: x > y
This expression is called a relational expression. It is used to determine whether x greater than y. The fo ll owing expression determines whether x is less than y :
IS
x < y
Table 4-2 shows examples of severa l relational expressions that compare the variables x and y. Table 4-2 Expression x > y x < y x >- y x <; ... y
x "'''' y x != y
~
What the Expression Mean s Is x greater than y ? Is x less than y? Is x greater than or equal to y?
Is x less than or equa l to y? Is x equa l to y? Is x not equal to y?
NOTE: All the relational operators have left-to-right associa tivity. Reca ll that
~ L._a,_,_o_c_ia_t_iv_i_tY__i'__th_e__o_,d_e_'_'_'n__w_h_ic_h__a_n_o_p_e_,_a_t_o_t _w_o_'_k_,_w __it_h_'_ ' ~__o_p_e_,a_n_d_,_,______________--"
The Value of a Relationship So, how are relational expressions used in a program ? Remember, all expressions have a value. Rela tional expressions are also known as Boolean expressiotts. which means their value can only be true o r false. If x is greater than y, the expression )( > y w ill be true, while the ex pression y == )( will be false.
4.1 Relational Operators
The == operator determines whether the operand on its left is equal to the operand on its right. If both operands have the same value, the expression is true. Assuming thar a is 4,
the follow ing expression is trlle: a --
4
But [he following is false: a
CD
::=
2
WA R N I NG! Notice the equality operator is twO = symbols together. Don't confuse this operatOr with the assignmem ope rator, which is one .. symbol. The -- operator determines
whether a variable is equal to another val ue, bur the .. ope rator assigns the value on the operator's right to the va riable on its left. T here will be more about this later in the cbapter. A coup le of the relational operators actua ll y test for tWO relationships. The >= operator dete rmines whether the operand on its left is greate r than or equa l to the ope rand on the right. Assuming tha t a is 4, b is 6, and c is 4, both of the fo llowing expressions arc true : b >= a a >- c
Bur the following is false: a >- 5
The <- operator determ ines whether the operand on its left is less than or equa l to the o perand on its righ t. Once agai n, assuming tbar a is 4, b is 6, and c is 4, both of the fol lowing expressions arc true: a <=
C
b <= 10
Bur the following is fa lse: b <= a
The last re lati onal operatO r is 1=, which is [he not-eq ual operator. It det ermines wh eth er the o perand on its left is not equa l ro the operand on its right, which is the opposite of the =- operator. As before, assum ing a is 4 , b is 6, a nd c is 4, both of the fo ll owing expresSIons are rrue : a 1"" b b !: c
T hese expressions are true because a is Il o t equal to band b is not equal to c. But the fol lowing expression is fa lse because a is equal to c: a
! ::
c
Table 4 -3 shows other re lationa l exp ressions and their true or false values.
165
Chapter 4
166
Table 4 -3
Making Decisions
(Assume X Is 10 and y is 7 .)
Expression )( <
Value
y
False, because x is nOt less than y.
x > y
True, because x is greater tha n y.
x >= y
True, because x is greater than or eq ual to y.
X <= Y
Fal se, because x is not less tha n or equa l to y. True, because y is not equal to x.
Y
! '" x
What Is Truth? The question "what is truth?" is one you would expect ro find in a phil osophy book, nOt a c ++ progra mming text. It's a good qu esti on for us to consider, though. If a relational expr ession can be either tru e o r false, how are t ho se values represented interna lly in a pro -
gram ? How does a computer store true in memory? How does it Stor e fa lse?
As you saw in Program 2-16, those two abstract states are converted to numbers. Tn C++, relational expressions represent true states with the number 1 and false states with the number O.
O L _N_O_T_E_:_ A_'_Y _O _"_W_i_Il_,_e_e_I_,_te_t_'_'n_th_i_,_c_h_,_p_te_,_,_I_i_,_n_o_t_t_h_e_o_n_l_y_v_,_I_"_e_,_eg_'_'_d_e_d_as_tr_u_e_,__~ To illustra te t his more fully, look a t Program 4-1.
Program 4-1 1 2 3 4 5 6
II This program displ ays the values of true and false states. 'include using namespace std; int main () {
7
bool trueValue, falseVa l ue; = 10;
a
int x - 5, Y
9
10 11
trueValue - x < y; falseValue y == x;
=
12 13
cout « "True is " « trueVa lue « endl ; cout « ., False is ~ « falseValue « end l ; return 0 ;
14
15
16
)
Program Output True is 1 False is 0
4.1 Relational Operators
Let's exa mine the statements contai ning the relational expressio ns, in lines 10 and I I , a little closer: truevalue = x < Y i falsevalue = y = = Xi These statements may seem odd because they are assigning the value of a comparison to a variable. In line 10 the variable trueValue is being assigned the result of x < y. Since x is less than y. the expression is true, and the variable trueValue is assigned the value 1. In line 11 the expression y == x is false, so the variable falseVa l ue is set to O. Table 4A shows examples of other statements usi ng rela ti onal expressions and their outcomes. NOTE : Relational expressions have a higher precedence than the assignment operator. In the statement z
=x
< y;
the expression x < y is evaluated fi rst. and then its value is assigned to z.
(Assume x is 10, y is 7, and z , a, and bare ints or boo Is)
Table 4 -4 Statement 2
=
x < y
cout « a
=x
cout « b
Outcome 2 is assigned 0 because x is not less than y.
=Y
Displays 1 because x is greater tha n y.
(x > Y) i
>= Yi
a is assigned 1 because x is greater than or equal to y.
(x <=
Displays 0 because x is not tess than or eq ual to y. b is assigned 1 because y is not equal to x.
Y)i
!= Xi
When writing Statements such as these, it sometimes helps to enclose the rela tiona l expression in parentheses, such as: trueValue = (x < y); falseValue - (y m_ xli As interesting as relational expressions are. we've only scratched the surface of how to use thern. In this chapter's remaining sections you will see how to get the most from relational expressions by using them in Statements that take action based on the results of the comparison.
~ Checkpoint 4.1
Assuming x is 5, Y is 6, and z is 8, indicate by circling the T or F whether each of the fo llowing relational expressions is true or false: A) x -- 5 T F B) 7 <:= (x + 2) T F C) 2 <4 T F D) (2 + x) !- y T F
E) z
!:= 4
T
F) x
>- 9
T
G) x
<:= (y
•
2)
T
F F F
\67
168
Chapter 4 Making Decisions
4.2
4.3
Indicate whether the following statements about relational expressions are correct or incorrect. A) x <=: y is the same as y > x . B)
x! ""
is the same as y >=
C)
x >= Y is the same as y
y
<=
X.
x.
Answer the following questions with a yes or no. A) If it is true that x > y and it is also trLle that x < Z I does that mean y < Z IS true? B) If it is true that x >= y and it is also tfue that z = = x, does that mean that z - - y is true? C) If it is true that x
z 4.4
!= y
! ..
Y a nd it is also true that x
!=
Z
f
does that mean that
is true?
What will the following program display?
#include usi ng names pace std ; int main {
()
int a
0, b "" 2, x = 4, Y
cout « cou t «
(a -- b) « endl; (a 1= y) « endl; (b <= X) « endl; (y > a) « end l ;
cout «
0;
cout « return 0; }
The i f Statement CONCEPT: T he if statemem can cause other sta temem s to execute only under certain condi tions.
You might think of the stateme nts in a procedural program as individual steps taken as
you are walking down a road. To reach the destination, you must sta rt at the beginning
-
The i f Statemem
and take each step, one after the other, until you reach the destination. The programs you have written so far are like a "path" of execution for the program to follow. The type of code in Figure 4-1 is called a sequence structure, because the statements are executed in sequence, without branching off in another direction. Programs often need more than one path of execution, however. Many algorithms rcquire a program to exeCutc
some statements only under certa in circumstances. This can be accomplished with a deci sion structure. In a decision structure's simplest form, a specific action is taken only when a specific condirion exists. If the condition does not exist, the action is not performed. The fl owchart in Figure 4-2 shows the logic of a decision structure. The diamond symbol represents a yeslno
4.2 The i f Statement
Figure 4-1
II A program to calculate the area of a rectangle Step 1
#include using namespace std;
a SteP. 2 , '
Step3
•
Ii
I
Step 4 •• ,
i
~ cout
SlepS
• Step 6 ,
int main() { double length, width, area ;
c~n
«
"Ente r the lengt h of t he rect angle : " ;
» l ength j
cout « "Enter the width of the rectangle : cin » width ; ... area = length '* width ;
~:~~r~\ ;The
area i, ; " «
area «
"j
eod 1
question or a truclfalse condition. If the answer ro the question is yes (or if [he condition is truc), the program flow follows one path, which leads to
1 Is il cold outside?
Yes
Wear a coat. No
In the flowchart, the action "Wear a coat" is performed only when it is cold outside. If it is nOt cold outside, the action is skipped. The action is conditionally executed because it is performed only when a certain condition (cold ou tside) exists. Figu re 4-3 shows a more elaborate fiowchort, where three octions ore taken only when it is cold outside. We perform memal tests like these every day. Here are some other examples;
If the car is low on gas, S[OP at a service station and get gas . H ir's raining ourside, go inside . If you're hungry, ger somerh ing to ear.
169
170
Chapter 4
Making Decisions
Figure 4-3
J Is it cold outside?
Yes
Wear a coat.
No Wear a hat.
Wear gloves.
One way to code a decision structure in C++ is with the if statement. Here is the general fo rmat of the i f statement: if (expression ) statement;
The i f statement is simple in the way it works: If the value of th e expression inside the parentheses is (rue, the ve ry next statement is execured. Otherwise, it is skipped . The statement is conditionally executed because it on ly execures under the condicion that the
expression in the parentheses is true. Program 4-2 shows an example of an if sta tement . T he user enters three test scores and the program calculates theif average. If the average is greater than 95, the program congratula tes the user on obca ining a high score. Program 4-2 1 2
II This program averages three test scores
3 4
'include usi ng names pace std ;
5 6
int main()
7
{
B 9
10
'include
int scorel, score2, score3 ;
double average;
II To hold three test scores II To hold the average score
4.2 The i f Statement
11 12 13 14
]5
16 17 18 19
20 2' 22
23
II Get the three test scores . cout « "Enter 3 test scores and! will average them : " : cin » scorel » score2 » score): II Calculate and display the average scor e . = (scorel + score2 + score3) I 3 .0 ; cout « fixed « showpoint « setprecision(l); cout « "Your average is " « average « end l ;
average
II If the average is greater than 95, congratulate the user . if (average> 95) cout « "Congratulations ! That's a high score!\n"; return 0 ;
" Program Output with Example Input Shown in Bold Enter 3 test scores and I will average them: 809070 (Enter] Your average is 80 .0 Program Output with Different Example Input Shown in Bold
Enter) test scores and I will average them: 100 100 100 [Enter] Your average is 100 . 0 Congratulations ! That · s a high score!
Lines 2 '] and 22 ca use the congratulatory message to be primed: if (average> 95) cout « "congratulations! That'S a high score! \nn ;
T he cout statement in line 22 is executed only jf the average is greater than 95. If the average is not greater than 95, the cout statement is skipped. Figure 4-4 shows the logic of this i f statemcnr. Figure 4 -4
j average > 95
True Display "Congratulations!
False 1 _ _ _~T=h=a=t='s=a=h=;9==h_S_C_O_,_ e !"_-, I
Table 4-5 shows other examples of if staremenrs and their outcomes.
1 71
172
Chapter 4
Making Decisions
Table 4-5
Statement
Outcome
i f (hours> 40)
Assigns true to the boal variable overTime only when hours is greater than 40
overTime = true;
Displays the message "Invalid number" only
i t {value> 32)
cout «
"Invalid number\n" ;
when value is greater than 32 Mu ltiplies payRate by 2 only w hen overTime is equa l to true
if (overTime
true) payRate *= 2;
Be Careful with Semicolons Semicolons do not mark the end of a line, but the end of a complete C++ statement. T he if statement isn't complete withom the conditiona ll y executed statement tha r comes after it. So, you must not put a semicolon after the i f (expression) portion of an if statement. No semicolon goes here. if
(expreSSion) ~ stat e ment ;
~
Semicolon goes here.
If you inadvertently put a semicolon after the if part, the compiler will assume you are placi ng a null statement thete. The mdl statemeflt is an empty sta tement that does nothing. This wi ll premat urely terminate the i f statement, which disconnects it from the Statement that fo llows it. T he sra rement fo llowmg the i f will always execute, as shown in Program 4-3. Program 4-3 1 2 3
4 5 6 7 8 9 10 11
12 13
II This program demonstrates how a misplaced semicolon II prematurely terminate s an if statement.
'include using names pace std ; int main( ) {
int x
= 0,
y
= 10 ;
cout « "x is " « x « " and y is " « y « end!; if (x> y ); II Error! Misplaced semicolon cout « " x is great er t han y\ n" i I/This is always executed . return 0;
14 Program Output
X is 0 and y is 10 x is greater tha n y
4.2 The if Statement
Programming Style and the if Statement Even though i f statements usually span more than one line, they are technically one long statement. For in stance, the following if statements are identical except in style: if (a >= 100)
cout « "The number is out of range. \n" ; if (a >= 100) cout« "The number is out of range.\n";
In both the examples above, the com piler considers the i f part and the cout stacement as one unit, with a semicolon properly placed at the end. Indention and spacing are for the human readcrs of a program, nOt the compiler. Here are rwo important style rules you should adopt for writing i f sta tements: • •
The conditionall y executed Statement sho uld appear on the line after the if statement. The conditionally executed statement should bc indented o ne " level " from the if sta tement.
~ L-_N_O__T_E_:__ln__m __ o_'t_e_d_,_to_,_,_,_e_a_c_h_t_'m __e_y_o_u__p_tC_,_,_t_h_e_,_a_b_k_,_y_, _y_o_u_a_t_e_,_n_d_c_n_"_'n_8_0_n_e__I'_v_e_I.____-' By indenting the conditionally executed Statement you are causing it to stand out visually. This is so you can tell at a gla nce what parr of the program the i f Statement execlltes. Tbis is a standard way of writi ng if statements and is the method you should usc.
~
NOTE: Indentation and spacing are for the human readers of a program, not the compile r. Even though the cout statement following the i f sta tement in Program 4-3 is indented, the semicolon still renninates the if statement.
Comparing Floating-Point Numbers Because of the way that floating-point numbers are stored in memory, rounding errors sometimes occur. This is because some frac rional numbers cannOt be exactly represented using binary. So, you should be careful when using the equality operator (== ) to compare floating point Ollmbers. For example, Program 4-4 uses two double variables, a and b. Both variables are initialized to the value 1.5. Then, the value 0.0000000000000001 is added to a. This should make a's contents different than b's contents. Because of a roundoff error, however, the two variables are still the same. Program 4 -4
1 2 3
4
II This program demonstrates how floating - point II round-off errors can make equality operations unreliable . 'include using namespace std;
5 (program continues)
173
174
Chapter 4
Making Decisions
Program 4 -4 6 7
(continued)
int ma i n() {
8
double a
9
double b
~
1.5;
1/ a is 1. 5 . 1/ b is 1.5 .
1. 5 ;
10
a += 0 . 0000000000000001; i f ( a == b)
11
12
cout«
13
14
"Both a and b are the same . \n";
else cout «
15 16 17 18
1/ Add a little to a .
"a and b are not the same . \n" ;
return 0; }
Program Output
Bot h a and b are the same.
To prevent round-off errors from causing this type of problem) yOll should stick with greater-than and less-than comparison.s with floating-point numbers.
And Now Back to Truth Now that you've gonen your feet wet with relational expressions and i f statements, ler's look at the subject of truth again. You have seen that a relational expression has the value 1 when it is true and 0 when fa lse. In the world of the i f statement, however, the concept of truth is expa nded. 0 is still fa lse, but all values other than 0 are considered true. This means [hat any value, even a negative number, represe nts true as long as it is not o. J ust as in real life, trurh is a complicated thing. Here is a summary o f the rules you have seen so far: •
When a relational expression is true it has the value l.
• •
When a relational expression is false it has the value O. Any expression that has the value 0 is considered false by the i f statement. T his includes the bool value false, which is equivalent to O. Any expression that has any value other than 0 is considered true by the i f statement. T his includes [he bool value true, which is equivalent to 1-
•
The fact that the if statement considers any nonzero value as true opens many possibilities. Relational expressions are not rhe only conditions that may be tested. For example, the fo llowing is a legal i f statement in C++: if (value)
cout «
"It is True !";
The if statement a.bovc does n o t test ~ rebtion"l e)(pression, bur rathe r the co ntents of ~ variable. If tbe variab le, va lue, contains any number o ther than 0, rhe message "It is True ! " will be displayed . If value is set to 0, however, the cout statement will be
skipped. Here
IS
i f (x + y) cout «
another exa mple: "It is True!";
4.2 The i f Statement
175
a
In this statement the sum of x and y is tested like any other value in an i f statement: is false and <"III other v<"llucs arc true. You may also use rhe return value of function calls as con ditional expressions. Here is an example that uses the pow function: if
(pow(a, b» cout « "It is True!" i
This i f statement lIses the pow function to raise a to the power of b. If the result is anything other than 0, the cout statement is executed. Th is is a powerfu l programming technique that yo u will learn morc about in Chapter 6.
Don't Confuse ;; With ; Earlier yOLl saw a warning nOt to confuse the equality operator operator ("'), as in the follow ing statemen t: i f (x :::: 2)
cout «
(==)
with the assignment
IICaution here! "It is True!" j
T he statement above docs nor determine whether x is equal to 2, it assigns x the value 2! Furchermore, the cout sratemenr will always be executed because the expression x :::: 2 IS always true. T his occurs because the value of an assignment expressio n is rhe value being assigned to
the variable on the left side of the = operator. T hat means the value of the expression x:::: 2 is 2. Since 2 is a nonzero value, it represents a true condition. Program 4-5 is a version of Program 4-2 that anempts to test for a perfect average of 100. T he"" operator, however, was mistakenly used in (he i f statement. Program 4 -5
2
3
4
, S
, 9 ]0
II This program averages 3 test scores . The if statement II uses the = operator, but the == operator was intended.
#include #include us i ng namespace std ; i nt main () {
int scorel, score2, score3; double average;
II To hold three test scores II TO hold the average scor e
11 l~
13 14 15
II Get the three test scores . cout « "En t er 3 test scores and I will average them : .. i cin » scorel » score2 » score3j
18
II Calculate and display the average score. average:::: (scorel + score2 + score3) I 3 . 0; cout « fixed « showpoint « setpreC is ion(l} i
1.9
cout «
16 17
"Your average is " «
averag .. «
end~;
20 (program continues)
Chapter 4
1 76
Making Decisions
Program 4 -5
(continued)
21
II Our intention is to congratulate the user
22 23 24 25 26
/1 for having a perfect score. But , this doesn't work. if (average = 100) II WRONG! This is an assignmentl cout « "Congratulations! That's a perfect score!\n"; return 0;
)
Program Output with Example Input Shown In Bold
Enter three test scores and I will average them: 809070 [Enter] Your average is 80.0 Congratulations! That's a perfect score !
Regardless of the average score, th is program will print the message congratulating the lIser on a perfeer score.
Flags CONCEPT: A fl ag is a Boolean or integer vari abl e that signal s when a condition exists. A {lag is typica lly a bool variab le rhat signals when some condition exists in the program .
When the flag variable is set ro false, ie indicates that the condition does nor yet exist. When the Aag variable is set
to
true, it means the condition does exist.
For example, suppose a program simi lar to the prev ious test averaging program has a bool variab le named highScor e, defined and initialized as shown here: bool hi ghscore = falsej When we define the variable, we initia lize it with false because we do not yet know if a high score has been ach ieved. Afrer the average score is calculated, we can use the following code to determine whether it is greater than 95. If it is, the highS core variable is set to true. if (average> 95) highscore = true; Later, the same program might use code similar to the followi ng to test variable, in o rder ro determine w hether a high score has been achieved. if
[h~
highscore
(highscore) cout « "Congratulations! That ' s a high score! ";
Integer Flags Integer variables mlly also be used as flags. This is because in C++ rhe vallie 0 is consiuered false, and any nonzero value is considered true. In a test averaging program we could define the highscore variable with the following statement: illt
highScore
=
0;
II 0 means false .
4.4 Expanding the i f Statement
A5 before, we initialize the variable with 0 because we do nOt yet know whether a high score has been achieved. Afrer the average score is calculated, we can use the follow ing code to determine whether it is greater than 95. [f it is, the highScore variable is set to a nonz.ero value. if (average> 95) highScore = 1;
II A nonzero value means true.
Later in the program we might use code similar to the following to rest the highScore variable, in order to determine whether a high score has been achieved. if (highScore) cout « "Congratulations ! That's a high score!" ; You will find flag variables useful in many circumstances, and we will come back to them in furure chapters. NOTE: Variables that are created inside a function, like main, are not automa tically initialized. If you need a va riable to start with a particular value, you should initialize it to that value.
Expanding the if Statement CONCEPT: T he i f statement can conditionally execute a block of statements enclosed in braces.
What jf you want an if statement co conditiona lly execute a group of statements, not just one line? For instance, what if the test averaging program needed to use several cout statements when a high score was reached? The answer is to enclose all of the conditionally executed statements inside a set of braces. Here is the format: if (expression) {
statement; statement; II place as many statements here as necessary. )
Program 4-6, another modificarion of the test-averaging program, demonstrates this type of if statement.
Program 4-6 1 2
3
4 5 6
II This program averages 3 test scores . II It demonstrates an if statement executing II a block of statements. Vinclude 'include using names pace stdi
7
(program continues)
1 77
178
Chapter 4 Making Decisions
Program 4-6 8 9
(con tinued)
intmain () {
10
iot scorel, score2, scoreJ;
11
double average;
12 13
II To hold three test scores II To hold the average score
II Get the three test scores. "Enter 3 test scores a nd I will average them : "; ein » scorel » score2 » score3 :
cout «
14 15 16 17
1/ Calculate and display the average score . average - (scorel + score2 + score3) I 3 .0;
18 19
20
CQut «
fixed «
cout «
"Your average is " «
showpoint «
setprecis i on(l) : average « endl;
21 22
/1 If the average is greater than 95, congratulate the user .
23 24
if (average> 95) { cout « cout« cout «
25 26
27 28
)
29
retur n 0;
30
"Congratulations! \n" ; "That's a high score.\n";
"You deserve a pat on the back!\n ";
)
Program Output with Example Input Shown in Bold
Enter 3 test scores and I will average them : 100 100 100 [Enter] Your average is 100.0
Congratulations! That's a hi~h score . You deserve a pat on the back! Program Output with Different Example Input Shown in Bold Enter 3 test scores and I will average them : 8090 70 [Enter]
Your average is 80.0
Program 4-6 prints a more elaborate message when the average score is greater than 95 . The if statement was expanded to execute three cout statements when highScore is set to true. Enclosing a group of state ments inside a set of braces creates a block of code. The if statement will execute all the statements in the block, in the order they appear, only when average is greater than 95. Otherwise, the block will be sk ipped. Notice all the statements inside the braces are indented. As before, this visually sepa rates the statements from lines that arc not indented, making it more obvious [hey are part of rhe if s tatement .
./'\
NOTE: Anytime your program has a block of code, all the sta temen ts inside the braces
~L-s_h_o_ul_d_b_e_i_nd_e_n_te_d_.________________________________________________-"
4.4 Expanding the i f Statement
Don't forget the Braces! If you inrend ro conditionally execure a block of sta temenrs with an i f statement, don 't forget rhe braces. Remember, withoUT a set of bnlces, the if sta tement only executes the very IIt::Xt blatcmcnt. Program 4-7 snQw<;; the rcst-averaging program with the braces inadvertently left out of the i f statement's block. Program 4 -7 t 2 3
4
, 5
7 8 9 10 11
II This program averages 3 test scores. The braces II were inadvertently left out of the if statement . 'include 'include using names pace std ;
int main () {
II To hold three test scores II To hold the average score
in t scorel, score2, score3; double average;
II Get the three test scores . cout « "Enter 3 test scores and I will a verage them : "; cin » scorel » score2 » score3;
12
13
14 15
II Calculate and display the average score . average - (scorel + score2 + score3) I 3 . 0; cout « fixed « showpoint « setprecision(l); cout « "Your average is " « average « endl;
16
17 18 19 20 21 22
II ERRORl This if statement is missing its braces I if (average> 95) cout « "Congratulations! \n" i cout « "That ' s a high score . \n"; cout « "You deserve Cl pat o n the back!\n" ; ret urn 0;
23
24 25
26
27
}
Program Output with Example Input Shown In Bold Enter 3 test scores and I will average them: 8090 70 [Enter] Your average i6 80
That's a high score . You dese rve a pat on the back!
The cout sratemenrs in lines 24 and 25 are always executed, even when average is nOt grea ter than 95. Beca use the braces have been removed, the i f statement only controls execu tion of line 23. This is illustrated in Figure 4-5. Figure 4-5 Only this statement is
conditionally executed. if
(average > cout
statements are .___cout « always executed. ~ CQut «
These
95)
/"
« "Congr at ul a t i on s! \n"; nThet' s a high score, \n n ; ""{au deserve 8. pat on the back! \n~ :
179
180
Chapter 4
~
Making Decisions
Checkpoint 4.5
TR UE or FALSE: Borh of [be followi ng if statements perform the same operation. if (sales> 10000) commissionRate - 0 . 15;
4.6
if (sales> 10000) commissionRate = 0.15; TRUE or FALSE: Both of the fo llowing i f statements perform the same opera tion. if (calls rate 1.(
4.7
*=
20) 0 .5;
~~
( L:c:ll is = 20) rate "'= 0 . 5;
Although the following code segments afe syntactically correct, each contains an error. Locare the error. A) if (hours> 40); cout «
hours «
" hours qualifies for o v ertime . \n" ;
B) balance = 1000; if (interestRate - . 07) cout « "This account
C) if (interestRate cout «
is e arning the maximum rate. \n" ;
> . 07)
"This account earns a $10 bonus.\n";
bala nce += 10 . 0 ;
4.8
Write an
4.9
Wri te an i t statement that multiplies payRate by 1.5 if hours is greater tha n 40.
4.10
if
statement that assigns 0 to x if y is equal to 20.
Write an i f statement that assigns .20 to commission if sales is greater than or
equa l to 10000.00. 4.11
Write an if statement that sets the variable set to true.
fers
to 50 if the flag variable max is
4,5 The if/else Statement
The if/else Statement CO Ne EPT: The if / else statement will execute one group of statements if the expression is rrue, or another group of statements jf th e expression is false. The if/els e statement is an expansio n of the i f statement. H ere is its format: if
(expression )
statement Or block else statement or block
The if/ .. l. "e Statement
As with the i f statement, an expression is eva lu ated. If the expression is true, a !Srart:melll or block of statements is executed. If the expression is false, however, a separate group of statements LS execu ted. Program 4·8 uses the if/else Statement a long with the modu lus o perator to determine if a nu mber is odd or even.
Program 4·8 1
2 3 4
// This program uses the modulus ope r ator to determine // if a numbe r is odd or eve n . If t he number is e venly divisible /1 by 2, it is an even number. A remainder indicates it is odd .
'include
5
using nomespace stdi
6 7
int mai n ()
a { int number ;
9
10
cout « "Enter an integer and I will tell YOll if it\n·' ; cout « His odd or even. " ; cin » number ; 0) i f (number 2 cout « number « is even.\n" ; else cout « number « is odd . \ n " i return 0;
11 12 13 14 15 16 17
18 19
, --
)
Program Output with Example Input Shown In Bold Enter an i nteger a nd I wil l t e ll you if it i 5 odd. or e ve n. 17 [Enter1 17 is odd .
The else part at the end of the if statement specifies a statement [ha t is to be executed when [he expression is false. When number' 2 does not equa l 0, a message is printed indicating the number is odd. Note that the program w ill onl y take one of the two paths in the if/else statcmenr. If you think of the statements in a co m puter program as steps taken
181
182
Chapter 4
Making Decisions
down a road, consider the if/else statcmenc as a fork in the road. Instea d of being a
momentary detour, like an if sta tement l the if/else statement causes program execution to follow aile of two exclusive parhs. The flowchart in Figure 4-6 shows the Jogic of this if/else statemenr. Figure 4-6
I True
, _ _ _ ~ nu mber % 2 == 0 Indicate that the
number is even.
Fa lse >-___ --, Indicate thallhe number is odd.
Norice rhe programming sryle used to construct rhe if/else statement. The word else is at the same level of indention as if. The statement whose execution is controlled by else is indented one level. This visually depicts the two paths of e.'(ecllrion that may be followed.
Like the if part, the else part control s a single sratcmen(. If you wish [0 control more rhan one statement with the else parr, cre:::lte :1 block by writing the lines inside :l set of braces. Program 4-9 shows this as a way of handling a classic programming problem: division by zero. Division by zero is mathematically impossible to perform and it normal ly causes a program to crash. This means the program will prematurely Stop run ning, sometimes with an error message. Program 4-9 shows a way to rest the vallie of a div isor before rhe division takes place. Program 4-9 1 2 3 4
5
II This program asks the user for two numbers, numl and num2. 1/ numl is divided by num2 and the result is displayed. II Before the division operatio n, however, num2 is tested II for the value O. If it contains 0, the division does not II take place. iinclude
6 7 8
using namespace std;
9
int main(}
to { 11
t2
double n uml , num2 , quotient;
4.5 The if/else Statement
13
1/ Get the first number.
l4
cout « "Enter a number : "; cin » nurnl;
15
I.
1/ Get the second number . cout « "Enter another number : "i cin » num2;
17
18 19 20 21
/1 If num2 is not zero, perform the division.
22
i f (num2 .. -
23
{
24
25
2.
cout « cout «
"Division by zero is not possible. \0"; "Please run the program again and enter\n" ;
cout «
"a number ot he r than zero. \0" i
27
}
28
else
29 30
{
quotient ~ nurol / num2: cout « "The quotient of " « numl « ~ divided by "; cout« num2 « " is " « quotient « ". \0 ";
31 32 33
34 35
0)
1 return 0 ; }
Program Output with Example Input Shown In Bold
(When the user enters 0 for num2) Enter a number: 10 [Enter] Enter another number : 0 [Enter] Division by zero is not pos sible . Please run the program again and enter a number other than zero .
The value of num2 is tested in line 22 before the division is performed. If the user enters 0, the lines controlled by the if part execute, displaying a message which indicates that the program cannot perform a division by zero. Orherwise, the else part takes control, which divides numl by num2 and displays the resul t.
~
Checkpoint 4.12
TRUE or FALSE: The following if/else statements cause the same output to display. A)
i f (x :> y)
cout «
"x is the greater.\n";
else
B)
cout « "x is not the greater.\n··; i f (y <- xl cout « "x is not the greater. \n";
else
cout «
"x is the greater.\n";
183
184
Chapter 4
Making Oecisions
4.13
Write an if/else statement that assigns l to x if y [s equal to 100. O therwise it should assign 0 to x .
4.14
Write an if/els e sraremenr thar assigns 0 . .10 to conunission unless sales IS greater than or equal to 50000.00, in which case it assigns 0.20 to commission.
4,15
Complete the following program skeleron so it computes the correcr sales cax. If the customer is an in-stare resident, taxRate should be set to .OS. If the customer is an oLit-of-state resident, taxRate should be set to O. iinc l ude
using names pace std i int main() {
double taxRate, saleAmount ; char residence;
cout « "Enter the amount of the sale: "; cin » saleAmount ; cout « "Enter I for in-state residence or 0 for out-of - \n" ; cout <::<:: ··stote : .. i cin . get(residence); II Write code here that assigns a to taxRate if residen~e II is set to '0' or .05 to taxRate i f residence is set II to 'I'
saleAmount +; saleAmount * taxRatei cout « "The tota l is " « saleAmount; return 0; )
Nested if Statements CONCEPT: To test more than one condition, an
if
statement can be nes ted in side
a nother if statement.
Sometimes an if statement must be nested inside another if statement. For example, consider a banking program thac determines whether a bank custome r qualifies for a specia l, low inrerest rate on a loan . To qualify, [wo conditions must exist: (1) the customer must be cu rren tly employed, and (2) the customer must have rece nrly graduated from college (in the past two years). Figure 4 -7 shows a flowc hart for an algorithm that could be used in such a program. If we follow the flow of execution in the flowchart, we see that th e expression employed ;:: ''i' is tested. If this expression is false, there is no need to perform furt her tests; we kno,"" th .. t the eUHorner docs not qualify (O( d lC s ped
expression is true, however, we nc:ed to test the second condition . This is done with a nested deCision structure rhar tests the expression recentGrad =::: 'Y'. If rhis expression
is true, then the customer qualifies for the special interest rate. If this expression is false, then the cuStomer docs nor qualify. Program 4-10 shows the code for the complete program.
4.6 Nested i f Statements
False
True limp/eyed = 'Y'
Display ·You must be employed 10 qualify." False
r()Ccn'GraCl _ 'Y'
Display ·You must have gradualed from ~lege in the past two years to qualify."
True
Display ' You quality tor the special interest rate ."
1 II This program demonstrates the nested if statement. 2 3
'include using names pace std;
4
5
int main()
6
{
7 8
char employed, recentGrad ;
II currently employed, y or II Recent graduate, Y or N
N
9
10 11
12 13 14
15 16 17 18 19
II I s the user employed and a recent graduate? cout « "Answel:" the f ollowing questions\n cout « "with either Y for Yes or "i cout « " N fOl:" No.\n"; H
;
cout «
"Are you employed? " ;
cin »
employed; cout « "Have you graduated from college .'; cout « "in the past t wo years? ,.; cin » recentGrad: (program continuel)
185
Chapter 4
186
Making Dec.isions
Program 4 · 10
(confinued)
II Determine the user's loan qualifications. i f (employed -- 'Y' )
20 21 22
{
i f (recentGrad == 'Y' ) IINested i f {
23 24
cout « COllt «
25 26 27 28
)
29
r eturn 0,
30
.
"You qualify for the special " , " interest rate.\n";
)
)
Program Output with Example Input Shown In Bold
Answer the following questions with either Y for Yes or N for No. Are yOll employed? Y [Enter]
Have you graduated from college in the past two years? Y (Enter) You qualify for the special interest rate. Pro gram Output with Diffe rent Example Input Shown In Bo ld Answer the following queetions
with e ith er Y for Yes or N for No. Are you employed? Y [Enter] Have you graduated from college in the past two years? N [Enter]
Look at the if statement that begins in line 21. It tests the expression employed == 'Y'. 1£ (his ex pression is true, {he if statement that begins in line 23 is executed. Otherwise rhe program jumps to the return statement in line 29 and the program ends.
Notice in the second sample execution of Program
4~ 1 0
chat the program output does not inform the user whether he or she Qualifies for rhe specia l interest rate. If the user enrer~ an 'N' (or any character other than 'Y') for employed or recentGrad , the program does not print a message lening the user know that he or she does not qualify. An else Statement should be able to remedy [his, as illustrated by Program 4-11.
Program 1
2 3 4 5 6 7
,
B
10 11 12 13 1<
15 16
4~ 11
II This program demonstrates the nested if statement . 'include using namespace std;
intmain() {
char employed, II Currently employed, Y or recentGrad; II Recent graduate, Y O~ N
N
II Is the user employed and a recent graduate? cout « "Answer the following questions \n " : cout « "with either Y for Yes or "; cout « "N for No . \n" i cout « "Are you employed? "i cin » employed; cout « "Have you graduated from college ";
4.6 Nested i f Statement5
17 18
cout «
cin »
"in the past two years? ";
recentGrad;
19
20 21
/1 Determine the user's loan qualifications . if (employed == 'Y') { if (recentGrad ~ ~ '~'J II Nested if
22 :':!J
24
{
25
cout «
"You qualify for the special H;
2.
cout «
.. i nterest rate. \n" ;
21
}
28 29
else II Not a recent grad , but employed (
30 31
32 33
cout « cout «
"You must have graduated from "; "college in the past two\n":
cout «
"years to qualify . \n" ;
)
"35
else II Not employed
36
(
37 38
)
.,
cout «
"You must be employed to qualify . \n" ;
return OJ
39
)
Program Output with Example Input Shown In Bold Answer the following questions
with either y for Yes or N for No . Are you employed? N [Enter] Have you graduated from college in the past two years? Y [Enter)
You must be employed to qualify. Program Output with Different Example Input Shown In Bold
Answer the following questions with either Y for Yes or N for No. Are you employed? Y [Enter] Have you graduated from college i n the past two years? N [Enter] You must have graduated from college in the past two years to qualify . Program Output with Different Example Input Shown In Bold
Answer the following questions with either Y for Yes or N for No. Are you employed? Y [Enter] Have you graduated from college in the past two years? Y [Enter] You qualify for the special interest rate.
In this version of {he program, borh if starements have else clauses rhac inform the user WllY he or she does not quahfy tor the specia\ interest rate.
187
188
Chapter 4
Making Decisions
Programming Style and Nested Decision Structures For readability and e:lsier debugging, it's important to use prope r alignme nt and indentation in a set of nested if sta tements. This makes it easier to see which actions a re performed by each parr of the decision struCture. For example, the fo llowi ng code is funcrionally eq ui valen t to lines 21 through 38 in Program 4-1 ! . Although thiS code is logically correct, it is very difficult to read, and would be very diflicult to debug because it is not properly indented .
if (employed == 'Y' ) {
it (recentGrad
==
' Y') /1 Nested if
DOll't wr 1 te code
{
cout «
cout «
qualify for the special "interest rate . \n "; " YO U
.. ;
li ke thi s!
)
else /I Not a rece nt grad, but employed {
cout « cout « cout «
"Yo u must
.
have graduated from " ,
"college in the pa st two\ n" i "years to qualify . \n" i
) )
else II Not employed {
cout «
"You must be employed to qualify.\n" i
)
Proper indenrarion and alignmem also makes it easier ro see whi ch if and else clauses belong together, as shown in Figure 4-8. Figure 4-8 if (employed .. - 'Y') {
1f (recentGrad "'''' ' Y') II Nested i f
r
ThiS 1f and else go together This
i t and else go IOge\her.
(
cout« cout «
"You qualify for the special ~ interest rate . \n~;
"i
)
~
else /1 Not 0 recent grad. but employed (
cout « cout « cout «
~you must have graduated from "; "college in the past t wo\n"; "years to qualify . \n";
)
else
II Not employed
cout «
"You must be employed to qUl.llify . \n";
4.6 Nested i f Statements
Testing a Series of Conditions In the prev ious example you saw how a program can lise nested decision structures ro test more than one condition. It is not uncommon for a program to have a series of conditions to test, and then perform an acrion depending on which condirion is true. One way to accomplish tllis is to have a decision scrucrure with numerotls other decision SfctlCrUres nested inside it. For example, co nsider the program presented in the following In the S"O/~ light section.
In the Spotlight: Multiple Nested Decision St ructures Dr. Sua rez teaches a lite rature class a nd uses the followi ng 10 poi n[grad ing scale for all of his exams: Test Score 90 and above
G rade
A
80-89
B
70-79 60-69 Below 60
C D F
He has asked you to write a · program thar. will all ow a student to enter a test score and then display the grade for tha t score. Here is the algorithm char you will use: Ask the user to enter a test score. Determine the grade in the following mal/ner: If the score is less than 60. thell the grade is F. Otherwise, jf the score is Jess than 70, then the grade is D. Otherwise, -if the score is less than 80, then the grade is C. Otherwise, if the score is less than 90, then the grade is B. Otherwise, the grade is A. You decide that the process of determining the grade will req uire several nested decisions structures, as shown in Figure 4-9. Program 4-12 shows the code for the complete program . The code for the nested decision structu res is in lines 17 through 45.
189
190
Chapter 4
Making Decisions
figure 4-9 Nested decision structure to determine a grade
False
score < 60
True
Display "Your
Fal.se
score
True
<70
False
score
True
<80 Display ·Your
False
score
True
grade is C.u
< 90 Display ~Your grade Is A.--
Program 4-12 1 II This program uses nested if/elsa statements to assign a 2 I / le~ter grade (1?-, 8, C, 0, or F) to ,a numeric test sco:r;-e. 3 'include
4' using names pace std; 5 6 int main() 7 { ~ int testScore ; II To hold a numeric
te~t
score
9
10
11 17 13
If Get cout « cout«
cin »
~he
numeric teat score.
"Enter your numeric test score and I will\n "; "t"ell you the lett er grad.a you earnedl "I testScarei
,14 I)eterm~ne
the letter grade "
1>
I f
16
if (testScore < 60)
17
(
,.
19 20
cout « ) el.se
"Your grade io F. \ n";
grade is
F.~
4.7 The if/else if Statement
21
{
i f (testScore < 70 )
22 23
{
cout «
2. 25 26
else
27
{
"Your grade is o. \n-";
}
2.
i f (testScore < ~o ) {
2' 30 31 32 33 3.
cout «
"Your" grade is c . \n";
}
else {
i f (testScore < '0)
35
{
36 3.7 3.
}
~.\n";
cout «
"Y.our grade is
cout «
"Your grade is A. \n ";
.'
else
3'
{
41
)
40
42 43 44
}
}
}
45 return 0,
'6
47
}
Program Output with bample Input Shown In Bold Enter your numeric test score and I will tell you the letter grade you earned: 78 [Enter] Your grade is C. Program Output with Different Example Input Shown In Bold
Enter your numeric test score and I will tell you the letter grade you earned: 84 [Enter] Your grade is B.
The if/else if Statement CONCEPT: The if /elsa i f statement tests a series of conditions. If is often simpler lO test a series of conditions with the if/else i f statement than with a set of nested if/else statements.
Even though llrogram 4-U is a simple example, the logic of the n~sted decision. structure i.s The if/else i f Slatement
fairly complex" In C++, and many other \anguages, you can a\ternatwe\y test a set\e~ of conditions using r he if/else if scatement. The if/else if statement makes eer.tam types of nested decision logic simpler to write. H ere is the genera l fo rmat of the i.f/else 1.f statement:
191
192
Chapter 4 Making Decisions
if (expreSSiOn_I) {
statement statement elc.
If express.i.on_ l is true these Sfme-
}
strllcture is ignored.
}
Otherwise, if expression _2 is trU8 these statements are executed, alld the rest of the stmctllre is igllored.
ments are executed, and the rest of (he
)
else i f lexpressioD_2) {
statemellt statement etc.
lnsert as malty else i t clauses as necessary
else {
statement
statement
etc.
}
These stalemellls arc executed If
nOlle of the expressions above are true.
)
When the statement exeClHCS, expression _1 is tested. 1£ exp ression _1 is true, the block of statements that immediately follows is executed, a nd the rest of the structure is ignored. If expression _1 is fa lse, however, the program jumps to [he very next else if clause and tests expression_2 . If it is true, the block of sta tements that immediate ly fo1lows is executed, and then the rest of rhe structure is ignored. T his process continues, from the top of the srructure to the bottom, until one of the expressions is found to be true. If none of the expressions are true, the last else clause ta kes over and the block of statements im mediately following it is exccllted. T he last else clause, which does not have an i f statement foiJowing it, is referred to as the trailing else. The trailing else is optional, but in most cases you will use it.
()
NOTE : T he general format shows braces surrounding each block of con ditionally executed statements. As wi th other forms of the if sta temen t, the braces a re required only when more than one statement is conditionally executed .
Progra m 4-13 shows an exampJe of the iflelse if statement. T his program IS a modification of Program 4-12, which appears in the previolls Til the Spotlight section. Program 4 - 13 1 II This progr a m uses an iflelse i f statement to assign a 2 II l etter grade (A, B, C, 0, or F) to a numeric test score .
3 'include 4 using namespace std; 5 6 int main() 7 ( 8 int testScore i
II To hold a numeric test score
4.7 The if! else if Statement
9 10 11
12
13
II Get the numeric test score . cout« "Enter your numeric test score and I will\n" ; cout« "tell you the letter grade you earned ; "; cin» testScore i
14
IS 16 17
18
19 20 21
22
23 24 25
// Determine the lette r grade . if (testScore < 60) cout « "Your grade is F . \n··; else i f (testScore < 70) cout « "Your grade is D. \n" i else if (testScore < 80) cout « "Your grade i s C . \n" ; else if (testScore < 90 I cout « "Your grade i s B . \n" i else cout « "Your grade is A . \n" i
26
27
return 0;
28 Program Output with Example Input Shown in Bold
Enter your numeric test score and I will tell you t he letter grade you earned : 78 [Enter1 Your grade is C . Program Output with Different Example Input Shown In Bold
Enter your numeric test score and I will tell you the letter grade you earned : 84 [Enter] Your grade i s a .
Let's an a lyze how [he if/else i f staCcrneIH in lines 16 thro ugh 25 works. Fi(st, the exp ression testScore < 60 is tesecd in line 16:
..
(testSco re < 60) cout « "Your grade is F. \ n " i else if (testScore < 70 ) cout « "Your grade is O . \n" ; else if (tes t Score < 80 I cout « "Your grade is C. \n" i else i f (testScore < 90 ) cout « "Your grade is B . \n "; if
else
cout «
"Your grade is A. \n" ;
If testScore is less [han 60, [he message "Your grade is
F . In" is displayed and [he rest of the if/else if statement IS skipped. H testScore is not less {han 60, the el.se clause in line] 8 la kes over and ca uses rile next if sratcmCI1l ro be executed:
it \te.tScore cout «
< GQ) grade i.s
"Your
"F . \n";
;
193
194
Chapter 4 Making Decisions
-+
e l se i f (testScore < 70) cout « "Your grade is D. \n";
else if (testScore < SO) cout « "Your grade is C.\n"i else i f (testScore < 90) cout « "Your grade is B. \n ",-
else cout « T he first
"Your grade is A. \n" ;
sraremenr handles a ll of the grades less than 60, so when this if sta tement executes, testScore will have a va lue o f 60 or greater. If testScore is less than 70, the message "Your grade is D. \n" is displayed and the rest of the if/else if statement if
is skipped. This chain of events continues umil one of the expressions is fo und to be true, or the last else clause at the end of the statement is encou ntered. Notice the alignment and indentation that is used with the if/else if statement: The starting i f clause, the else if clauses, and the tra iling e ls e clause are all aligned) and t he conditionally executed statements are indented.
Using the Trailing else To Catch Errors The tra iling else clause, which appears at the end of the if/else i f statement, is oprional, bu r in ma ny situa tions you w ill use it to catc h erro rs. For example, Prog ram 4-13 w ill assign the grade 'A' to any rest score that is 90 or greater. What if the highest possible test score is lOO? We ca n modify the code as shown in Program 4-14 so rbe trailing else clause catc hes any va lue greater than 100 and displays a n error message.
Program 4-14 1 II This program uses an iflelse if statement to assign a 2 II letter grade (A, a, C, 0, or F) to a numeric test score. 3 'include 4 using names pace std; 5
6 int main()
7 { 8 9 10
11 12 13
int testScore;
II To hold a numeric test score
II Get the numeric test score . cout « "Enter your numeric test score and I will\n"; cout « "tell you the letter grade you earned : "; cin » testScore:
14
15 16
17 18 19 20
21 22
23
II Determine the letter grade. if (testScore < 60) cout« "Your grade is P.\n"; else if (testScore < 70) cout « "You r grade is O. \n" j else if (teatScore < BO) couto « "Your grade is C. \n" ; else if (teatScora < 90) cout « .. '{our grade is B. \n " ;
4.8 Menus
else i f (testScore <~ 100) cout « "Your grade is 1\ . \n "; else cout« "We do not g ive scores higher than 100 . \ n";
24 25
26 2'
28
return 0 ;
29 30
Program Output with Example Input Shown In Bold Enter your numeric test score and I will tell you the latter grade you earned : 105 [Enter] we do not give scores higher than 100 .
The if/else i f Statement Compared to a Nested Decision Structure You never have to usc the if/else if statement because its logic can be coded with nested if/else statements. H owever, a long senes of nested if/ el s e statements has two particular disadvantages when you are debugging code: • •
The code can grow complex and become difficult to understand . Because indenting is important in nested statements, a long series of nested ifl else statements can become tOO long to be displayed on the com purer screen witllOllt horizont
The logic of an if/else i f sraremenr is usually easier to follow th an that o f a long series of nested if/else statements . And, because all of the clauses arc aligned in an i f /else i f statement, the lengths of the lines in the statement tend to be sho rter.
..... 4.8
Menus CONCEPT: You ca n use nested if / else statements or th e if/else if statement to crea le menu-driven programs. A mellu -driven program allows th e user to determine th e course of action by selecting it from a list of actions. A Illenu is a screen displayi ng a set of choices the user sciens from . For example, a program t ha t manages a ma il ing list might give yOll the followin g menu: 1. Add a name to the lise
2. Remove a name from the list. 3. Change a name in the \ist. 4. Print the list.
5. Qu it the program.
195
Chapter 4
196
Making Decisions
T he user se lects o ne of the o pera tions by emering its number, Emering 4, {o r example, ca uses rhe mailing lisr ro be printed , and entering 5 causes the program to ttld . Nested
if/else statements or an if/else if structure can be used to set up such a menu. After the user enters a num ber, th e program compares the number with the ava ilable selections and execu tes th e Stateme nts th at p erform that opera tion.
Program 4-15 calculates the charges for membership in a health dub . The club has three membership packages to choose from: sta ndard adult membership, chil d membership, and senior citizen membersh ip. The program presents a men u that allows the user to choose the desired package and then calcula tes the cost of the membership.
Program 4-15 1 2 3 4
// This program displays a menu and asks the user to make a // s e lection . An if/else i f statement determines which item // the user ha s chosen. 'include 5 'include 6 using namespace std ; 7 8 int ma in () 9 { 10 int choice; /1 Menu choice int months; // Number of months 11 double charges; II Monthly charge s 12 13
/1 Constan t s const doub le canst double canst double
14 15
16 17
lB 19
for membersh i p rates ADULT -
4 0 . 0;
SENIOR = 30.0; CHILD = 2 0 . 0j
// Display the menu and get a choic e . cout « "\t\tHea lth Club Membership Menu \n\n "; cout « "1. Standard Adult Membership\n"j cout « "2. Chi l d Membership\n"; cout« " 3 . Senior Citizen Membership\n "; c out« "4. Quit the program\n \nn j cout « "Enter your choice: " ; cin » choice;
20 21 22 23
24
25
26 27
// Set the numeric output formatting. cout « fixed « showpoint « setPrec i s ion(2);
28 29 30
31
II Respond to the user's menu sel ection .
32
i~
33
{
3. 39 40
1)
c out « "For how ma ny months? "; cin » months; charges = months * ADULT; cout « "The total charges $
34 35 37 3B
(choice
are
}
else i f ( c h o~c . e (
==
2)
"«
charges «
endl;
4.8 Menus
cout « "For how many months? "; cin » months;
41 42
43
charges
= months
44
cout «
"The total charges are $" «
* CHILD; charges «
endl;
charges «
endl;
4S
46
else if (choice
"
\
48
49 50 51
==
3)
cout « "For how many months? "; cin » months ; charges = months * SENIOR; cout « "The total charges are $" «
52
}
53 54
else if (choice
==
4)
(
cout«
55 56 57
"Program ending . \ n ";
)
else
"
{
59
cout «
"The valid choices are 1 through 4. Run the\n ,. ;
60
cout «
"program again and select one of those.\n" ;
61 62
63
return 0; }
Program Output with Example Input Shown In Bold
Health Club Membership Menu 1. 2. 3. 4.
Standard Adult Membership Child Membe rship Senior Citizen Membership Quit the Program
Enter your choice : 3 [Enter] For how many months? 6 [Enter] The total charges are $180.00
Notice that three double constants ADULT, CHILD, and SENIOR are defined in lines 15 through 17. These constants ho ld the monthly membership rates for adult, child, and senior ci tizen memberships. Also notice that the program lets the user know when an inval id cho ice IS made. If a number other tha n 1, 2, 3, or 4 is entered, an error message is printed. This is known as input validation.
~ Checkpoint 4,16
Program 4-14 asks the user for a numeric test score and displays the letter grade if the USCI:' enters a test score less than O. for t hat score, Modify;t so an e n'Of message is displayed
197
198
Chapter 4
4.17
Making Decisions
What will the following program display? linclude using namespace std; int main() (
int funny = 7 , serious funny
=
2
15;
serious \ 2 ;
i f (funny ! =
1)
{
funny = 0; serious'" 0 ; }
else if (funny
2)
(
funny'" 10; = 10;
serious )
else {
funny
1;
serious" 1; }
cout «
f unny «
"" «
serious «
endl;
return 0; }
4.18
The following program is lIsed in a bookstore to determ ine how ma ny discount coupons a customer gets. Complete The table {h ar appea rs after the program. fi nc l ud e
using names pace std ; i n t main() {
int nurnBooks, numcoupons; cout «
cin »
"How many books are being purchased? ";
numBooks ;
if (numBooks < 1) nurnCoupons = 0; else if (numBooks < 3)
numCoupons
=
1;
else if (numBooks < 5)
numCoupons
2 ,.
else
numcoupons '" 3 ; cout «
"The number of coupons to give is " « endl ; return 0; «
}
numCoupons
4.9 logical Operators
If fhe customer purchases rhis many books
Th is many coupons arc given.
1 2
3 4
5 10 Write nested if sta temenrs rhat perform rhe follow ing rcst: If amount 1 is grearer than 10 and amount2 is less rhan 100, display rhe grearer of (he [W Oo
4.19
4.9
-t
Logical Operators CONCEPT: Logical operators con nect two or morc relational expressions imo ODe or reverse the logic of an expression. In [he previous section you sa w how a program tests twO cond irions with twO i f statements. In this section yon will see how to use logical operarors ro combine two or more relational expressions into one. Table 4-6 lists C++'s logical operators .
Table 4-6 Operaror
/I
Meaning
Effect
AND
Connects two expressions into one. Borh expressions rhe overall expression to be true.
OR
Connects twO expresSIons into one. One or both expressions must be true for rhe overall expression ro be true. It is only necessary for one to be true, and if does not matter which.
NOT
The ! operator reverses the "truth " of an expression. It makes a true expression false, and a false expression rrue .
The
&&
mUSt
be tfue for
Operator
Th e && operator is known as rhe logical AND o perato r. It takes two expressio ns as oper· ands and creates an expression thar is tcue only when both su b-expressions arc true. H ere is an example of an if statement that uses the && operator:
if (temperature < 20 && minutes> 12) cout « "The temperature is in the danger zone."i In the statement above the twO rela tional expressions are combi ned into a single expression. The cout statement will only be execured if temperature is less [han 20 AND minutes is greatce than 12. If either relational test is false, the entire expression is false and the cout statement is not executed.
199
200
Chapter 4
Making Decisions
TIP: You muSt provide complete expressions on both sides of the && operator. For exa mple, the followi ng is not correct because the condition on the right side of the && operator is not a complete expression. temperature > 0 && < 100 The expression must be rewritten as
temperature > 0 && temperature < 1 00
Table 4+7 shows a (futh tab le for the && operator. The truth table lists all the possible combina tions of va lues th at two expressions may have, and the result ing va lue returned by the &&
operator connecting the two expressio ns .
Table 4-7 Expression true
&&
Value of Expression
false
fa ls e
false && true
to)
false (0) false (0) true (1)
false && false true && t r ue
As the tab le shows, both sub-expressions must be true for the true value.
&&
ope rator to ret urn a
NOTE: If the sub-expression on the left side of an && opera tor is false, the expression on the right si de will nOt be checked. Since the en tiLe expression is fa lse if only one of the subexpressions is fa lse, it wou ld waste CPU time to check the remain ing expression. This is ca lled short circuit evaluation, T he && opera[Qr can be used to sim plify programs that otherwise would lise nested if sta tements. Program 4-16 performs a similar opera tion as Program 4-11 , wh ich qualifies a bank cusromer for a special interest rate, Th is program uses a logical operator. Program 4-16 1 2 3
II This program demonstrates the finclude using names p ace std ;
&&
logical operator.
4
5 6 7 8
, 10 J.1 12 13
int main() { char employ ed , recentGrad;
II Currently employed, Y or N II Recent graduate, Y or N
II Is the user employed and a recent graduate? cout « " Answer the following questions'n"; cout « "with either Y for Yes or "; cout « "N f or No . \n" ;
4.9 logical Operators
cout « "Are you employed? H; cin » employed; cout « "Have you graduated from college "; cout « "in the past two years? "; cin » recentGracl ;
14 15 16 17 18
I'
20
/1 Determine the user ' s loan qualifications.
21
if (employed
22
{
cout « cout «
23 2. 25 26 27 28 2. 30
==
'Y')
"You qualify for the special " ; "interest rate . \n" ;
)
else {
cout « cout « cout «
31
32 33
'Y' && recentGrad
"You must be employed and have\n" ; "graduated from col l ege in the\n" i "past two years to qualify.\ n";
)
return 0 ; )
Program Output with Example Input Shown In Bold Answer the following questions
with either Y for Yes or N for No . Are you employed? Y [Enter] Have you graduated from college in the past two years? N [Enter]
You must be employed and have graduated from college in the past two years to qualify. Program Output with Example Input Shown In Bold Answer the following questions with either Y for Yes or N for No . Are you employed? N [Enter] Have y ou graduated from college in the past two years ? Y [Enter] You must be employed and have graduated from college in the past two years to qualify . Program Output with Example Input Shown In Bold Answer the following questions with either Y for Yes or N for No . Are you employed? Y [Enter] Have you graduated from college in the past two years? Y [Enter] You qualify for the special interest rate.
The message "You qualify for the special interest rate" is only displayed when both the expressions employed == 'Y' and recentGrad ..... 'Y' are (rue. If either of these iJ: false, the message "You must be employed a nd have Qraduated from col lege in the past two years to qualify . " is primed.
201
Chapter 4
20 2
~
V
Making Decisions
Although it is similar, Program 4-16 is nO{ the logical equivalent of Program 4-11. LF _o_,_'e_x_,_m_p_l_e,_P _r_o_g_ra_m_4_-_16_ d_o_cs_n_'t_d_i_sp_1_,_y_th_ c_m_e_ss_,_g_e_"_Y_o_u_m _us_t_b_e_e_m_p_l_o_yc_d_ro_q_u_._I_if_Y._"-, NOTE:
The
II
Operator
The \ \ operator is known as the logical OR operatOr. 1t takes two expressions ~s operands and crea tes a n expression tha t is {rue when either of the sub-exp ressions are true. Here is a n exam ple of an if Statement that uses tbe I I operator; if (temperature < 20
cout «
II
temperature> 100)
"The temper ature is in the danger zone. ";
The cout statement will be executed if temperature is less than 20 O R temperature is greater than 100. If either relational test is true, the entire expression is lwe and th e cout statement is executed. TIP : You mUSt provide complete expressions on both sides of the I I oper:nor. For examp le, the fo ll ow ing is not correct because the condition on the right side of the I I operator is not a comp lete expression . temperature <
a II
> 100
The expression must be rewn cten as temp erature < 0 II temperature> 100
Table 4-8 shows a truth table for the
I I operator.
Table 4-8 Expression
Va lue of (he Express io n
true 11 false fa l se 1 I true f alse II false t rue ! I true
tr ue (1) true ( 1 ) f alse (0) true (1)
All it ta kes fo r an O R expressio n to be true is for o ne o f rhe su b-ex pressions to be true. It doesn'r maner if the other su b-expression is false or true. NOTE : The I I o perator also perfor ms s hort circuit eval uation . If the sub-expressio n on rhe left side of a n ! I ope rator is true, the expression on the right side wi ll no r be checked . Si nce it's o n ly necessa ry for one o f rhe sllb-cxprcssions to be true, it wou ld waste CPU
rime to check rhe remaining expression. Program 4-17 performs diffe rent rests to q ua lify a person for:l loa n. Th is o ne deter.
mi nes if the customer earns at leas t $35,000 per year, or has been employed for mo re tha n five yea rs.
4.9 Logical Operators
Program 4 -17 1
II This program asks the user for annual income and
2
II the numbQr of years of employment at the current
3
II job. The
II
operator is used in an if statement that
4 II determines if the income is at least $35,000 or the time ~
6
9 10 11 1_
the job is more than 5 years . 'include using namespace std ; lion
int main() { double income; int years ;
II Annual income II Years at t he current job
1'
14 15 16
II Get the annual income cout « MWhat is your annual income? "; cin » income;
17
19 19 21 21
II Get the number of years at the current job . cout « "Ho.... many years have you ....orked at M « "your current job? M; cin » years ;
22 2~
25 26
,',
29
"3031
Determine the user's loan qualifications. if (income >- 35000 II years> 5) cout« Myou qualify . \n" : else II
cout « cout «
"You must earn at least $35,000 or have\n "; ., bee n employed for more than 5 years . \n" ;
return 0;
32
Program Output with Example Input Sho wn in Bold What is your annual income? 40000 [Enter] Ho.... many years have you worked at your current job? 2 [Enter] You qualify . Program Outpu t with Exa mple Input Shown in Bo ld What is your annual i ncome? 20000 [Enter] Ho.... many years have you worked at your current job? 7 [Ente r] You qualify. Program Output with Example Input Shown in Bold
what is your annual income? 10000 [Enter] How many years have you worked at your current job? :1 [Ente r] You must earn at least $35,000 or have been employed for more than 5 years . The message "You qualify\n . " is displayed when either or both the expressions income >35000 or years> 5 are true. If both of these are fa lse, rhe disqualifying message is p rimed.
20 3
204
Chapter 4
Making Decisions
The I Operator The! o perator performs a logical NOT operation. It ta kes a n ope rand a nd reverses irs truth or fa\sehood. In other words, Ii the expression is true, the! operator returns false, and if the expression is false, it remrns true. Here is an if statement using the ! operator: if {!(temperature > 100» cout « "You are below the maximum temperature . \n"; First, the expression (temperature> lOO) is tested to be true or false. T hen the! opcra -
cor is applied to that value. If the expression (temperature> 100) is true, the! operator returns false. If it is fa lse, the ! operator returns tf ue. In the example, it is equivalent to asking "is the temperature not greacer than 100?" ~
Table 4-9 shows a ([urh tab le fo r the! operator.
Table 4-9 Expression
Value of the Expression
!true
false
(0)
! false
true
(1)
Program 4-18 performs the same task as Program 4-1 7. The i f statement, however, uses the I operator to determine if the user does flot make at least $35,000 or has not been on the job more than five years. Program 4-18
1 2
3 4 5 6
/1 Th is program asks the user for his or her annual income and 1/ the number years the user been employed at the current 1/ job. The ! operator re verses the l09ic of the expression II in the i f le l se statement . ' i nclude using names pace std;
7 8
9 10 11
i nt main ( ) { double income; int years;
II Annual income II Years at the current job
12
13 14 15
16 17
18 19
20 21
22
/1 Get the annual income c out « "What is your annual income? " ; cin » income; II Get the number of years at the current job . cout « "How many years have you worked at " « ~your current job? "; cin » years;
II Determine the user's loan qual i f i cations.
4.9 Logical Operators
23 24 25
i f ( !( income >= 35000
II years> 5»
{
cout « cout «
26 27 28 29
"You must earn at least $35,000 or have\n"; "been employed for more than 5 years . \n";
)
else cout« return 0 ;
30 31
"You qualif y. \n";
)
The outpU t of Program 4-18 is the same as Program 4-17.
Precedence and Associativity of Logical Operators Table 4-10 shows the precedence of C++'s logical operators, from highest to lowest.
Table 4 -10 Logical Operators in Order of Precedence &&
II The! operator has a higher precedence than many of the C++ operators. To avoid an error, you shou ld always enclose its operand in pa rentheses unless you in tend to apply it to a var iable or a simp le expression with no other operators . For example, consider the following expressions: ! (x !x
;> 2) ;> 2
The first expression applies the I operator to the expression x ;> 2. It is asking "is x not greater than 2?" The second expression, however, applies the! operator to x only. lr is asking uis the logica l negation of x greater than 2?" Suppose x is sec to 5. Since 5 is nonze ro, it woul d be considered true, so the! operator would reverse it to fal se, which is O. The;> operator would then determine if 0 is greater than 2. To avoid a ca rasrrophe like th is, always use parentheses! The && and II operators rank lower in precedence than the relational operators, so precedence problems are less likely to occur. If you feel unsu re, however, it doesn't hun ro use pa rentheses anyway.
(a ;> b) && (x < y) == y) 11 (b > a)
(x
is the same as is the same as
a ;> b && x < y x==yllb;>a
The logical operaro rs have left-ro-rig hr associarivity. In rhe follOWing expression, a < b is evaluated before y """ z. a
205
206
Chapter 4
Making Decisions
In the followlllg expression, y == z is evaluated first, however, because the higher precedence than II . a < b
1I
y
==
&&
operator has
z && m > j
The expression is equiva lent ro (a
II
((y==z)
&&
(rn>j))
Checking Numeric Ranges with Logical Operators CO NC EPT: Logical operators arc effective for determining whether a number is in or
out of a range. When determining whether a number is inside a numeric range, it's best co usc the
&&
operator. For example) the following i f statement checks the value in x to determine whether it is in the range of 20 through 40: if
(x >=
20 &&
cout «
K
x «
<= 40)
" is in the acceptab l e range . \n";
The expression in the if statement will be true only when x is both greater than or equal to 20 AND less than or equal to 40. x mUSt be within the range of 20 through 40 for this expression to be true. When determining whether a number is outside a range, the II operator is best to use. The foHowing Statement determines whether x is outside rhe range of 20 to 40: if (x < 20
cout «
II
x > 40)
x «
" is outside the acceptable range . \n";
It's important nor to get the logIC of these logical operators confused. For example, the following i f statement would never test true: if (x < 20 && x > 40) cout « x « " is outside the acceptabl e range.\n";
Obviously, x cannot be less than 20 and at the same time greater than 40.
NOTE : C++ does nOt allow you to check numeric ranges with expressions sllch as 5 < x < 20 . Instead, you mUSt use a logical opera tor to connect two relational expressions, as previously discussed.
Checkpoint 4.20
What is the disadvantage of llsing the && logical operator In Program 4-16 instead
of the nested 4.21
if statement
in Program 4-11?
The following [[uth table shows various combinations of the values true and false connected by a logical operator. Complete the table by indicating jf [he resulr of such a cornbinarion is TRUE or FALSE.
4.11
Focu~
on Software Engi neering: Validating User Input
Logical Exp1:cssion
true true
&& &&
Result (true or fal se)
false true
false && true fa l se && false
II
true
false
true 11 true false II true fa l se II fa l se
!true !false Assume the variables a '" 2, b = 4, and c = 6. Indicate by ci rcli ng [he T or F if each of the following conditions is true or fa lse:
4.22
a == 4 6 <~ c
II
b > 2 a > 3 1 != b c 1= 3 a >= - 1 II a <= b ! (a > 2 )
4.23
""
T T T T
F
T
F
F F F
W rite an if statement that prints t he message "The n umber is va li d" if the vari-
able speed is within the range
a through 200.
W rite an if statement that prints t he message "The number is not va lid " if t he va riable speed is outside the range 0 through 200.
4.24
Focus on Software Engineering: Validating User Input CONCEPT: As long as the user of a program enters bad input, the program will produce bad oUtpUI. Programs should be written to filter out bad input. Perhaps the most famous saying of the computer world is "garbage in, garbage out.» The integrity of a program's output is only as good as its input, so you should try to make sure garbage docs not go into your programs. Input validation is the process of inspecting data given to a program by [he user and determ ining if it is va lid. A good program shou ld give clear instructions abou t the kind of input that is acceptable, and nOt assume the user has followed those instructions. Here are just a few examples of input validations performed by programs: •
• •
•
Numbers are checked to ensure they are within a ra nge of possible values. For example. there are 168 hOllrs in a week. It is not possible for a person to be at wo rk longer than 168 hours in one week. Values are checked for their "reasonableness." Although it might be possible for a person to be at work for 168 hours per week, it is nOt probable. Irerr!!; selected from ;:l menu or other sets of choices arc checked to ensure they are availabJe options. Vanables are checked for values that might cause problems, such as division by zero.
Program 4-19 is a modification of Program 4-13 , the test scoring program. It rejects any test score less than or greater [han 100 .
a
Z07
208
Chapter 4 Making Decisions
Program 4-19
! II This program uses an if/else if statement to assign a
2 II letter grade (A, B, C, OJ or F) to a numeric test score . 3 #include 4 using namespace std;
,
6 int main() 7 {
8
int testScore;
1/ To hold a numeric test score
9
10 11
If Get coot«
12
cout« "tell you the le tter grade you earned : "; cin» testScore ;
13
the numeric test score . "Enter your numeric test score and I will\n";
14
15
if (tes tScore < 0
16 l' 18 19
{
cout «
2
}
22
e lse
23
{
,. 25
27 28
29
30 31 32
33
3. 3' 3. 37
testScore > 100) //Input validation
II An invalid score was entered. cout « testScore « " is an invalid score. \n"; cout « "Run the program again and enter a value\n";
20
2.
II
"in the range of 0 to 100 .\n";
1/ Determine the let ter grade . if (testSco~e < 60) cout « "You~ grade is F.\n" , else if (testScore < 70 ) cout « "You~ grade is O. \n", else i f (testScore < 80 ) cout « "Your grade is C. \n"; else if (testscore < 90) cout « "Your g~ade is B. \ n"; else i f (testScore <: 100) cout « "Your grade is A.\n";
re turn 0,
3!! }
Program Output with Example Input Shown in Bold
Enter your test score and I will tell you the letter grade you earned: - 12 [Enter] - 12 is an invalid score . Run the program again and enter a value in the range of 0 to 100. Program Output with Example Input Shown In Bold
Enter your test score and I will tell you the letter grade you earned : 81 [Enter] Your grade is B
4.12 M ore About Variable Definitions and Sc.ope
More About Variable Definitions and Scope CONCEPT; The scope of a varjable is lim ired
to
rhe block in which it;s defined .
c++ allows you to create variables almost anywhere in a program. Program 4-20 is a modification of Program 4-17, which determines if the user qualifies for a loan . T he definitions of the variables income and years have been moved to late r points in the program.
Program 4 -20 1
2 3
II This prog ram demonstrates late variable definition iinclude using namespace std ;
4
5 6 7
int ma in() { 1/ Get the annua l income . cout « ·'What i s your annual income? ";
8
9
double income: cin »
10 11 12
II Variable de fi nition
income;
/1 Get the number of years a t the current job. cout « "How many years have you worked at " « "your current job? "; int years ; 1/ variable definition cin » years;
13 14 15 16 17
II Determine the user's l oan quali fica t i ons. if (income >= 35000 I I years> 5) cout« "You qualify.\n··; else
18 19 20 21
"
{
23 24 25 26
27
cout « cout «
"You must ear n at least $35 ,000 or have\n"; "been employed for more than 5 years . \n";
)
return
Oi
}
It is a com mon practice to define a ll of a function's variables at the top of the function. Sometimes, especially in longer programs, it's a good idea to define variables near the part of the program wher e they arc used. Th is makes the purpose of the variable more evident. Reca ll fro m Chapter 2 that the scope o f a va riab le is defin ed as the part of the program where rhe variable may be used.
In Program 4-20, the scope of the income va riab le is the part of the program in lines 9 through 26. The scope of the years varia ble is the part of the program in lines 15 through 26. The variables income and years arc defined inside (unction main's braces. Variables defined inside a set of braces have local scope o r block scope. T hey may only be used in the pare of the program between their definition and the bl ock's closing brace.
209
210
Chapter 4 Makjng Decisions
You may define variables inside any block. For exa mple, look at Program 4-21. This version of the loan program has the variable years defined inside the block of the if statement. The scope of years is the part of the program in lines 17 through 26. ProgrAm
4~ 21
1 II This program demonstrates a 2
'include
3
using namespace std;
4 5 6
int main()
variable defined in
an inner
{
7 S 9
II Get the annual income. cout « ~What is your annual income? "; double income; /Ivariable definition
10
cin »
11 12
if (income >= 35000)
13 14
income;
( II Get the number of years at the current job.
>5
cout «
16
"your current job? "i lnt years; //variable definition cin » years;
"How many years have you worked at. "
«
17
18 19 20
if (years> S) cout « ftyou qualify. \n" ; else
21 22 23 24
(
cout « cout «
25
26
)
27 28
) else
29
(
"you must have been employed tor\n··; "more than S years to qualify.\n~i
30
cout «
'''tou must earn at least $35,000 to\n"i
31 32 33
cout «
"qualify. \n";
34
b~ock.
return 0: )
Notice the scope of years is only within the block where it is defined. The variable is not visible before its defin ition or after the closing brace of the block. This is true of any variable defined inside a set of braces. NOTE : When a program is running and it en ters the section of code that constitutes a
variable's scope, it is said that the variable comes into scope. This simply means the variable is now visible and the program may reference it. likewise, when a variable leaves scope, it may no longer be used.
4.12 More About Variable Definitions and Scope
Variables with the Same Name When a block is nested inside anorher block, a variable defined in rhe inner block may have the same name as a variable defined in the outer block. As long as the variable in the inner block is visible, however, the variable in the outer block will be hidden. This is illustrated by Program 4·22. Program 4-22 1
2 3
, 5 6 7 S 9 10 11 12
// This program uses two variables with the name number . 'include using names pace stdi
i nt main( 1 ( /1 Define a variable named number. int number ; cout « "Enter a number greater than 0: "j cin » number; if (number> 0) ( int number; II Another variable named number . cout « "Now enter another number : "; cin » number; cout « "The second number you entered was "; cout « number « endl;
13
"
15 16 17 lB 19
)
20 21 22
cout « "'lour first number was " « return 0;
number «
endl;
)
Program Output with Example Input Shown In Bold Enter a numbe r greater than 0: 2 [Enter] Now enter another number : 7 [Enter] The second number you entered was 7 Your first number was 2
Program 4 · 22 has twO separate variab les named number. The cin and cout statements in the inner block (belonging to the i f statement) can only work with the number variable defined in that block. As soon as the program leaves (hat block, (he inner number goes out of scope, reveal ing the outer number variable.
CD
WARN ING! Although it's perfectly acceptable to define variables inside nested blocks, you should avoid giving them the same names as va riables in the outer blocks. It's too easy
to conmse one variable wi.th another.
211
212
Chapter 4
Making Decisions
Checkpoint 4 .25
The following program skeleton asks the user for twO numbers and then multiplies them. T he first should be negative a nd the second should be posi tive. Write the inpLH va lidation code for both numbers . 'include
using namespace std ; lnt main() {
lnt first , second , result ; cout « "Enter a negative integer : " ; cin » first ; cout «
" Now enter a positive integer ; " ;
ci n » second ; II II Write input val i d a t i on code ff
result cout «
=
first * second ; first « " times " «
«
r es ult « return 0 ;
4.26
second «
" is "
endl ;
Find and fix the errors in the fo llowing program: 'include using names pace std; int main() {
cout «
"This program calculates t he area of a "
"rectangle . Enter t he leng t h : " ; cin » lengt h ; cout « "Enter the width : "j cin » width ; int length, width, area i area : length * width ; cout « "The area is " « area « e ndl ; retur n 0 ; «
}
4.27
What will the following program display if the lIser enters 40 for testl and 30 for test2? 'include using namespace std j int main (1 {
cout « "Enter your first test score , ". int testl ; ci n >::> test! ;
4.1 3 Comparing Strings
cout « "Enter your second test score: int test2; cin » test2 ; int sum = testl + test2: if (sum > 50)
"j
(
test! += 10; t est2 += 10; int sum = test l + test2; )
cout « "test l : " « cout « "test 2 : « cout « "sum « return 0 ;
testl « endl; test2 « endl; sum « endl j
)
Comparing Strings CONCEPT: You mu st use the strcmp library function to compare
C~strings.
The relational operators can be used to compare numbers, but not C-strings. Program 4-23 asks the user (Q enter two strings. stores them in arrays as C-strings, and incorrectly tries to compare them using the equality operator. Program 1
2 3 4 5 6
7 8 9
10
4~23
II This program illustrates that you cannot compare C- strings II with relational operators. Although it appears to test the II stri ngs for equality, that is NOT what happens. linclud e using names p ace std; intmain() ( const int SIZE = 40; char firs tString [SIZE J, secondString[SIZEl:
11
12
II Get two strings . cout « "Enter a string : M; ci n. getline(firstString, SIZE); cout « "Enter another string: " ; cin.getline (secondString, SIZE):
13
14
15 16 17 18
II Can you use the ~= ope rator to compare them? if (firstString == secondString) cout « "You e ntered the same st ri ng twice.\n"; else cout « "The strings are not the same. \n "; return OJ
19 20 21 22 23
24
)
(program output continues)
213
214
Chapter 4
Making Decisions
(continued)
Program Output with Example Input Shown In Bold Enter a s tring : Alfonso [Enter] Enter a nother s tring : Alf onso [Enter] The strings are not t he same .
Although (Wo identica l strings may be entered, the progra m will always report they are not the same. T his is beca use of the way c+ + ha ndles C-stri ngs. When you use the name of an array or a sm ng lireral, you are actually working with the memory address of the array or literal. In line 19, the follow in g statement is comparing the memory addresses of firstStri ng and secondString :
if (firstString
-= secondString)
Because the addresses of firstString and secondString are not the same (the two a rrays are not located in the same place in memory), the comparison will always be fa lse.
The strcmp Function In C++, C-string compansons are done with the library fu nction strcmp. To use the strcmp fu nction, you must include the cstring header file. H ere is the funct ion's genera l format: strcmp(stringl, string2) ; T he func tion compares the contents of s t ri ngl with the con tents of s t ring2 and returns one of the following va lues :
•
If the two stnngs are identica l, strcmp retums O.
•
If string! < string2, s t rcmp returns a nega tive number. If stringl > string2, strcmp returns a positive number.
•
In general, strcmp compares the ASCII codes of each character in the two strings. If it goes all the way through both strings find ing no cha racters different, it returns O. As soon as it fi nds twO co rrespond ing characte rs th at have diffe rent codes, however, it swps the compa rison. If the ASC II code for the character in string2 is highe r tha n the code in stringl, ir returns a negative number. But, if the code in string2 is lower than the code in stringl, a positive num ber is returned. H ere is the format of an if/e l se statement usi ng strcmp to determine if two strings are equa l: if (strcmp(stringl. string2) =~ 0 ) s t a t ement ; 1/ The strings a r e the same else statement; II The strings are NOT the same
TIP : It might help you to thi nk of strcmp as using inverted logic: If the twO strings arc equa l, strcmp returns false (zero). If the twO stri ngs are not equal, strcmp returns true (a nonzero va lue).
Program 4-23, which incorrectly rested two C-strings with a relarional operaror, can be correctly rewritten with the strcmp funct ion, as shown in Program 4-24.
4.13 Comparing Strings
Program 4-24 1 2
II This program correctly tests two C-strings for equality II with the strcmp function.
3
jinclude
4 5
tinc lude using names pace std:
6
7 8 9 10 11 12 13 14 15 16
int main() { canst int SIZE ~ 40; char firstStringlSIZEI, secondString(SIZE]:
II Get two strings cout « "Enter a string: "; cin . getline(firstString, SIZE): cout « "Enter another string: "; cin . getline(secondString, SIZE):
17 18
II Compare them with strcmp.
19 20 21 22 23
if (strcmp(firstString, secondString) ;: 0) cout « "You entered the same string twice. \n"; else cout « "The strings are not the same . \n" ; return 0;
24
}
Progra m Output with Example Input Shown In Bold Enter a string: Alfonso [Enter) Enter another string : Alfonso [Enter) You entered the same string twice .
The function strcmp is case-sensitive when it compa res t he two strings. If the user enters " Dog" and "dog" in Program 4·24, it w ill report they a re IlOt [he same. Most compilers provide nonstandard versions of strcmp that perform case-insensitive comparisons . For instance, Borland C++ has the stricmp function. It works identically to strcmp except the case of the characters is ignored. Program 4-25 is a more practical example of how strcmp can be used. It asks {he uset to enter the part number of [he stereo they w ish to purchase. The part number contains num bers, letters, and a hyphen, so it must be stored as a String. Once the user enters t he part number, the program d ispla ys the price of the stereo. Program 4-25
1 2 3 4 5 6 7
II This program uses strcmp to compare the string entered
1/ by the user with the valid stereo part numbers . 'include 'include tinclude using namespace std; (program continues)
215
216
Chapter 4
Making Decisions
(continued)
Program 4-25 8 9 10
lnt main{) {
canst double APRICE BPRICE
II 12 13 14
=
249.0, 1/ Price A II Price B /1 Array size II To hold the part number
= 299.0;
canst iot SIZE 9; char partNumISIZE};
16
II Get a part number from the user . cout « " The stereo part numbers are : \n";
17 IS 19 20
cout cout cout cout
15
« « «
21
"\tBoom Box, part number S147-29A\n"; "\tShelf Model, part number 5147-298\0"; "Enter the part number of the stereo you\n"; « "wish to purchase: "; cin.width{SIZE); II Restrict input for code safety .
22
cin »
partNum;
23
II Set the numeric output formatting . cout « fixed « showpoint « setprecision(2);
24
25 26 27 2B 29 30 31
endl; else if (strcmp(partNum, "5147-298") "',., 0) cout « "The price is $" « BPRIeE « endl;
32
else
33
cout « return 0;
/1 Determine and display the correct price . if (strcmp(partNum, "S147-29A") ""', 0) cout « "The price is $" « APRICE «
34 35
partNum «
" is not a valid part number . \ n";
}
Program Output with Example Input Shown in Bold The stereo part numbers are: Boom Box, part number S1 47-29A Shelf Model. part number S147-29B Enter the part number of the stereo you wish to purchase : S147-298 (Enter] The price is $299.00
Using ! with strcmp Some programmers prefer to use the logical NOT operaw( with strcmp when testing strings for equality. Because 0 is considered logically false, the! operator converts tha t value to true. The expression !strcmp(stringl, string2) will rerurn true when both
strings are the same, and false when they are different . The rwo following statements perform [he sa me operarion: if (strcmp(firstString, secondString) == 0) if (!strcmp(firstString, s econdString)
4.13 Comparing Strings
Sorting Strings Programs are frequenrly written to prinr alphabetically sorred lists of items. For example, cOr"lsider a department store computer system that keeps customers' names and addresses in a file. The names do nor appear in the file alphabetically, bur in the order the operator eluered them . If a list were to be printed in this order, it would be very difficult to locate any specific name. The list would have ro be soreed before it was printed .
Because strcmp's remrn value indicates which of the twO strings is higher on the ASCII chart, if can be used in programs thar sorr strings. Program 4-26 asks the user to enter two names. Then it prints the names alphabetically. Program 4 -26 1
2 3 4
5 6 7
8 9 10
II This program uses the return value of strcmp to alphabetically II sort two strings entered by the user.
iinclude 'include using namespace std; int main{) { const int SIZE = 30; char namel ( SIZE], name2!SIZEj i
11
12
II Ge t the first name . cout « "Enter a name (last name firs t) : "; cin . getline(namel, SIZE);
13
14 15
16
// Get the second name . cout « "Enter another name : "i cin.getline(name2, SIZE) ;
17 18 19
1/ Display them sorted in alphabetical order . cout « "Here are the names sorted alphabetically : \n"; if (strcmp(namel, narne2) < 0) cout « namel « endl « name2 « endl; else if (strcmp(name1 , narne2) > 0) cout « name2 « endl « namel « endl; else cout « "You entered the same name twi ce ! \n"; return 0;
20 21 22
23 24 25
26 27 28
"
}
Program Output with Example Input Shown In Bold Enter a name (last name first): Smith, Richard [EnterJ
Enter another name : Jones, John [Enter1 Here a re the names sorted alphabetically: Jones, John Smi th, Richard
2 17
218
Chapter 4
~
Making Decisions
Checkpoint 4.28
Indicate whether (he following strcmp func rion ca lls will rerurn 0, a negative number, or a positive number. Refer to the ASCII table in Appendix B if necessary. A) strcmp( "ABC", "abc"); B)
strcmp("J ill", "Jim" ) ;
C) strcmp ( "123", "ABC");
DJ 4.29
strcmp( "Sammy", "sally" 1;
Complete the if stateme ms in the fo llowing program skeleton. 'include 'include
using names pace std ; lnt main() {
const int SIZE -
20;
char iceC ream[SIZE); cout « cout «
"What flavor of ice cream do you like best? " ;
"Chocolate, Vanilla, or Pralines and Pecan? "; cin.getline(iceCr eam , SIZE): cout « "Here is the number of fat grams for a half "j cout « "cup serving:\n";
II II Finish the following if/else if statement II so the program will select the ice cream ente red II by the user . /! if (/ * insert your code here * /) cout « "Chocolate : 9 fat grams . \ n"; else if (/* insert your code here * 1 ) cout« "Vanilla: 10 fat grams.\n" ; else if (/* insert your code here * 1) cout « "Pralines & Pecan: 14 fat grams. \n"; else cout « "That's not one of our flavors!\n"; retu rn 0: }
The Conditional Operator CONCEPT: You can use th e conditional operator to create short expression s that work like if /e lse statements . The conditional operator is powerfu l and unique. It provides a shorthand method of expressing a simple if/e l se Statement. The operator consists of th e q uestion -mark (?) a nd the colon{:). Its format is: expression ? expression
expression;
4.14 The Conditional Operator
Here is an example of a statement using the conditional operator: x < 0 ? Y -
10 : z - 20;
The statement above is called a conditional expression and consists of three sub-expressions separated by the? and: symbols. The expressions are x < 0, y '" 10, and z = 20, as illustrated here: x < 0 ~
y =
?
10
z
=
20 ;
NOTE : Since it takes three operands. the conditional operator is considered a
~L-t_e_rn_a_ry __o_p_e_ra_t_o_,______________________________________________________-"
The conditional expression above performs the same operation as the fo llowing if/else statement: if(x
= 10;
else Z ..
20;
The part of the conditional expression thar comes before rhe question ma rk is the expression (0 be tested. It's like the expression in the parentheses of an i f statement. If the expression is true, the part of the statement between the? and the: is executed. Otherwise, the part after the: is executed. Figure 4-10 illustrates the roles played by the three sub-expressions. figure 4-10
3rd Expression: Executes if the 1st
1st Expression: Expression to
expression is false.
be tested.
"'-.x
< 0
Y =
?
10
/
z - 20;
2nd Expression : Executes if the 1st
expression is true.
If it helps, you ca n put parentheses around the sub-expressions, as in the following: (x < 0) ? (y
= 10)
: (z
= 20);
Using the Value of a Conditional Expression Remember, in C++ all expressions have a value, and this includes the conditional expression. If the first sub-expression is true, the value of the conditional expression is (he value of the second sub-expression. Otherwise it is the value of the third sub-expression. Here is an examp le of an assignment statement using the va lue of a conditional expression: a
~
x > 100 ? 0 : 1 ;
219
Chapter 4
220
Making Decisions
The value assigned to a will be either 0 or I , depending upon whether x is greater than
100. This statement could be expressed as the following if/else statement: if (x > 100) a : 0;
else
= 1;
a
Program 4-27 can be used (0 help a consultant calculate he r charges. Her ra re is $50.00 per hour. but her min imum charge is for five hou rs. The condirional opera tor is used in a statement that ensures the number of hours does not go below five. Program 4-27
1 2 3 4 5 6 7 a
,
II This program calculates a consultant's charges at $50 1/ per hour, for a minimum of 5 hours. The ? : operator 1/ adjusts hours to 5 if less than 5 hours were worked . 'include 'include using namespace std; intrnain() (
10 11
const double PAY RATE = 50 . 0 ; double hours, charges;
12
13
cout « "How many hours were worked? "; cin » hours ; hours = hours < 5 ? 5 : hours; //conditional operator charges = PAY_ RATE· hours; cout « fixed « showpoint « setprecision(2)i cout « "The charges are $" « charges « endl: return 0:
14 15 16 17
18
19 20
)
Program Output with Example Input Shown in Bold How many hours were worked? 10 [Enter]
The charges are $500.00 Program Output with Eumple Input Shown In Bold
How many hours were worked? 2 [Enter] The charges are $250 . 00
Here is the statement in line 15, with the conditiona l expression: hours
=
hours < 5 ? 5 : hours;
If the value in hours is less than 5, then 5 is stored in hours. Otherwise hours is assigned the value it already has. hours will not have a value less than 5 when it is used in the next starement, which calculares the consulranr's charges. As you can see, the cond itiona l operatOr gives you [he ability to pack decision. mak ing power into a concise line of code. With a little imagination it can be applied to many other programming problems. For instance, consider the following statement: cout
«
"Your grade is:
"
«
(score < 60 "' "Fail."
:
"Pass.");
4.14 The Conditional Operator
11 you wefe CO use an it/else staremenr, the statement above would be written as follows: if (score < 60 ) cout else
«
"Your grad e
cout « "Your grade
()
is ; F o i l . "i
is: Pass.
"
.,
NOTE: The parentheses are placed around the conditional expression because (he« operaror has higher precedence than the ?: operaror. Witham t he parentheses, juSt the value of the expression score < 60 would be sent to couto
Checkpoint 4.30
Rewrite the fo llowing if/else statements as conditional expressions:
A) if Ix > YI z ::: 1 i
e lse z
= 20i
B) i f (temp> 45)
population
= base
* 10 i
else popu l ation::: base * 2;
C)
if (hours ~ 40)
wages *: 1.5; else wo<;es *- 1;
D ) if (result >= 0) cout «
"The res ul t is positive\n";
cout «
"The result is negative. \ n":
else 4 .3 1
The followi ng statements use cond itional expressions. Rewrite eac h wi rh an if I
else statement.
=
k > 90 ? 57 : 12 ;
A)
j
B)
factor = x >= 10 ? Y
*
22 : y
*
35;
C) total += count == 1 ? s ales : count * sales; D ) cout« ((nurn % 2):,:: O)? "Even\n" : "Odd \n "):
4.3 2
What
will the fo llowing program display?
'include using name s pace std ;
int main( )
I
const int UPPER - a , LOWER: 2 ; int nurnl, num2, nurn3 '" 12, num4
= 3;
nurnl - nurn3 < num4 ? UPPER LOWER; num2 = num4 > UPPER ? nurn3 LOWER; cout « nurnl « " "« nurn2« endl: return 0; }
221
222
Chapter 4
Making Decisions
The switch Statement CONCEPT: T h e sw itch statement lets the va\uc of a vatiab\e or determine wh ere the prog ram will b ran ch.
eXpreSS-lOn
A branch occurs when one part of a program causes another part to execute. T he if/else i f statement allows your program co branch into one of several possible paths. It performs a series of tests (usually relational) and branches when one of these rests is true. T he swi tch staremcm is a similar mechan ism . lr, however, rests the va lue of an integer expression and then uses that value to determ ine which set of statemenrs to bra nch ro. Here is
the format of the switch statement: switch (IntegerExpression) {
case ConstantExpression : II place one o r more II statements here
case ConstantExpression : II place one or more II statements here
II case statements may be repeated as many II times as necessary default : 1/ place one or more II statements here
T he fi rst li ne of the statement Starts with the wo rd switch, followed by an integer exptession inside parentheses. This can be ei ther of the followi ng: • •
a variable of a ny of the integer da ta types (including char) an expression whose value is of any of the integer da ta types
O n the next line is the beginning of a block con taming several case statements. Each case statemenr is for ma tted in the following manner: cas e ConstantExpression : II p l ace one or mor e II statements here
After the word case is a constant expression (which must be of an integer type), followed by a colon. The constant expression may be an inrcger litera l or an integer named constant. The case statement marks the beginning of a section of statements. T he program branches to these statements jf the value of the switch express ion matches that of the case expressIOn.
CI)
WARN I N G I The expression of each case statement in the block must be unique.
4.15 The switch Statement
A
NOTE : The expression following the word case must be an integer literal or consrant. It
~L-_c_a_n_n_o_'_b_,_,__v'_r_i_a_b_I,_,_a_n_d_J_·r_c_'_n_n_o_'_b_,_,_n__,_x_p_f_"_'_io_n__,_"_c_h_'_'_X __<__2_ 2__0_f_n__'_~__5_0_.________J An optional default secrion comes after all the case sratements. The program branches to this section if none of the case expressions match the switch expression. So, it functions like a tra iling else in an iflelse if statement. Program 4-28 shows how a simple switch statemenr works,
Program 4-28 1
2
II The swi tch statement in this program tells the user something II he or she alre ady knows : the data just entered!
3 4 5
' i nclude using namespace std ;
6 7
i ntmain() (
8
char choice;
9
cout « "Enter A, B, or C : ": cin » choice: switch (Choice)
10 11
12 13 14
(
cout « break; case 'B' ; cout « break; case 'c' : cout « break; default : cout « case
IS 16 17
"
19
20 21 22 23
'A' :
"You entered A. \n"; "You entered B . \n"; "You entered C . \n"; "You
did not enter A, B, or C!\n";
}
return 0; )
Program Output with h .ample Input Shown in Bold Enter A, B, or C: B [Enter] You entered B , Program Output with Example Input Shown In Bold t;nter A, B , or C : F [Enter] You did not enter A, B, or C! The first case statement is case 'A' : . the second is case 'B' : , a nd the third is case 'C': . These statements mark where the program is to branch to if the variable choice contains the val ues 'A', 'B' 1 or . C' , (R emember, c ha racter variables and literals are considered integers. ) The default section is branched to if the user enters anything other
than A, B, or C,
223
224
Chapter 4 Making Decisions
Notice the break sta temen ts t hat are in t he case' A', case' B' . a nd case' C' sections. sw i tch (choice) {
case ' A' ;cout «
"You entered A . \n" ;
break; case '8' :cout «
•
bre ak; case 'C':cout « break ; d efault : COllt «
•
"You e ntered
B . \n";
"You entered C.\n";
•
"You did not enter A, B, or CJ\n"j
}
The case statements show rhe program where [Q start executing in the block and the break statements show rhe program where to stop. Without the break statements, the program would execute all of the lines from the marching case statement to the end of the block. NOTE : The default section (or [he last case section, if there is no default ) does nor
need a b reak statemen t. Some programmers prefer to put one there anyway, for consistency. Program 4-29 is a modi ficarion of Program 4-28, without the break sta[ements.
2
1
II The switch statement in this program tells the user something II he or she already knows: the data just entered !
3 4
'include using names pace std;
5
6
in t main()
7 8
{
,
char choice;
10 11 12
cout « "Enter A, B, or C: " ; cin » choice; II The fo llowi ng switch is 1/ missing its break statements ! switch (choice)
13 14 15 16 17
,.
(
19 20
}
21
return
22
case 'A' : case ' B' : case ' C ' : default ;
cou t cout cout cout
«
« «
«
"You entered A. \n" ; "You entered B. \ n"; '''iou entered C. \n "; '''iou did no t enter A, B, or C! \n";
o,.
)
Program Output with f:Xample Input Shown In Bold Enter A, B, or C: A [Enter] you ente red A. 'lou entered B. You entered C. You d id not enter A, B, or C!
4.15 The swi tch Statement
Program Output with Example Input Shown In Bold Enter A, a, or C: C [Enter] You entered C. You did not enter A, B, or C!
Without the break statement, the program "falls through" all of the Sta tements below the one with the marching case expression. Sometimes this is wha t you want. Program 4-30 lists the features of three TV models a CUStOmer may choose from. The Model 100 has remote comrol. The Model 200 has remote comrol and stereo sound. The Model 300 has remote control, stereo sound, and picture-in-a-picture capabiliry. The program uses a switch sta tement with carefully omitted breakS to print the features of the selected model. Progra m 4 -30 1
2 3 4
II This prog ram is carefully constructed to use the "fall through" II feature of the switch s tatement. 'include using namespace std ;
5
6 7 8 9 10 11
int main() {
int model Num ;
I I Model number
II Get a mod e l number from the user. cout « "Our TVs come in three models : \n"; cout « "The 100, 200, and 300. Which do you want? "; cin » modelNum ;
12 13
"15 16 17
II Display the model's features . cout « "That model has the following f eatures :\n " : switch (modelNum)
19
{
case 300 : cout « case 200 : cout « case 100 : cout « break; default : cout« cout «
19 20 21 22 23 24 25
26 27
"\ tPicture-in-a-picture. \n" ; " \tStereo sound . \0" i "\ tRemote control . \0" ;
"You can only choose the 100,": "200, or 300.\0";
return 0; }
Program Output with Example Input Shown In Bold Our TVs come in three models: The 100, 200, and 300. Which do you want? 100 [Enter]
That model has the following features : Remote contr91.
(program output continues)
22.
226
Chapter 4
Program 4·10
Making Decisions
(continued)
Program Output with Example Input Shown In Bold Our TVs come in" three models : The 100 , 200, a nd 300 . Which do you want? 200 [Enter]
That model has the following feature s : Stereo sound. Remote control . Program Output with Example Input Shown In Bold Our TVs come in three models : The 100, 200, and 300 . Whic h do you want? 300 [Enter]
That model has the following f eatures : Picture - in - a-picture. Stereo sound . Remote c ontrol. Program Output with Example Input Shown In Bold Our TVs come in three models : The 100, 200, and 300 . Which do you wan t? 500 [Enter]
That model has the following features : You can only choose t he 100, 200, or 300 .
Anothe r example of how useful this "fall through" capability can be is when you want the program to branch to the same set of statements for multiple case expressions. For insta nce, Program 4-31 asks the user to select a grade of pet food. The available choices are A. B. and C. The switch statement will recognize either upper or lowercase letters. Program 4 -31
1 2 3 4
II The switch statement i n this program uses t he "fall through" 1/ feature to catch both uppercase and l owercase letters entered II by the user. 'include
5
using namespace std ;
6 7
int main()
8
(
9
char feedGrade;
10 11 12
13 14
1/ Get the desired grade of feed. cout « "Our pet food is available in three grades:\n"; COllt « "A, B, and C . Which do you want pricing for? "; cin » feedGrade ;
15
16 17 18 19 20 21
II Disp lay the price . switch (£eedGrade) {
case 'a ': case 'A' ; COllt « break ;
"30 cents
per pound . \n"
i
4.15 The switch Statement
22
case ' b' :
23
case
2.
"20 cents per pound.\n";
break; case 'c' : case ' C': cout« break; default: cout«
25 26 27
28 29 30 31
'B': cout«
"15 cents per pound,\n";
"That is an invalid choice, \n" ;
return 0: }
Program Output with Example Input Shown In Bold
Our pet food is available in three grades: A, B, and C. which do you want pricing for? b [Enter] 20 cents per pound . Program Output with Examp le Input Shown In Bold
Our pet food is available in three grades: A, B, and C. Which do you want pricing for? B [Enter] 20 cents per pound,
When the user enters' a' the corresponding case has no statementS associated with it, so t he program falls through to the next case, which corresponds with
'A' .
case 'a': case
'A':
cout« break;
"30
cents per pound. \n";
The same technique is used for' b' and' c ' .
Uling switch in Menu Systems The switch statement is a natural mechanism for building menu systems. Recall that Program 4-15 gives a menu to select which hea lth club package the user wishes to purchase. The program uses iflelse if statements to determine which package the user has selected and displays the calcu lated charges . Program 4-32 is a modification of that program, using a switch statement instead of if/else i f ,
Program 4 -12 1 II This program displays a menu and asks the user to make a 2 II selection , A switch statement determines which item 3 II the user has chosen. 4 'incl ude 5 'include 6 using names pace std; 7
8 int main() 9 { (program continues)
227
228
Cha pter 4
Making Decisions
Program 4 <J2
(confinued)
II Menu choice
10
iot choice;
11
iot months;
1/ Number o f months
12
double charges ;
II Monthly charges
13
I' 15 16 17 18
1/ Constants for membership rates canst double ADULT ::: 40.0; const double SENIOR ,., 30 . 0 ; canst double CHI LD = 20.0;
19
II Display the menu a nd get a choice .
20 21 22 23
cout cou t cout cout
24
cout « "4 . Quit the Program\n\n" ; cout « " Enter your choice : "; cin » choi ce ;
2S
26
«
« « «
"\t\tHealth Club Membe rship Menu\n\n"; " 1 . Standard Adult Membership\ n"; "2 . Child Me mbers h ip\n~ j "3 . Senior Citiz e n Membership\n" ;
27
28 29
II Set the numeric output formatting . cout « fixed « showpoint « setprecision(2ji
30
31 32
1/ Respond to the user ' s menu selection . switch (choice)
33
{
34
35 36 37 38
39 40
41
case 1 ; cout « "For how many months? "j ci n » months ; charges = months • ADULT; cout « "The t o tal char ges are $" « break ;
endl;
charges «
endl j
charges «
endlj
case 2 :
42 43
cout « "For how many months? cin » months ;
46
charges months • CHILD; cout « "The total char ges are $" « break ;
4' 45
c harges «
"j
2
47
48 49 50 51 52
53 5' 55 56 57 58
case 3: cout « "For how man y months? " j cin » months; charge s = months • SENI OR; cout « "The tota l charges are $" « break ; case 4; cout« break ;
"Program e nding . \n";
4.15 The switch Statement
59
default: cout « cout «
60 61
62
"The valid choices are 1 through 4. Run the\n"; "program again and select one of those . \n";
)
63 return 0 ;
64
65 ) Program Output with Example Input Shown In Bold
Health Club Membersh i p Menu 1. 2. 3. 4.
Standard Adult Membership Child Membership Senior Citizen Membership Quit the Program
Enter your choice : 2 [Enter] For how many months? 6 [Enter] The total charges are S120 . 00
~ Checkpoint 4.33
Explain why you cannot convert the follow ing if/else if statement into a switch statement. i f (temp == 100 ) x : 0;
else if (population> 1000) x == 1;
else if
(rate < .1)
x = -1;
4.34
What is wro ng with the followi ng switch sta tement? switch (temp) {
case temp
,
COllt « break; case temp -- 0 , cout « break ; case temp > 0 cout « break; < 0
,
"Temp is negative. \n"; "Temp is zero.\n"; "Temp is pos itive . \n";
)
4.35
What will the following program display? #include using namespace std; int main ( ) {
int funny funny switch
=
=
7 , serious - 15;
serious * 2 ; (funny)
229
230
Chapter 4
Making Decisions
{
,
case 0
cout «
"That is funny . \n" ;
break;
case 30 : cout « break; case 32: cout «
"That is serious.\n";
"That is seriously funny . \n";
break; default: cout «
funny «
endl;
)
)
4.36
return O·•
Complete the following program skeleton by writing a switch statement that displays "one" if the user has emered 1, "twO" if the user has entered 2, and "th ree" if the user has entered 3. If a number other than 1, 2, or 3 is entered, the program should display an error message. tinclude
using namespace std; iot main() {
iot userNum; cout «
cin » II
"Enter one of the numbers 1, 2, or 3: ";
userNum:
1/ Write the switch statement here.
II return 0; }
4.37
Rewrite the fo llowmg program. Use a switch statement instead of the if/else if statement. 'inc~udQ using namespace std;
int main() {
int selection; cout « "Which formula do you want to see?\n\n"; cout « "1. Area of a circle\n" ; cout « "2. Area of a rectangle\n"; cout « "3. Area of a cylinder\n" cout « "4. None of them! \n"; cin » selection; if (selection =- 1) cout « "pi times radius squared\n"; else if (selection - ~ 2) cout « "Length times width\n"; else if (se~ection == 3) cout « "Pi times radius squared times he ight\n"; else if (selection ~= 4) cout « "Well okay then, good byet\n";
else
cout « return 0;
)
"Not good with numbers, eh?\n";
4. 16 Testing for F-iJe Open Errors
Testing for File Open Errors CONCE.PT: When opening a file you can tes t the file stream object co determine if an error occurred. In Chapter 3 you were introd uced to file operations and saw that the file stream member function open is used to open a file. Sometimes the open member function will not work. For example, the fo llowing code will fail if the file info.txt does not exist: ifstream inputFile ; inputFile .open ( "info. txt" ) ; You ca n determine when a file has fa iled to open by testi ng the va lue of the file stream object with the ! operator. T he fo llow ing program segment attempts to open the file customers. txt. Jf the file cannot be opened, an error message is displayed: ifstream inputFile : inputF ile . open ( "customers. txt" ) ; if (!inputFile) {
cout «
"Error opening file. \n";
)
Another way to detect a fa iled attempt shown in the followi ng code:
to
open a file is with the fail member function, as
ifstream inputFile i inputFile.open{"customers . txt~);
if (inputFile.fail()) {
cout «
"Error opening file . \n ";
The fail member function retu rns true when an attempted fi le operation is unsllccessful. When using fi le UO, you should always test the file stream object to make sure the file was opened successful ly. If the file could not be opened, the user should be informed and appropriate action taken by the program. For instance, the following program segment attempts ro open the file cusromer. txt for Output. In the event the file ca nnOt be opened, the user is informed and given some clue as to why. of stream outputFile ; outputFile .open ( "customer. txt" ) ; if (outputFile.fail(» {
cout« cout « cout « cout «
"The c ustomer. txt file could not be opened . \n"; "Perhaps the disk is full or you do not have\n" ; "sufficient privi leges. Contact your system\n"; "manager for assistance . \n" :
)
G:0
Case Study on CD: See the Sales Commission Case Study on the Student CD.
231
232
Chapter 4 Making Decisions
Review Questions and Exercises Short Answer 1. Describe the dIfference between the if/else if statement and a series of if statements. 2. In an i f /else if statement, what is the purpose of a trailing else? 3. What is a flag and how does it work? 4. Ca n an if statement test expressions other than relational expressions? Explain.
5. Briefly describe how the
&&
6. Briefly describe how the
I \ operator works.
operator works.
7. Why are the relational operators called relational?
8. Why do most programmers indent the conditionally executed statements in a decision structure?
FIII-in-the-Blank 9. An expression using the greareNhan, less-than, greater-than-or-equa l to, less-than-orequal -ro, equa l, o r not-eq ual to operator is called a(n)
expression.
10. A relational expression is either ____ or ____ 11. The value of a relational express ion is 0 jf the expression is _ ____ or 1 if the expression IS _ __ _ _
12. The
if statement regards an expression with the value
0 as _ _ _ __
13. T he i f statemenr regards an expression with a nonzero value as ____ _ 14 . For an i f statement to conditionally execute a group of statements, the statements
must be enclosed in a sec of _ _ __ 15. In an if/ e lse sratement, the if part executes its statement or block if the express ion IS , and the else part executes its statement or block if the expression is 16. The [railing else in an if/else i f Statement has a similar purpose as the _ _ _ _ _ section of a switch state ment.
17. T he if/else if statement is actually a form of the _____ if sta tement. 18. If the sub-expression on the left of the _ _ _ _ logical operator is false, the right sub-expression is not checked. 19. If the sub-expression on the left of the _ _ _ _ logical operator is true, the fight sub-expression is not checked. 20. The _ ____ Iogical operator has higher precedence than the other logical operators. 21. The logical operators have _____ assOClatlvlty. 22. The .~,--_ _ logical operato! works best when resting a number to determine if it is within a range. 23. The logical operator works best when tesring a number to determine If it is oU[side a range.
Review Questions and Exercises
24. A variable with scope is only visible when the program is executing in the block containing the variable's definition. 25. The strcrnp function is used to compare _____
26. An expression using the conditional operator is called a(n) _____ expression. 27. The expression that follows the switch statement must have a{n) _____ value .
28. The expression following a case statement must be a(n) _ _ _ _ _ _ __ 29 . A program wi ll "fall through" a case section if it is missing the _____ statement.
30. What value will be stored in the variable t after each of the following statements executes? A} t B)
(12 > I) , _ _ __
t - 12 < 0), _ _ __
qt-IS--
( 3 · 2 ) ) ' _ __
D)
5)' _ _ __
t
15
_
Algorithm Workbench 31. Write an
if statement that assigns 100 to x when y is equal to
32. Write an if/else srarement that assigns
O.
a to x when y is equal to 10. Otherwise it
shou ld assign 1 to x.
33. Using the following chart, write an if/else if statement that assigns .10, .15, or .20 to corrunission, depending on the value in sales. Sales
Commission Rate
Up to $10,000 $10,000 to $15,000 Over $15,000
10% 15% 20%
34. Write an if statement that sets the variable hours to 10 when rhe flag variable minimum is set. 35. Write nested i f statements that perform the following tests: If arnountl is greater than 10 and amount2 is less than 100, display the greater of the two. 36. Write an if statement that prints the message "The number is valid " if the variable grade is within the range 0 through 100. 37. Write an i f statement that prints the message "The number is valid" if the va riable temperature is within rhe range -50 through IS 0.
38. Write an i f statement that prints the message "The number is not valid" if the vari· able hours is outside the range 0 through 80.
39. Write an if/else statement that displays the strings in the arrays titlel and title2 in alphabetical order. 40. Convert the following if/else if statement into a switch statement:
if (choice --
cout «
1)
fixed «
showpoint «
setprecision(2) ;
233
234
Chapter 4
Making Decisions
}
else if (choice
:~
II
2
choice
:~
3)
{
cout «
fixed «
}
else if (choice (
cout «
showpoint «
==
setprecision(4);
4)
fixed «
showpoint «
setprecision(6);
fixed «
showpoint «
setprecision(8)i
}
else {
cout « }
41. Match the conditional expression with the if le 1se sta tement that performs the same operation. AI q • x < y ? a + b x • 2 ,•
BI
•
q = x < y ? x
a + b,
2
C) x < y ? q = 0
q = l ',
if Ix < y) 0, q else q = if (x <
"
y)
q .. a + bi
else q "'" x •
2,
U(x
::0
X
..
2;
else q "" a -+ bi
True or False
42. T F
The"" operator and the "'= operator perform the same operation.
43. T
F
A variable defined in an inner block may not have the same name as a variable defined in the outer block.
44. T
F
A conditionally executed statement should be indented one level from the i f Statement.
45. T 46. T
F F
47. T F 48. T F
All lines in a block should be indented one level. It's safe to assume that all uninitialized variables automatically start with 0 as their value. When an if statement is nested in the if part of another statement) t he only time the inne r if is execu ted is when the expression of the outer i f is true. When an i f statement is nested in the else part of another statement) as in an if/ e lse if, t he only t ime the inner if is executed is when the expression of the outer if is true.
Review Questions and Exercises
49. 50. 51. 52. 53.
T F The scope of a variable is limited ro the block in which it is defined. T F Stri ngs may be direcrly compared by using the == operator. T F x != y is the same as (x> y I I x < y) T F y < x is the same as x >= y T F x >= y is the same as (x> y " X = y)
Assume the variabl.es x .. 5, 'i ;;. 6, and 7. ;;. S. Indicate by circling the T or F whether each of the following conditions is true or fa lse:
54. T 55. T
F F
56. T
F
57.
T F
x == 5
II
7 <= x " 2 1'" Y x >= 0
3 z > 4
y >
1= 4
&&
Z
II
x <'" y
Find the Errors Each of the following programs has errors. Find as many as you can .
58. II Th i s program averages 3 test scores . II It uses the variable perfectScore as a flag . include using namespace std; int main() {
cout «
"Enter your 3 test scores and I will ";
"a verage them:" ; int score1, score2, score3, cin » score I » score2 » score3; double average: average ~ (scorel + score2 + score3) I 3.0; if (average - 100)1 perfectScore = true; II Set the flag variable cout « "Your average is " « average « endl: bool perfectScore; if (perfect5core): «
{
cout « "congratulations!\n" : cout« "That's a perfect score.\n"; cout « .. You deserve a pat on the back! \n" : return 0 ; }
59. II This program divides a user- supplied number by another II user-supplied number . It checks for division by zero .
'include using namespace std ; int main() {
double numl, num2, quotient; cout « "Enter a number : " ; cin » numl : cout « "Enter another number : " ;
2 35
236
Chapter 4
Making Oecisions
cin »
num2i if (num2 "" ... 0) cout « "Division by zero is not possible. \n~ ; cout « ~Please run the program again ~ ;
cout « else quotient
cout « cout « cout « return 0;
"and enter a number besides zero.\n ~ numl I num2; "The quotient of M divided by " «
quotient «
~
M
;
« numl « num2 « .. is Hi
endl;
)
60. II This program uses an if/else if statement to assign a II letter grade (A, a, C, D, or F) to a numeric test Bcore. 'include using namespace std: int maine 1 (
int testScore;
cout « "Enter your test score and I will tell you \ n"; cout « "the letter grade you earned: "; cin » t estSco re; if (testScore < 60) cout « "Your grade is F.\n"j else if (teatScore < 70) cout « "Your grade is D. \ 0"; else if (testScore < 80)
cout else if cout else cout else if cout
« HYour grade is C.\n": (testScore < 90) « "Your grade is B . \n M
;
« "That is not a valid score. \n (testScore <- 100) « "Your grade is A. \n" ;
M ;
return 0; )
61 . II This program tests two strings for equality. tinclude using nameapace std; int main ( ) (
canst int SIZE - 40; char string1[SIZE). string2 {S IZE );
cout « ~ Enter a string: "; cin.getline(string1, 80); caut « "Enter another l5tr ing:
M;
cin.getline(string2, 80); if (stringl -- string2) cOut «
else
"The strings are the same . \n";
Review Questions and Exercises
cout « return 0;
"The strings are not the same.\n";
)
62. II This program uses a switch-case statement to assign a II letter grade (A. B. C. 0, or F) to a numeric test score.
'include using namespace std; int main( ) {
double testScorej cout « "Ente r your test scor e and I will tell you\n"; cout « "the letter grade you earned: "; cin » testScore; switc h (testScore) {
case (testScore < 60 . 0) : cout « "Your grade break; case (testScore < 70.0) : cout « "Your grade break; case ltestScore < 80.0) : cout « "Your grade break ; case (testScore < 90 . 0) : cout « "Your grade break; case ltestScore <= 100.0): cout « "Your grade break; default : cout « "That score retur n 0;
is F.\n";
is D. \n";
is C . \n " ;
is B. \0" i
is A. \n ";
isn't valid\n";
)
63. The following statement should determine if x is not greater than 20. What is wrong with it? i f ilx > 20)
64. T he followIng Statement sho uld deter mine if count is within the ra nge of a through 100. What is wrong w it h it? if (cou nt > - 0
II
count <- 100)
65. T he followi ng statement should determine if count is outside the range of 0 through 100. What is wrong with it? i f (count < 0 && count> 100)
66. The fo llowing sta tement sh ould assign 0 to z if a is less than 10, otherwise it should assign 7 to z. Wha t is wrong w ith it? Z :
(a < 10) : 0 ? 7:
23 7
238
Chapter 4
Making Decisions
Programming Challenges 1. Minimum/ Maximum
Write a program (hat asks the user to enter
twO
numbers. The program should use the
conditional operator to determine which number is the smaller and which is the larger.
2. Roman N umeral Converter Write a program that asks the user to enter a number within the range of 1 through 10. Use a switch statement to display the Roman numeral version of that num ber.
Input Validation: Do not accept a number less than 1 or greater than 10. 3. Magic Dates
la, 1960 is special because when we write it in the fo llowing format, the monrb times the day equals the year.
The da te J une
6/10/60
Write a program that asks the user to enter a month (in numeric form), a day, and a two-digit yea,f. The program should then determine w hether the month times the day is equa l to the year. If so, it shou ld disp lay a message saying the date is magic. Otherwise it should display a message saying the date is not magic. 4. Areas of Rectangles The area of a rectangle is the rectangle's length times its width. Write a program that asks for the length a nd width of two rectangles. The program should tell the user which rectangle has the greater area, or if the areas are the same.
5. Body Mass Ind ex Write a program that calculates and displays a person's bod y mass index (BMI ). The BMI is often used to determine whether a person with a sedentary lifestyle is over-
weight or underweight for his or her height. A person's BMI is calculated with the following fo rmula:
BMI = weight x 703 1 height' where weight is measured in pounds and height is measu red in inches. T he program sho uld d isplay a message indicating whether the person has optima l weight, is underweight, or is overweight. A sedentary person's weight is considered to be optimal if his
or her BMl is between 18.5 and 25. If the BMI is less [han 18.5, the person is considered to be underweight. If the BMl value is greater than 25, the person is co nsidered to be overweight.
~tJllj@mll/1l~
6. Mass and Weight Scientists measure an object's mass in ki lograms and its weight in newto ns. If you know the amount of mass that an object has, yOll can ca lculare itS weight, in newtons, with rhe followi ng formula:
Weight:: mass x 9.8
Review Questions and Exercises
Write a program rhar asks the user fO enter an object's mass, and then calcula tes an d displays its weight. If the object weighs more than 1,000 newtons, display a message indicating that it is toO heavy. If the object weighs less tha n 10 newtons, display a message indicating that the object is toO light.
7. Time Calculator Write a program that asks the user •
Solving the Time
•
CalculalOr problem
•
fO
enter a number of seconds.
There are 60 seconds in a minute. If the number of seconds entered by the user is greater than or equal fO 60, the program should display the numbe r of minutes in thar many seconds. There are 3,600 seconds in an hour. If the number of seconds entered by the user is grea ter than or equal to 3,600, the program should display the number of hours in that ma ny seconds. There are 86,400 seconds in a day. If the number of seconds entered by the user is greater than or equal to 86,400, the program should display the nu mber of days in that many seconds.
8. Sorted N ames Write a program that asks the user to cnter three na mes, and then displays the names sorted in alphabet ica l order. Assume that none of the names are the same. For example, if the user entered "Charl ie," " Leslie," and" Andy," the program would display:
Andy
Charlie Leslie
9. Math Tutor This is a modification of Programming Challenge 15 from Chapter 3. Write a program that can be used as a ma th tutor for a young student. The program should display two random numbers that are to be added, such as:
247 + 129
T he program should wait for the student to enter the answer. If the answer is correct, a message of congratulations should be prim ed . If the answer is incorrect, a message should be printed showing the correct answer. 10. Software Sales
A software compa ny se lls a package that retails for $99. Quantity discounts are given according to the following table. Quantity
10- 19
Di scount 20%
20-49
30%
50-99 100 or more
40% 50%
23 9
240
Chapter 4
Making Decisions
Write a program that asks for the number of units sold and computes the total cost of the purchase. Input Validation: Make SIIre the number of units is greater than O. 11 . Book Club Points Serendipity Booksellers has a book club that awards points to its customers based on the number of books purchased each month . The points arc awarded as fo llows:
• • • • •
If a customer purchases 0 books, he or she ea rns 0 points. If a custo mer purchases 1 book, he or she earns 5 points. If a customer purc hases 2 books, he o r she earns 15 points. If a customer purchases 3 books, he Or she earns 30 points. If a customer purchases 4 or more books, he or she earns 60 poims.
\Vrite a program that asks the user to enter the number of books that he or she has purchased [his month and then displays the number of points awarded. 12. Bank Charges
A bank cha rges $10 per month plus the following check fees for a commercial checkmg account:
$ .1 0 each for fewer than 20 checks $.08 each for 20-39 checks
$.06 each for 40-59 checks $.04 each for 60 or more checks T he bank also charges an extra $15 if the balance of the accOunt falls below $400 (before any check fees are applied). Write a program that asks for the beginn ing balancc and the number of checks written. Com pute and display the bank's service fees for the moneh. InpHt Validation: Do not accept a negative value for the number of checks written. If a Ilegative value is given for the begimlillg balance, display a ll urgent message illdicat· ing the account is overdrawn .
13. Shipping Charges The Fast Freight Shipping Company charges the followi ng rates: Weight of Package (in Kilograms ) 2 Kg or less Over 2 Kg but not more than 6 kg Over 6 Kg but not more than 10 kg Over 10 Kg but nor more than 20 kg
Ra ce per 500 Miles Shipped
$1.10 $2 .20 $3.70 $4. 80
Write a program that as ks for the weight of the package and the distance it is to be shipped, and then displays the cha rges. Input Validation: Do not accept values of 0 or less for the weight of the package, Do not accept weights of more than 20 Kg (this is the maximum weight the company will ship). Do not accept distances of less than 10 miles or more than 3,000 miles. These are the company's minimum and maximJlm shipping distances,
Review Questions and Exercises
1 4. Running the Race
Write a program rhar asks (or the names of three runners and the rime it rook each of them to finish a race.lhe program should disp\ay who came in nrst, second, and third place.
Input Validation: Be sure the names do not overflow the arrays. Only accept positive nllmbers (or the times.
15. Personal Best Write a program thar asks for the name of a pole vaulter and the dates and vault heights (in meter s) of the athlete's three best vatl lrs . It should then report, in order of height (best fi rst), the date on which each vauh was made and its height.
Input Validation: Only accept values between 2.0 and 5.0 for the heights.
16. Fat Gram Calculator Write a program thar asks for the number of calories and fat grams in a food. The program should display the percentage of calories that come from faL If the calories from fat are less than 30% of the total calo ries of the food, it should also display a message indicating that the food is low in fat.
One gram of fat has 9 calories, so Calories from fa t = fat grams'" 9
The percentage of calor ies from fat can be calcu lated as Calories from fat -:- cotal calories
Input Validation : Make st/1'e the number of calories and fat grams are nOlless than O. Also, the number of calories from fat cannot be greater thall the total number of calories. If that hap/Jens, display an error message indicatillg that either the calories or fat grams were incorrectly entered. .
17. Spectral Analysis
1£ a scientist knows the wavelength of an electromagnetic wave, he or she can determine what type of radiation it is. Write a program that asks for the wavelength of an electromagnetic wave in mete rs and then displays what that wave is according co the chart below. (For example, a wave with a wavelength of 1£-10 meters would be an X-ray.) 1 x 11}-2
@__
1)( 1(J-3
7x10-7
4)( 10-7
1 )( 10""8
1)( 10-11
I Gamma Rays
18. Tbe Speed of Sound The following table shows the approximate speed of sound in air, water, and steel. Medium Air
Speed
Water
4,900 feet pe r secon d
Steel
16,400 feet pe r second
1,100 feet per second
241
242
Chapter 4
Making Decisions
Write a program that displays a menu allowing the L1ser to select air, water, or steel. After the user has made a selection, he or she should be asked to emer the distance a sound wave will travel in the selected medium. T he program will then display rhe amounr of ti me it wilJ take. (Rou nd the answer to four decimal places.)
Input Validation: Check that the user has selected one of the available choices from the menu. D o not accept distances Jess than O. 19. The Speed of Sound in Gases When sound travels through a gas, its speed depends primaril y on the density of rhe med ium. The less dense the med ium, the faste r t he speed wi ll be. The following ta ble shows the approxima te speed of SOllnd at 0 degrees centigrade, measured in meters per second , when traveling th rough carbon dioxide, air, helium, and hydrogen. Medium Carbon Diox ide
Speed (Meters per Second)
Air Helium Hydrogen
331.5
258.0 972.0
1,270.0
Write a program that displays a menu allowing the user ro select one of these four gases. After a selecti on ha s been ma de, the user should enter the num ber of seco nds it rook for [he sound ro travel in (h is medi um from its sou rce to the loca tion at which it
was detected. The program should then report how far away (in meters) the source of the sound was from the detection loca tion. blput Validation: Check that the user has selected 011e of the available menu choices. Do not accept times less than 0 seconds or more than 30 seconds.
20. Freezing and Boiling Points The following tab le lists the freezing and boiling po ints of several substances. Write a program that asks the user to enter a tempera tu re, and then shows a ll the substances that will freeze at that temperature and all th at wi ll boil at that temperature. For example, if the user en ters -20 the progra m should report that water will freeze and oxygen will boil a t that temperature. Substance Ethyl a lcohol Mercury Oxygen Water
Freezing Point (C F)
Boiling Point r F)
- 173 -38 -362 32
172 676 -306 212
Review Questions and Exercises
243
21. Geometry Calculator Write a program that displays the fonowing menu: Geometry calculator 1 . Calculate the Area of a Circle 2. Calculate the Area of a Rectangle J. calculate the Area of a Triangle 4. Quit Enter your choice (1 - 4):
If the user enters 1, the program should ask for the radi us of the circle and tben play its area. Use the fo llowing formu la:
dis~
Use 3. 14 159 for 1t and the radi us of the circle for r. If the user enters 2, the program should ask fo r the length and width of the rectangle and then display the rectangle's area. Use the following formula: area
=
length * width
If the user enters 3 the program should ask for the length of the triangle's base and its height, and then display its area. Use the following formula: area = base * height * .5
If the user enters 4, the program should end. Input Validation; Display an error message if the user enters a number outside the range of 1 through 4 when selecting an item from the menu. Do not accept 11egative values for the circle's radius, the rectangle's length Dr width. Dr the triangle's base or height. 22.
Long~Distan ce
Calls
A !ong~ di stance carrier charges the fo llowing (ates for telephone calls; Starting Time of Call
Rate per Minute
00,00-06,59
0.12 0.55 0.35
07,00-1~,00
19,01-2359
Write a program that asks for the starting time and the number of minutes of rhe call, and displays the charges. The program shou ld ask for the time to be entered as a floatingpoint number in the form HH.MM. For example, 07:00 hours will be entered as 07.00, and 16:28 hours will be entered as 16.28.
Input Validation: The program should not accept times that are greater than 23,59. Also, no number whose las! cwo digits are greater thatt 59 should be accepted. Hzm: Assuming num is a floating-point variable, the following expression will give you its fractional part:
num - static_cast(num)
244
Chapter 4
Making Decisions
23. In(ernct Servi ce Provider
An [merner service provider has three different subscription packages for its customers: Package A:
For $9.95 per month 10 hours of access afe provided . Additional h-o u(s
are $2.00 per hour. Package B:
For $14.95 per month 20 hours of access are provided. Additional hours are $ 1.00 per hou r.
Package C:
For $19 .95 pcr month unlimi ted access is provided.
Write a progra m that calcu lates a c ustomer's month ly bill. It shou ld ask which package the cuStomer has pu rchased and how ma ny hours were used. It sho uld then display the total amount due .
Input Validation: Be sure the user only selects package A, B, or C. Also, the 1Iumber
of hOllrs used in a month cannot exceed 744. 24 . Internet Ser vice Provider, Part 2
Modify the Prog ~T m in Programming Challenge 23 so tha t it also disp lays how much money Package ~cus rome r s would save if they purchased packages B or C, and how much money Pac~age B customers would save if they pu rchased Package C. If there would be no savings, no message shou ld be primed. 25. Intern et Service Provider, Part 3 Months with 30 days have 720 hours, and months with 31 days have 744 hours. February, with 28 days, has 672 hou rs. Enha nce the in put validation of the Internet Service Provider program by asking the user for the month (by name), and validating that the number of hours emered is nO( more than the max im um for the entire mo nth . Here is a ta ble of the months, their days, and number of hours in each .
Days 31
744
28
672
744
June Ju ly August
31 30 31 30 31 31
September
30
720
Ocrober
31 30 31
744
Month Janua ry February March April
May
November December
Hours
no 744
720 744 744
720 7 4'>
26. fife Input (Freezing and Boiling Points Modificacion )
Modify the progra m that you wrote fo r Program ming Challenge 20 (Freezing and Boiling Poi nts) so it reads its inpUt from a file instead of the keyboard. Perform the necessary test to determine if an error occurs when (he fi le is opened. If an error occurs, display a message info rming the use r.
Review Questions and Exercises
Serendipity Booksellers Software Development ProJectPart 4: A Problem-Solving Exercise 1. The Main Menu
A. Modify the mainmenu.cpp program so it validates the user's input. If a value outside the range of 1 through 4 is entered, the program should display an error message. Here is an example screen:
Serendipity Booksellers MaIn Menu
1. 2.
Cashier Module . Inventory Database Module
3: Report Module Exit
4.
Enter Your Choice: S Please enter a number In the range 1-4.
B. Later, in Chapter 6, you w ill begin merging all the programs you have wrirten into the mainmenu.cpp file. You will now start making preparations for that. After the user input has been validated, add a switch statement that branches to
a section of code, depend ing on wh ich menu choice the user made. For now, the program should simply display a message like "You selected item 1" when
the user enters a number. Here is an example of the screen: Serendipity Booksellers Main Menu
1. 2.
Clshler Module Inventory Database Module
3.
Report "'adule
4.
Exit
Enter Your Choice: 3 You selected Item 3.
2. The Inventory Database Menu You will make the same modifications to invrnenu . cpp that you made to mainmenu. cpp.
245
Chapter 4 Making Decisions A. Modify (he invrnenu.cpp program so it val idates the user's input. If a value out~
side the range of 1 through 5 is emered, rhe program should display an error mes ~ sage. Here is an example screen: Serendipity Boo.bellers Inyentory Database 1. look Up a Book 2. Add a Book 3. Edit a Book 's Record 4. Delete a Book S. Return to the Main Menu Enter your choice: 9
Please enter a number In the range 1-5.
B. After the user input has been validated, add a switch statement thar branches to
a section of codc, depending on which menu choice the user made. For now, the program should simply display a message like "You selected item 1" when the user enters a number. Here is an example of the screen: Serendipity Booksellers
Inyentory Database 1. Look Up a Book 2. Add a Book 3. Edit a Book' s Record 4. Delete a Book 5. Return to the Main Menu
Enter your choice:
2
You selected Item 2.
3. Th e Reports Menu You will make the same modifications to reports . cpp as you made to mainand invrnenu. cpp.
me nu . cpp
Review Questions and Exercises
A. Modify the reports . c pp program so it validates the user's input . If a value outside the range of 1 through 7 is emered, the program should displ ay an error message. H ere is an example screen: Serendipity Booksellers Reports 1. Inventory Listing 2. Inventory Wholesale Value 3, Inventory Retail Value 4, listing by Quantity S. listing by COlt 6. Listing by Age 7, Return to the Main Menu Enter Your Choice: 8 please enter a number in the range 1- 7. B. After the user input has been validated, add a switch statement that branches to
a section of code depending On whic h menu choice the user made. For now, the program should simply display a message like " You selecte d item 1" when the user enters a number. Here is an example of the screen: Serendipity Booksellers Reports 1 , Inventory Listing 2. Inventory Wholesale Value 3, Inventory Retail Value 4. LIsting by Quantity 5. LIsting by Cost 6. Listing by Age 7. Return to the Main Menu Enter Your Choice: S You selec:ted Item 5.
TOPICS 5.1
Th e Increment and Decrement
5.7 5.B
Sentinels
5.2
Operators Introduction to lOOps:
5.9
5.J
The while Loop Using the while l oop for Input Validation
Using a l OOp to Read Data from a I=ile
5.10 Focus on Software Engineering: Deciding Which loop to Use
5.4 5.5 5.6
The do- while l oop
5.11 5.12
The for l oop
5.13 The continue Statement
Cou nters
Keeping a Running Total
Nested Loops Breaking Out of a Loop
The Increment and Decrement Operators CONCEPT: ++ a nd -- are operators that add and subtract 1 from their operands.
To increment a value means to increase it by one, and to decrement a value mea ns to decrease it by one. Both of the fo llowing sta remems increment the variable num: num = num + 1; num += 1;
And num is decremented in both o f the fo llowing sta tements:
num
=
nurn -;;:
num - 1 ; t;
24.
2 50
Chapter 5
Looping
c++ provides a sec of simple unary operatOrs des igned just for incrementing and decrementing variables . The increment operato r is ++ and the decremem ope rator is - - . The following statement uses the ++ o perator to increment num; nllm++;
And the following statement decrements
num:
num-- j NOTE : The expression num++ is pronounced "num plus plus," and num- - is pronounced ( ) "-_"_"_"_"' __"' __'_ " _"_,_"' __i"__"_,_ .'_ ' ____________________________________________________________-'
Our examples so fa r show the increment and decrement operators used in postfix mode, whic h means the operator is placed after the variable. The operators also work in prefix mode, where the operator is placed before the variable name: ++num;
--num;
In borh postfix and prefix mode, these operators add 1 ro or subtract J from their operand. Program 5-1 shows how they work. Program 5 - 1
1
II This program demonstra tes the
2
iinclude using names pace std ;
, 3
5 6 7 8
9 10 11
lnt main () { int num ... 4;
++ and -- operators.
II num starts out with 4.
II Display the va l ue i n num . cout « "The variable num is " « num « endl; cout « "I will now increment num . \n\n";
12
13 14
II Use postfix num++;
15
cout « cout «
16
++ to increment num .
"Now the variable num is " « num « "I will increment num a9ain . \n\n";
endl;
17
18 19
1/ Use prefix ++ to increment num. ++n u mi
20 21 22
cout « cout «
23
/1 Use postfix -- to decrement num . num- - ; COllt « "Now the variable num is " « num « COllt« "1 will decreme nt num a9aio . \0\n " ;
24 25
26 27
"Now the variable num is " « oum « "I will now decrement num. \0\0";
endl;
end l ;
5.1 The Increment and Decrement Operators
28 29 30 31 32
II Use prefix -- to increment num. --numi cout « "Now the variable num is " « return 0:
num «
endl ;
}
Program Output The variable num is 4 I will now increment num. Now the variable nurn i, 5 I will increment nurn again .
Now the variable nurn i , 6 I will now decrement num. Now the var~able num is 5 I will decrement num again .
Now the variable num is 4
The Difference Between Postfix and Prefix Modes In the simp le statements lIsed in Program 5-1, it doesn't matter if the increment or deere· mcnr operator is used in postfix or prefix mode. The difference is important, however, when these operators are used in statcmen ts that do morc than just incrementing or dec remenring. For exam ple, look at the fo llowing lines: num = 4: cout « num++;
Thi s cout statement is doing two things: (l) displaying the va lue of num, and (2) incrementing num. But which happens first? cout will display a different va lue if nurn is incremented first than if num is incremented last. The answer depends on the mode of the increment operator.
Postfix mode causes the increment to happen after the vallie of the variable is used in the expressio n. In tbe example, cout will display 4, then num will be incremented to 5. Prefix mode, however, causes the increment to happen first. In the followi ng statements, num will be incremented ro 5, then cout will display 5: num '" 4 ; cout « ++num ;
Program 5-2 illustrates these dynamics further:
Program 5-2 1 2 3 ~
II This program demonstrates the prefix and postfix II modes of the increment and decrement operators, 'include using names pace std: (program continues)
25 1
252
Chapter 5 looping
Program 5-2
(continued)
5 6
iot main( )
7
{
int nurn = 4 ;
8 9
II Displays 4 II Displays 4, then adds 1 to nurn « num « endl; II Displays 5 cout « « endl; ++num II Adds 1 to nurn, then displays 6 cout « endl: II Displays a blank line cout
10 11 12
nurn <;< endl; num++ « endl:
cout « cout «
nurn « endl: /I Displays 6 num-- « endl; II Displays 6, then subtracts 1 from nurn num « endl; II Displays 5 « endl: II Subtracts 1 from nurn, then displays 4
cout «
13 14 15 16 17 18 19
cout
«
cout «
20 21 ?2
cout «
~-num
return 0; }
Prog ram Output 4
4 5 6
6
6 5 4
Let's ana lyze the statements in this program.
(0
line 8, nurn is initialized with the value 4,
so the cout s tatement in line 10 disp lays 4. Then, lin e 11 sends the expression nllm++ to couto Because the ++ operator is used in postfix mode, the value 4 is first sem to cout , and then 1 is added to num, making its value 5.
When line 12 executes, num will hold the value 5, so 5 is displayed . Then, line 13 sends the expression ++num to couto Because the ++ operator is used in prefix mode, 1 is first added to num (making it 6), and then the val ue 6 is sent to couto This same sequence of events happens in lines 16 through 19, except the -- operator is used. For another example, look at the following code: int:x:=l; int y y "" x++;
II Postfix increment
The first statement defines the variable x (init ial ized wirh me value 1) an d [he second sta tement defines the variable y. The third statement does tWO things: •
•
It assigns the value of x to the va riable y. The variable x is incremented.
The value that will be stored in y depends on when the increment takes place. Because the ++ operator is used in postfix mode, it actS after the assignment takes place. So, this code
5.1 The Ir, crement an d Decrement Operators
wil l srore 1 in y. After the code has executed, x will contai n 2. Let's look a t the sa me code, but with (he ++ operaror used in prefix mode: int x = 1; int y,
y
II Prefix increment
= ++x;
In the third statement, the + + operator is used in prefix mode, so it acts on the variable x before the assignment takes place. $0, this cod e will store 2 in y. After the code has executed, x will also contain 2.
Using ++ and -- in Mathematical Expressions The increment and decrement operators can also be used on variables in mathematical expressions. Consider the foll ow ing program segment: a - 2; b : 5; c = a
*
cout «
b++ ;
a «
" " «
b
«
" " «
c,
In the statement c = a *' b ++, c is assigned the value of a times b , which is 10. The va riable b is then incremented. The cout statement will disp lay 2 6 10
If the statement were changed ro read c
=a *
++b ;
The variable b would be incremented before it was multi plied by a. In this case c would be ass igned the val ue of 2 times 6, so the cout statement would d isplay 2 6 12
YOll can pack a lot of action into a single statement usi ng the increment and decrement operators, bu t don't get tOO tricky with them. You might be tempted to try something like the following, think ing that c will be assigned 11 : a "" 2; b = 5; c=++(a*b);
/ / Error!
But this assignment statement simply wi ll nOt work because the operand of the increment and decrement operators mllst be an Ivalue. Reca ll from C hapter 2 that an Ivalue identifies a place in memory whose contcnts may be ch a nged. T he increment and decrement operators usually have variables for their operands, bu t generally spea ki ng, a nyt hing that ca n go on the left side of a n = operator is legal.
Using ++ and -- in Relational Expressions Sometimes you will see code where the ++ and -- operators a re used in relation al expressions . Just as in mathematical expressions, the difference between postfix a nd prefix mode is critical. Consider the fo llowing program segment: x "" 10:
if (x++ ) 10) cout « "x i s greate r than 10.\n";
253
254
Chapter 5 looping
Two operations are happening in this i f statement: (I ) The value in x is tested co determine if it is greater than 10, and (2) x is incremented. Because the increment operator is llsed in postfix mode, th e comparison happens first. Since 10 is not greater than 10, the cout statement won't execute. If the mode of the increment operator is changed, however, the i f statement will compa re 11 co 10 and the cout sta tement will execute: x = 10; i f (HX > 10)
cout «
"x is greater than 10. \n ";
Checkpoint 5. 1
What will the following program segments display? A) x = 2 ; y - x++; cout « x «
Yi
B) x = 2; y
= ++X;
cout «
C) x
x «
y;
= 2;
y '" 4; cout «
x++ «
--y ;
D) x = 2; y
=2
x
= 99;
* x++; cout « x « Yi E)
i f (x++ < 100)
cout
"It
else cout «
is true ! \n" ; "It is false! \n";
F) x = 0; if (++x) cout « else cout «
"It
is true ! \n" ;
" It is false ! \n";
Introdudion to Loops: The while Loop CONCEPT: A loop is part of a program that repeats.
Chapter 4 inrroduced the concept of control structures, which di rect the flow of a program. A loop is a con trol structure that ca uses a srateme m or group of statemen ts to repeat. C++ has three looping control structu res: t he while loo p, the do-whilk loop, and the for loop . The difference between rhese structures is how they control the rbpctition. The while L~p
5.2 Introduction to Loops: The while Loop
The while Loop The while loop has twO imporram parts: (1) an expression that is rested for a true or fa lse value, and (2 ) a statement or block that is repeated as long as the expression is true. Figure 5-1 shows the logic of a while loop. Figure 5 -1
True Expression)----j Statement(s)
False
Here is the general format of the while loop: whi l e
(expression)
statement;
In [he general formar, expression is any expression that can be evaluated as true or false, and statement is any va lid C++ sta tement. The first line shown in the format is sometimes called the loop header. It consists of the key word while followed by an expres sion enclosed in parentheses. H e re's how the loop works: the expression is tested, and if it i$ true, the statement is executed, Then, the expression is tested again. If it is nue, the statement: is executed.
This cycle repeats umi l the expression is fa lse. The statement that is repeated is known as the body of the loop. It is also considered a conditionally executed statement, because it is executed only under the condition that the expression is true. Norice there is no semicolon after the exptession in parentheses. Like the if statement, the while loop is not complete witham the statement that follows it.
If you wish the while loop to repeat a block of statements, its format is: while (expression) {
statement; statement ;
II Pl ace as many statements here II as necessary. )
255
Chapter 5 looping
256
The while loop works like an i f statement that executes over and over. As long as the expression inside the parentheses is true, the conditionally executed statement Of block will repeat. Program 5-3 uses the while loop to print " Hello" five times. Program 5-3 1
/1 This program demonstrates a simple while loop .
2 3
,
using names pace std ;
5 6 7
int main() {
B 9 10
' i nclude
iot number: 1 ; while (number <= 5) {
11
cout «
12 13 14
number++ ;
15 16
~Hello\n" ;
)
cout « "That ' s a11!\n" ; ret urn 0 ;
Program Output Hello
Hello Hello Hello Hello
That's all!
Let'S take a closer look at this program. In line 7 an integer variable, number, is defined and initialized with the value 1. 1n line 9 the while loop begins w ith this sta tement:
while (number
<~
S)
T his statement tests the variable number to determine whether ir is less than or equal ro 5. If it is, then {he statements in rhe body of the loop (lines 1 1 and 12) are executed: cout « "Hello\n"; number++; The statement in line 11 prints the word "Hello." The statement in line 12 uses the increment operator to add one to number. T his is the last statement in the body of the loop, so after it executes, the loop starts over. It tests the expression number <= 5 again, and if it is true, the sta[(~ments in the body of the loop a re executed again . This cycle repeats until the expression number <= 5 is false. This is illustrated in Figure 5-2.
Each repetition of a loop is known as an iteration. This loop will perform five iterations because the variable number is initial ized wim the value 1J and it is incremented each rime the body of [he loop is executed. When the expression number <= 5 is tested and found to be false, the loop wi ll terminate and the program will resume execution at tht: St 'ltt:mcm that immediately follows the loop. Figure 5-3 shows [he logic of this loop.
5.2 Introduction to Loops: The while Loop
Figure 5·2
Test this expression.
j while (number <= 5) (
cout « "Hello\n"; number++;
If the expression is true, pertorm these statements.
~
)
L _ _ _ Afler executing the body of the loop, start over.
Figure 5-3
I True
number <= 5
Print "Hello"
Add 1 to number
False
In this example, the number variable is referred to as the loop control variable because it
controls the number of times that the loop iterates.
The
whi~e
Loop Is a Pretest Loop
The while loop is known as a pretest loop, which metlns it tests its expression before c:ach iteration. Notice the variable definition in line 7 of Program 5-3: int number
=
1;
The number variable is ini tialized with the value 1. If number had been initialized with a value that is greate r than 5, as shown in the fo ll owing program segment, the loop would never execute:
int number = 6; while (number <= 5) (
cout « "Hello\n"; number++; )
An important characteristic of the while loop is chat the loop will never iterate jf the test expression is false to scart with. If you want [Q be sure that a while loop executes the first time, you must initialize the relevant data in such a way rhat thc test expression starts o ur as true.
257
258
Chapter 5
Looping
Infinite Loops In aH b ut rare cases, loops must contain within themselves a way to terminate. This means that something inside the loop must eventually make the test expression fa lse. The loop in Program 5·3 stopS when the expression number <= 5 is fal se.
if a loop does not have a way of stopping, it is ca lled an infinite loop. An infinite loop continues to repeat until the program is interrupted. Here is an exa mple of an infinite loop: int number
= Ii
while (number <= 5) {
cout «
"Hel10\n";
}
This is an infi nite loop because it does not contain a statement that changes the va lue of the number variable. Each rime the expression number <", 5 is rested, number will contain the va lu e 1. It's also possi ble to create an infinite loop by acci denta ll y placing a semicolon after the first line of the while loop. H ere is an example: int number .. 1; while (number <: 5);
II This semicolon is an ERROR !
{
cout « "Hello\n"; number++; }
T he semicolon at the end of the first line is assumed to be a null sta tement and d isconnects the while sta temenr from the block rhar comes afrer tt. To the compi ler, this loop looks like: while (number <= 5);
T his while loop will fo rever cXecU(e the null statement, which does nothing. The program will appear ro have "gone into space" because there is no thing to disp lay sc reen ourput or show activity.
Don't Forget the Braces with a Block of Statements If you write a loop that cond itionally execures a block of statements, don't forget to enclose all of the sta tements in a set o f braces. If th e braces are accidenta lly left out, the while statement cond itionally executes only the very next statement. For example, look at the following code. iot number:. 1; II This loop is missi ng its braces! while ( number <= 5)
cout « '·Hello\n"; number++;
In this code th e number++ statement is nor in the body o f the loop. Because the braces are m issing, the while statement only executes the statement char immediately follows it. This loop w ill execute infi nitely because there is no code in its body tha t changes rhe number va riable.
5.2 Introduction to l oops: The while loop
Another common pitfall with loops is aCcidentally using the '=- operator when you intend to use the ... '" operator. The following is an infin ite loop because the rest expression assigns 1 to r emainder each time it is eva luated instead of testing whether remainder is equal to 1. while (remainder : 1) II Error: Notice the assignment {
cout « "Enter a number: cin » num; remainder: num % 2;
"i
)
Remember, any nonzero val ue is evaluated as true.
Programming Style and the while Loop !t's poss ible to create loops that look like this: while (number <=
5)
{
cout «
"Hello\n" ; number++ i
}
Avoid this style of programming, The programming style you should use w ith the while loop is similar (0 that of the i f statement: •
•
If there is only one staternenr repeated by the loop, it should appear on the line after the while statement and be indented one additio nal leve l. If the loop repeats a block, each line inside the braces should be indented,
This programming style shou ld visually set the body of the loop apart from the surround ing code, In general, you'll find a si milar style being used with the other types of loops presented in this chapter.
In the Spotlight:
Designing a Program with a while Loop -A project currently underway at Chemica ll,..aps, In~. req1J.ires that a substance be continuaUy heated in a vat. A technician must check the substa nce's temperature every 15 min~res, If the substance's temperature does not exce~d i02.5 degrees Celsi us, then the '. technician does nothing, However, if the temperature is. greater than 102..5 degrees CeJsius, the technician IIJ.ust turn down the vat's therntostat, wait 5 minutes, and check the temperature again. The technician repeats .these steps until the temperature does not exceed 102.5 degrees CC;lsius. The director of engineering has asked yo u to write a program that guides the (ecbnician through this process.
·
Here is the.aigorirhm:.
.
1. Promp! !he user to enter the substance's teinperature. 2, Repeat the following steps as long as the temperature'is greater than 102.5 degrees Ce/si",s;
a, Tell the technician to tum down the thermostat, wait 5 minutes, and check the temperature agaill,
b. Pro»Jpt the user to enter the substance's temperature.
259
260
Chapter 5
Looping
3. After the loop fin;she~, tell the tecbnician thqt the temperature is acceptable and tQ c;heck it ag(lin in 1S minute~._ After reviewing this algorithm~ you realize that steps 2a and 2b sho"uld not be petformed if th~ rest cond.ition (temperature, is greater than-102.5) is fa lse to begin with. The while iOQP will work well in ,this situation, because it will POt execute even on~e ff its' condition is false. "Program 5-4 shows the code f?c the program. Program 5-4 1 1/ Tpis program as§ists ~ technician in the process 2 II of checking a substance's ~emperature. 3. tincluqe . 4 using names pace s t d; 5
6 int
~ain()
7 1 B
canst' double MAX TEMp:::: 1-02.5 ; double temperature;
9
II Maximum temperatur e II TQ hold the temperature
10 12
d
I I Get. 'the ·current te:mperatur.e. oo"ut « UEnter t"e substance's Celsius temper ature: "; ci~ » temperature ;
15 16
"
j l As long as neoessary, instruct the technician
17 19
whil~
H
II to adjust the thermostat . (temperature> MAx_TEMP ) {
cout « cou'l;: « ccut « cout «
19 20 21 " 22
cin »
'1. "2'
"The temperature is- too high. Turn the\n " ; "thermostat down and wait 5 mi nute s.\n"; "Then take the ce l sius t emper ature agai n\n""_: "and enter it;, here: "; temperature;
1
2~
.~6
l I Remind the- tech.nician to check the t~mperature / I again in 15" minutes . cout « "The. temI?erature is act;::e ptable . \n "; .cou1;: « "Check it again in l _S min ut"e s. \n" ;
21
2.
2' 30"
_return 0 ;
31
32
)
Program Output with Example Input Shown In Bold Enter the substance ' s Celsius temperature : 104.7 [Enter]
The temperature is too high . Turn the
thermostat down and wait 5 minutes . Then take the Celsius temperature ag~in and enter it here : 103.2 [Enter] The temperature is too high. Turn the thermostat down and wait 5 minutes. Then take the Celsius temperature again and enter i t here : 102.1 [Enter] The temperature is acceptable . Check it again in 15 minutes.
5.3 Using the while l oop for Input Validation
Using the while Loop for Input Validation CONCEPT: Th e while loop can be used to create input routines that repeat unti l acceptable data is en tered.
Perhaps the most famous saying of the computer industry is "garbage in, garbage o ut." The integrity of a program's output is only as good as irs input, so you shou ld try to make sure garbage does not go into your programs. Input validatiOlI is the process of inspecti ng data given to a program by the user and determi ning if it is valid . A good program should give dear instructions abo ut the kind of input tha t is acceptable, and not assume the user has followed those instructions. T he while loop is especially usefu l for va lidating inpll t. If an invali d value is entered. a loop can require that the user re-enter it as many times as necessa ry. For exa mpl e, rhe fol· lowing loop asks for a number in rhe range of 1 through 100: cout « "Enter a number in the r ange 1-100 : " ; cin » number; whi l e (number < 1 I I number> 100) (
cou t « "ERROR: Ente r a value in the range 1-100 : " ; cin » number ; )
T his code fi rst allows {he user to enter a number. This takes place JUSt before the loop. If the input is valid. the loop will not execute. If the input is inva lid. however, the loop will display an errot message and requ ire the tlser to enter another number. The loop will contin ue to execute until the user enters a valid number. The genera l logic of perfo rmi ng input validation is shown in Figure 5-4. Figure 5-4
j Read the first value.
Isthe value invalid?
No
Yes
Display an error message.
Read another value.
26 1
262
Chapter 5 l ooping
Th e read operation that cakes place Juse beforc the loop is called a prin1ing read. It provides the first value for the loop to test. Subsequent values are obtained by the loop.
Program 5-5 calculates the number of socce r teams a youth league may create, based on a given number of playe rs and a maximum number of playe rs per ream. The program uses while loops (in lines 21 through 27 and lines 34 through 38 ) to validate the user's input.
Program S-S 1 2 3 4 5
6 7
•
9 10 11
12 13 14
1/ This pr ogram calculates the number of soccer teams 1/ that a youth league may create from the number of II available players. Input validation is demonstrated II with while loops. ' i nclude
using namespace std; int main( ) {
int players, teamPlayers, numTeams , leftOver;
II II 1/ II
Number Number Number Number
of of of of
available players desired players per team teams players left over
15 16 17 18
II Get the number of pl ayers per team . cout « '·How many players do you wish per team?\n": cout « "(Enter a value in the range 9- 15): "; cin » teamPlayers;
20 21
II Validate the input . while (teamPlayers < 9
22 23
{
I.
teamPlayers > 15)
cout « "You should have a t least 9 but no\n""; cout « ··more than 15 per team. \ n'·; cout « "How many players do you wish per team? "; cin » teamPlayers ;
24 25 26 27
II
)
2. 29 30 31
II Get the number of players available. cout « ""How many players are available? .. ; cin » players;
32
33 34
II Validate the i nput. while (playe r s <= 0)
35
{
36 37 38 39 40
41 42 43
44
45
cout « "Please enter a positive number: cin » players;
)
II Calculate the number of teams . numTeams = p l ayers I teamPlayersi II Calculate the number of leftover players . leftOver = players % teamPlayers;
"i
5.4 Counters
46 47 48 49
sa
/1 Display the results. cout « "There will be " « numTeams « " teams with ": cout « leftOver « " players left over . \n "; return 0 ;
}
Program Output with Example Input Shown in Bold How many players do you wish per team? (Enter a value in the range 9-15) : 4[Enter] You should have at l ea st 9 but no more than 15 per team. How many players do you wish per team? 12 [Enter] How many p layers are available? - 142 [Enter] Please enter a positive number: 142 [Enter] There will be 11 teams with 10 players left over .
~
Checkpoint 5.2
Write an input validation loop that asks the user to eorer a number in the fange of 10 through 25.
5.3 5.4
Write an input validation loop that asks the user to enter ' Y', 'y', ' N', or 'n'. Write an Inp ut validation loop that asks the user [Q emer "Yes" or "No" .
Counters CONCEPT: A cou nler is a va riable thal is regularly incremented or decremented each t'ime a loop iterates.
Sometimes it's important fo r a program to conrrol or keep track of the number o f iterations a loo p performs. For example, Program 5-6 displays a table consisti ng of the numbers 1 through 10 and their squares, so its loop must iterate 10 times.
1 2 J 4 5 6
// This program displays the numbers 1 through 10 and // thei r squares. 'include using names pace stdi
7
(
8
intmain() I : II Initialize the counter.
int num
~
cout «
"Number Number Squ a J:'ed\n";
9
10
(program continues)
263
Chapter 5
264
Looping
Program 5·6
(continued)
11
cout «
12 13
while (nurn <= 10) {
I.
cout « nurn « "\t\t" « ( nurn * nurn) « num++; I/Inc remen t the counter.
15
"
17 18
" - -- - ------------ --- - ----- \ n"i
endlj
return 0 ; )
Program Output
Number 1
Number Squared 1
•
2
3
9
•5
I'25
•
3.
7 8 9 10
49
6' 81 100
In Progra m 5-6, (he variable nurn, which starts at 1, is incremented each time through the loop. When nurn reaches 11 (he loop SlOp S. nurn is used as a counter variable, wh ich means
it is regularly incremented in each iteration of the loop. In essence, nurn keeps CQum of rhe number o f iterations the loop has performed .
.A
NOTE : It's important that num be properly initialized. Remember, variables defined
~L-_;n_'_;d_'__a_f_u_n_c_';_o_n_I_'a_'_'__n_o_g_u_a_'_a_n_',_,_d__ ,'_a_'_';_n_g_'_a_l_u,_.______________________________--'
In Program 5-6, num is increme nted in the last statemen t o f the loop, Another approach is to combine the incremen t operation with the relational rest, as shown here: int nurn
c:
0;
while (num++ < 10 ) cout « num « ,,\t\t" «
( n um • num) «
endl;
This code will produce the same outpu t as Program 5-6,
Notice that num is now initialized to 0, rarher than 1, and the relat ional expression lIses the < operator instead of <=. This is because of the way the increment operator works when combi ned with the relational expression. The increment operator is used in postfix mode, which means it adds one to nurn aIter the relational test. When the loop firs t execu tes, num is set to 0, so 0 is compared to 10. The ++ operator then increments num immediately after the comparison. When the eOllt statement exc;cutes, num has the value 1. Thi s is shown in Figure 5-5.
5.5 The do- while Loop
Figure S-S
num is compared to 10, then it is incremen ted. When l he cout statement
executes, num is 1 greater than il was in the relalionallesl.
/
while (num++ <10) cout « num « "\t\t" «
(num * nurn) «
endl;
Inside the loop, num always has a value of 1 greater than the value previously compared ro < insread of <"'-. When num is 9 in the relational
10. That's why the relational operaror is test, it will be lOin the cout statement.
The do-while Loop CONCEPT: The do-while loop is a posttesf loop, whicb means its expression is tested after each iteration.
The do-while loop looks something like an in verted while loop . Here is the do-whi l e loop's format when the body of the loop contains only a single statement: do
statement; while (expression);
Here is the format of the do-while loop when the body of the loop contains multiple statements: do {
statement; statement; II Place as many statements here /1 as necessary . } while (expressi on );
~L-N __O__ T_E_:__T_h_e_d_o_-_W_h_i_,_e_l_o_o_p__m_u_,_t_b_e_t_e_'_",_i_"_a_te_d__ w_i_th__a_'_e_m_i_c_o_lo_,_,o__________________~ The do-while loop is a postlest loop. This means it does not rest irs expression until it has complered an iteration. As a resulr, rhe do-wh ile loop always performs at least one iteration, even if rhc expression is false to begin wirh. This differs from the behavior of a while loop, which you will recall is a pretest loop . For examp le, in rhe following while loop [he cout state ment will not execute at all~ int x = l; while (X < 0) cout « x «
endl;
26S
Chapter 5 looping
266
But the cout statement in the following do-while loop will execute once because the do-while loop docs not evaluate the expression x < 0 until the end of the iteration. int x '" 1 i do
cout « x « while (x < 0);
endli
Figure 5-6 illustrates the logic of the do-while loop. Figure 5-6
Statemenl(s)
True
Expression
r---'
False
You should use the do-w h ile loop when you want
to
make s ure the loop execu tes at least
oncc. For example, Program 5-7 averages a series of three rest scores for a srudcnr. After tbe average is displayed, it asks the user jf he or she wants to average another set of test scores. The program repeats as long as the user enrers Y for yes. Program 5-7 1 2 3
II This program averages 3 test scores . It repeats as 1/ many times as the user wishes_ 'include using namespace std;
4 5 6
int main()
7
{
•
9 10
int scorel, score2, score3; II Three scores double average ; II Average s c ore char again; II To hold Y or N input
11
12
13 14 IS 16 17 18
do {
II Get three scores . cout « "Enter 3 scores and I will average them : "; cin » score 1 » score2 » score3; II Calculate and display the average.
5.5 The do-while Loop
I.
average = (scorel + score2 + score3) I 3.0; cout « "The average is " « average « ". \n" ;
20 21
22 23 24 25 26 27
II Does the user want to average another set? cout « "00 you want. to average anot.her set? (YIN) "; cin » again; while (again ='" 'Y' II again == 'y'); return 0; )
Program Output Enter 3 scores The average is Do you want to Enter 3 scores The average is Do you want to
with Example Input Shown In Bold and I will average them: 8090 70 [Enter] 80. average another set? (YIN) y [Enter] and I will average them: 60 75 88 [Enter] 74.3333. average another set? (YIN) n [Enter]
When [hi s program was written, [he programmer had no way of knowing the number of t imes the loop would itera te. This is because the loop asks the user if he or she wants to repeat the process. This type of loop is known as a user-controlled loop, because it allows the user to decide the number of iterations.
Using do-while with Menus The do-while loop is a good choice for repeating a menu. Recall Program 4-32, which displayed a menu of healrh club packages. Program 5-8 is a modification o f that program which uses a do-while loop to repeat the program until the user selects item 4 from the men u.
Program 5-8
II This program d isplays a menu and asks the user to make a 2 II selection. An iflelse if statement determines which item 3 II the user has chosen.
1
4 'include 5 'include 6 us i ng namespace std;
. 7
8 int main() ( i nt choice; 10 11 int months; 12 double charges; 13 14
15 16 17
II Constants canst double canst double const double
II Menu choice II Number of months II Monthly charges
for membership rates ADULT - 40 . 0; SENIOR ~ 30 . 0; CHILD = 20.0;
18 (program continues)
267
Chapter 5 looping
268
(continued)
Program 5·8 19 20
II Set the numeric output formatting. cout « fixed « Showpoint « setprecision(2);
21 22
do
23 24
{
25 26
27 2B
29 30 31
32 33 34 35
36 37 38
1/ Display the menu and get a choice . cout « cout «
"\n\t\tHealth Club Membership Menu\n\n"; "1. Standard Adult Membership\n";
cout «
"2. Child Membership\n"; "3. Senior Citizen Membership\n";
cout « cout « cout « cin »
"4. Quit the Program\n\n"; "Enter your choice: " ; choice;
I I Validate the menu selection. while (choice < 1 I J choice> 4) { cout « "Please enter 1, 2, 3, or 4: ";
cin »
choice;
)
39
40
II Respond to the user's menu selection .
41
switch (choice)
42 43
{
44
45
46 47
""
50 51 52
53 54 55 56 57
case 1 : cout «
"For how many months? ";
cin » months; charges = months * ADULT; cout « "The total charges are $" « charges « endl, break; case 2: cout « "For how many months? "; cin » months; charges - months * CHILD; cout « "The total charges are $" « charges « endl; break;
58 59 60
61 62
63 64 65
case 3: cout «
"For how many months? "; months; charges = months * SENIOR; cout « "The total charges are $" « charges « endl, break, cin »
66
61 68
case 4 : cout «
"Program ending. \n" ,
5.5 The do-while Loop
69
break;
70
}
71 72
}
73 74
75
while (choice 1= 4);
return 0; )
Program Output with Example Input Shown In Bold Health Club Membership Menu 1. Standard Adult Membership 2. Child Membership 3. Senior Citizen Membership 4. Quit the Program Enter your choice: 1 [Enter] For how many months? 12 [Enter] The total charges are $480 . 00
Health club Membership Menu 1. Standard Adult Membership 2 . Child Membership 3 . Senior Citizen Membership 4 . Quit the Program
Enter your choice: 4 [Enter]
Program ending.
~
Checkpoint 5.5
What will the following program segments d isplay? A)
int count
~
10;
do
cout «
"Hello World\n":
while (count++ < 1); B) int v = 0: do cout « v++; while (v < 5); C) lnt count ~ 0, funny do
1, serious = 0, l imit -
{
funny+ +; serious +- 2 ; } while (count++ < limit); cout « funny « " .. « ser ious « cout « count « endl;
.. ";
4;
269
270
Chapter 5
looping
The for Loop CONCEPT: T he for loop is idea l for performing a known number of iterations.
In general, there are fWO ca tegories of loops: conditional loops and counr-conrrol1ed loops. A conditional loop executes as long as a particular condition exists. For example, an input validation loop exeClHes as long as the inp ut value is inval id. When you w rite a conditional loop, you have no way of knowing the number of times it will iterate.
-
The for Loop
Sometimes you know the exact nu mber of iterations that a loop must perform. A loop that repeats a specific nllmber of times is known as a count-controlled loop. For example, if a loop asks the user to enter the sales amounts for each month in the year, it will iterate twelve times. In essence, the loop couors to twelve and asks [he user to entcr a sales amount each time it makes a count. A cOunt-controlled loop must possess three elements: 1. It must initialize a counter variable to a starting value.
2. It must test the co unter variable by compa ring it {Q a max imum value. When the counte r variable reaches its maximum value, the loop terminates. 3 . Jr mUSt update the counter variable during each iteration. This is usua lly done by incrementing the variable. loops are so common that C++ provides a type of loop specifically for them. It is known as the for loo p. T he for loop is specifica ll y designed to in itialize, test, and update a counter variable. Hen: is the forma t of the fo r loop when it is used to repeat COli nt-controlled
a single statement: for (initialization ; test ; update) statement ,.
J
The format of the for loop when it is used to repeat a block is
for (initialization; test,· update) {
statement ; statement,' II Place as many statements here / / as necessary .
T he first line of the for loop is the loop header. After the key word fo r , there are three expressions inside the parentheses, sepa rated by semicolons. (Notice there is not a semico lon after the third expression. ) The first expression is the initia/izatioll expression. It is normally used ro initialize a counter variable to its sta rting value. This is the nrst action performed by the Joop, and it is only done once. The secon d expression is the test expression. This is an expression thar controls the execution of the loop. As long as this expression is true, the body of the for loop will repeat. T he for loop is a p retest loop. so it eva luates the test expression before each ireration. The third expression is the update
5.6 The for Loop
expression. Ir executes at the end of each iteration. Typica lly, this is a statemenr that increments the loop's counter variab le. Here is an examp le of a simple for loop that prints " Hello" five times: for (cou nt - 1; count <- 5; count++) cout « "Hello" « endl;
In this loop. the initialization expression is count'"
the test expression is count <'" 5, and the update expression is count++, The body of the loop has onc statement, which is the cout statement. Fi gure 5-7 illustrates the sequence of events that takes place during the loop's execution. Notice that Steps 2 through 4 are repeated as long as the test expression is true. 1,
Figure 5-7 Step 1: Perform the initialization expression.
!
Step 2: Evaluate the test expression . If it is true, go 10 Slep 3.
1
Otherwise, terminate the loop.
for (count'" 1; count <'" 5; count++) cout « "Hello" « end l ;
1-
Step 3: Execute the body of the lOOp.
Step 4 : Perform the update expression, then go back 10 Step 2.
Figure 5-8 shows the loop's logic in [he form of a flowchart. Figure 5-8
j Assign 1 to
count
count <-
5
True
cout statement
Increment count
False
Notice how the counter variable, count, is used ro control the number of times that the loop iterates. During the execution of the loop, this variable rakes on the values 1 through 5, and when the test expression count <= 5 is false, the loop terminates. Also notice thar in this example th e count variable is llsed only in the loop header, to control the
271
272
Chapter 5
Looping
number of loop iterations. It is not used for any other purpose. It is also possible to use the counter va riable within the body of the loop. For example, look at the following code: for (number = 1; number <- 10; number++) cout « number « ~ " « endl;
The counter variable in this loop is number. In addition to controlling the number of iterations, it is also used in the body of the loop. This loop will produce the following output: 1 2 3 4 5 6 7
a
9 10
As you can see, the loop displays the contents of (he number variable during each iteration. Program 5-9 shows another example of a for loop that uses its counter variable within the body of the loop. This is yet another program that d isplays a table showing the
numbers 1 through 10 and their squares.
Program 5 -9 1 2 ] 4 5 6 7 8
II This program displays the numbers 1 through 10 and II their squares. jinclude using namespace stdi int main() {
,
iot nurn;
cout «
10 11
12 13 14 15 16
cout «
"Number Number Squared\n" ; "-- - - -- ---- --------- ------\n" i
for (nurn = 1; num <~ 10; num++) cout « num « "\t\t" « (num '" nurn) « return 0;
endl;
)
Program Output Number
Number Squared
1
1
2 3
, 4
4
16
5
25
6 7
36
8
"64
9
81
10
100 Figure 5·9 illustrates the sequence of events performed shows the logic of the loop as a flowchart.
by this for loop, and Figure 5- 10
5.6 The f or Loop
Figure 5·9 Step 1: Perlorm the initialization expression.
j for ( n um COllt
«
I
Step 2: Evaluate the test expression. It it is true, go to Step 3. Otherwise, terminate the loop. l; n urn <= lO ; nurn++) num « "\t\t" « l
Step 3 : Execute the body of the loop.
Step 4: Perform the update expression, then go back to Step 2.
Figure S-10
j Assign 1 to
nurn
num <'" 10
True
Display num and num * nurn
Increment
nurn
False
Using the :for Loop Instead of while or do- while You shou ld use [he for loop instead of the while or do-while loop in any situation that clea rl y requires an initialization, uses a fa lst: condition to Stop the loop, and requ ires an update to occur at the end of each loop iteration. Program 5·9 is a perfect example. It requites that the num variab le be initialized to I , it stops the loop when the expression num <= 10 is false, and it increments nurn at the end of each loop iteration. Recall that when we first introduced the idea of a counter variable we examined Program 5·6, which uses a while loop to display the table of numbers and their squares. Because the loop in that program req uires an initialization, uses a false test expression to Stop, and performs an increment at the end of each irerarion, it can easily be converted to a f or loop. Figure 5·11 shows how the while loop in Program 5 -6 and the for loop in
Program 5-9 each have initialization, test) and update expressions.
2 73
2 74
Chapter S looping
Figure 5-11 Initialization expression /
Test expression
int nuro ~ 1; ~ while (nurn <= 10) {
cout «
"
nurn «
"\t\t" «
(nurn '* nurn) «
endl ;
num++ ;
)
Update expression
Initialization Test expression expression
t ,.,
for (nurn '"'
cout «
t
Update expression
t
nurn <- 10; nurn ++) num « "\t\t" « (nurn
•
nurn) «
endl;
The for Loop Is a Pretest Loop Beca use the for loop tests irs test expression be fore it performs an iteration, it is a pretest loop. It is possible to write a for loop in such a way that it will never iterate. Here is an ·exa mple: for (count; 11; count <= 10; count++) cout « "Hel lo " « endl;
Because the variable count is initialized co a value that makes the rest expression false from the beginn ing, this loop terminates as soon as it begi ns.
Avoid Modifying the Counter Variable in the Body of the for Loop Be careful not co place a statemenr that modifies rhe counter variable in the body of the for loop. All mod ifications of the counter variable should take place in the update expression, wh ich is alltomatica!!y executed at the end of each iteration. [f a Statement in the body o f the loop also modifies the counter variable, the loop wi ll p ro bably not te rmin ate yOll expect it to. The following loop, for example, increments x tw ice for each iteration :
when
for (x = 1; x <= 10; x++) {
cout « X++i
x «
endl;
/ / wrong !
5.6 The for loop
Other Forms of the Update Expression You arc not limited to using increment statements in the update expression. Here is a loop that displays aU the even numbers from 2 through 100 by adding 210 its counter: for (num = 2; num <= 100; num += 2) cout « num « endl; And here is a loop that countS backward from 10 down
[0
0:
for (oum ~ 10j num >= OJ num--) cout « num « endl ;
Defining a Variable in the for Loop's Initialization Expression Not only may the coumer variable be initialized in the initia lization expression, it may be defined there as well. The following code shows an example. This is a modified version of the loop in Program 5-9. for tint num = Ij num <= 10j num++) cout « num « "\t\t" « (num * num) «
endl;
In this loop, the num variable is both defined and init ialized in the initialization expression. If the counter v3{iabJe is used only in the loop, it makes sense to define it in the loop header. This makes the va riable's purpose more clear. When a variab le is defined in the initia lization expressio n of a for loop, [he scope of the variable is limited ro the loop. T his means you cannot access the variable in statements outside the loop. For example, the following ptogram segment will nOt compile because the last cout statement cannot access the variable count. for (int count - 1; count cout « count « endl; cout « '·count is now ·· «
count++)
count «
endlj
II ERROR!
Creating a User Controlled for Loop Sometimes you want the user to determine the maximum value of rhe couorer variable in a for loop, and therefore determine the number of rimes the loop iterares. For example, look at Program 5-10. It is a modification of Program 5-9. Insread of displaying the num bers 1 rh rough 10 and their squares, this program allows the user to enter the maximum value to display. Program 5-10 1
1/ This program demonstrates a user controlled for loop .
2 tinc l ude 3
using namespace std;
5 6
i nt main()
• 7
{
int num;
II Loop counter variable (program conrinues)
275
Chapter 5 looping
276
Program 5-10 S
(continued)
int maxValue;
II Max imum value to di splay
9
10
II Get the maximum value to display.
11 12
cout «
"1 will display a table of numbers and\n";
cout « "their squares. How high should I go? "; cin » maxValue;
13 14
,.15
cout «
"\nNumber
cout «
"-------------------------\n";
17 18 19
for (num : 1; num <= maxValue; num++) cout « num « "\t\t" « (num * num) «
20
return 0 ;
2l
Number Squa r ed \n";
endl;
)
Program Output with Example Input Shown In Bold I will display a table of numbers and their squares. How high should I go? S (Enter]
Number
Number Squared
2
1
1 4
3
9
4
,.
5
25
Before [he loop, this program asks the use r to enter the highest va lue to display. This va lue is stored in the maxValue variable: cout « "I will display a table of numbers and\n" ; cout « "their squares. How high should I go? ,.; cin » rnaxValue;
The for loop's rest expression then uses this value as rhe upper limit for [he control varia ble: for (nurn = Ii nurn <= maxValue; num++)
In this loop, the nurn variable takes on the values 1 through maxvalue, and then the loop terminates.
Using Multiple Statements in the Initializatio n and Update Expressions It is possible to execute more than one statement in the initialization expression and the update expression. When using multiple statemenrs in either of these expressions. simply separa te the SCatemenrs with commas. For exa mple. look at the loop in the following code, which has two sta te m ents in the initialization expression. int x, Y i
for (x = 1, Y I
= 1;
x <= 5; x++)
5.6 The for loop
cout «
« «
x « " plus " « y " equals" « (x + y) endl;
This loop's initialization expression is
x
=
1, Y "" 1
This initializes twO variables, x and y. The o utput produced by this loop is 1 plus 1 equals 2 2 plus 1 equals 3
3 plus 1 equals 4 plus 1 equals 5 5 plus 1 equals 6
•
We can further mod ify the loop to execute is an example;
two
statements in the update expression. Here
int x, y; for
Ix
=
{
cout
" « « «
Y
E
1; x <= 5; x++, y++)
x « .. plus equals " « endl;
«y (x + y)
)
The loop's updare expression is x++, y++
This update expression increments both rhe x and y variables. The o utput produced by th is loop is 1 plus 1 equals 2 2 plus 2 equals
•
3 plus 3 equals 6
4 plus 4 equals 8 5 plus 5 equals 10
Connecting multiple statements with commas wo rks well in rhe in itia lization and update expressions, bur do not try to connect multiple expressions this way in th e test expression. If you wish to combine mu ltiple expressions in the test exp ression, you must use the && or
I I operatOrs.
Omitting the for Loop's Expressions The initialization expression may be om itted from inside the for loop's parentheses if it has already been performed or no initialization is needed. H ere is an example of the loop in Program 5-10 wirh t he initia lization being performed prior to the loop: int num = 1 ; for ( ; num <- maxValue; num++) cout « num « "\t\t" « (num * num) «
endl;
277
278
Chapter 5 looping
You may a lso omit the update expression if it is being performed elsewhere in rhe loop or if none is needed. Although this type of code is nOt recommended, the fo llowing for loop works just like a while loop: int num - 1; for ( ; num <= maxValuei {
cout «
nurn «
"\t\t" «
(num * num) «
endl:
num++; }
You can even go so far as to omit all three expressions from the for loop's parentheses. Be warned, howeve r, th at if you leave out rhe rest expression, me loop has no built-in way of terminating. Here is an example: for ( ; ; ) cout « "Hello World\n";
Because chis loop has no way of scopping, it will display "Hello World\n" forever (or until something interrupts the program) .
,
.In the Spotlight: Designing a Count-Controlled Loop with the for Statement Your friend Amanda just inherited a European.sports car from her uncle. Amanda lives in the United States, and she is afraid she will get a speeding ticket because the car's speedometer indicates kilometers per h our. She has asked you to write a program thar displays a table of speeds in kilometers per hour with thei r values converted. to miles per hour. The formula for converting kilometers per how: to miles per hour is:
MPH = KPH' 0.6214
In the formu la, ~PR is the speed)n rniles per hour and KPH is rhe speed in kilometers per hoUl';
The table that your program displays should show speeds £rom 60 kiJometers per hour th ro ugh 130 kilometers pec hour, in increments of 'I 0, along-with their values converted to m)les per hour. The table should look something like this:
KPH
MPH
60
37.3
70
43.5
8Q
49.7
etc . ...
130
80.8
After thinking about this table of values, you decide that you will write a for loop that uses· a counter variable to hold the kilometer-per-hour speeds. The cou~ter's starting value.
5.6 Th.e for Loop
will be 60, its.ending value wiU be J30, and you wiU add 10 to the <:Qunter variable after each ireratiop. Insid~ the loop you wi(! \.Ise the counter variable to calculate a speed In ·hJiles-per-hour. Program 5:11 shows thl! tode. Program 5-11
1 II This prog~am co~verts the speeds 60 kph through 2 11130 kph (in 10 kph increments) to mph. J 'inc.lude <.iostream> .4 .incll:lde ' 5 using namespace std; 6 7 int main( l 8 (
int kphi double mph;
9 ·10
11 12
II To hold speeds in kph II To ·hold s~eeds in mph
II Set the numeric out'put fOl:::matting. _ cout « fixed « showpoint « setpre:ci~i0n,
l3
"
1S
II Display the table headings. « "KPB\tMPH\n";
16
cout cout
17
\"
Ig
«
"--------------\n·';
II Display the speeds. for (kph = 60 ; kph .<= 130; '-kph +=
2.0 21
~O)
{
22
II Calculate mph
2~
mph
= kph *
0 . 6214;
.24
II Displ ay the speeds in kph and mph. cout « kph « ' ·\t ·, « mph « endl;
25
26 27
28 .29 .]{)
} return 0; }
Program Output KPH
MPH
--------------
60 70 80 90 100 110 120 130
37.3 43 . 5 49.7 55 . 9
62 . 1 6S . 4 74 .6 SO.8
279
280
Chapter 5
~
looping
Checkpoint 5 .6
Name the three expressions that appear inside the parentheses in the for loop's
header. 5. 7
You wa nt to write a for loop that displays " I love co program" 50 ti mes . Assume t hat you w ill use a counrer variable named c ount.
A) W hat initia lization expression wi ll you use?
B) What test expression wiH you use? C) What update expression will you use?
D) Write the loop.
5.8
W hat will the fo llowing progra m segments displ ay? A) for (iot count: 0 ; count < 6 ; count ++) cout « (count + count);
B) for (i nt value = - 5; value < 5 ; v alue++) cout « va l ue ; C) iot x; for ( x -
5; x
cout « X « endl ; cout « x « endl ; 5.9
W rite a f o r loop t ha t displays your name 10 times.
5.1 0
Write a f or loop that displays all of the odd numbers, 1 through 49.
5.11
Write a f o r loop that displays every fifth number, zero through 100.
Keeping a Running Total CONCEPT: A nHltting total is a s um of n umbe rs that accumulates w ith each itera ti on
of a loop. T he var iable used to keep the running rotal is called an accumulator. Many progra mming tasks require you ro calculate the ronll of a series of numbers. For example, suppose you are writing a program tha t ca lcula tes a busi ness's rotal sales for a week. T he program wou ld read the sales for each day as input and calculate t he total of those numbers. Programs that calculate the total of a series of numbers typically use two elements: •
A loop that reads each nu mber in the series.
•
A variable that accumula tes the total of the numbers as they are read.
The variable that is used ro accumulate the total of the nu mbers is ca lled an accu111ulator. It is often said t har the loop keeps a running total because it accumulates [he toral as it rea ds each number in the series. Figu re 5-12 shows rhe genera l Jogic of a loop thar calculates a running tota l.
5.7 Keeping a Running Total
Figure 5 -12
Logic for calculating a running total
Set accumulator to 0
Yes Is there a number to read?
(True)
Read the number
Add the number to the accumulator
No (False)
When the loop fi nishes, the (1ccumularor wi ll cont(1 in the tOral of the numbers thar were read by (he loop. Notice that the first step in the flowchaa is to set the accumulator variable to O. This is a critical step. Each time the loop reads a number, it adds it to the accumulatOr. If the accumulator stans with any value othe r than 0, it will not contain the correct total when the loop finishes. Let's look at a program that calculates a running total. Program 5-12 calcula tes a company's total sales ovcr a period of time by taking daily sales figures as input and calculat-
ing a running total of them as they arc gathe red Program 5-12 1 2
] 4 5 6
7 8
9 10
II This program takes daily sales figures over a period of time II and calculates their total .
'include ' include using names pace std; intmain() {
int days; double total
= 0 . 0;
II Number of days If Accumulator , initialized with 0
11 12
II Get the number of days.
13
cout. «
"For how many days do you have sales; figures? ";
(program cominues)
281
Chapter 5 Looping
282
Program 5·12 ci n »
14
(continued)
days;
15
,.
II Get the sales for each day and accumulate a total . for (int count ~ 1 ; count <= day s ; count++)
16 17
{
19
double sales;
20
cout «
11
cin »
total +.. sales ;
22
23 24
M
«
count «
" : ";
1/ Ac cumulate t he running total .
)
1/ Display the t otal sales. fixed « showpoint «
25 26
cout « cout «
27
28 29
"Enter t he sales f or day
sa les;
setprecision(2);
"The total sales are S " «
total «
endl;
retur n 0 ; )
Program Output with Example Input Shown In Bold For how many days do you have sales figures? 5 [Enter] Enter the sales for day 1 : 489.32 [Enter) Enter the sales for day 2 : 421.65 [Enter] Enter the sales for day 3 : 497.89 [Enter] Enter the sal es f o r
day
4,
$1;2. )7 [lEnte r)
Enter the sales for day 5 ; 506.92 (Enter)
The total sales are $2448 . 15 Le['s take a closer look at this program. Line 9 defines the days variable, which will hold rhe number o f days that we have sales fi gures for. Line 10 defines the tot al variab le, which will hold the total sales. Because total is an accumu lator, it is initia lized with 0.0. In line 14 the use r enters the number of da ys that he or she has sales figu res for. The number is assigned to the days variable. Next, the for loop in lin es 17 through 23 executes.
In the loop's initia lization express ion, in line 17, the variable count is defined and ini tialized with 1. The test expressio n specifies the loop wj ll repeat as long as count is Jess than or equal to days. The update expression increments count by one at the end of each loop iteration. Line 19 defi nes a va ria ble named sal es . Beca use the variable is defined in the body o f rhe loop, irs scope is lim ited to rhe loop. During each loop iteratio n, the lIser en ters the amou nt of sales for a specific day, which is assigned ro rhe sales variable. This is done in line 21. Then, in line 22 the value of sales is added to the existi ng value in [he tota l variable . (Note that line 22 does not assign sales to total, but adds sa les to total. Put another way, rhis line increases total by the amou nt in sales.) Because total was initially assigned 0.0, after the first iteratio n of [he loop, total will be set to the same va lu e as sales. After each subsequent iteration, tota l will be increased by the am ount in sales. After the loop has finished, total will contain [he tota l of a ll t h e dail y sa les figures enter ed. Now it should be clear why we assigned 0.0 to total before the loop executed. If total starred at any othe r va lue, the rotal would be inco rrect .
5.8 Sentinels
Sentinels C ONC EPT: A sentinel is a special va lue that marks the eo d of a list o f values. Program 5-12, in the previous section, requi res the lIser
to
know in advan ce the number
of days he or she wishes to enter sales fi.gures for. Sometimes the user has a list that is very long and doesn't know how many items t here are. In other cases, the user might be
entering severa l lists and it is impractica l to requi re that every item in every list be cou nted. A technique tb at can be used in these situations is to ask the user to enter a sen tinel at the end of the list_ A sentinel is a special value tha t cannot be mistaken as a member of (he list and signa ls that there are no mOfe va lues to be entered. When the user enters the sentinel, the loop terminates.
Program 5-13 calculates the total points earned by a soccer team over a series of games. It allows the user to emer the series of game poims, then -1 to Signal tbe end of the list. Program 5-1:J 1 II This program calculates the total number of points a 2 II soccer team has earned over a series of games . The user
3 4 5 6 7 8 9 10
1/ enters a series of point values , then -1 when finished. 'include using namespace std; int main() {
int game - 1, pOints, total = 0;
11
II Game counter II To hold a number of points II Accumulator
12
cout « "Enter the number of points your team has earned\n"i cout « "so far in the Season, then enter - 1 when finished . \n\ n"; cout « ··Enter the points for game ., « game « cin » points;
13 14 15
M.
16
";
17
while (points 1= -1)
IS 19
{
20
total += points; game++ ; cout « "Enter the points for game" « ein » points;
21
22 23
24
I
25
cout « "\nThe total points are" « return 0 ;
26
27
game «
total «
": ";
endl;
)
(program output continues)
283
284
Chapter 5 looping
Program 5- 13
(continued)
Program Output with Example Input Shown In Bold Enter the number of points your team has earned so far in the season, then enter - 1 when finished. 7 [Enter] Enter the points for game Enter the points for game 2 , 9 [Enter]
"
Enter the points for game 3 , 4 [Enter]
Enter the points for game 4 , 6 [Enter] Enter the points for game 5 , 8 [Enter) Enter the points for game 6 , -1 [Enter] The total pOints are 34
The value -1 was chosen for the senti nel in this program because it is not possible for a team to score negative points. Notice that this program performs a priming read in line 18 to get the firs t value. This makes it possib le for the loop to immediately termina te if rhe user enters -1 as the first va lue. Also note that the sentinel value is not included in the runni ng total.
Using a Loop to Read Data from a File CONCEPT: When reading a value from a fil e: with the stream extraction operator, th e
operator returns a true or false value indica ting whether th e val ue was successfull y read. T his return valu e can be used to detect when the end of a fi le has been reached. A loop can be used to read {he items stored in a file. For example, sup pose the file numbers. txt exists with rhe following coments. 8 7 3 9 12
As you ca n see, there are five numbers stored in the file. Program 5-14 uses a loop to read the five numbers and display them on the screen.
Program 5-14
1
II This program displays five numbers in a file.
2 3
'include ' include using namespace std;
4
5 6 7
a
int main( l {
ifstream inputFilei
II File stream object
5.9 Using a l oop to Read Data from a File
9 10
int numberi
II To hold a value from the f ile
int count'" 1:
II Loop counter , initialized with 1
11
12
inputFile . open("nurnbers.txt"Ji if (!inputFile)
13
cout « else
14 15 16 17 18 19 20
"Error opening file . \n";
{
whi l e (count <= 5) {
inputFile » number ; cout « number « endl: count++;
21
22 23 2. 25 26
II Open the file. II Test for errors.
/1 Read a number. II Display the number. /1 Inc~ement the counter.
)
II Close the file.
i nputFile.c l ose(); )
return 0 : )
This program is limited, however, beca use it depends on the file hav ing five numbers stored in it. If the file con tains fewer than five numbers, a n error w ill occur because the program will attempt to read beyond the end of the file. 1£ the file ha s mo rc rhan five numbers stored in it, the program will on ly display the first five. In many cases the exact number of items sto red in a file is unknown and the program must have a way of detecting the end of the fi le. Fortuna tely, you can use rhe » operator to do this. T he stream extraction operator (») not only reads data from a file, but it also returns a value indicating whether the data was successfull y rea d or not. If the ope rator returns true, then a value was successfull y read. If the operator returns false, it means that no value was read from the file. For example, look at the following code. if (inputFile »
number)
{
1/ Data was successfully read fr om the f il e. cout « "The data read from the file is " « number «
endl;
)
else {
1/ No data was read from the file, COUt ~~ "Could nolo road an item f rom the f ile. \ n" ; )
Notice that the statement that reads an item from the file is a lso used as the conditiona l expression in the if statement: if (inputFile »
number)
This sta temen t does two things:
1. It uses the exp ress ion inputFile » number to read an item from the fil e and stores the item in the number variable. T he» operator returns true if the item wa s successfully read, or false otherwise. 2. It tests the value returned by the srrearn extraction operator.
28'
286
Chapter 5 Looping
You can use the stream extraction operatOr's return value in a loop to determine when the end of the file has been reached. H ere is an example: while (inputFile »
number)
{
cout «
number «
endl:
)
Because the va lue returned from the» operator controls the loop, it will read items from the file until the end of the file has been reached. Program 5-15 is a modification of Program 5-14. Instead o f reading the nrst five items in the file, however, this program reads all of the items in the fi le rega rdless of how ma ny there are .
Program 5-15 1
1/ This pr ogram displays all of the numbers in a file .
2
'include
3
'include
4
using narnespace std;
5
6
intmain()
7
{
8
ifstream inputFile ;
g
lnt number:
II File stream object II To hold a v alue from the file
10 inputFile. open ( "n umbers. txt" ) ; II Open the file. inputFile) II Test for errors. cout « "Error opening file. \n"; else
11
12
i f (I
13 14 15
16
while (inputFile »
17 18
{
19 20
}
cout «
end1;
inputFi1e.c1ose{ )i
21 22
23
number «
number)
II Re ad a number
II Display the number. II Close the file.
return 0; )
~ Checkpoint 5.12 5.13
Write a for loop thar repeats seven rimes, aski ng rht: user ro ente r a number. T he loop should also calcu late the sum of the numbers entered. In the followi ng program !;cgment, which va riable is the counter variable and which is the accumu lator? int a , x, y 0; for (x ,., 0; x < 10 ; x++) (
cout « "Ent er a number : " ; cin » a; Y + .. a j )
cout «
"The sum of those numbers is " «
y «
endl;
5.11 Neted l OOpS
5.14
Why should you be careful when choosing a sentinel va lue?
5.15
How would you modify program 5-13 so any negative value is a sentinel?
5.] 6
Assume that a file named values. txt exists and that it coma ins a series of nllmbers, ooe per lioe in the file. Also assume that a program can successfully execute the following statements to open the file: ifstream inputFilei input File . open ( "values. txt" ) ; Write a loop that reads each number from the file and displays each number on the screen .
Focus on Software Engineering: Deciding Which Loop to Use CONCEPT: Although most repetitive algorithms can be written with any of the three types of loops, each works best in different situations.
Each of the three C++ loops is idea l to use in differem sicu arions. Here's a short summary of when each loop shou ld be used. •
•
•
The while loop. The while loop is a conditional loop, which means it repeats as long as a particular condition exists. It is also a pretest loop, so it is ideal in situations where yOti do not want the loop [Q iterate if the condition is false from the begi nning. For example, va lidati ng input that has been read and reading lists of data terminated by a sentinel value are good applications of ~he while loop. The do-while loop. The do-while loop is also a conditional loop. Unl ike the while loop, however, do-while is a posttest loop. It is ideal in situations where you always want the loop ro iterate at least once. The do-while loop is a good choice for repeating a menu. The for loop. T he for loop is a pretest loop that has bu ilt-in expressions for initializing, testing, and updat ing. T hese express ions make it very convenient to use a counter variable to conrrol [he number of iterations [hat the loop performs. The initialization expression can in itialize the counter variab le to a srarting val ue, the test expression can rest the counter variable to determine whether it holds the maximum value, and the upda te expression can increment the coumer variable. The for loop is ideal in situations where the exaCt num ber of iterations is known.
Nested Loops CONCEPT: A loop that is inside another loop is called a nested loop. A nested loop is a loop that appears inside another loop. A dock is a good example of somedung that works like a nested loop. The second hand, minute hand, and hour hand all spin
around (he face of {he dock. The hour hand, however, only makes one revolution for every 12 of the minute hand's revolutions. And it rakes 60 revolutions of the second hand for [he
287
288
Chapter 5 l ooping
minute hand to make one revo lution. T his means [hat for every complete revolution of the hour hand. the second hand has revolved 720 rimes.
Here is a progra m segment with a for loop that partially simulates a dig ital clock. It displays the seconds from a [Q 59: cout «
fixed «
couto fill( '0') i
for (int seconds cout «
right ;
= 0;
s e tw{2) «
seco nds < 60; seconds++ ) seconds «
end1;
NOTE : The fil l member function of coutchanges the fi ll character, which is a space by defa ult. In the program segment above, the fill fu nction causes a zero to be printed in front of all single digit numbers. We can add a minut es va riable and nt;s[ the loop above inside a not her loop that cycles
th rough 60 minutes: cout « fixed « right; cout.fill( ' O' ) ; for ( int minu t es = 0; minutes < 60; minutes++) {
for (int seconds = 0 ; seconds < 60; seco nds++ ) {
cout « cout «
minutes « seconds «
setw( 2 ) « setw( 2 ) «
.
. .
" . "
endl ;
} }
To make the simulated dock complete, an o ther va riable and loop can be added the hou rs:
cou t « fixed « right ; cout . fi ll ( '0' I; for (int hours = 0 ; hours < 24 ; hours++) {
for (int minutes
=
0 ; minutes < 60 ; minutes++ )
{
f or (int seconds
=
0 ; seconds < 60; seconds++)
{
cout « cout « cout «
setw(2) « setw(2) « setw( 2) «
hours « " :" ; minutes « ":"; seconds « end l;
}
}
}
The output of the previous program segment follows: 00 : 00 : 00 00 : 00 : 01 00 : 00:02
(The program will count through each secon d of 24 ho urs.)
23 : 59 : 59
to
count
5.11 Nested l oops
T he innermoSt loop will iterate 60 times for each iteration of tbe middle loop. The middle loop will iterate 60 times for each iteration of the outermost loop. When the outermost loop bas iterated 24 times, the middle loop will have iterated 1,440 times and the innermost loop will have ite rated 86,400 times! The simulated clock example brings up a few points about nested loops: • • •
An in ner loop goes through al l of its itera tions for each iteration of an outer loop. Inner loops complete their iterations faster than outer Joops. To get the total number of iterations of a nested loop, multiply the number of iterations of all the loops.
Program 5-16 is another tcst-averaging program. It asks the user fo r the number of S[Udents and the nllmber of test scores per student. A nested inner loop, in lines 26 through 33, asks for all the test scores for one student, itera ting once fo r each test score. T he outer loop in Jines 23 through 37 iterates once fo r each student. Program 5-16 1
II II
This program averaqes test scores . It asks the user for the number of students and the number of test scores per student. 3 'include 4 'include 5 using namespace std ; 6 7 int main( 1 2
8 (
9 10 11 12
int numStudents, numTests ; double total , average;
II II II II
Number of students Number of tests per student Accumulator for total scores Average test score
13
14 IS 16 17
18 19 20 21 22
23 24 25
II Set up numeric output formatting. cout« fixed « showpoint « setprecision(l) ; II Get the number of students . cout« "This program averages test score s . \n" ; cout« "For how many students do you have scores? "; cin » numStudents; II Get the number of test scores per student . cout« "How many test scores does each student have? "i cin » numTests;
27
II Determine each student's average score . for (int stude nt : 1; student <= n umStude nts; student++)
28
{
26
2'30 31
32 33 3<
total"" 0; for (int test
II Initialize the accumulator . 1 ; test <= numTests ; test++)
(
double score; cout « "Enter score " « test « " for "; cout « "student" « student « " . ";
(program continues)
289
290
Chapter 5
Program 5- 16
Looping
(continved)
score; total += score;
35 36
cin »
37
)
38 39
average = total I numTests; cout « "The average score for student " « cout « " is " « average « ".\n\o";
40 41 42 43 }
student;
return 0;
Program Output with Example Input Shown In Bold This program averages test scores. For how many students do you have scores? 2 [Enter) How many test scores does each student have? 3 [Enter] Enter score 1 for student 1: 84 (Enter] Enter score 2 for student 1 : 79 [Enter]
Enter score 3 for student 1 : 97 [Enter]
The average score for student 1 is 86 . 7. Enter score 1 for student.
,,
92 [Enter]
Enter score 2 for student 2 , 88 [Enter] Enter score 3 for s tudent 2 , 94 [Enter] The average score for student
, is
9 1. 3.
Breaking Out of a Loop CONCEPT: T he break statement causes a loop to terminate early.
CD
WAR N I NG! Use the break. sta tement with great caution. Beca use it bypasses the loop condition to terminate the loop, it makes code difficult to understand and debug. For th is reason, you should avoid using break when possible. Because it is part of the C++ language, we discuss it briefly in this section.
Sometimes it's necessary to StOp a loop before it goes through a ll its iterations. The break statement, which was used with switch in Chapter 4, can a lso be placed inside a loop. When it is encountered, the loop stops and the program jumps to the statement immediately foll owi ng tbe loop. The while loop in rhe following program segment appears break. statement causes it to StOp after the fifth iteration. int count'" 0; while (count++ < 10) {
cout « count « if (count == 5) break; )
endli
[Q
execure 10 rimes, bur [he
5.12 Breaking Out of a l oop
Program 5-17 uses the break sta tement to interrupt a for loop . The program asks the user for a number and rhen disp lays the value of that number raised to the powers of a through 10. The user cao StOp the loop a r any rime by entering Q.
Program 5-17
, 2 3 4 5 6
, 7
II This program raises the user ' s number to the
'include iinclud e using names pace std; int main() {
double value; char choic e i
9
10 11 12
COllt « "Enter a number : "; cin » value; COllt « "This program will raise " « value; cout « " to the po~ers of 0 t hrou gh 10 , \n" ; for (int count = 0 ; count <= 10; count++)
13 14
15 16 17 18
{
cout « value « " r aised to the power of "; cout « count « is " « pow(value, cou nt) ; cout « "\nEnter Q to quit or any other key" ; c out « "to continue. " ; cin » c hoice ; i f (choice """ ' Q' II choice """" 'q') break;
19 20 21 22 23 24 25
return 0;
26 27
po~er5
II of 0 through 10.
}
Program Output with Example Input Shown In Bold Enter a number: 2 [Enter] This program will raise 2 to the powers of 0 through 10. 2 raised to t he power of 0 is 1 Enter Q to quit or any other key to continue. C (Enter) 2 raised to the power of 1 is 2 Enter Q to quit or any other key to continue. C (Enter] 2 raised to the power of 2 is 4 Enter Q to quit or any other key to continue. Q [Enter]
Using break in a Nested Loop 10 a nesred loop, (he break stltemen t only inrcrrupcs rhe loop it is pl aced in. The foUowi ng program segment displays five rows of asterisks on the screen. The outer loop controls the number of rows and me inner loop comrols the number of asterisks in each row. The inner loop is designed to display 20 asterisks, but the break statement StOpS it during [he eleventh iteration. for (int row
= 0;
row < 5; row++)
{
for (int star {
=
0; star < 20; star++ )
291
292
Chapter 5 looping
cout«
·It'j
i f (star == 10) break; )
cout «
endl;
)
The output of the program segment above is:
** •••••••••
........ .. "'** •• * .... _• _
.. " ........ ** •••
*_ ... ",,,,.,,* ...
The continue Statement CONCEPT: The continue statement ca uses a loop to stop its current iteration and begi n the next one.
CD
WARNING! As wi th the break sta tement, use continue with great caution. It makes code difficu lt to understand and debug. Because it is part of the C++ language, we discuss it briefl y in this section.
The continue statement causes the current iteration of a loop to end immediately. When continue is encounte red, a ll the statements in the body of the loo p thar a ppea r aftcr it ace
ignored, and the loop prepares fo r the next iteration. In a while loop, this means the program ju mps to the test expression at the top of the loop. As usual, if the expression is still true, the next iteration begins. In a do-while loop, the program jumps to the test expression a t the bottom of the loop, which determines whether the next iteration will begin. In a for loop, continue causes the update expres· sian to be executed, a nd then the test expression to be eva luated. T he following program segment demonsrrates the lise of continue in a while loop:
int testval = 0; while (testVal++ < 10) {
if (testVal == 4) conti nue; cout « testVal «
"
" ,-
This loop looks like it displays the integers 1 through 10. When testVal is equal to 4, however, the continue statement causes the loop to skip the cout statemem and begin the next iteration. The Output of the loop is 1 2 3 5 6 7 8 9 10
Program 5·18 shows a practical application of the continue statement. The program calculates the charges for DVD rentals. where current releases cost $3.50 and all others cost
5.13 The continue Statement
$2.50. If a customer rents severa l OVOs J eve ry th ird o ne is free. The continue statement is used to skip the part of the loop that calculates the charges fo r every third DVO .
Program 5-18 1 II This program ca lculates the charges for OVO rentals. 2 /1 Every th ird OVO is free. 3 ' i nclude 4 iinclude
.
5 using namespace std ; 6 7
9 10
11 12 13
int main ( ) { int dvdCount = Ii int numDVDs; double total = 0.0; char current;
14
II DVO counter II Number of DVDs rented II Accumulator II Current release, Y or N
II Get the number of DVDs. cout « "!:low many DVOs are being rented? "; cin» numDVDs;
15 16
17 18
II Determine the charges .
19
do
20
{
21
if ( (dvdCount % 3)
22
{
==
0)
cou t « "OVO t" « dvdCount « " is freel\n"; c o ntinue: // Immediately start the next itera tion
23 24 25
}
cout « "Is DVD '" « dvdCount; cout « " a c urrent release? (YIN) "; cin » current; if (current == 'Y ' I I current == 'y' J total += 3 .5 0 ; else total += 2 . 50; while (dvdCount++ < numDVDs) ;
26 27 28 29
30 31
32 33 34
II Disp lay the t otal. cout « fixed « showpoint « setprecision(2); cout« '·The total is $" « total « endl: return 0 ;
35
36 37 38 39 )
Program Output with Example Input Shown In Bold How m,any DVDs are being rented? 6 (Enter] Is DVD t1 a cur rent release? ( Y IN) 'f [Enter) Is DVD '2 a current release? (YIN) n [Enter] DVD '3 is free! Is DVD a current release? (YIN) n [Enter] Is DVD a current release ? (YIN) y [Enter) ovo 16 is free ! The total is $12 . 00
,.
'5
C=:.>
Case Stud y on CD: See the Loan Amortization Case Study on the Student CO.
293
294
Chapter 5 looping
Review Questions and Exercises Short Answer 1. Why should you indent the sta tements in the body of a loop? 2. Describe the difference between pretest loops and posttesr loops.
3. Why are the statements in the body of a loop called conditionall y executed statements? 4. What is the difference between t he while loop and the do-while loop ?
5. Which loop should you use in situations where you wish the loop to repeat until the test expression is fa lse, and the loop should not execute if the test expression is false to begin with ?
6. Which loop should you use in situations where you wish the loop to repeat until the test expression is false , but the loop should execute at least one time ? 7. Which loop should you use when you know the number of required ite rations? 8. Why is it critical tha t counter variables be properly initia lized? 9. Why is it critica l that accumulator variables be properly in itia lized? 10. Why should you be careful not to place a statement in the body of a for loop that cha nges the value of the loop's counter variable?
Fill-in-the-Blank 11. To a value means to increase it by One, and to decrease it by one.
to _ _ _ _
a val ue mea ns
12. When the increment or decrement operator is placed before the operand (or to the mode. operand's left), the operator is being used in 13. When the increment or decrement operator is placed after the operand (or to the opermode. and's right), the operator is being used in 14. The statement or block that is repeated is known as the _ _ _ _ of the loop. 15. Each repetition of a loop is known as a(n) _ _ __ 16. A loop that evaluates its test expression before each repetition is a(o ) _ _ _ _ loop.
1? A loop that evaluates its test expression after each repetition is a(o)
loop.
18. A loop that does not have a way of stopping is a(o) _ _ _ _ loop. 19. A( n) _ _ _ _ is a variable that "counts" the number of times a loop repeats. 20. A(n)
is a sum of numbers that accumwates with each iteration of a loop.
21. A(n) is a variable that is initialized to some starti ng value, usually zero, and then has numbers added to it in each iteration of a loop. 22. A{o) _ _ _ _ is a specia l value that marks the end of a series of values. 23. The
loop always iterates at least once.
Review Questions and Exercises
24. The -,-_ _ _ and _ _ _ _ loops wi ll not iterate at all if their test expressions are false to start with.
25. The _____ loop is ideal for situations that require a counter.
26, Inside the for loop's parentheses, the first expression is the _ _ _ _ , the second expression is the
, and the third expression is the _____
27. A loop that is inside another is ca lled a(n) 28. T he
loo p.
statement causes a loop to terminate immed iately.
29. The _____ statement causes a loop to skip the remaining sta tements in the current iteration.
Algorithm Workbench 30. Write a while loop that lets the user enter a num ber. The num ber should be multiplied by 10, and the result stored in the va riable product. The loop shou ld iterate as long as product conta ins a value less than 100. 31. Write a do-while loop that asks the user to enter two numbers. The numbers should
be added and the sum displayed. The user should be asked if he or she wishes to perform the operation again. If so, the loop should repeat; otherwise it shou ld terminate.
32. Write a for loop that displays the following set of numbers: 0,
la,
20,
30,
40,
SO . . . 1000
33 . Write a loop that asks the user to enter a number. The loop should iterate 10 times and keep a runn ing total of the numbers entered.
34. Write a nested loop that displays 10 rows of '#' characters. There should be 15 '#' cha racters in each row.
35. Convert the following while loop to a do-while loop: int x .. 1 ; while (x > 0) {
cout « "e nter a number: "; cin » x; )
36. Convert the following do -while loop to a while loop:
char sure; do {
cout « "Are you sure you want t o quit? n; cin » sure ; } while (sure 1= 'Yo && sure != 'N');
37. Convert the following while loop to a for loop: int count:. 0 ; while (count < 50) {
cout « "count is " « count++; )
count «
endl;
295
296
Chapter 5
Looping
38. Convert the fo llowing for loop to a while loop: for (int x
= 50;
x > OJ x-- )
(
cout «
x «
" seconds to go.\n";
)
True or False 39. T
F
T he operand of the increment and decrement operarors can be any va lid
mathematica l expression.
40. T
F
The cout statement in the following program segment wi ll display 5: iot x - 5 ;
cout «
x++;
41. T
F
T he cout statement in the following program segment will display 5: int x ;" 5; cout « +'tXj
42, T
F
T he while loop is a pretest loop.
43, T
F
The do-while loop is a pretest loop.
44, T
F
The for loop is a posttest loop.
45. T
F
It is not necessary to initia lize counter variables.
46. T
F
All three of the
47. T
F
One limitation o f the for loop is that only onc variable may be initialized in the initialization expression.
48. T
F
Variables may be defined inside the body of a loop.
49. T
F
A variable may be defin ed in the initializa tion expression of the for loop.
50. T
F
In a nested loop, the ou ter loop executes faster than the inner loop.
51. T
F
Tn a nested loop, the inner loop go!!.\; th rough all of irs iterations for every sin-
for
loop's expressions may be omitted.
gle iteration of the o uter loop.
52. T
F
To calcu late the total number of iterations of a nested loop, add the number of iterations of all the loops.
53. T
F
The break sta tement causes a loop to stop the current iteration and begin the next one.
54. T
F
The continue statement causes a terminated loop to resume.
55. T
F
In a nested loop, the break statement only interrupts the loop it is placed in.
Find the Errors Each of the following programs has errors. Find as ma ny as you can.
56. II Find the error in this program . tinclude
using namespace stdj int main ( ) {
int num1
0, num2 : 10, result:
Review Questions and Exercises
numl++; result'" ++(nurnl + nurn2l; cout « nurnl « " " « num2 « return 0 ;
" " «
result;
)
57. II This program adds two numbers entered by the user . 'include using narne space std; i nt main ( ) {
int nurn l, num2 ; char aga in ; while (agai n .... 'y' II again == 'Y') cout « "Enter a number : " ,. c i n » numl; cout « "Enter another number : "; cin » num2 ; cout « "Their sum is « (nurnl + nurn2) « endl; cout « " Do you want to do this again? n; cin >::> again ; retur n 0 ; }
58. I I This program uses a loop to ra i se a number to a power. ' i nclude us i ng name s pace std ; int main() {
int nurn, bigNum, power , count ; cout « "Enter an integer : " ; cin » num ; cout « "What power do you want it raised to? n; cin » power; bigNum '" num ; while (count++ < power); bigNum w= nurn; cout « "The result is « bigNurn « endl; return 0:
59. 1/ This program averages a set of numbers . ' include using namespace std: int main() {
int numCount, total ; double average: cout « "How many numbers do you want to average? " ; cin » numCount ;
297
298
Chapter 5
Looping
0; count < numCount; count++)
for (int count {
int num; cout « "Enter a number : ft;
cin »
num;
total += nurn; count++; }
average = total / numCount; cout « "The average is « return 0 ;
average «
endl ;
}
60. II
This program displays the sum of two numbers.
'include using namespace std;
int main() {
int choice, numl, num2; do {
cout « cin »
"Enter a number:
cout «
cin »
M;
numl;
"Enter another number: ";
num2;
cout « "Their sum is " « (num! + num2) « cout « "Do you want to do this again?\n"; cout « "1 = yes, 0 : no\n"; cin » choice ;
} while (choice
endl:
= 1)
return 0 ;
61. II This program di splays the sum of the numbers 1-100. 'include using namespace std;
iot main() {
int count
c
1, total;
while (count <- 100) total +'" count ; cout « "The sum of the numbers 1-100 is cout « total « end1 ; return OJ }
"j
Review Questions and Exercises
Programming Challenges 1. Sum of N umbers Write a program that asks the user for a positive integer value. The program should use a loop to get the sum of aU the integers from 1 up to the number entered. For example, if the user enters 50, the loop will find the sum of 1, 2, 3, 4, ... 50.
Input Validation: Do not accept a negati/Je starting number. 2. Characters for the ASCII Codes Write a program that uses a loop to display the characters for the ASCII codes 0 through 127. Display 16 characters on each line.
3. Ocean Levels Assuming the ocean's level is currently risi ng at about 1.5 millimeters per year, write a program that displays a table showing the number of millimeters that the ocean will have risen each year for the next 2S years .
4. Calories Burned Running on a particular treadmill you burn 3.9 ca lories per minute. Write a program that uses a loop to display the number of calories burned after 10, I S, 20, 25, and 30 minutes. Solving the Calories BlImed
Problem
5. Membership Fees Increase
A country club, which currently charges $2,500 per year for membership, has announced it will increase its membership fee by 4% each year for the next six years. Write a program that uses a loop to display the projected rates for the next six years. 6. Distance Traveled The dista nce a vehicle navels can be calculated as follows: distance
~
speed * time
For example, if a trai n travels 40 miles per hour for 3 hou rs, the distance traveled is 120 mi les. Write a program that asks the user for the speed of a vehicle (in miles per hour) and how many hours it has traveled. The program should then use a loop to display the distance the vehicle has traveled for each hour of that time period. Here is an example of the output: What is the speed of the vehicle in mph? 40 How many hours has it traveled? 3 Hour Distance Traveled
2
40 80
3
120
I
Input Validation: Do not accept a negative number for speed and do not accept any /Jalue less than 1 for time trafJe/ed.
299
300
Chapter 5 l ooping
7. Pennies for Pay Write a program that ca lculates how much a person would earn over a period of time if his or her sa lary is one penny the first day and two pennies the second day, and continues to double each day. The program should ask the user for the number of days. Display a table showing how much the sa lary was for each da y, and then show the tota l pay at the end of the period. The output should be displayed in a dollar amount, not the number of pennies. Input Validation: Do ,lOt accept a number less than 1 for the number of days worked.
8. Math Tutor This program started in Programming Challenge 15 of Chapter 3, and was modified in Programming Challenge 9 of Chapter 4. Modify the program again so it displays a menu allowing the user to selecr an addirion, subrraction, multiplication, or division prob lem. The final selection on the menu should ler the user quit the program. After the user has finished the math problem, the program should display the menu again. This process is repeated until the user chooses to quit the program. Input Validation: If the user selects an item not on the menu, display an error message and display the menu again.
9. Hotel Occupancy Write a program that calculates the occupancy rate for a hotel. The program should start by asking the user how many floors the hotel has. A loop should then iterate once foe each fl oor. In each iteration, the loop should ask the user for the number of rooms on the floor and how man y of rhem are occupied. After all rhe iterations, the program should display how many rooms rhe hotel has, how many of them are occupied, how many are unoccupied, and the percentage of rooms that are occupied. The percentage ma y be ca lculated by dividing the number of rooms occupied by the number of rooms.
o
is traditiona l that most hotels do not have a thirreenth floo r. The loop in this id _ skip the enti re _ th__ irreenth irera L program -_ _ _ _sholl ___ __ __ __ ___ _ _rion. ____________________ NOTE : It
~
Input Validation: Do not accept a value less than 1 for the number of ~oors. Do not accept a number less than 10 for the number o( rooms on a {loor. 10. Average Rainfall Write a program that uses nested loops to collect data and ca lculate the average rainfall over a period of years. The program should first ask for rhe number of years . The outer loop will iterate once for each year. The inner loop will iterate twelve times, once for each month. Each iteration of the inner loop will ask the user for the inches of ra infall for that month. After all iterations, the program should display the number of months, the total inches of rainfall , and the average rainfall per month for the entire period. Input Validation: Do not accept a number less than 1 (or the number of years. Do not accept negative numbers for the monthly rainfall.
Review Questions and Exercises
11. Population Write a program that will predict the size of a population of organisms. The program should ask the user for [he starring number of organisms, their average daily population increase (as a percentage), and the number of days they will multipJy. A loop should display the size of the population for each day. Input Validation: Do not accept a number less than 2 for the starting size of the population. Do not accept a negative number for average daily population increase. Do not accept a number less than 1 for the number of days they will multiply.
12. Celsius to Fahrenheit Table In Programming Challenge lOaf C!w.pter 3 you were asked to write a program th at converts a Celsius temperature to F;Hrcn heit. Modify that program so it uses a loop to display a table of the Celsius temperatures 0-20, and their Fah renheit equ ivalents.
13. The Greatest and Least of These Write a program with a loop that lets the user enter a series of integers. The user should enter -99 to signal the end of the series. After all the numbers have been entered, the program should display the largest and smallest numbers entered. 14. Student Line Up
A teacher has asked all her studen ts to line up single fi le according to their first name. For example, in one class Amy will be at the front of the line and Yolanda will be at the end. Write a program that prompts the user to enter the number of students in the class, then loops to read in that many names. Once all the names have been read in it reports which student wou ld be at the front of the line and which one would be at the end of the line. You may assume that no two students have the same name. Input Validation: Do not accept a number less than 1 or greater than 25 for the number of students.
15 . Payroll Report Write a program that displays a weekly payroll report. A loop in the program should ask the user for the employee num ber~ gross pay, state tax, federal tax, and FICA withholdings. The loop will terminate when 0 is entered fo r the employee number. After the data is emered, the progra m shou ld display totals for gross pay, state tax, federal tax, FICA withhold ings. and net pay. Input Validation: Do not accept negative numbers for any of the items entered. Do not accept values for state. federal, or FlCA withholdings that are greater than the gross pay. If the sum state tax + federal tax + FICA withholdings for any employee is greater than gross pay, print an error message and ask the user to re-enter the data for that employee.
16. Savings Account Balance Write a program that calcul:ttes the balance of a savings account at the end of a period of time. It should ask the user for the annual interest rate, the sta rting balance, and the number of months thar ha ve passed since the account was establ ished. A loop should then iterate once for every month, performing the following:
301
302
Chapter 5
looping
A) Ask the user for the amount deposited into the account during the month. {Do not accept negarive numbers.} This amount should be added to the balance. B) Ask the user for the amount withdrawn from the account during the month. (Do not accept negative numbers.) This amount should be subtracted from the ba lance.
C) Calculate the monthly interest. The monthly interest rate is the annual interest rate divided by twelve. Multiply the monthly interest rate by the ba lance, and add the result to the balance. After the last iteration, the program shou ld display the ending balance, the total amount of deposits, the total amount of withdrawa ls. and the total interest earned. ~
NOTE : If a negative balance is calcu lated at any point, a message should be displayed
~ L-j_n_d_jc_a_t_jn_gO-th_e__a_c_co_u_n_t__h_a_s_b_c_c_n_c_lo_s_e_d_a_n_d__'_h_e_l_o_o~p_s_h_o_u_ld__,_e'_m __jn_a_,_e_.________________~
17. Sales Bar Chart Write a program that asks the user to enter today's sales for five stores. The program should then display a bar graph comparing each store's sales. Create each bar in the bar graph by displaying a row of asterisks. Each asterisk should represent $100 of sales. Here is an example of the program's output. Enter Enter Enter Enter Enter
today's today's today's today's today's
sales sales sales sales sales
for for for for for
store store store store store
"2,
1000 [Enter] 1200 [Enter]
3, 1800 [Enter] 4, 800 [Enter] 5, 1900 [Enter]
SALES BAR CHART
..
(Each * ... $100) 1; -~~~« **. 2 : ************ 3: ******************
Store Store Store Store Store
4: ******** 5 : *******************
18. Population Bar Chart Write a program that produces a bar chart showing the population growth of Pra irieville, a small town in the Midwest. at 20-yea r intervals during the past 100 years. The program should rcad in the population figures (rounded to the nearest 1,000 peo-
ple) for 1900, 1920, 1940, 1960, 1980, and 2000 from a file. For each year j, should display the date and a bar consisting of one asterisk for each 1,000 people. The data can be found in the people. dat file.
Here is an example of how the charr might begin; PRAIRIEVILLE POPULATION GROWTH (each· represents 1,000
1900 ** 1920 **** 1940 *****
peop~e)
Review Questions and Exercises
19. Budget Analysis Write a program that asks the user to enter the amount that he or she has budgeted for a month. A loop should then prompt the user to enter each of his or her expenses for the month , and keep a running total. When the loop fin ishes, the program should display the amount that the user is over or under budget. 20. Random Number Guessing Game
Write a program that generates a random number and asks the user to guess what the number is. If the user's guess is higher than the random number, the program should display "Too high, try again." If the user's guess is lower chan the random number, the program should display "Too low, try again." The program should use a loop that repeats until the user correctly guesses the random number. 21. Random Number Guessing Game Enhancement
Enhance the program that you wrote for Programming Challenge 20 so it keeps a count of the number of guesses that the user makes. When the user correctly guesses the random number, the program should display the number of guesses. 22. Square Display
Write a program that asks the user for a positive integer no greater than 15. The program shou ld then display a square on the screen using the character 'X'. The number entered by the user wi ll be the length of each side of the square. For example, if [he user enters 5, the program shou ld display the following:
xxxxx xxxxx xxxxx
xxxxx xxxxx If the user ente rs 8, [he program should display the follow ing:
xxx xxx xx xxxxxxxx xxxxxxxx xxxxxxxx
xxxxxxxx
xxxxxxxx
xxxxxxxx xxxxxxxx 23. Panern Displays
Write a program that uses a loop to displa y Pattern A below, fo llowed by another loop that displays Pattern B.
303
304
Chapter 5 l ooping
Pattern A
Pattern B
+
+++++++ +++
++
+++++++++
+++ ++++
++++++++ +++++++
+++++
++++++
++++++
+++++
++++ ++++++++ +++++++++ ++++++++++
+++ ++ +
24. Using Files-Numeric Processing The Student CD contains a fil e named random. txt. This fi le contains a long list of random numbers. Copy the file to your hard dri ve and then write a program that opens the file, reads all the numbers from the fi le, and calculates the fo llowing: A) The number of numbers in the fi le B) The sum of all the numbers in the file (a running total ) C) The average of all the numbers in the fil e The program should display the number of numbers found in the file, the sum of the numbers, and t he average of the n umbers.
25 . Using Files-Student Line Up Modify the Student Line Up program described in Programming Cha llenge 14 so that it gets the names from a da ta fil e. Names should be read in until there is no more data to read . Dam to tesr your program can be found in rhe Lineup.dat file. 26. Using Files-Savings Account Balance Modification Modify the Savings Account Balance program described in Programming Cha llenge 16 so that it writes the final report to a file. After the program runs, print the file to hand in to your instructor.
Serendipity Booksellers Software Development ProjectPart S: A Problem-Solving Exercise 1. Data Validation Modification
In Part 4 of this project you used i f statements in each module to valida re the input. Modify the code to use while loops instead. 2. The Main M enu Item four on the Main Menu is "Ex it," which allows the user to end the program. Add a loop to the mainmenu. cpp program that causes it to repeatedly display the menu until rhe user selects irem four.
Review Questions and Exercises
3. The Inventory Database Menu Item five on the Inventory Database Menu is "Return to the Main Menu ." When the project is complete, this item will cause the program to branch back to the main menu. For now, add a loop to the invrnenu. cpp program that causes it to repeatedly display the menu until the user selects item five. 4. The Reports Menu
Item seven on the Reports Menu is "Return to the Main Menu." When the project is complete, this item will cause the program to branch back to the main menu. For now, add a loop to the reports . cpp program that causes it to repeatedly display the menu until the user selects item seven. 5. The Cashier Module After the user ha s entered the data for a sa le and the sim ulated sa les slip is displayed,
add code that asks the cashier if another transaction is to be processed. If so, the program should repeat.
6.1 6.2 6.3 6.4 6.5 6.6
Focus on Software Engineering: Modula r Prog ramming Defining and Call ing Functions Function Prototypes Sending Data into a Function PaSSing Data by Value Focus on Software Engineering: Using Functions in a Menu-Driven
Program 6.7 6.8
6.9
6.13
Returning a Boolean Value Local and Global Variables Static Local Variables Default Arguments Using Reference Variables
6 .14
Overloading Functions
6.10
6.11 6.12
as Parameters 6.15 The exit ( ) Function 6.16 Stubs and Drivers
The return Statement Returning a Value from a Function
Focus on Software Engineering: Modular Programming CONCEPT: A program may be broken up into manageable fu nctions. A function is a collection of statementS that performs a specific task. $0 far you have experi-
enced functions in rwo ways: (1) you have created a function named main in every program you've wrirren, and (2) you have used library functions such as pow and strcmp. In this chapter you will lea rn how to create your own fu nctions that can be used like library functions. Functions are commonly used to break a prob lem down into small manageable pieces. Instead of writing one long function that contains all of the statements necessary to solve a problem, several small functions that each solve a specific parr of the problem can be written. These small functions can then be executed in the desired order to solve the problem. 'This approach is sometimes called divide and conquer because a large problem is 307
308
Chapter 6
Functions
di vided into several smaller problems thar are easily sol ved . Figu re 6-1 illustrates this idea by comparing twO progra ms: one that uses a long complex function conta ining all of the statements necessary [0 solve a problem. and another that divid es a pro blem into smaller problems, each of which are hand led by a sepa rate function. FI9ure 6 -1
This program has one long, complex function containing all althe statements necessary to solve a problem .
In this program the problem has been divided into smaller problems, each of which is handled by a separate function.
j
j int main ( ) {
sta tement;
statement ; 3tlltement ; statement; statement;
statement; s tatement : statement ;
.. int maine) {. statement ; s.tatement: statement:
.
}
.
void function2_1)
!
statement;
statement ;
statement ; statement ; statement ; statement ; statement; statement; statement; statement ; statement; statement; statement ; statement; statement; statement;
main functIon
statement; statement; statement;
function 2
}
.
v:oid function3() {
statement ; s~,!ltement;
,..
function 3
statement: }
J
void function4 ( ) {
statement; stateme\'Lt; . statement; }
function 4 .
Another reason to write functions is that they simplify programs. If a specific task is performed in several places in a program, a function can be written once to perform that task, a nd then be executed anytime it is needed. This benefit of using func tions is known as code reuse beca use you are writing the code to perform a task once a nd t hen reusi ng it eac h time you need to perform the task.
6.2 Defining and Calli ng Functions
Defining and Calling Functions CONCEPT: A function call is a statement that causes a function to execu te. A fun crion definition contains rhe statements ,hat make up tbe fun ction .
When creating a funct ion, you must write its definition. All fu nction definitions have the following parts: Return type:
A func tion can send a value to the part of the program that executed it. T he return type is the data type of the va lue that is sent from the fu nction.
Name;
You should give each function a descriptive name. In general, the salle rules that apply to variable names also apply to funct ion na mes.
Parameter list:
The program ca n send data into a functio n. The parameter list is a list of variables that hold the values being passed to the function.
Body:
T he body of a fu nction is the set of statements that perform the function's operation, They are enclosed in a set of braces.
Figure 6-2 shows the definition of a simple func tion with the various partS labeled. Figure 6-2 Return type Parameter list (This one is empty) \ Function name/
...
~nt
..
,f
Function body
main ()
/
cout «
'·Hello World\n";
return 0; }
The line in the definition that reads int main () is called the functioll header.
void Functions You a lready know that a function can return a va lue. The main func tion in a ll of the progra m s
yO ll
have seen in this book is declared to re turn an int va lue to t he o p er a t ing sys-
tem. T he return 0; statement causes the value 0 to be returned when the main function fin ishes execu ting.
Jr isn't necessary fo r all functions ro retu rn a value, however. Some functions simply perform one o r more statements which follows terminate. These are ca lled void (linctions. The displayMessage function, which follows is an example. void displayMessaqe() {
CQut « }
"Hello from the function displayMessage. \n" ;
309
Chapter 6 Functions
3 10
The func tion's name is displayMessage. This name gives an indication of what the fune rion does: It displays a message. You sho uld always give functio ns names tha t reflect their
purpose. Notice that the function's reru m type is void. This means the function does not return a value ro the part of the program that executed it. Also notice [he (unction has no r e t urn statement. It si mply displays a message on th~ !Screen and exits .
Calling a Function A function is executed w hen it is wl/ed. Function main is called a uto matically when a program sta rts, but all other functions must be executed by (unction call Statements. When a function is called, the progra m branches to that function and executes the statements in its body. Let's look a t Program 6- 1, which contains (Wo functions: main and displayMessage. Program 6-1
] 2 3
II This program has two functions: main and displayMessage ' inc lude using namespace std i
4 5
6 7
ff ********************** * ****************** ff Definition of function di splayMessage *
fl This function d i sp lays a greeting .
*
8 9
10 II
void displayMessage() {
cout «
12 13
"
15 I.
17
"Hello from the function displayMessage. \n";
)
/1 ***************************************** II Function main //* ************************ **** ************
•
18 19 20
int main() {
21
cout « "Hello from main . \ n"; displayMessage(); cout « "Back i n fu nct ion main aga i n. \ n"; return 0 ;
22 23 24
25
)
Program Output
Hello from main. Hello from the function displayMessage. BaCK in function main again .
The func tion displa yMe ssage is cal led by [he followi ng statemenr in line 22: displayMessage();
6.2 Defining and Calling Functions
This statement is the func tion call. It is simply the name of the function followed by a set of parentheses and a semicolon. Let's compare this with the function header! Function Header - - ---+1 void displayMessage() Function Call I displayMessage() ; T he function header is pa rt of the func tion definition. It declares the function's return type, name, and pa rameter list. It is not terminated with a semicolon because the definition of the fun ction's body fo llows it. T he function call is a statement that executes the fu nction, so it is termi nated with a semicolon like all other C++ statements. The return type is not listed in the fu nction call, and, if the program is nOt passing data into the function, the parentheses are left empty. ~
NOTE: Later in this chapter you will see how data ca n be passed into a fu nction by being
~ L-J_;s_r_e_d_;_n_s;_d_e_r_h_e_p_a_r_e_n_r_he_s_e_s_._ _ __ _ _ _ _ __ __ _ _ _ _ _ __ _ _ _ _ _--' Even though the program starts executing at main, the function displayMessage is defined first. This is because the compiler must know the func tion's return type, the number of parameters, and the type of each parameter before the function is ca lled. One way to ensure the compiler will know this information is to place the function defini tion before a ll calls to that funct ion. (Later you will see an alternat ive, pre ferred method of accomplishing this.) NOTE: You should always document your fu nctions by wriring commentS (hat describe ()
what they do. These comments should appear just before the function definition. ~-----------------------~
Notice how Program 6-1 flows. It starts, of course, in function main. When the call to displayMessage is encounrered, the program branches to that func tion and performs its statements. Once displayMessage has fi nished executi ng, the program bra nches back to function main and resumes with the li ne that follows the fu nct ion call. Th is is illustrated ill Figu re 6-3.
Figure 6-3
void displayMessage ( ) (
cout «
"Hello from the funct i on displ a yMessllge . \n";
)
int main() (
cout « "Hello from main. \n displayMessagell i cout « "Back io function main again. \n": retur n 0, ft
)
311
312
Chapter 6
Functions
Function call statements may be used in control structures like loops, i f statements, and switch statements. Program 6-2 places the displayMessage functlon call \ns\de a loop. Program 6-2 II The function displayMessage is repeatedly called from a loop. 2 3
linclude using naroespace std;
4
5 6 7
/1** *************************************** 1/ Definition of function displayMessage * II This function displays a greeting. *
89 11-----.··_-_·_·_--_·_--------_·-·--_····_· 10
void dispiayMessage()
II
{
12 13 14 15 16 17
,. 19
20 21
cout «
•
II Function main
11 *************************··*********·***· iot main() {
cout «
"Hello from main. \n" i = 0: count < 5; count++) displayMessage(); /1 Call displayMessage cout « "Back i n function main again. \n" i return 0;
22
for (int count
23 24
25 26
"Hello from the function displayMessage . \n";
}
}
Program Output Hello from main . Hello from the function displayMessage . Hello from the function displayMessage. Hello from the function displayMessage. Hello from the function displayMessage. Hello from the function displayMessage. Back in function main again. It is poss ible to have many functions and function calls in a program. Program 6-3 has
three functions: main, first , and second. Program 6 -3
1 II This
program
has three functions: main, first ,
2
'include
,
using names pace std;
3
and second .
6.2 Defining and Calling Functions
, 6 7
8 9 10
313
11***************************************** II Definition of function first • II This function displays a message. • II~****************~***********************
void first{)
11 12
{
13
)
cout «
"I am
now inside the function first. \0";
14
15
16 17
II~+~******************************~~~*****
II Definition of function second • II This function displays a message . • 11************************************ * ****
18 19 20
void second{)
21
{
22 23
)
cout «
"I
am now inside the function second. \n";
2'
2,
II**********************************~******
II Function main
26 27 28 29
int main ( )
30
{
cout « "I am starting in function main . \n~; first{); I I Call function first second(); II Call function second cout « "Back in function main again. \0" ; return 0;
31 32 33
34
35 36
•
)
Program Output I am starting in function main. I am now inside the function first . I am now inside the function second. Back in function main again.
In lines 32 and 33 of Program 6·3, function main contains a ca ll to first and a ca ll to second: first() i second ( ) ; Each call statement causes the program to branch
to
a funct ion and then back
to
when the funct ion is finished. Figure 6-4 illustrates the pa ths taken by the program.
main
Chapter 6 Functions
314
Figure 6 -4
void first( ) {
cout «
"I am oow inside eh_ function firs t .\n";
}
void second( I {
cout «
"I am oow inside the function second.\n";
}
lnt maine ) (
cout «
"I am starting
first();
second() ;
cout «
"Back
return 0,
'0
'0
function main . \n"
fUnction mo.in again . \n";
)
Functions may also be called in a hierarchical, or layered fashion. This is demonstra ted by Program 6A, which has three functions: main, deep, and deeper. Program 6 -4
1
II This program has t hree functions : main , deep , and deeper
2 3
using namespace std;
'include
4 5
•
1/********** * **************·***************
7
II Definition of function deeper II This function displays a message.
8
//*********** * *************************** **
9 10 11
I. 17
18 19
*
void deeper() (
12 13 14 15
*
cout «
"I am now inside the fUnction deeper.\n";
)
11**** ***** *** *** **** ***** ****** * ********** * * 11****** **** ********** *********** **********
II Definition of function deep II This function displays a message .
6.2 Defining and Calling Functions
20
void deep()
21 22
{ cout «
23
cout «
24
25 26
"I am now inside the function deep. \n"; II call function deeper "Now I am back in deep . \n";
deeper(J: }
27
2.
II Function main
29
1/*****************************************
30 31
lnt main()
32
{
33 34 3S 36
•
cout «
"1 am starting in function main.'n" : deep(); I I Call fu nction deep cout « "Back in function main again. \n": return 0;
37
Program Output 1 am starting i n function main. I am now inside the function deep . I am now inside the function deeper . Now I am back in deep. Back in function main again. In Program 6 -4, fu nction main only calls the function deep . In turn, deep ca lls deeper.
The paths taken by the program are shown in Figure 6-5 . Figure 6-5
void deep() (
",
cout « "r am now i nside funct.ion deep.\n··; deeper!) ; cout « "Now r am back in deep.\nH; }
vo i d deeper() (
cout «
"r am now im th, funct.ion deeper . \n";
}
int main() (
cout « "I am starting im function ""ain. \n" ; deep() ; cout « "Back im function main again. \n"; return 0 , }
315
3 16
Chapter 6 Functions
~ Checkpoint 6.1
Is the following a function header or a fu nction call? calcTotal ( ) i
6.2
[s the following a function header or a funct ion call? void showResults()
6.3
What will the output of the fol lowing program be if the user enters 10? tinclude using names pace stdi vo id funcl() (
cout «
"Able was I\n";
)
void func2 ( ) {
cout «
"I saw Elba\n";
}
int main( ) {
int input; cout « "Enter a number: " ., cin » input; i f ( input < 10 ) (
funcl(); func2() ; ) Al!".E"
{
fund ( ) ;
funcl (); )
return 0 ; )
6.4
The followi ng program skeleton determ ines whether a person qualifies for a cred it ca rd. To qualify, the person must have worked on his or her current job for at lea st two years and make at least $17,000 per year. Finish the program by writing the definitions of the funct ions qualify and noQualify. T he function qualify should explain that the applicant qua lifies for the card and that the annual interest rate is 12%. The function noQualify should explain that the applicant does not qualify fo r the card and give a general explanation why. linclude using names pace std;
II You must write definitions for the two functions qualify II and noQualify.
6.3 Function Prototypes
lnt main() {
double salary; int years ; cout «
"This program will determine if you qualify\n";
cout «
"for our credit card. \n ";
cout «
cln » cout « cout «
"What is your annual salary? ";
salary; "How many years have you worked at your ";
"current job? "; cin » years; if (salary >= 17000.0 && years >= 2) qualify() ;
else noQuality ( ) i
return 0; )
Function Prototypes CON C f. PT: A function prorotype eliminates the need ro place a fun ction definition before all calls to the fun ctio n. . Before the compiler encounters a call to a particular funct ion, it must already know the fu nction's return type, the number of parameters it uses, and the type of each parameter.
(You will learn how to use parameters in the next section.) One way of ensuri ng that the compiler has this information is to place the function definition before all ca lls to that function. This was the approach taken in Programs 6·1, 6-2, 6-3, and 6-4. Another method is to declare the function wi th a ftlnction prototype. Here is a prototype fo r the displayMessage function in Program 6-1: void displayMessage();
T he protO[ype looks similar to the func tion header, except there is a semicolon at the end. T he statement above tells the compiler that the funct ion displayMessage has a void return type (it doesn't return a va lue) and uses no parameters.
~L-N __O_T __E_:__F_u_n_C_ti_O_n_p_t_o_t_o_ty_p_e_s_a_t_e_a_I_so__k_n_o_w__n_a_s_~_"_n_e_"_o_n_d_e_e_'_a_,a_t_io_,_,s_.________________~
CD
WARNING! You must place either the function definition or eitherlthe function prototype ahead of all calls to the function. Otherwise the program will not compile.
Function prototypes are usually placed near the top of a program so the compiler will encounter them befo re any funct ion ca lls. Program 6-5 is a modification of Program 6-3 . The definitions of the functions first and second have been placed after main, and a funuion protOtype has been placed after the using namespace std statement.
317
3 18
Chapter 6
Functions
Program 6-5 1 2
3
II This program has three functions: main, first, and second. 'include using namespace std;
4
5
/ 1 Function Prototypes
6
void first();
7
void second();
, 9 10 11
12
13 14 15
16
lnt main() ( cout « "1 am starting in function main. \0 "; /1 Call function first first()j second() ; 1/ Call function second cout « "Back in f unction main again. \0";
return 0; )
17 18 19 20
1/'* ·** ******** ******** ******** *******' 1/ Definition of function first. * II This function displays a message . * 1/** *** ******* *****·***********········
21 22 23
void first()
24
(
cout «
25 26 27 28 29
30 31
~I
am now inside the function first.\n";
) 1/**** **· · · · · ·******* ***·*·***********· II Definition of function second. * II Th i s function displays a message. • II*~~*~ **** *********~* *********~*******
32
33
void second()
34 3S
( cout «
"1 am now inside the function second. \n";
36
Program Output
(The program's output is the same as the output of Program 6-3.) When the compiler is reading Program 6-5, it encounters the ca lls to the functions first and second in li nes 12 and 13 before it has read the definition of those fu nctions. Because of the function prototypes. however, the compiler already knows the rerum type and parameter information of first and second. ~
NOTE: Although some programmers make main the last function in the program, many
'-"L-p_,_,_k_'__'t_t_o_b_,__h_, ,_,_h_e_c_._"_,_e _'_, _',_,_h_e_D __ ' o_g_'_._m_'_'_' _'._r_'_in_g__D_o_in_'_o____________________----~
6.4 Sending Data jn to a Function
Sending Data into a Function CONCEPT: When a function is called, the program may send values into the fun ction.
Values that are sent into a funct ion are called arguments. You're already familiar with how to use arguments in a function ca ll. In the followi ng statement t he function pow is being called and two a('guments, 2.0 and 4.0, are passed to it: Functions and Arguments
result = pow{2.0, 4.0); By using parameters, you ca n design your own functio ns that accept data this way. A parameter is a special variable that holds a va lue being passed into a function. Here is the definition of a func tion that uses a parameter: void displayValue(int nurn) {
cout «
"The value is " «
nurn «
endl;
)
Notice the integer variable definition inside the parentheses (int num), The variable num is a parameter, Th is enables the function displayvalue to accept an integer value as an argument. Program 6-6 is a complete program using this func tion.
NOTE: In this rext, the values that are passed into a fu nction are called arguments, and the variables that receive those values are called parameters. There are several variations of these terms in use. Some call the arguments actual parameters and call the parameters formal param eters, Others use the terms actual argument and formal argument. Regardless of wh ich set of terms you use, it is important to be consistent. Program 6·6 1
II This program demonstrates a function with a parameter.
2
'include using names pace std ;
, 3
5 6
II Function Prototype void displayvalue(int);
7
8
9 10
intmo.in() {
cout « "I am passing 5 to displayvalue . \n"; displayva lue(5) ; II Call displayValue with argument 5 cout « "Now I am back. in main . \n "; return 0 ;
11
12
13 14 15
)
(program continues)
319
Chapter 6 Functions
320
I
Program 6-6
(continued)
16 17
11·*····**·*·*-_·······--****·· __ ·**-*----_·_·_*--*--- *****• /1 Definition of function displayValue.
18
1/ It uses an integer parameter whose value is displayed. *
19 20
11*.*****.********** · ***************** ****************
21
void displayValue(int num)
22 23 24
{
cout «
"The value is " <:< num «
--**-
endl;
)
Program Output
I am passing 5 to displayValue . The value is 5 Now I am back in main . First, notice the function prototype for displayvalue in line 6: void displayValue(int); It is not necessary to list the name o f the parameter variable inside the parentheses. Only
its data type is required . The function prototype shown above cou ld optionally have been written as: void displayValue(int nurn); However, the compiler ignores the name of the parameter variable in the fUllction prototype.
In main, the displayValue fu nction is called with the argument 5 ins ide the parentheses. The number 5 is passed infO nurn, which is displayValue's parameter. This is illustrated in Figure 6-6. Figure 6 -6
.'.. ...'.. ~
'~
void displayValue(int num) cout «
nThe value is n «
num «
endl;
}
Any argument listed inside the parentheses of a func tion ca ll is copied into the function's parameter variable. In essence, parameter variables are initialized to the value of their corresponding arguments. Program 6-7 shows the function displayValue being called several times with a different argument being passed each time.
6.4 Sending Da ta into a Function
1 2 3
II This program demonstrates a function with a parameter. finclude using namespace std;
5 6
II Function Prototype void displayvalue (int);
7 8
int main()
9
{
•
cout « "I am passi ng se veral values to displayvalue . \n " ; displayvalue{5) ; II Call displayvalue with argument 5 displayvalue(lO); II Call displayValue with argume nt 10 displayvalue(2); II Call disp l ayValue with argument 2 displayValue( 16); II Call displayvalue with argument 16 cout « "Now I am back in main. \n return 0 ;
10 11
12
13
I.
15
16 17 IS
19 20 21 22 23 24 25 26 27
M
;
)
11************** ************ ************************** ***** II Definition of function displayValue. * II It uses an integer parameter whose value is d is played . * 11 **** **** *** *********** ************ **** ***** ***** *** * ***** void displayValue ( int num) { cout « "The v alue is " «
num «
endl ;
)
Pro gra m Output I am passing s e ve ral values to di splayValue. The value is 5 The value is 10 The value is 2 The value is 16 Now I am back in main .
CD
WARNING ! When passing a variable as an argument, simply write the variable name
ins ide the parentheses of the function call. Do not write the data type of the argument variable in the function cal l. For example, the following fun tion call will ca use an er ror: displayValue(int x); II Error!
The functio n call should appear as displayvalue ( x);
II Correct
Each rime the funct ion is called in Program 6-7, num takes on a differen t value. An y expression whose value could normally be assigned to num may be used as an argument. For example, the following funct ion ca ll would pass the va lue 8 into num:
displayvalue(3 + 5);
321
32
Chapter 6
Functions
If you pass an argument whose type is not the same as the parameter's type, the argument will be promoted or demoted automatica lly. For insrance, the argument in the follow ing function call would be truncated, causing the va lue 4 to be passed to num: displayValue(4 . 7)i
Often, it's useful to pass several arguments into a fun ction. Program 6-8 shows the definition of a fu nction with three parameters.
Program 6-8 1
1/ This program demonstrates a function with three parameters.
2
'include
3
using names pace stdj
4
5 6
/1 Function Prototype void showSum(int, int, intI;
7 8 9
iot main() (
10
iot valuel, value2, value3;
11
12
II Get three integers. cout « "Enter three integers a nd I will display "i cout « "their sum: "; cin » va1ue1 » value2 » va1ue3;
13 14 15 16
II Call shawSum passing three arguments . showSum(valuel, value2 , value3); return 0;
17 18 19 20
)
21 22 23
1/**·*······*··*········*························***** ** *** •• * 1/ Definition of function showSum .
24
25
•
II It uses three integer parameters . Thei r sum is displayed . • //
...•......•.•.••••••••••.•.•.•..........................••.•
26 27
void showsum(int numl, int num2, int num3)
28
{
"
)
30
cout «
(num1 + num2 + num3) «
endl;
Program Output with Example Input Shown In Bold
Enter three integers and I will display their sum: 487 [Enter] 19
In the function header for showSum, the parameter list contains th ree variable definitions sepa rated by commas: void showSum(int numl, int num2 , int num3)
6.4 Sending Data into a Function
CD
WARNING! Each parameter variable in a parameter list must have a data type listed before irs name. For example, a compiler error would occur if the parameter list fo r the showSum funct ion were defined as shown in the following header: void showSum(int num!, num2, num3) II Error ! A data type for all three of the parameter variables must be listed, as shown here: void showSurn(int numl, int num2, int num3) II Correct In the funct ion call in line 18, the variables valuel, value2 , and value3 are pa ssed as arguments: showSum(valuel, value2, value3); When a function with multiple parameters is ca lled , the arguments are passed to the parameters in order. T his is illustrated in Figure 6-7.
Figure 6-7
Function Call ---.- showSum(value 1, value2, value3)
I r
void showSum(int n! ml, int num2 , int num3) (
eout «
(numl + num2 + num3) « endl ;
}
The following function ca ll will cause 5 to be passed into the numl parameter, 10 to be passed into num2, and 15 to be passed into num3: showSum(5, 10, 15) ; However, the following function call will ca use 15 to be passed into the nurn1 parameter,S to be passed into num2 , and 10 [0 be passed into num3: showSum(15, 5, 10)i
~L-N__O_T_E __ :_T_h_e_f_u_n_c_ ti_o_n_p_,_o,_o_t_yp_ e__m_u_s_' _Ii_s'_ '_h_e_d_a_t_a_ty_p_e_ o_f_e_a_c_h_p_a_,_a_m_e_te_'_. __________--" ./'\
NOTE : Like all variables, parameters have a scope. The scope of a parameter is limited
~ L-t_o__'h_c__b_o_d_y_o_f_'_h_e_f_u_n_c_ti_o_n_t_h_a_,_u_s_e_s_i'_.________________________________________~
323
32
Chapter 6
Functions
Passing Data by Value CONCEPT: When an argument is passed into a parameter, amy a copy of the argument's value is passed. Changes to the parameter do nOt affect the origina l argument.
As you've seen in this chapter, parameters are special-purpose variables that are defined
inside the parentheses of a function definition. They arc separate and distinct from the arguments that are listed inside the parentheses of a function ca ll. The val ues that are stOred in the parameter variables are copies of the arguments. Normally, when a parameter's value is changed inside a funct ion it has no effect on the original a rgumenr . Progra m 6·9 dcmonSfrates this concept.
Program 6-9 II This program demonstrates that changes to a function parameter have no effect on the original argument. 'include using namespace std i
2 II 3 4 5 6
7 8 9 10
II Function Prototype void changeMe(int) i int main() (
11 12 13 14
int number
= 12;
II Display the value in number . cout « "number is " « number «
endl ;
15
II II
16
Cal l changeMe, passing the value in number as an argument . changeMe(number)i
17
18 19
II Display t he value in number again . cout « "NOW back in main again, the value of "; cout « "number is " « number « endl; return 0;
20 21 22 23 24
25 26 27 29
29
30
)
II·· ················ •••••• • ••••••••••••••••••••••••••• •••••••••• II Definition of function changeMe. • II This function changes the v alue of the parameter myValue . • II •• •••••••••••••••••••••••••••••••••••••••••••••••••• ••••••••••
6.5 Passing Data by Value
31
void changeMe(int myValue)
32
{
II Change the value of myvalue to O. myValue ~ 0 ;
33 34 35
II Display the value in myvalue . cout « "Now the value is " « myValue «
36 37 38
endl;
}
Program Output number is 12 Now the value is 0 Now back in main again, the value of number is 12 Even though the parameter variable myValue is changed in the changeMe function, the argument number is nor modified. The myvalue variable contains only a copy of the number vari a ble. The changeMe function does nor have access to the original argu ment. When only a copy of an argument is passed to a function, it is said to be passed by va/lie. This is because the function receives a copy of the argument's va lue, and does not have access to the origina l argument. Figure 6-8 illustrates that a pa rameter variable's storage location in memory is se parate from that of the original argument. Figure 6-8 Original Argument (in its memory location)
12
I~ Function Parameter (in its memory location)
12
NOTE : Later in th is chapter you will learn ways to give a function access to its original ( ) L-a_r_g_u_ 'n_e_ n_ ~_.__________________________________________________________~
325
32
Chapter 6
Functions
Focus on Software Engineering: Using Functions in a Menu-Driven Program CONCEPT: Funcrions are ideal for use in menu-driven programs. When th e user selects an item fcom a menu, th e progra m can call the appropriate function.
In Chapters 4 and 5
YOll
saw a menu-driven program that calculates the charges for a
health club membership. Program 6-10 shows the program redesigned as a modular program. A modlliar program is broken up into functions that perform specific [asks. Program 6-10 1 2
II This is a menu-driven program that makes a function call II for each selection the user makes.
3
'include
4
'include
5 6 7 8
using namespace std; II Function prototypes void shoWMenU()i
9 10
void showFees(double, i nt I;
11
int main ( )
12 13
{
14
15 16 17
18 19
int choice; II Constants const doub l e const double const double
20
21 22 23 24
25
26 27
28
"
II To hold a menu choice II To hold a number of months
int months;
for membership rates ADULT = 40.0; SENIOR
CHILD
--
30.0; 20.0;
II Set up numeric output formatting. cout « fixed « showpoint « setprecision(2): do {
II Display the menu and get the user's choice . showMenu(): cin » choice;
6.6 Focus on Software Engineering: Using Functions in a Menu-Driven Program
30
II Validate the menu selection.
31
while (choice < 1
32
{
33
cout «
34
cin »
choice> 4)
"Please enter 1, 2, 3, or 4 : ";
choice;
35 36
}
37
if (choice 1= 4)
38 39
{
II Get the number of months. cout « "For how many months? "i cin » months;
40 41
42 43 44
II Display the membership fees. switch (choice) { case 1: showFees(ADULT, months); break;
45 46 47
48 49 50 51
case 2 :
showFeeS(CHILD , months); break:
case 3 :
showFees(SENIOR, months);
}
52 53
} while (choice 1=
54
return 0;
55
II
}
q)j
)
56 57 58
1/************************** ************************** ***** •• ****** II Definition of function showMenu which displays the menu. •
60 61
void showMenu()
62 63
{ cout cout cout cout cout cout
64 65 66 67 68
"71
« « « « « «
"\n\t\tHealth Club Membership Menu \n \n" ; " 1. Standard Adult Memhership\n" ; "2 . Child Membership\n"; "3 . Senior Citizen Membership\n" ; "4. Quit the Program\n\n"i "Enter your choice: " ,
.
)
70
72 73
74 75 76
//*********.**.*** ************************************************* II Definition of function showFees. The memberRate parameter holds* II the monthly membership rate and the months parameter holds the * II number of months. The function displays the total charges. * 11 **************************************************** *************
77
void showFees(double memberRate, int months)
78
{
79 80
81
cout « «
"The total charges are $" (memberRate * months) « endl;
} (program output continues)
327
32
Chapter 6
Program 6- 1 0
Functions
(continued)
Program Output with Example Input Shown In Bold Health Club Membership Menu
1. Standard Adult Membership 2. Child Membership 3. senior Citizen Members hip 4. Quit the Program Enter your choice : 1 [Enter] For how many months? 12 [Enter]
The total charges are $480.00
Health Club Membershi p Menu 1 . Standard Adult Membership 2. Child Membership
3. Senior Citizen Membership 4 . Quit the Program Enter your choice: 4 [Enter]
Let's rake a closer look at this program. First notice thac the
double
constams
ADULT,
CHILD, and SENIOR are defined in lines 17 through 19. Recall that these constants hold the
monrhJy membe rship rates for adult, child, and senior citi zen mem berships. Next, notice the showMenu function in lines 61 th rough 69 , Th is fu nction displays the menu, and is called from the main function in line 27, T he showFees function appears in lines 77 through 8L ]ts purpose is to d isp lay the tota l fees for a membership lasting a specified number of months, T he fun cti on accepts two arguments: the monthly membership fee (a double) and the number of months o f membership (a n int), The function uses these va lues to calculate and display the total ch arges. For exa mple, if we wanted the functio n to displa y the fees for an adult membership lasting six months, we would pass the ADULT constant as the first argu ment and 6 as the second argument. T he showFees function is ca lled from three different loca tions in the switch statement which is in the main funCtion. T he first location is line 46 . This statement is exec uted when the user has selected item 1, standard adulr membership, from the menu. The showFees function is ca lled with the ADULT constant and the months varia ble passed as arguments. The second location is line 4 8. This statement is executed when the user has selected item 2, child membersh ip, from the menu. The showFees funct ion is ca lled in this line with the CHILD constant and the months variable passed as arguments. Th e third location is line 50. T his statement is executed when the user has selected item 3, senior citizen membership, fr om the menu . The showFees fun ction is ca lled with the SENIOR constant and the months variable passed as argu ments. Each time the showFees function is called) it d ispla ys (he total membership fees for the specified type of membership, for the specified number of months.
6.6 Focus on Sohware Engineering: Using Functions in a M enu-Driven Program
~ Checkpoint 6.5
Ind ica te w hich of the foHowing is the function prototype, the function header, and the function call: vo id showNum(double num) void showNum(double) i showNum(45 .67 );
6.6
Write a funct ion named timesTe n The function shou ld have a n integer parameter named number. When timesTen is called, it should d isplay the product of number
times ten. (Note: just write the function. Do not write a complete program.) 6.7
Write a function prototype for the timesTen function you wrote in Question 6.6.
6.8
What
is the o urput o f the following program?
'include using namespace std; void showOouble(int); II Function prototype
i nt main{) {
i nt num ; for (num : 0; nurn < 10: num++) s howDOuble(num ); return 0: )
II De£inition o f function showDouble. void showDouble(int value) {
cout «
value «
" \t" «
(value '" 2) «
endl;
)
6.9
What is the o utp ut of the. following program? 'include us ing namespace s td; void funCl(double, intI : II Function prototype