Page 1

Bismillah hir Rehman nir Raheem ------------------------------------Assalat o Wasalam o Allika Ya RasoolALLAH

Starting Out With C++ from Control Structures through Objects (6 Ed.) th

Tony Gaddis

Introduction Ch  Ch

Published By: Muhammad Hassan Riaz Yousufi

To Read Online & Download:

WWW.ISSUU.COM/SHEIKHUHASSAN


START~

NG OUT WITH Fr,o m Contr,o t Structures, through Objoects sixth edition


Bismillah hiir Rehman nir Raheem-----------------------------Assalat c++ Quick Reference o Wasalam o Alika Ya RasoolALLAH c++ Data Types

Commonly Used Operators As signment Operators =

Assignment Combined addition/assignment Combined su btraction/assignment Combined multiplication/assignment Combined di vision/assignment Combined modulus/assignment

+..

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

Yo

Unsigned Character Integer

i

CbanK::ter

us uf

Description

<

Less than Less than or equal to Greater than Greater Ihall or equal 10 Equal to Not equal to

<> >'" -!;-

Logical Operators

az

Data Type char unsigned char

AND

Ii Ii

II

OR

I

NOT

++

Example i f (x < y) x++;

Conditional Operator 7:

For-m:

Example

if/else i f ( expression)

x++;

,statement;

else

statement;

Ha

x--;

ss

i f (x < y)

else

if/el se if

Example

i f (expression)

i f (x < y)

statement; else i f (expression) statement;

x++; else i f (x < z) x--; else

ad

else

y++;

m

statement;

I

uh a

statement; statement;

m

To conditionally-execute more than one statement, enclose the statements in braces: Form Example if (expression) i f (x < y) (

expression ? expression ; expression Example: x '" a < b ? a : b; The sratement above works like: if(3<b) g

'"

a;

e18e

x - b;

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;

)

(

x++; cout « )

Web Sites

M

lncrement Decrement

an

Forms of the 1f Statement Simple if i f (expression) statement;

Ri

Increment/Decrement

For tbe Sf1lrting Out with C++ Series aw.com/gaddisbooks For Addison-Wesley Computing

x,

The do-wbile Loop Form:

Example:

do

do

statement,

cout «

x++ «

while (expres sion):

while (x < 100);

do

do {

{

endl;

statement; cout « x « end1; statement; x++ ; } while (expression) ; } while (x <: 100);

aw.com/computing

To Read Online & Download: WWW.ISSUU.COM/SHEIKHUHASSAN


Bismillah hiir Rehman nir Raheem-----------------------------Assalat o Wasalam o Alika Ya RasoolALLAH

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

us uf

Chapter 1

i

LOCATION OF VIDEO NOTES IN THE TEXT

Yo

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 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

ad

m

m

Dynamically Allocating an Array, p. 535 Solving the getString Function Problem, p. 554

uh a

Chapter 9

Ha

ss

an

Ri

az

Chapter 3

M

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 To Read Online & Download: WWW.ISSUU.COM/SHEIKHUHASSAN


Bismillah hiir Rehman nir Raheem-----------------------------Assalat o Wasalam o Alika Ya RasoolALLAH

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

Ri

Operator Overloading, p. 843 Class Aggregation, p. 872 Solving the NumDays Problem, p_ 888

us uf

Chapter 12

Yo

Creating a Structure, p. 611 Passing a Structure to a Function, p. 630 Solving the Wea ther Statistics Problem, p. 664

-:"';' ."",

az

Chapter 11

(continued)

Chapter 15

Redefining a Base Class Function in a Derived Class, p. 917 Polymorphism, p. 927

an

Solving the Employee and ProductionWorker Classes Problem, p. 960 Chapter 16

Throwing an Exception, p. 972 â&#x20AC;˘ 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

'.

m

ad

Ha

ss

'''.~

Storing Objects in an STL stack, p. 1083 Storing Objects in an STL queue, p_ 1098 Solving the File Compare Problem, p. 1104

m

Chapter 18

uh a

Chapter 19

M

Chapter 20

--

i

LOCATION OF V IDEO NOTES IN THE TEXT

Reducing a Problem w ith Recursion, p_ 1112 Solving the Recursive Multiplication Problem, p. 1141

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

To Read Online & Download: WWW.ISSUU.COM/SHEIKHUHASSAN


an

Ri

az

Yo

us uf

i

Bismillah hiir Rehman nir Raheem-----------------------------Assalat o Wasalam o Alika Ya RasoolALLAH

Ha

ss

From Control Structures through Objects

M

uh a

m

m

ad

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

To Read Online & Download: WWW.ISSUU.COM/SHEIKHUHASSAN


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.

Yo

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

us uf

i

Bismillah hiir Rehman nir Raheem-----------------------------Assalat o Wasalam o Alika Ya RasoolALLAH

az

Access the latest information about Addison-Wesley titles from our World Wide Web site: http:www.aw.comJcomputi ng

Ri

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.

an

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

..

lSBN-13,978-0-321-54588-6 [SBN-l0, 0-321-54588-5

Ha

ss

Gaddis, Tony. Srarring out with C++ : from control structures through objects I Tony Gaddis. - 6th cd. p. em. Includes index. I . C++ (Compu ter program language) 1. Title.

QA76.73.CI53G332008 005.J3'3--dc22

~

2009 Pearson Education, Inc.

m

. Copyright

ad

2008008001

uh a

m

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.

M

ISBN n 978-0-321 -54588-6 ISBN 10, 0-321-54588 -5 23456789 IO-QWT-ll10 09 08

To Read Online & Download: WWW.ISSUU.COM/SHEIKHUHASSAN


us uf

i

Bismillah hiir Rehman nir Raheem-----------------------------Assalat o Wasalam o Alika Ya RasoolALLAH

j

Yo

o

Preface

az

'1

xiii

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

29

163

249

an

307

ss

387

559

Ha

CHAPTER 10

1

Ri

CHAPTER 1

CHAPTER 11

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 12

CHAPTER 19

Stacks and Queues

Recursion

1067

1107

Binary Tree.

1145

1171

Appendix B: The ASCII Character Set 1199 Appendix C: Operator Precedence and Associativity

1203

1205

M

uh a

Appendix A: Getting Started with Alice

Index

971

1027

m

CHAPTER 20

m

CHAPTER 18

ad

CHAPTER 13

v

To Read Online & Download: WWW.ISSUU.COM/SHEIKHUHASSAN


Bismillah hiir Rehman nir Raheem-----------------------------Assalat o Wasalam o Alika Ya RasoolALLAH Contents at a Glance

Student CD

Th e fo llowing appendices arc on the accompany ing Student CD.

i

vi

us uf

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

az

Yo

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

M

uh a

m

m

ad

Ha

ss

an

Ri

Append ix Appendix Appendix Appendix Appendix Appendix Appendix Appendix

To Read Online & Download: WWW.ISSUU.COM/SHEIKHUHASSAN


Table of Locat ion of Video Notes

Introduction to Computers and Programming

CHAPTER 1

1.1

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

1.2

ss

an

1.3 1.4 1.5 1.6 1.7

Introduction to C++

29

Ha

CHAPTER 2

m

ad

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++

uh a

m

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

xiii

Ri

Preface

az

Yo

us uf

i

Bismillah hiir Rehman nir Raheem-----------------------------Assalat o Wasalam o Alika Ya RasoolALLAH

M

CHAPTER 3

3. 1 3.2 3.3

Expressions and Interactlvity

71

83

The cin Object 83 Mathematical Expressions 91 When You Mix Apples and Oranges: Type Co nversion

100

To Read Online & Download: WWW.ISSUU.COM/SHEIKHUHASSAN

vii


Bismillah hiir Rehman nir Raheem-----------------------------Assalat o Wasalam o Alika Ya RasoolALLAH viii

CHAPTER 4

us uf

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

4.8 4.9 4.10 4.11 4.12 4.13 4.14 4.15 4.16 CHAPTER 5

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

m

m

ad

5.1

ss

4.7

Ha

4.5 4.6

an

Ri

4.4

5.2 5.3 5.4 5.5 5.6 5.7 5.8 5.9

Making Decisions 163

az

4.1 4.2 4.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

Yo

3.4 3.5 3.6 3.7 3.8 3.9 3.10 3.11 3.12 3.13 3.14

uh a

5.10

5.11 5.12 5.]3

M

CHAPTER 6

6.1

6.2

6.3

i

Contents

Functions 307 Focus on Softvvare Engineering: Modular Programming Defining and Ca Uing Functions 309 Function Prototypes 317

287

307

To Read Online & Download: WWW.ISSUU.COM/SHEIKHUHASSAN

130


Bismillah hiir Rehman nir Raheem-----------------------------Assalat o Wasalam o Alika Ya RasoolALLAH

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

i

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

an

Processing Array Contents 404 Focus on Software Engineering: Using Parall el Arrays Arrays as Function Arguments 41 5 Two-Dimensio nal Arrays 426

7.9

412

ss

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

Ha

7. 10 7.11 7.12

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

m

m

ad

CHAPTER 8 8.1 8.2

M

uh a

CHAPTER 9 9.1 9.2 9.3 9.4 9.5 9.6 9.7 9.8 9.9 9.10

326

us uf

Yo

az

Arrays 387 Arrays Hold Multiple Values 387 Accessing Array Elements 389 No Bounds Checking in C++ 396 Array Ini tia lization 399

Ri

CHAPTER 7 7. 1 7.2 7.3 7.4 7.5 7.6 7.7 7.8

8.3 8.4 8.5

ix

Contents

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

To Read Online & Download: WWW.ISSUU.COM/SHEIKHUHASSAN


11.5 11.6 11.7 U.S 11.9 11.10 lUI

11.12

us uf

Yo

az

11.3 11.4

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

Ri

CHAPTER 11 11.1 11.2

598

an

10.7 10.8

ss

lOA 10.5 10.6

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

Ha

CHAPTER 10 10.1 10.2 10.3

i

Rehman nir Raheem-----------------------------Assalat o Wasalam o Alika Ya RasoolALLAH xBismillah hiirContents

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

695

M

uh a

m

m

ad

CHAPTER 12 12.1 12.2 12.3 12.4 12.5 12.6 12.7 ' 12.8 12.9 12.10

13.6 13.7 13.8 13.9

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

To Read Online & Download: WWW.ISSUU.COM/SHEIKHUHASSAN


Bismillah hiir Rehman nir Raheem-----------------------------Assalat o Wasalam o Alika Ya RasoolALLAH

â&#x20AC;˘

13.15 13.16

i

13.12 13.13 .13.14

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

us uf

13.11

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

Ri

an

ss

Ha

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

ad

15 .5 15.6 15.7 15.8

878

m

1.').4

az

CHAPTER 14 14.1 14.2 14.3 14.4 14.5 14.6 14.7 14.8

IS .1 15.2 15.3

1027

uh a

m

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

M

CHAPTER 18 18.1 '18.2 18.3 18.4

xi

Yo

13.10

Contents

Stack. and Queue. 1067 Introduction to the Stack ADT 1067 Dynamic Stacks 1078 The STL stack Container 1083 Introduction to the Queue ADT 1085

To Read Online & Download: WWW.ISSUU.COM/SHEIKHUHASSAN


Bismillah hiir Rehman nir Raheem-----------------------------Assalat o Wasalam o Alika Ya RasoolALLAH xli

Contents

Dynamic Queues 1093 T he STL deque and queue Containers

1097

CHAPTER 19 19.1 19,2 19,3

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

19,7 19.8 19.9 19.10

Binary Trees 1145 Definition and Appl ications of Binary Trees 1145 Binary Search Tree Operations 1148 Template Considera tions for Binary Search Trees 1165

ss

CHAPTER 20 20.1 20 .2 20.3

1路131

Ri

19,6

an

19,5

az

Yo

19.4

us uf

i

18.5 18,6

Ha

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.

ad

Appendix D: Introduction to Flowcharting Appendix E: Using UML

~n

Clan Design

m

Appendix F: Namespaces Appendix G: Writing Managed C++ Code for the .NET Framework

M

uh a

m

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

To Read Online & Download: WWW.ISSUU.COM/SHEIKHUHASSAN


Bismillah hiir Rehman nir Raheem-----------------------------Assalat o Wasalam o Alika Ya RasoolALLAH

us uf

i

â&#x20AC;˘

Yo

1 JO JLJ

DO

az

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

ss

an

Ri

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

Ha

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.

m

m

ad

â&#x20AC;˘

M

uh a

~.

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

To Read Online & Download: WWW.ISSUU.COM/SHEIKHUHASSAN


Bismillah hiir Rehman nir Raheem-----------------------------Assalat o Wasalam o Alika Ya RasoolALLAH 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.

â&#x20AC;˘

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.

us uf

i

â&#x20AC;˘

Yo

Organization of the Text

az

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.

Ri

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.

an

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.)

Ha

ss

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.

ad

Brief Overview of Each Chapter

m

Chapter 1: Introduction to Computers and Programming

uh a

m

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.

M

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.

To Read Online & Download: WWW.ISSUU.COM/SHEIKHUHASSAN


Bismillah hiir Rehman nir Raheem-----------------------------Assalat o Wasalam o Alika Ya RasoolALLAH Preface

xv

uf

i

Figure P-l

Yo us

Chapter 1 Introduction

Chapters 2-7 Basic Language Elements

I

I

Chapter 8 Searching And Sorting Arrays

Chapter 12 Advanced File Operations·

az

Chapter 9 Pointers

Ri

I

• A few subtopics in Chapter 12 requir e Chapters 9 and 11

I

Chapter 10 Characters, Strings, and the string Class

an

Chapte r 11 Structures

I

M uh

am

m

ad

Ha

ss

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

To Read Online & Download: WWW.ISSUU.COM/SHEIKHUHASSAN


Bismillah hiir Rehman nir Raheem-----------------------------Assalat o Wasalam o Alika Ya RasoolALLAH x vi

Preface

i

Chapter 3: Expressions and Interadivity

Yo

us uf

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

Ri

az

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

ss

Chapter 6: Functions

an

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,

ad

Ha

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

uh a

m

m

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.

M

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.

To Read Online & Download: WWW.ISSUU.COM/SHEIKHUHASSAN


Bismillah hiir Rehman nir Raheem-----------------------------Assalat o Wasalam o Alika Ya RasoolALLAH Prefac.e

xvii

i

Chapter 9: Pointers

us uf

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.

Yo

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.

az

Chapter 11: Structured Data

Ri

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.

an

Chapter 12: Advanced File Operations

ss

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.

.

Ha

Chapter 13: Introduction to Classes

ad

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 .

m

Chapter 14: More About Classes

uh a

m

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.

M

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.

To Read Online & Download: WWW.ISSUU.COM/SHEIKHUHASSAN


Bismillah hiir Rehman nir Raheem-----------------------------Assalat o Wasalam o Alika Ya RasoolALLAH xviii

Preface

i

Chapter 16: Exceptions, Templates, and the Standard Template Library (STL)

us uf

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).

Yo

Chapter 17: Linked Lists

az

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.

Ri

Cha pter 18: Stacks and Queues

Chapter 19: Recursion

an

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.

Ha

ss

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

m

ad

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

uh a

m

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

M

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.

To Read Online & Download: WWW.ISSUU.COM/SHEIKHUHASSAN


Bismillah hiir Rehman nir Raheem-----------------------------Assalat o Wasalam o Alika Ya RasoolALLAH

,

Preface

xix

us uf

i

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.

Yo

Appendix E: Using UML in Class Design '~

az

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

Ri

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 to

the concepts surrounding managed C++ m

an

This appendix introdllces the student Microsoft's .NET environment.

ss

Appendix H: Passing Command Line Arguments

Ha

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

m

ad

This appendix provides a reference for the C++ library functions and header files discussed in the book.

Appendix ,: Binary Numbers and Bitwise Operations

m

A guide to the C++ bitwise operators, as we ll as a tutorial on the intern al storage of integers.

uh a

Appendix K: Multl路Source File Programs

M

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, com-

To Onlinesave & Download: WWW.ISSUU.COM/SHEIKHUHASSAN pile Read a program, source files, and more.


Bismillah hiir Rehman nir Raheem-----------------------------Assalat o Wasalam o Alika Ya RasoolALLAH xx

Preface

i

Appendix N: Answers to Checkpoints

us uf

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

Yo

Another roo! that students can use ro gauge their progress.

Feature s of the Text Concept

az

Each major section of the text Starts with a concept sw tement. This statement summarizes the ideas of the section.

Statements

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

ad

Video Notes

Ha

>t.

m

Checkpoints

uh a

m

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 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 appear at appropriate places throughout the text. They are short explanations of interesting or often misunderstood points relevam to rhe topic at hand. Warnings are notcs that caution the studcnt about certain C++ features, programming techniques, or practices that can lead to malfunctioning programs or lost data.

M

Warnings

ss

an

Ri

Example Programs

To Read Online & Download: WWW.ISSUU.COM/SHEIKHUHASSAN


Bismillah hiir Rehman nir Raheem-----------------------------Assalat o Wasalam o Alika Ya RasoolALLAH Preface

xxi

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.

m

m

ad

Software Development Project: Serendipity Booksellers

Ha

ss

an

Ri

az

Yo

us uf

i

Case Studies

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.

M

uh a

C++ Quick Reference Guide

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.

To Read Online & Download: WWW.ISSUU.COM/SHEIKHUHASSAN


Bismillah hiir Rehman nir Raheem-----------------------------Assalat o Wasalam o Alika Ya RasoolALLAH x x ii

Preface

us uf

i

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

all odd-numbered Review Questions and Exercises (Appendix 0)

az

(0

Yo

Ri

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

an

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

m

ad

Ha

ss

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

M

uh a

m

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 computing@aw.comfor information on how to access them.

To Read Online & Download: WWW.ISSUU.COM/SHEIKHUHASSAN


Bismillah hiir Rehman nir Raheem-----------------------------Assalat o Wasalam o Alika Ya RasoolALLAH

Preface

xxiii

i

Textbook Web site

us uf

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!

Yo

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.

az

Which Gaddis C++ book is right for you?

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.

an

• •

Ri

The Starring Our with C++ Series includes three books, one of which is sure to fit your cou rse:

ss

The following chart will help you determine which book is right for your co urse .

• 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.

m

m

ad

Ha

• FROM CONTROL STRUCTURES THROUGH OBJECTS • BRIEF VERSION

M

uh a

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.

To Read Online & Download: WWW.ISSUU.COM/SHEIKHUHASSAN


Bismillah hiir Rehman nir Raheem-----------------------------Assalat o Wasalam o Alika Ya RasoolALLAH xxiv

Preface

i

Acknowledgments

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

Ri

az

Yo

Ahmad Abuhejleh U11iversity of Wisc011sin, River Falls

Dennis Fairclough Utah Valley State College

Tjaz A. Awan Savannah State University

an

Mary Astone Troy University

Richard Flint North Central College

ss

Robert Baird Salt Lake Community College

Ann Ford Florida Stare University

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

m

m

ad

Ha

Don Biggersra ff Fayetteville Technical Community College

uh a M

us uf

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.

George Masoll University

To Read Online & Download: WWW.ISSUU.COM/SHEIKHUHASSAN


Bismillah hiir Rehman nir Raheem-----------------------------Assalat o Wasalam o Alika Ya RasoolALLAH

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

Yo

az

Ri

Gadsden State Community College

Alberto Ram o n

R ay Larson Inver Hills Community College

an

Diablo Valley College Sazlur Rasheed Sault College of Applied Arts and Technology

Norman H . Lieb ling San jacillto College

ss

Jennifer Li Ohlone Col/ege

Farshad Ravanshad Bergen Commllnity College 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

m

m

ad

Ha

Zhu-qu Lu University of Maine, Presque l sle

uh a

James McGuffee Austin Community College

M

us uf

Mike Holland Northern Virginia Community College

xxv

i

Preface

South Dakota State Univers ity

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

To Read Online & Download: WWW.ISSUU.COM/SHEIKHUHASSAN


Bismillah hiir Rehman nir Raheem-----------------------------Assalat o Wasalam o Alika Ya RasoolALLAH Preface

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

az

Yo

us uf

i

Cherie Stevens South Florida Community College

Ri

xx vi

M

uh a

m

m

ad

Ha

ss

an

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!

To Read Online & Download: WWW.ISSUU.COM/SHEIKHUHASSAN


Bismillah hiir Rehman nir Raheem-----------------------------Assalat o Wasalam o Alika Ya RasoolALLAH x x vH

Preface

us uf

i

About the Author

Yo

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

M

uh a

m

m

ad

Ha

ss

an

Ri

az

Addison-Wesley.

To Read Online & Download: WWW.ISSUU.COM/SHEIKHUHASSAN


M

uh a

m m

ad

Ha

ss

an

Ri

az

Yo

us uf

i

Bismillah hiir Rehman nir Raheem-----------------------------Assalat o Wasalam o Alika Ya RasoolALLAH

To Read Online & Download: WWW.ISSUU.COM/SHEIKHUHASSAN


az

Yo

us uf

i

Bismillah hiir Rehman nir Raheem-----------------------------Assalat o Wasalam o Alika Ya RasoolALLAH

'.4

Why Program? Computer Systems: Hardware

The Programming Process Procedural and Object路Oriented Programming

Ha

Why Program 7

1.6 1.7

What Is a Program Made of? Input, Processing, and Output

ss

and Software Programs and Programming Languages

'.5

an

1 .1 1.2

Ri

TOPICS

CONCEPT: Computers can do many different jobs because they are programm able.

ad

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

m

as belonging ro a single profession. For example, surgeons have certain tools that are

m

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.

M

uh a

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

To Read Online & Download: WWW.ISSUU.COM/SHEIKHUHASSAN


Bismillah hiir Rehman nir Raheem-----------------------------Assalat o Wasalam o Alika Ya RasoolALLAH Chapter 1 Introduction to Com puters and Programming

2

us uf

i

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 .

Yo

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

Ri

az

• •

an

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

ss

computers do not understand English or other human languages. Languages such as C++ have strict fules that muSt be carefully followed.

Ha

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.

ad

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.

m

m

CONCEPT: All compute r

Hardware

uh a

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:

M

1. The central processing unit (CPU)

2. Main memory

3. Secondary storage devices 4. Input devices 5. Output devices

To Read Online & Download: WWW.ISSUU.COM/SHEIKHUHASSAN


Bismillah hiir Rehman nir Raheem-----------------------------Assalat o Wasalam o Alika Ya RasoolALLAH 1.2 Computer Systems: Hardware and Software

us uf

Figure 1-1

-

i

The organization of a computer system is depIcted in Figure] -1.

3

Yo

Central Processing Unit

Output Devices

az

-

Main Memory (RAM)

an

-

Ri

Inpu t Devices

â&#x20AC;˘

The CPU

Ha

ss

,t

-

Secondary Storage Devices

m

m

ad

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.

M

uh a

Figure 1-2

Central Processing Unit Arithmetic and LogiC Unit Result (Ou tput)

Instruction (Input)

â&#x20AC;˘ Control Unit

To Read Online & Download: WWW.ISSUU.COM/SHEIKHUHASSAN


Bismillah hiir Rehman nir Raheem-----------------------------Assalat o Wasalam o Alika Ya RasoolALLAH Chapter 1 Introduction to Computers and Programming

4

us uf

i

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 ~

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 .

Yo

Fetch

az

These steps are repeated as long as there are instructions to perform.

Main Memory

Ri

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.

Figure 1-3

ad

Ha

ss

an

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 .

f.'J

2l

~

f'J

2l

i'!J

~

~

~

1!3

~

~

11'1

nI

" f'iI

inI

§I

f.'-I

~ ~

m

m

.£J

'"

f.'-I

f!J

.£J

~

~

~

IW

~

nI

uh a

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.

M

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.

To Read Online & Download: WWW.ISSUU.COM/SHEIKHUHASSAN


Bismillah hiir Rehman nir Raheem-----------------------------Assalat o Wasalam o Alika Ya RasoolALLAH '.2 Computer Systems: Hardware and Software

5

us uf

i

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.

az

Yo

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.

an

Ri

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

Out put Devices

Ha

ss

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.

m

m

ad

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.

uh a

Software

M

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.

To Read Online & Download: WWW.ISSUU.COM/SHEIKHUHASSAN


Bismillah hiir Rehman nir Raheem-----------------------------Assalat o Wasalam o Alika Ya RasoolALLAH 6

Chapter 1 Introduction to Computers and Programming

i

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.

us uf

Multitasking

Yo

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.

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

az

Single lIser

multiuser syste m s .

Ri

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.

an

~ Checkpoint

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?

m

ad

Ha

ss

1.1

m

Programs and Programming Languages

uh a

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.

M

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:

To Read Online & Download: WWW.ISSUU.COM/SHEIKHUHASSAN


Bismillah hiir Rehman nir Raheem-----------------------------Assalat o Wasalam o Alika Ya RasoolALLAH '.3 Programs and Programming languages

i

us uf

1. Disp lay a message on the screen asking " H ow many hours did you wor k?"

7

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?"

Yo

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.

az

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.

Ri

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.

Ha

1011010000000101

ss

an

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:

ad

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

m

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.

m

Program 1-1 shows how the pay-calcu lating algorithm might be written in C++.

M

uh a

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.

To Read Online & Download: WWW.ISSUU.COM/SHEIKHUHASSAN


Bismillah hiir Rehman nir Raheem-----------------------------Assalat o Wasalam o Alika Ya RasoolALLAH Chapter 1

,

using namespace std;

5

int main ()

6 7

{

Yo

II This program calculates the user's pay. iinclude <iostream>

2 3

double hours, rate, paYi

II Get the number of hours worked .

9 10 11

12 13

az

cout « "How many hours did you work? "; c i n » hours;

1/ Get the hou rly pay rate.

cout « "How much do you get paid per hour? "; cin » rate:

14 15

Ri

1

1 ~1

i

Program

Introduction to Computers and Programming

us uf

8

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;

ss

}

an

16

Program Output with Example Input Shown In Bold

You have e arned $150

Ha

How many hours did you work? 10 [Enter] HOW much do you get paid per hour? 15 [Enter]

Programming Languages

m

ad

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.

m

Many high-level languages have been created. Table 1-1 lists a few of the well-known ones.

M

uh a

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.

To Read Online & Download: WWW.ISSUU.COM/SHEIKHUHASSAN


Bismillah hiir Rehman nir Raheem-----------------------------Assalat o Wasalam o Alika Ya RasoolALLAH 9

'.3 Programs and Progr1!lmming languages

us uf

i

Figure 1-4

Ri

Low level (machine language)

az

Yo

High level (Close 10 human language)

10100010 11101011

Description Begi nners All-purpose Symbolic In struction Cod e. A general programming language originally designed to be simple enough for beginners (0 learn.

ss

Language BASIC

an

Table 1-1

ad

Ha

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++

m

C#

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.

m

Java

uh a

JavaScript Python

M

Ruby

VisuaJ Basic

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.

To Read Online & Download: WWW.ISSUU.COM/SHEIKHUHASSAN


Bismillah hiir Rehman nir Raheem-----------------------------Assalat o Wasalam o Alika Ya RasoolALLAH 10

Chapter 1 (ntroduction to Computers and Programming

c++ is popular nOt on ly because of its

us uf

i

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.

Yo

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

Ri

az

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.

Ha

ss

an

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.

uh a

m

m

ad

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.

M

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

To Read Online & Download: WWW.ISSUU.COM/SHEIKHUHASSAN


Bismillah hiir Rehman nir Raheem-----------------------------Assalat o Wasalam o Alika Ya RasoolALLAH 1. 3 Programs and Programming l anguag es

,

Source (ode Is entered with a text editor by the p'OfJrommer.

1

I

,

Rinclude <io$ '~ e~n> using n ... Up.ce ltd;

Preprocessor

,

in t

".i"O CO"tÂŤ"Heiio IOorld\,,",

Modified Source Code

r eturn 0;

Yo

Source Code

us uf

i

Figure 1-5

11

1

Ri

I Object Code

1

1J

linker

I

ss

bu"bbl .. Cod ..

an

I

az

U

Compiler

.i"iet

Ha

Appendix G on the Student CD expla ins how comp il ing work s in .Net.

Checkpoint

m

~

ad

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.

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?

M

uh a

m

1. 10 1.1 1 1. 12

To Read Online & Download: WWW.ISSUU.COM/SHEIKHUHASSAN


Bismillah hiir Rehman nir Raheem-----------------------------Assalat o Wasalam o Alika Ya RasoolALLAH 12

Chapter 1 Introduction to Computers and Programming

us uf

': Grm.~Poly

i

Figure 1-6

~§fE]

MicrO!oOftVlsu41 Ch (i;k>s.ign) · Prl I cpp'

!j/It~~~t""~

.l

a..

• DeW;

H

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. ~OClU

- Holl :weh do .tAt e:

gee p aid per hour? ";

Ri

, ,• " " "

az

Yo

:5J~ ~ . ~g"

!_~~

:~

II Ol",pla:.' che pay.

coue «

- You bavt e ar ned S-

«

"'''CIa'' 0 ;

pay

« eod1;

Ha

"23,,

I I Calculate che pay . pay • hou r " • rate;

ss

u:

an

:6:

17:

"""

+.

Content

l-

Rltl';'Q.

CIC

n,IP

Reltb'y. P.MII

Co6e

. . - t;

.. \- \.. l,.. 1100'S

ad

What Is a Program Made of?

m

CON CE PT: There ace certain elements that are common to all programming languages.

Language Elements

m

All programming languages have a few things in common . Table 1-2 lists the common elements you will find in almost every language.

M

uh a

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.

To Read Online & Download: WWW.ISSUU.COM/SHEIKHUHASSAN


Bismillah hiir Rehman nir Raheem-----------------------------Assalat o Wasalam o Alika Ya RasoolALLAH 13

1.4 What Is a Prog ram Made of?

us uf

i

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.

Yo

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 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

az

Punctuation

Ri

how key words and ope rators may be used, and where punctuation symbols ml,lsr appear.

an

Program 1-1

II This program calculates the user's pay .

2

3

' include <iostream~ using namespace std;

5

intrnain()

6 7 8

{

double hours , rate, pay ;

Ha

ss

1

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;

ad

13 14 15 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;

uh a

}

m

m

17 16

M

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 <l spc.-;ial meaning in C++ and can only be used for rhe-ir in tended purposes . As you Will see, rhe programmer is allowed to make up his or her

To Read Online & Download: WWW.ISSUU.COM/SHEIKHUHASSAN


Bismillah hiir Rehman nir Raheem-----------------------------Assalat o Wasalam o Alika Ya RasoolALLAH 14

Chapter 1

Introduction to Computers and Programming

NOTE: The !include <iostream> statement in line 2 is a preprocessor directive.

NOTE: In C ++, key words arc written in al l lowercase.

Programmer-Defined Identifiers

Yo

o o

us uf

i

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.

Ri

az

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 pay

=

an

On line 18 the following code appears: hours * rate ;

ad

Ha

ss

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

uh a

m

m

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.

M

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 .

To Read Online & Download: WWW.ISSUU.COM/SHEIKHUHASSAN


Bismillah hiir Rehman nir Raheem-----------------------------Assalat o Wasalam o Alika Ya RasoolALLAH 15

1.4 What Is a Program Made of?

cout 芦

us uf

i

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: "How many hours did you work? ";

Yo

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

an

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.

ss

o

Ri

az

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.

Ha

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

~

~

~

~

~

ad

~ ~

m

m

~

72

\

\

length

M

uh a

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.

To Read Online & Download: WWW.ISSUU.COM/SHEIKHUHASSAN


Bismillah hiir Rehman nir Raheem-----------------------------Assalat o Wasalam o Alika Ya RasoolALLAH 16

Chapter 1 Introduction to Computers and Programming

us uf

i

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

Yo

numbers, or integers: 5 7

-129 32154

az

The fo ll owing arc real, or floating-point numbers: 3 . 14159 6 .7

Ri

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;

an

double hours , rate , paYi

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.

m

ad

()

Ha

ss

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.

m

Input, Processing, and Output

M

uh a

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

To Read Online & Download: WWW.ISSUU.COM/SHEIKHUHASSAN


Bismillah hiir Rehman nir Raheem-----------------------------Assalat o Wasalam o Alika Ya RasoolALLAH

17

1.6 The Programming Process

cin » cin »

us uf

i

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: hours; rate;

pay

~

Yo

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: 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-

az

marion sen t to any device connected to the computer. Lines la, 14, and 21 in Program 1-1 all perform ou tput:

Ri

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;

an

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

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?

Ha

ad

1.23

ss

1.17

m

The Programming Process

m

CONCEPT: The programming process consists of severa l steps, which include design, crea tion, tes ting, and debugging activities.

M

uh a

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.

To Read Online & Download: WWW.ISSUU.COM/SHEIKHUHASSAN


Bismillah hiir Rehman nir Raheem-----------------------------Assalat o Wasalam o Alika Ya RasoolALLAH 18

Chapter 1 Introduction to Computers and Programming

Clearly define what the program is to do. 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. Type the COde, save it, and compile il.

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.

Ri

az

5.

6.

Yo

1, 2. 3.

us uf

i

Figure 1-8

an

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. Clearly d efi ne w hat the program is to d o.

ss

1.

Ha

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: 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

Visualize the program funn ing o n the computer.

m

2.

ad

Purpose

uh a

m

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:

M

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.

To Read Online & Download: WWW.ISSUU.COM/SHEIKHUHASSAN


Bismillah hiir Rehman nir Raheem-----------------------------Assalat o Wasalam o Alika Ya RasoolALLAH 19

Use design tools sl1ch as a hi erarchy chart, flowcharts, or pseudocode to create a model of (h e program.

us uf

3.

i

'.6 The Programming Process

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 one anot her. Figure 1-9 shows a hierarchy chart

to

Yo

way that illustrates their relationship for the pay-calcu lating program.

Ri

Calculate Gross Pay

az

Figure 1-9

I

Multiply Hours

Get Payroll Data

Worked by Pay Rate

I

Display Gross Pay

an

from User

I

I

Read Number of Hours Worked

Read Hourly Pay Rate

Ha

ss

I

ad

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.

m

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.

uh a

m

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

M

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.

To Read Online & Download: WWW.ISSUU.COM/SHEIKHUHASSAN


Bismillah hiir Rehman nir Raheem-----------------------------Assalat o Wasalam o Alika Ya RasoolALLAH 20

Chapter 1

Introduction to Computers and Programming

i

Display "H ow many hours did yotl work?",

us uf

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.

Yo

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.

5. Type the code, save it, and compi le it.

Ri

az

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.

6.

ss

an

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 . Correct any errors found during compil atio n. Repeat Seeps Sand 6 as many times as necessary.

7.

Ha

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. Run the program with test data for inpur.

ad

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 .

Correct any run-rime errors fo und while running the program. Repeat Steps 5 through 8 as many times as necessary.

m

8.

m

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.

M

uh a

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

To Read Online & Download: WWW.ISSUU.COM/SHEIKHUHASSAN


Bismillah hiir Rehman nir Raheem-----------------------------Assalat o Wasalam o Alika Ya RasoolALLAH 21

'.7 Procedural and Ob;ect-Oriented Programming

9.

us uf

i

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. Validate the resuhs of th e program.

When you believe you have correcred all rhe run-time errors, enrer rest data and determine

Yo

whether the program solves the original problem .

What Is Software Engineering?

Ri

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

an

• • • • • •

az

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:

Ha

ss

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.

m

ad

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.

m

Procedural and Object-Oriented Programming

uh a

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

M

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.

To Read Online & Download: WWW.ISSUU.COM/SHEIKHUHASSAN


Bismillah hiir Rehman nir Raheem-----------------------------Assalat o Wasalam o Alika Ya RasoolALLAH 22

Chapter 1

Introduction to Com puters and Programming

us uf

i

Figure 1-10 Program

Yo

PAOCEDUREA Variables Programming END OF PROCEDURE A PAOCEDURE B Variables Programming

az

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 program-

Ri

ming 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.

an

Figure 1-11

Program

Objec t A

Variables Programming END OF PROCEDURE A

PROCEDURE B Variables Programming END OF PROCEDURE B

PROCEDURE A Variables Programming END OF PROCEDURE A

PROCEDURE B Variables Programming END OF PROCEDURE B

m

ad

PROCEDURE B Variables Programming END OF PROCEDURE B

Variables

Ha

Programming

END OF PROCEDURE A

Object C

Variables

PROCEDUAEA

PAOCEDUAEA Variables

Object B

ss

Variables

m

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

uh a

aspecrs of object-orienred programming.

~

Checkpoint

M

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.

To Read Online & Download: WWW.ISSUU.COM/SHEIKHUHASSAN


Bismillah hiir Rehman nir Raheem-----------------------------Assalat o Wasalam o Alika Ya RasoolALLAH

i

Review Questiom and E.x.ercises

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.

Yo

us uf

] .29

Review Questions and Exercises Short Answer

1. Both main memory and seconda ry sto rage are types of memory. Describe the differ-

az

ence between the two.

2. What is the difference between operating system softwa re a nd application softwa re?

Ri

3. Indicate al l the categories that the following operating systems belong to. 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

an

System A

ss

4. Why must programs written in a high-Ievcllanguage be translated into machine language before they can be run?

Ha

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?

ad

Fill-in-the-Blank 8. Computers can do many diffcrem jobs because they ca n be _ _ __

m

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 _ _ __

m

11. A{n)

is an example of a secondary storage device.

12. The two general categories of software are

and _ _ __

I

13. A program is a set of _ _ __

uh a

I

14. Since computers can't be programmed in naturaf human language, algorithms must be written in a(n )

language.

1

M

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

To Read Online & Download: WWW.ISSUU.COM/SHEIKHUHASSAN


Bismillah hiir Rehman nir Raheem-----------------------------Assalat o Wasalam o Alika Ya RasoolALLAH 24

Chapter 1 Introduction to Computers and Programming

20. Words or names defined by the programmer afe caned _ _ __

us uf

i

19. Words that have special meaning in a programming language are called _ __ __ .

21. ___-,---_ are characters or symbols tha r perform operations on one or more

operands.

characters Of symbols mark the beginning or ending of programming statements, or separate items in a list.

Yo

22.

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.

az

26. The three primary activities of a program are _____ _ _ __ .,and

Ri

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.

an

Algorithm Workbench Draw hierarchy charts or flowcharts that depict the programs described below. (See Appendix D for instructions on creating flowcharts. )

ss

30. Available Credit

Ha

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.

S.

ad

3.

Subtract t he Llsed credit from t he max;mllm c red it to get the customer's available

credit,

m

6. Display a message that shows the customer's available credit. 31. Sales Tax

The sa les tax rate

uh a

m

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

M

Once these items have been entered, the program shou ld calculate and display: The sales tax for the purchase The rotal ohhe sale

To Read Online & Download: WWW.ISSUU.COM/SHEIKHUHASSAN


Bismillah hiir Rehman nir Raheem-----------------------------Assalat o Wasalam o Alika Ya RasoolALLAH 25

Review Questions and Exercises

Balance Program

us uf

Acc(l .. n t

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

Yo

De$igning Ihe

i

32. Account 'Balance

Once [he program calculates the current balance, it sho uld be displayed on the screen.

Predict the Result

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.

Ri

33 . The variable x starts with the value O. The variable y stans with the value 5. Add 1 to x.

az

Questions 33-35 are programs expressed as English statements. What would each display on the screen if they were actual programs?

Ha

ss

an

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.

m

ad

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.

m

Find the Error

M

uh a

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.

To Read Online & Download: WWW.ISSUU.COM/SHEIKHUHASSAN


Bismillah hiir Rehman nir Raheem-----------------------------Assalat o Wasalam o Alika Ya RasoolALLAH Chapter 1

26

Introduction to Computers and Programming

us uf

i

Serendipity Booksellers Software Development ProjectPart 1: Program Specifications

Yo

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 <l databas~ of all the bpoks in the bookstore. In gene ral, the software is to perform the fo llowing wsks:

Calculate the roral of a sale, including sales tax When a book is purchased, subtract it from the sro re's inventory file

• • •

az

Add, change, delete, and look up books in the inventory file Display various reports

Ri

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

Cashier module Inventory Database module Report module

ss

• • •

an

T he program wil l be organ ized into the following three modules:

Ha

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

ad

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.

m

The Inventory Database Module

M

uh a

m

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:

To Read Online & Download: WWW.ISSUU.COM/SHEIKHUHASSAN


Bismillah hiir Rehman nir Raheem-----------------------------Assalat o Wasalam o Alika Ya RasoolALLAH

i

Review Questions and Exercises

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.

az

Yo

us uf

Field

Ri

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.

an

The Report Module The Report module will ana lyze the information in the Invento ry Da tabase to produce any of the following repofts: A list of information on all books in the inventory.

ss

Inventory List.

Ha

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.

ad

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.

m

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.

M

uh a

m

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.

To Read Online & Download: WWW.ISSUU.COM/SHEIKHUHASSAN


M

uh a

m m

ad

Ha

ss

an

Ri

az

Yo

us uf

i

Bismillah hiir Rehman nir Raheem-----------------------------Assalat o Wasalam o Alika Ya RasoolALLAH

To Read Online & Download: WWW.ISSUU.COM/SHEIKHUHASSAN


az

Yo

us uf

i

Bismillah hiir Rehman nir Raheem-----------------------------Assalat o Wasalam o Alika Ya RasoolALLAH

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 Floating-Point Data Types

2.9

The boo1 Data Type

2.10

Determining the Size

Variable Assignments and Initi;;llization

Scope

Arithmetic Operators

Comments Focus on Software Engineering:

2.16

Programming Style If You Plan to Continue

in Computer Science: Standard and Prestandard C++

Ha

of a Data Type

2.12 2. 13 2.14 2.15

ss

2.8

2.11

an

2.1 2.2 2.3 2.4 2.5

Ri

TOPICS

ad

The Parts of a c++ Program

m

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

m

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 .

uh a

Lec's examine the program line by line. Here's the first line:

M

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

To Read Online & Download: WWW.ISSUU.COM/SHEIKHUHASSAN


Bismillah hiir Rehman nir Raheem-----------------------------Assalat o Wasalam o Alika Ya RasoolALLAH 30

i

Chapter 2 Introduction to C++

1 2

II A simple c+ + program 'include <iostream>

3

using namespace std ;

4 5 6

intmain()

cout ÂŤ

Yo

{

7 8 9

us uf

Progra m 2-1

"Progranuning is great fun!";

return 0; }

az

The olltpur of the program is shown be low. This is what appears on the screen when the program runs.

Ri

Pro gra m Output Programming is g r eat fun!

Lin e 2 looks like this: iinclude <i ostream>

an

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.

Ha

ss

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<ltt:ment appears. T he iostream

file is called a header file. so it should be included at the head, or top, of the program .

ad

Line 3 reads:

using namespace std ;

m

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

uh a

m

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.

M

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

To Read Online & Download: WWW.ISSUU.COM/SHEIKHUHASSAN


Bismillah hiir Rehman nir Raheem-----------------------------Assalat o Wasalam o Alika Ya RasoolALLAH 31

i

2.1 The Parts of a C++ Program

us uf

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.

Yo

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

az

as "main," or "INT" the same as "int." This is true for all the C++ key words.

Ri

Line 6 contains a si ogle, solitary chanlCter:

an

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. YOll

your program! Afrer the opening brace cout ÂŤ

have a closing brace for every o pening brace in

ss

WARNING! Make sure

Ha

CD

YOll

see the following statement in line 7:

"programming is great fun!";

m

NOTE: T his is the only line in the program that causes anything to be printed on the screen . The other lines, like #include <iostream> 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.

M

uh a

m

()

ad

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.

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.

To Read Online & Download: WWW.ISSUU.COM/SHEIKHUHASSAN


Bismillah hiir Rehman nir Raheem-----------------------------Assalat o Wasalam o Alika Ya RasoolALLAH 32

c++

i

Chapter 2 Introduction to

us uf

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;

Yo

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.

az

Line 9 contains the closing brace:

comple~

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 .

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

( )

Openi ng and closing parentheses Opening and closing braces

Encloses a filename when used with the h nc l ude directive.

Ha

ss

< >

Used in naming a function, as in int main{) Encloses a group of statements, such as the

con rems of a function .

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.

ad

Opening and dosing quotation marks

m

~

an

Table 2-1

Ri

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 .

Checkpoint T he following C++ program will not compile because the lines have been mixed up.

m

2.1

M

uh a

int mai n ()

II A crazy mixed up program return 0 ; 'include <iostream> cout ÂŤ

"In 1492 Columbus sailed the ocean blue." ;

(

using names pace std;

To Read Online & Download: WWW.ISSUU.COM/SHEIKHUHASSAN


Bismillah hiir Rehman nir Raheem-----------------------------Assalat o Wasalam o Alika Ya RasoolALLAH 33

i

2.2 The cout Object

us uf

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 .

Yo

Rearra nge the Jines in rhe correct order. Test the program by enreri ng it on the compUTer, compiling it, and running it.

IIIIIIII

The cout Object

2.2

az

CONCEPT: Usc the cout object to d ispla y informati o n o n the co mputer's screen.

Ri

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

an

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.

A Console Window

uh a

m

m

ad

Ha

Figure 2-1

ss

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. )

M

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.

To Read Online & Download: WWW.ISSUU.COM/SHEIKHUHASSAN


Bismillah hiir Rehman nir Raheem-----------------------------Assalat o Wasalam o Alika Ya RasoolALLAH 34

In troduc tion to C++

i

Chapter 2

us uf

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.

Figure 2-2 cout «

"prograrMIing is great fun!" ;

Yo

Program 2-2 is another way to write the same program.

Think of the stream insertion operator as an arrow that pOints toward coul.

az

cout ___ "PrograllUTli n g is great fun!";

II A simple c++ program

2

tinclude <iostream>

3

using namespace std;

4 5

in t main()

6

{

7

cout «

8

return 0: }

"great fun!";

ss

9

" P r ogramming is " «

an

1

Ri

Program 2· 2

Programming is great fun !

Ha

Program Output

ad

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

II A simple c++ program

m

1

#include <iostream>

3

,

using namespace std;

5

int main ( )

6

{

m

2

cout « "Programming is ., cout « "great fun!"; return 0;

uh a

7

8

9

10

i

}

Program Output

M

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

To Read Online & Download: WWW.ISSUU.COM/SHEIKHUHASSAN


Bismillah hiir Rehman nir Raheem-----------------------------Assalat o Wasalam o Alika Ya RasoolALLAH 2.2 The cout Object

i

3S

uf

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.

Yo us

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.

1 2

II An unruly printing program iinclude <iostream>

3

using namespace std ;

Ri az

Program 2-4

4 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";

an

5 6

return 0 ;

}

ss

Program Output

Ha

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

Program 2-5 1

m ad

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.

1/ A well-adjusted printing program

#include <iostream>

3

using namespace std;

uh am

2

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 ;

M

10

11

12

13

"during the month of J une : " « "Computer games" « end l;

endl;

endl;

)

(program output continues)

To Read Online & Download: WWW.ISSUU.COM/SHEIKHUHASSAN


Bismillah hiir Rehman nir Raheem-----------------------------Assalat o Wasalam o Alika Ya RasoolALLAH Introduction to CH

Program 2-5

i

Chapter 2

(continued)

us uf

36

Program Output

The following items were top sellers during the month of June :

Aspirin

~

NOTE: The last character in endl is the lowercase lener L,

Yo

computer games Coffee

1I0t

the number one .

V~----------------------~

st(l temen ts show an example. cout <:< "My pets are" « cout « endl « "cat" «

endl « endl «

Ri

az

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 "dog"; "bird" «

endl;

Another way to cause cout to go ro a new line is to insert an escape sequence in the string

ss

an

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

6

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;

ad

7 8 9

10 l' 2

Ha

J 4 5

II Yet another well-adjusted printing program 'include <iostream> using namespace std;

}

m

Program Output

m

-

2

uh a

The followi ng items were top sellers during the month of June: computer games Coffee Aspirin

M

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.

To Read Online & Download: WWW.ISSUU.COM/SHEIKHUHASSAN


Bismillah hiir Rehman nir Raheem-----------------------------Assalat o Wasalam o Alika Ya RasoolALLAH 2.2 The cout Object

37

us uf

i

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":

Yo

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

II Error! This code will not compile. "Good" « \n ; "Morning'· « \n:

Ri

cout « cout «

az

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.

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:

an

II This will work . cout « cout «

"Good\n" : "Morning\n" i

ss

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.

Escape Seq uence

Name

Ha

Table 2-2 Common Escape Sequences

Description

\n

Newline

\t \b

Horizontal tab Alarm Backspace

\r

Return

\\

Backslash

Ca uses a backslash

\

Single quote

Causes a single quotation mark to be printed. Causes a double quotation ma rk to be printed.

.

ad

m

.

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.

Causes the cursor to go to the beginning of the current line, not the next lin e. to

be printed .

uh a

\

m

\a

Causes Causes Causes Causes

WAR N IN G! When llsing escape seq uences, do not put a space between the backslash and the control character.

M

CD

To Read Online & Download: WWW.ISSUU.COM/SHEIKHUHASSAN


Bismillah hiir Rehman nir Raheem-----------------------------Assalat o Wasalam o Alika Ya RasoolALLAH 38

Introduction to C++

us uf

i

Chapter 2

The #include Directive

Yo

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 <iostream>

az

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

Ri

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,

an

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.

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.

ad

CD

Ha

ss

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.

m

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.

m

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.

uh a

Checkpoint

M

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

To Read Online & Download: WWW.ISSUU.COM/SHEIKHUHASSAN


Bismillah hiir Rehman nir Raheem-----------------------------Assalat o Wasalam o Alika Ya RasoolALLAH 39

2.4 Variables and literals

us uf

i

'include <iostream> cout « "success\n": {

return 0:

Yo

When the lines are properly a rranged rhe program should display the following on rhe screen: Program Output Success success Success

az

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

II The Works of Wolfgang 'include <iostream>

using names pace std :

an

int main()

Ri

Srudy the following program and show what it will print on the screen .

(

ss

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 ;

Ha

)

2.4

ad

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.

m

Variables and Literals

m

CONCEPT: Variabl es represent storage locations in th e computer's memory. Lilerals arc consta nt values that arc assigned to variables.

uh a

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:

M

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 .

To Read Online & Download: WWW.ISSUU.COM/SHEIKHUHASSAN


Bismillah hiir Rehman nir Raheem-----------------------------Assalat o Wasalam o Alika Ya RasoolALLAH 40

c++

i

Chapter 2 Introduction to

/1 This program has a variable.

2 J 4

linclude <iostream>

using namespace std;

~

int main()

6

{

7

int number;

B 9

number = 5;

cout «

11 12

return 0;

number «

Program Output

Ri

The value in number is 5

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.

an

o

endl;

az

"The value in number is " «

10

Yo

1

us uf

Program 2-7

ss

Notice that variable definitions end with a semicolon. Now look at line 9: number = 5 ;

Ha

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

ad

behind the scenes, sroring a value in RAM. Look at line 10.

"The va l ue in number is " «

m

cout «

number «

endl;

m

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.

uh a

Program 2-8 1

M

2 3 4 5 6 7 8

II This program has a variable. #include <iostream> using names pace std i

int main{) { int number ; (program continues)

To Read Online & Download: WWW.ISSUU.COM/SHEIKHUHASSAN


Bismillah hiir Rehman nir Raheem-----------------------------Assalat o Wasalam o Alika Ya RasoolALLAH 41

Program 2 -8

~number"

ÂŤ

endl;

)

Yo

Program Output

us uf

(continued)

number 5; cout ÂŤ "The va lue in number is .. ÂŤ return 0 ;

9

10 11

12

i

2.4 Variables and Literals

The value in number is number

az

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.

Ri

Sometimes a Number Isn't a Number

As shown in Program 2 -8, juSt placing quotation marks around a vari:lblc name changes

an

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:

ss

number"" "5" ;

Ha

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.

m

ad

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

uh a

m

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

M

3

II This program has literals and a variable. 'include <iostream> using namespace std ;

4

5

int main()

6

{

To Read Online & Download: WWW.ISSUU.COM/SHEIKHUHASSAN


Bismillah hiir Rehman nir Raheem-----------------------------Assalat o Wasalam o Alika Ya RasoolALLAH 42

Chapter 2 Introduction to C++

Program 2-9

i us uf

7

(co ntinued)

int apples ;

8 9 10

apples cout «

11

return 0 ;

"Today we sold" «

apples «

" bushels of apples . \0";

}

Yo

12

= 20i

Program Output Today we sold 20 bushels o f apples .

az

Of course, the variable is apples. It is defined as an integer. Table 2-3 lists the literals found in the program.

Ri

Table 2-3

Type of Literal

20

"Today we sold "

Integer literal Stung literal

"bushels of apples.\n"

Srring literal

an

Literal

o

Intege r literal

ss

What are literals lIsed for? As you can see fcom this program, they arc commonly used to

Ha

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.

ad

~

m

IJ This program us es variables and li terals . l inc lude <iostream> using namespace std j iot main()

M

uh a

m

{

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 <iostream>

us ing names pace stdi

To Read Online & Download: WWW.ISSUU.COM/SHEIKHUHASSAN


Bismillah hiir Rehman nir Raheem-----------------------------Assalat o Wasalam o Alika Ya RasoolALLAH

i nt ma in ( ) (

int number;

number'" 712; cout « "The value is " « return 0;

"number" «

end l ;

Yo

)

us uf

i

2.5 Identifiers

Identifiers

az

CONCEPT: Choose variable names that indicate what the variables are used for.

The C++ Key Words

goto

continue default de l ete

a nd

and_eq asm

do

in1ine int long mutable namespace

ad

Ha

double dynamic_ cast else enum explicit export e xt ern false float f or

friend

m

auto bitand bitor bool break case catch ch a r cl a ss compl const canst cast

if

ss

Table 2-4

an

Ri

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 .

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

m

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: x;

uh a

int

The rather nondescript name, x, gives no clue as to the variable's purpose. H ere is a better example.

M

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.

To Read Online & Download: WWW.ISSUU.COM/SHEIKHUHASSAN


Bismillah hiir Rehman nir Raheem-----------------------------Assalat o Wasalam o Alika Ya RasoolALLAH 44

Introduction to C++

i

Chapter 2

us uf

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

Yo

together yo u get a variable defi nition like thi s:

io t i temsorderedi

az

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.

Ri

i nt items_orde red;

Legal Identifiers

an

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.

ss

Ha

a

Tab le 2-5 lists variable names and tells whether each is legal or illegal in C++ . Some Variable Names

Va riabl e Name dayO fW eek

lega l or Ulega l? Lega l.

m

3dG raph

ad

Tab le 2 -5

Illega l. Variable names cann ot begin with a digit. Lega l.

June1997

Legal. 1I1ega1. Variable names may only usc lerrers, digits, or underscores.

m

_ employee_ num

uh a

Mix turet3

M

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,

To Read Online & Download: WWW.ISSUU.COM/SHEIKHUHASSAN


Bismillah hiir Rehman nir Raheem-----------------------------Assalat o Wasalam o Alika Ya RasoolALLAH 2.6 Integer Data Types

45

us uf

i

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

Yo

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.

Ri

az

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:

an

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

ss

• • • •

Ha

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.

Table 2-6

ad

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.

Integer Data Types, Sizes. and Ranges

shor t

m

Da ta Type

Size

Range

2 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

2 bytes

int

4 bytes 4 bytes

m

unsigned short unsigned int

uh a

long

unsigned l ong

4 bytes 4 bytes

o to 4,294,967,29 5

M

Here are some examples of variable definitions: int days; unsigned speed; short month ; unsigned short amount; long deficit ; unsigned long insects;

To Read Online & Download: WWW.ISSUU.COM/SHEIKHUHASSAN


Bismillah hiir Rehman nir Raheem-----------------------------Assalat o Wasalam o Alika Ya RasoolALLAH Chapter 2

46

Introduction to C++

us uf

i

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.

Yo

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 ;

az

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 .

an

Ri

• • • • •

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.

Ha

ss

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

J

II This program has variables of several of the integer types . 'include <iostream> using namespace stdi

ad

1 2 4

5

int main()

6 7 S 9

{

m

int checking; unsigned int miles; long days ;

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 ;

M

uh a

m

10 11 12 13 14 15

miles;

"Our checking account balance is " « checking ; " j

)

To Read Online & Download: WWW.ISSUU.COM/SHEIKHUHASSAN


Bismillah hiir Rehman nir Raheem-----------------------------Assalat o Wasalam o Alika Ya RasoolALLAH 2.6 Integer Data Types

i

47

us uf

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 .

Yo

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:

az

int length, width;

Ri

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

,

'include <iostream>

3

using namespace std;

5

int main()

6

(

,

an

II This program shows three variables defined on the same line .

ss

1

2

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;

ad

Ha

7

)

m

Program Output

The Grande Hotel has 15 floors

m

with 300 rooms a nd 30 suites .

uh a

Integer and Long Integer Literals

Look at lines 9, 10,and 11 in Program 2-11:

M

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 .

To Read Online & Download: WWW.ISSUU.COM/SHEIKHUHASSAN


Bismillah hiir Rehman nir Raheem-----------------------------Assalat o Wasalam o Alika Ya RasoolALLAH Chapter 2 Introduction to C++

Yo

us uf

i

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

az

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.

Ri

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

an

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.

Ha

ss

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

ad

031

m

m

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

M

uh a

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?

To Read Online & Download: WWW.ISSUU.COM/SHEIKHUHASSAN


Bismillah hiir Rehman nir Raheem-----------------------------Assalat o Wasalam o Alika Ya RasoolALLAH 2.7 The char Data Type

i

Refer to the dara types listed in Table 2-6 for rhese questions .

us uf

2.9

49

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 On any computer, which data type llses more memOry, an integer or an uns igned intege r?

Yo

2.10

az

The char Data Type

NOTE: On some systems the char data type is largec than 1 byte.

an

<:)

Ri

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.

Ha

ss

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.

3 4

int main()

uh a

5 6 7

II This program demonstrates the close relationship between II characters and integers. 'include <iostream> using names pace std ;

m

1

2

m

Program 2-12

char letter;

8 9 10

letter = 65; cout « letter « letter = 66 ; cout « letter « return 0 ;

M

11

12

13

14 15

ad

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.

endl; endl;

)

(program output continues)

To Read Online & Download: WWW.ISSUU.COM/SHEIKHUHASSAN


Bismillah hiir Rehman nir Raheem-----------------------------Assalat o Wasalam o Alika Ya RasoolALLAH Chapter 2

Introduction to C++

Program 2-12

i

so

us uf

(continued)

Program Output A

8

Yo

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

az

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.

an

Ri

Figure 2-3

ss

is stored in memory as

Ha

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.

3

"

II This program uses character literals. Unclude <iostream> using namespace std;

5

int maine l

6

{

m

1 2

ad

Program 2-13

char letter ;

m

7 B 9

letter = 'A' ; caut « l etter « letter = '8' ; caut « letter « return 0 ,

uh a

10 11

12

endl;

}

M

l3 14

endl;

Program Output

A 8

To Read Online & Download: WWW.ISSUU.COM/SHEIKHUHASSAN


Bismillah hiir Rehman nir Raheem-----------------------------Assalat o Wasalam o Alika Ya RasoolALLAH 51

i

2.7 The char Data Type

us uf

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.

Yo

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

az

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.

Ri

a

e

a

b

s

a

n

\0

ss

s

an

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.

Ha

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.

NOTE: C++ automatically places the null termi nator at the end of string literals.

m

<:)

ad

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.

m

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.

M

uh a

Figure 2-5

.A' is stored as

"A" is slored as

A

\0

To Read Online & Download: WWW.ISSUU.COM/SHEIKHUHASSAN


Bismillah hiir Rehman nir Raheem-----------------------------Assalat o Wasalam o Alika Ya RasoolALLAH 52

Chapter 2 Introduction to C++

us uf

i

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

is slored as

65

o

Yo

~A"

65

az

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.

= 'A';

lette r

letter'" "A" ;

Ri

char letter ;

II This wil l work. II This will not work!

an

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,

ss

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

Ha

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.

6

m

4 5

II This program uses character l iterals. 'include <iostream> using namespace std; int main() {

m

1 2 3

ad

Program 2 - 14

char l etter;

7

uh a

8

9

10 11 12 13

M

14

letter - 'A'; cout « letter« letter = 'B' ;

'\n';

cout «

'\n';

letter«

return 0 ;

}

To Read Online & Download: WWW.ISSUU.COM/SHEIKHUHASSAN


Bismillah hiir Rehman nir Raheem-----------------------------Assalat o Wasalam o Alika Ya RasoolALLAH 2.7 The char Data Type

i

A B

Let's rev iew some important points regarding characters and strings:

Yo

az

• • • •

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.

Ri

• •

~ Checkpoint 2.11

us uf

Program Output

53

What are rhe ASCII codes for the following characters? (Refer to Appendix B)

an

C

F

2.1 2

ss

W

Which of the following is a character literal?

Ha

'.'

"B

U

Assuming the char dara type uses 1 byte of memory, how many bytes do rhe fol-

2.13

lowing literals lIse?

ad

'Q'

"Q"

"Sales"

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.

What is wrong with the fo llowing program?

M

uh a

m

2.15

m

'\n'

'include <iost r eam> using namespace std; int ma inj) {

char letter; letter = "Z"; ceut « letter « return 0;

endl;

)

To Read Online & Download: WWW.ISSUU.COM/SHEIKHUHASSAN


Bismillah hiir Rehman nir Raheem-----------------------------Assalat o Wasalam o Alika Ya RasoolALLAH Introduction to c++

Chapter 2

us uf

i

54

Floating-Point Data Types

Yo

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.

az

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

Ri

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.

an

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.

Floating Point Representations

ss

Table 2-7

Decimal No tation

Scientific Nota tion 10 2

2.4 791 x 7.2 x 10--4

2.4791E2

2.9 x106

2 . 9E6

Ha

247.91

0.00072 2,900,000

E Notation 7.2E- 4

In C++ there are three data types that can represent floating-po int numbers. They are

ad

float double long double

m

m

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 :

uh a

• •

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

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

M

Data Type

"Some compilers

US"

10 bytes fo r long doubles. This allows a range of :3.4E-4932 to ::t: 1.1£4832

To Read Online & Download: WWW.ISSUU.COM/SHEIKHUHASSAN


Bismillah hiir Rehman nir Raheem-----------------------------Assalat o Wasalam o Alika Ya RasoolALLAH 2.B Floating-Pain t Data Types

us uf

i

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

az

Yo

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.

5 6

an

3 4

II This p rogram uses floating point data types . 'include <ios tream> using namespace std; int main() (

7 8

f loat distance ; double mass ;

ss

1

2

Ri

Program 2 -15

9

13 14 15

Ha

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

)

ad

Program Output The Sun is 1. 49598e+Oll meters away .

m

The Sun ' s mass is 1 . 98ge+030 kilograms .

m

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

uh a

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.

M

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

To Read Online & Download: WWW.ISSUU.COM/SHEIKHUHASSAN


Bismillah hiir Rehman nir Raheem-----------------------------Assalat o Wasalam o Alika Ya RasoolALLAH Chapter 2

S6

Introduction to C++

us uf

i

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:

Yo

1.2F 45 . 907拢

az

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 ;

to

the floating -point

Ri

Yo u can sup press the warning message by appending the f suffix literal, as shown below: num = 14. 725f;

be srored as a long double, append an Lor 1

to

it, as in

ss

l034.56L 89.21

to

an

If you want to force a value the following examples:

Ha

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

ad

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.

m

int number; number -

7 . 5;

II Assi9ns 7 to number

uh a

m

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.

M

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 .

To Read Online & Download: WWW.ISSUU.COM/SHEIKHUHASSAN


Bismillah hiir Rehman nir Raheem-----------------------------Assalat o Wasalam o Alika Ya RasoolALLAH

57

i

2.9 The bool Data Type

us uf

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

CD

Yo

7.9 to an int variable will result in the value 7 be ing s(Q red in the variable.

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

az

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.

Ri

The bool Data Type

CONCEPT: Boolean va riables are set to either t rue or false .

an

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).

Program 2-16

Ha

ss

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.

1

1/ Th i s program demonstrates bool ean variables .

2 3

iinclude <ios t ream> using namespace std;

5

i nt main()

6

{

7

bool bool Value ;

m

boolVa l ue = true ; rout « boolvalue « boolValue = false; cout « boolvalue « return 0;

endl ; end l;

uh a

14

m

a 9 10 IJ 12 13

ad

4

Program Output 1

M

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.

To Read Online & Download: WWW.ISSUU.COM/SHEIKHUHASSAN


Bismillah hiir Rehman nir Raheem-----------------------------Assalat o Wasalam o Alika Ya RasoolALLAH 58

us uf

i

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

Yo

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

az

machines. If you are not sure what the sizes of data types are on your computer, C++ provides a way to find ou t.

cout «

Ri

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: "The size of an integer is " «

sizeof(int);

an

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.

ss

Program 2 -17

II This program determines the size of i ntegers, long II intege r s, and long doubles .

J

'include <iostream> using names pace std ; int main ( ) {

8

long double

9 10 L

cout « cout « cout « cout « cout « cout « return

12 lJ

I." 15

)

"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,•

uh a

17

apple;

ad

7

m

m

4 5

Ha

1 2

Program Output

The size of an integer is 4 bytes .

The size of a long integer is 4 bytes .

M

An apple can be eaten in 8 bytes!

To Read Online & Download: WWW.ISSUU.COM/SHEIKHUHASSAN


Bismillah hiir Rehman nir Raheem-----------------------------Assalat o Wasalam o Alika Ya RasoolALLAH 59

i

2.11 Variable Assignments and Initialization

us uf

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

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:

Yo

2.18

X

My age is 26 and my weIght is 180 pounds.

az

Program Output

Ri

(Feel free to lie to the computer about your age and your wcightit'll nevcr know !)

an

Variable Assignments and Initialization

ss

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

Ha

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;

m

ad

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.

m

12 ,. unitSSol d;

II Incorrectl

M

uh a

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.

To Read Online & Download: WWW.ISSUU.COM/SHEIKHUHASSAN


Bismillah hiir Rehman nir Raheem-----------------------------Assalat o Wasalam o Alika Ya RasoolALLAH 60

Introduction to C++

i

Chapter 2

us uf

You may also assign values to variables as parr of the definition. This is called initialization. Program 2·18 shows how it is done. 2~ 18

3

II This program shows variable initialization. ,include <iostream> usi ng namespace std j

5 6

iot main() (

, 7

iot mo nth

B 9

= 2.

days

cout « "Month" « retu rn 0 ;

10 11

=

28 i

month «

" has" «

days «

" days. \ n";

az

1 2

Yo

Program

Ri

)

Program Output

Month 2 has 28 days.

an

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.

= 12.9:

ss

doub le interestRate

Ha

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 ;

m

~

Scope

CONCEPT: A variable's scop e is t he part of th e p rogra m t hat has access to the variable.

m

2.12

ad

The variable flightNum is initialized to 89 and departure is initialized to 10. T he variables tr avelTime and distance remain uninitializcd.

M

uh a

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.

To Read Online & Download: WWW.ISSUU.COM/SHEIKHUHASSAN


Bismillah hiir Rehman nir Raheem-----------------------------Assalat o Wasalam o Alika Ya RasoolALLAH 61

i

2.13 Arithmetic Operators

1

II This program can't find its variab l e.

2 3

fiinclude <iostream> using namespace std ;

us uf

Program 2-19

int main()

6

{

7

cout 芦

value; II ERROR ! value not defined yet !

8

9 10

int value return OJ

=

100;

Yo

4

5

az

11

an

Ri

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.

ss

Arithmetic Operators

CONCEPT: There are ma ny operators fo r manipulating numeri c va lu es an d

Ha

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.

ad

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

m

m

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

uh a

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

M

arithmetic operators in C++.

To Read Online & Download: WWW.ISSUU.COM/SHEIKHUHASSAN


Bismillah hiir Rehman nir Raheem-----------------------------Assalat o Wasalam o Alika Ya RasoolALLAH Chapter 2

c++

Introduction to

i

62

us uf

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

rate;

original / 2 ;

Yo

,

= cost

- taxi

Binary

va lue

3;

amount

=

az

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: 4 + 8;

temperature

= 112 -

Ri

The subtraction operatOr returns the value of its right operand subtracted from its left operand. This statement will assign the value 98 w temperature: 14;

markUp

= 12 *

an

The multiplication operator returns the product of its two operands. In the following Statemem, markUp is assigned the value 3: 0.25 i

CD

Ha

points = 100 I 20;

ss

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:

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,

ad

parts is assigned the value 5: parts'" 17 / 3;

uh a

m

m

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 :

M

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.

To Read Online & Download: WWW.ISSUU.COM/SHEIKHUHASSAN


Bismillah hiir Rehman nir Raheem-----------------------------Assalat o Wasalam o Alika Ya RasoolALLAH 2.13 Arithmetic Operalors

i

63

us uf

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

az

Yo

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.

Ri

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 .

7

8 9 10 11 12

"

ss

int main () { double regularwages, basePayRate = 18.25, regularHours = 40.0, overtimewages , overtimePayRate = 27 . 78 , o vertimeHours = 10 , t otalWage s ;

Ha

5 6

II This program calculates hourly wages , i ncl uding overtime . ' include <iostream> using names pace std;

ad

1

2 3 4

an

Program 2· 20

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

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 ;

m

m

14 15 16 17

20

21

II Calculate the total wages. total Wages regu larWages + overtimeWages;

uh a

22 23 24

II Display the total wages.

25

cout « "Wages for this week are $" « totalWages «

26

return 0 ;

)

M

21

endl;

Program Output

Wage3 for thi3 weeK are $1007.6

To Read Online & Download: WWW.ISSUU.COM/SHEIKHUHASSAN


Bismillah hiir Rehman nir Raheem-----------------------------Assalat o Wasalam o Alika Ya RasoolALLAH 64

1ntroduction to (+ ...

i

Chapter 2

us uf

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 regularwages

basePayRate * regularHours;

~

Yo

in regularwages:

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 ;

az

Line 22 adds the regular wages and [he oven ime wages and srores the result in totalWages :

= regu larWages

+ over t imeWa ges ;

Ri

tota!wages

an

L ine 25 dis plays the message o n the screen re porting the week's wages.

ss

In the Spotlight: Calculating Percentages and Discounts

Ha

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

ad

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

m

Program 2-21

m

program shown in Program 2-21.

II This program calculates the amount of pay that /1 will be contributed to a retirement plan i f 5%, II 7% , or 10% of monthly pay is withheld . 'include <iostream> using namespace stdi

uh a

1 2 3

4 5' 6

, 7

M

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 .

To Read Online & Download: WWW.ISSUU.COM/SHEIKHUHASSAN


Bismillah hiir Rehman nir Raheem-----------------------------Assalat o Wasalam o Alika Ya RasoolALLAH 65

2.13 -Arithmetic Operators

I.

us uf

«

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. 20 21 22

Yo

cont;ribution = monthlyPay * 0',07; cout « "7 percent is $" « contribution « " per month. \ 0"; II Calculate and display a 10% contribution. contribution ~ monthlyPay * 0.1; cout « "10 percent is $" « contribution « .. per month . \0" ;

43 24

25 2. 27

return OJ

az

28 2'

)

Ri

Program Output 5 percent is $300 per month.

7 percent is S420 per month . 10 percent is $600 per month.

an

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.

Ha

ss

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.

ad

Calculating a Percentage Discount

m

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.

m

To determine the sale price you perform two calculations:

uh a

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.

M

Program 2-22 shows how this is done in C++.

To Read Online & Download: WWW.ISSUU.COM/SHEIKHUHASSAN


Bismillah hiir Rehman nir Raheem-----------------------------Assalat o Wasalam o Alika Ya RasoolALLAH Introduction to C++

i

Chapter 2

66

us uf

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 .

. 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;

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;

22 23 14 25

an

21

/1 Display the results. cout « "Regular price: $" « regularErice « endl; cout « "Discount amount: $" « discount « endl; cout « "Sale price: $" « salePrice « endl; return 0;

ss

2~

Ri

~

19

az

12 IJ 14 15

Yo

4 'include <iostream> 5 using namespace std;

Regular price: $59.95 Discount amount: $11 . 99 Sale price: $47 . 96

Ha

Program Output

ad

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.

uh a

m

m

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

M

2. 19

Is the following assignment statement valid or invalid? If it is invalid, why? 72 - amount;

To Read Online & Download: WWW.ISSUU.COM/SHEIKHUHASSAN


Bismillah hiir Rehman nir Raheem-----------------------------Assalat o Wasalam o Alika Ya RasoolALLAH 2. 14 Commen ts

us uf

How would you consolidate the following defini rions inro one starement?

i

2.20

67

int x '" 7 i int y 16 : int z '" 28 ;

Yo

What is wrong with the following program? How would yo u corren it?

2.21

*include <ios t ream> using namespace std ; int main()

number"'" 62 . 7; double number ; cout ÂŤ numbe r ÂŤ retur n 0 ;

az

{

e nd1 i

Ri

)

Is the following an example of integer division or floating-point division? What value will be stored in portion? portion

~

70 / 3 ;

ss

Comments

an

2.22

Ha

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.

ad

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.

m

m

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.

M

uh a

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.

To Read Online & Download: WWW.ISSUU.COM/SHEIKHUHASSAN


Bismillah hiir Rehman nir Raheem-----------------------------Assalat o Wasalam o Alika Ya RasoolALLAH 68

Chapter 2

Introduction to C++

us uf

i

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.

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 <iostream>

6

using namespace std;

7 8 9 10

int main() { double payRate i

Ri

~

az

2

Yo

Program 2 -23

II Holds the hourly pay rate

double hours; // Holds the hours worked lot employNumber; /I Holds t he employee number

11

an

12

{[he remainder of this program is left

Ollt.}

Ha

ss

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

ad

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.

1

/*

m

Program 2-24

PROGRAM : PAYROLL.CPP

3 4 5

Written by Herbert Dorfmann This program calculates company pay roll Last modi f ication : S/20/200S -/

uh a

6

m

2

7

B 'include <iostream> 9 using names pace std ;

M

10

To Read Online & Download: WWW.ISSUU.COM/SHEIKHUHASSAN


Bismillah hiir Rehman nir Raheem-----------------------------Assalat o Wasalam o Alika Ya RasoolALLAH

2.15 Focus on Software Engineering: Programming Style

us uf

i

69

12 13 14 15

Yo

int main() { double payRate ; 1/ Holds the hourly pay rate double hours; 1/ Holds the hours worked int employNumberi II Holds the employee number

11

([he remainder of this program is left Ollt.)

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.

Ri

()

az

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.

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.

an

â&#x20AC;˘ â&#x20AC;˘

Ha

ss

Both of these mistakes can be difficult to track down, and will prevent the program from compiling correctly.

Focus on Software Engineering: Programming Style

ad

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.

m

m

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.

M

uh a

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.

To Read Online & Download: WWW.ISSUU.COM/SHEIKHUHASSAN


Bismillah hiir Rehman nir Raheem-----------------------------Assalat o Wasalam o Alika Ya RasoolALLAH 70

i

Chapter 2 Introduction to C++

' incl ude <iostream> 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 }

Yo

1 2 3 4 5

us uf

Program 2 -25

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

az

very difficult to read. The same program is shown in Program 2-26, written in a more rea-

sonable style.

1 2 3

Ri

Program 2-26

II This example is much more readable t han Program 2- 25 . 'include <iostream> using namespace std; lnt

6

{

main()

7

double share s'" 220.0:

B

double avgPrice

= 14.67:

cout «

"There were

11

cout «

avgPr i ce «

12

return 0;

13

Program Output

shares « " s hares sold at per share.\n" ;

«

~"i

Ha

9 10

ss

5

an

4

ad

There were 220 shares sold at $14.67 per share.

m

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.

uh a

m

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 .

M

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:

To Read Online & Download: WWW.ISSUU.COM/SHEIKHUHASSAN


Bismillah hiir Rehman nir Raheem-----------------------------Assalat o Wasalam o Alika Ya RasoolALLAH

« « « «

71

"The Fahrenheit temperature i s " fahrenheit " and the Celsius temperature is celsius endl ;

us uf

cout «

c++

i

2.16 If You Plan to Continue in Computer Science: Standard and Prestandard

Yo

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

az

There are many other issues related to programm ing style. They will be presented throughout the book.

Ri

If You Plan to Continue in Computer Science: Standard and Prestandard C++ c++ programs written before th e language became standardized ma y appea r slightl y di fferent from programs written toda y.

an

CONCEPT:

ss

c++ is now a standardized programming language, but it hasn't always been. The lan-

ad

Ha

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.

m

Older Style Header Files

m

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 <ios tream . h>

uh a

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

M

nor support namespaces at all, and will produce an error message if a program has that

statement.

To Read Online & Download: WWW.ISSUU.COM/SHEIKHUHASSAN


Bismillah hiir Rehman nir Raheem-----------------------------Assalat o Wasalam o Alika Ya RasoolALLAH Introduction to C++

i

Chapter 2

72

us uf

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.

Yo

1/ A simple c++ program 'include <iostream .h> int main() {

cout 芦 "Progranuning is great fun!"; return 0;

Ri

Review Questions and Exercises

az

Most standard c++ compil ers support programs written in the older style. Presrandard compilers, however, may nOt support programs written in the newer style.

Short Answer

an

1. How many operands does each of the following types of operators require?

unary Binary

ss

Ternary

2. How may the float variables temp, weight, and age be defined in one statement ?

Ha

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.

times 4 and stores the resu lt in a.

ad

B) Multiplies

b

C) Divides a by 3.14 and srores the result in b.

m

D) Subtracts 8 from b and stores the resule in a. E) Stores the value 27 in a.

m

F) Srores the character 'K' in c. G) Stores the ASCII code for 'B' in c.

uh a

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?

M

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 <iostream> using namespace stdi

To Read Online & Download: WWW.ISSUU.COM/SHEIKHUHASSAN


Bismillah hiir Rehman nir Raheem-----------------------------Assalat o Wasalam o Alika Ya RasoolALLAH

73

int main,) (

)

8. What will the fo ll owing programs print on the screen?

A) t i nclude <iostream>

az

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;

Ri

{

Yo

couto « HTwo mandolins like creat.ures in the" : cout « "dark" ; c out « "Creating t he agony of ecstasy . " ; cout « - George Barker" ; r eturn 0 ;

us uf

i

Review Questions and Exercises

endl ;

hnclude <iostream> usi ng names pace std ; iot ma i n ( ) {

ss

B)

an

)

Ha

int x '" 0, y = 2; x = y * 4; cout « x « endl « r e turn 0; )

y «

endl ;

C) t include <iostrearn>

ad

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;

m

m

{

uh a

)

M

0 ) 'inc l ude <iostream> using namespace std; int main() {

cout « "Be careful \n"; c out « "This mi ght/n be a trick " i cout « "question \n " ; return 0 ;

To Read Online & Download: WWW.ISSUU.COM/SHEIKHUHASSAN


Bismillah hiir Rehman nir Raheem-----------------------------Assalat o Wasalam o Alika Ya RasoolALLAH

E)

i

Introduction to c++

Chapter 2

tinclude <iostream>

us uf

74

using namespace stdi int main () {

int a, x

23;

x «

endl «

a «

Yo

a - x % 2; cout «

endl;

return 0; )

az

Multiple Choice

AI

period

BI

t symbol

Ri

9. Every complere sta tement ends with a

C) semicolon

01 ending

brace

AI BI

'include (iostream) 'include {iostream}

ss

C) tinclude <iostream>

an

10. Which of the following statements is correct?

Ha

0 ) linclude [iostream] E) All 01 the above

11. Every CH program must have a

AI BI

cout statement. function main.

ad

C) tinclude statement.

0) All of the above

12. Preprocessor directives begin with a

m

AI , BI

m

C) <

DI •

uh a

E) None of the above

M

13. The lollow;ng data 72 ' A'

"Hello World" 2.8712

To Read Online & Download: WWW.ISSUU.COM/SHEIKHUHASSAN


Bismillah hiir Rehman nir Raheem-----------------------------Assalat o Wasalam o Alika Ya RasoolALLAH

75

i

Review Questions and Exercises

us uf

arc all examples of A) Variables

B)

Literals or conStants

C) Strings

Yo

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 <>

az

D) All of the above will do

]5. Which of the following are not valid assignment statements? (Circle all that apply.)

Ri

A) total::;: 9; B) 72 '" amount;

C) profit - 129

D) letter " 'W';

A) cout «

cout«

a nice day"\n;

"Have

ss

B)

"Hello World" ;

C) cout < value; D) cout «

an

16. Wh ich of the following are not valid cout statements? (Circle all thar apply.)

Ha

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 result =

,

2;

ad

B)

C) result = y I x; y D) result result

m

E)

- " - • w

2;

18. How would each of the following numbers be represented in E notatio n?

m

A) 3 . 287 x 10 6

B)

-978.65 x 10 12

uh a

C) 7 . 65491 X 10- 3

D)

-58710 . 23 x: 10- 4

19. The negation operator is

AI

Unary

M

B) Binary

C) Ternary

D) None of the ahave

To Read Online & Download: WWW.ISSUU.COM/SHEIKHUHASSAN


Bismillah hiir Rehman nir Raheem-----------------------------Assalat o Wasalam o Alika Ya RasoolALLAH

Inlroduction to C++

i

Chapter 2

20. When do preprocessor directives execute? A) Before the compiler compiles your program B) After the compiler compiles your program

True or False

Yo

C) At the same time as the compiler compiles your program D) None of the above

us uf

76

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.

31 characters long.

Algorithm Workbench 25. Convert the following pseudocode to

Ri

az

to

c++ code.

variables.

Be sute to defioe the appropriate

ss

an

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.

Ha

26. Convert the following pseudocode to C++ code. Be sure to define the appropriate variables.

ad

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

m

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? /*

m

'include iostream using narnespace std;

int inain();

M

uh a

)

int a, b, c\\ Three integers

a : 3 b

=4

c '" a +

b

Cout < MThe value of c is %d" < C; return 0;

{

To Read Online & Download: WWW.ISSUU.COM/SHEIKHUHASSAN


Bismillah hiir Rehman nir Raheem-----------------------------Assalat o Wasalam o Alika Ya RasoolALLAH

77

i

Review Questions and ExerCises

us uf

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.

Yo

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.

az

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.

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

an

Solving the Res taurant Bill problem

Ri

4 . Restaurant Bill

Ha

ss

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 __. __________________-"

ad

6. Annual Pay

m

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.

uh a

m

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.

M

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: â&#x20AC;˘

The number of mi llimeters higher than the current level that the ocean's level will be in 5 years

To Read Online & Download: WWW.ISSUU.COM/SHEIKHUHASSAN


Bismillah hiir Rehman nir Raheem-----------------------------Assalat o Wasalam o Alika Ya RasoolALLAH

Introduction to C++

i

Chapter 2

â&#x20AC;˘

â&#x20AC;˘

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

us uf

78

8. Total Purchase

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

az

Price Price ]'rice Price Price

Yo

A customer in a store is purchasing five items. The prices of the five items are:

Ri

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

ss

an

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

Ha

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);

ad

MPG = Mi les Driven I Gallons of Gas Used

11. Distance per Ta nk of Gas

m

m

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.

uh a

Hint: The follow ing formula ca n be used to ca lculate the d istance: Distance = Number of Gallons x Average Miles per Gallon

M

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.

To Read Online & Download: WWW.ISSUU.COM/SHEIKHUHASSAN


Bismillah hiir Rehman nir Raheem-----------------------------Assalat o Wasalam o Alika Ya RasoolALLAH

7'

i

Review Questions and Exercises

us uf

14. Personal Information

Write a program that displays the following pieces of information, each on a separate line:

Yo

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

az

Write a program that d ispla ys the following pattern on the screen:

...•

Ri

***** ****** *

16. Diamond Pattern

Write a progra m that displa ys the following pattern:

.......... . •••• * ...•

an

...•

Ha

ss

*****

17. Stock Commission

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)

m

• • •

ad

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:

18. Energy Drink Consumption

m

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

uh a

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: •

M

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

To Read Online & Download: WWW.ISSUU.COM/SHEIKHUHASSAN


Bismillah hiir Rehman nir Raheem-----------------------------Assalat o Wasalam o Alika Ya RasoolALLAH

80

c++

i

Chapter 2 Introduction to

us uf

Serendipity Booksellers Software Development ProjectPart 2: A Problem-Solving Exercise Screen Design

Yo

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:

az

mainmenu.cpp

cashier.cpp invrnenu.cpp

Ri

bookinfo.cpp reports.cpp

Assignments

an

1. Create the Main Menu Screen.

ss

Create a program called mainmenu. cpp. It should display the following screen:

Serendipity Boo ksellers

Ha

Main Menu

1. Cashier Module

ad

2. Inventory Database Module 3. Report Module 4. Exit

.

M

uh a

m

m

Ente r Your Choice :

To Read Online & Download: WWW.ISSUU.COM/SHEIKHUHASSAN


Bismillah hiir Rehman nir Raheem-----------------------------Assalat o Wasalam o Alika Ya RasoolALLAH Review Questions and Exercises

us uf

i

2. Create the Cashier Screen . Creare a program called cashier . cpp. Ie should display the following screen;

Date:

ISBN

-

Price

Title

Total

az

Qty

Yo

Serendipity Booksellers

Ri

Subtotal Tax Total

Thank You for Shopping at Serendipity!

an

3. Create the Inventory Database M enu Screen.

ss

Create a program called invrnenu . cpp. It shou ld display the following screen:

Ha

Serendipity BookSellers Inventory Database

1. Look Up a Book

ad

2. Add a Book ~ . Edit a B.ook's Record 4. Delete a Book 5. Return to the Main Menu

I

M

uh a

m

m

Enter Your Choice:

To Read Online & Download: WWW.ISSUU.COM/SHEIKHUHASSAN


Bismillah hiir Rehman nir Raheem-----------------------------Assalat o Wasalam o Alika Ya RasoolALLAH Chapter 2 Introduction to C++

us uf

i

4. Create the Book Information Screen. Create a program called book info . cpp. It shou ld display the following screen:

Yo

Serendipity Booksellers Book Informallon

' ISBN:

Tille:

5. Create the Reports Menu Screen.

an

Ri

az

Author: Publisher: Date Added : Quantity路Onpt:!and : Wholesale Cost: Retail Price:

ss

Create a program called reports. cpp. It should display the following screen:

Seren~ipity

Ha

Booksellers Reports

1. Inventory Listing Inventory Wholesale Value

?

3. Inventory Retail Value

Enter Your Choice:

M

uh a

m

m

ad

4. listing by Quantity 5. Listing by Cost 6, Listing by Age 7. Return to the Main Menu

To Read Online & Download: WWW.ISSUU.COM/SHEIKHUHASSAN


az

Yo

us uf

i

Bismillah hiir Rehman nir Raheem-----------------------------Assalat o Wasalam o Alika Ya RasoolALLAH

TOPICS The cin Object

3.4 3.5 3.6 3. 7

Overflow and Underflow

Mathematical Expressions When You Mix Apples and Oranges: Type Conversion

3.8

Formatting Output Formatted Input

a Program

3.13

3.14

Focus on Problem Solving: A Case Study Introduction to File Input and Output

Ha

3.9

Programming: More About Member functions More Mathematical library Functions Focus on Debugging: Hand Tracing

an

Multiple A!;signment and Combined Assignment

3.12

ss

Type Casting Named Constants

3. 11

Ri

3.10 Focus on Object-Oriented

3.1 3.2 3.3

ad

The c in Object

CON C E PT: T he cin object can be used

(Q

read data typed at the keyboard.

-

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.

uh a

Readi ng input

m

m

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.

M

with

cin

me

83

To Read Online & Download: WWW.ISSUU.COM/SHEIKHUHASSAN


Bismillah hiir Rehman nir Raheem-----------------------------Assalat o Wasalam o Alika Ya RasoolALLAH 84

Chapter 3 Expressions and Interact;vity

Program 3-1

4

'include <iost re am>

5 6

usi ng namespace std ;

7 8

lot main() { iot length, width, area;

9

Yo

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.

az

1 2 3

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

Ri

* width:

"The area o f the rectangle is " « OJ

}

area «

" . \n" i

ss

20

"This program calculates the area of a "; "rectangle. \n" ;

an

l:I.

us uf

i

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 Output with Example Input Shown in Bold

Ha

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.

ad

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 : "j

m

cout « "What is the length of the rectangle? cin » length ;

m

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.

M

uh a

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.

To Read Online & Download: WWW.ISSUU.COM/SHEIKHUHASSAN


Bismillah hiir Rehman nir Raheem-----------------------------Assalat o Wasalam o Alika Ya RasoolALLAH 8.

3. 1 The cin Object

us uf

i

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?

Yo

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.

az

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.

cou t cin

« "Wh at i s » le n gt h :

Ri

Fig ure 3-1

the le ng th of t h e rec t angle?

H .

an

Think ol lhe « and » operators as arrows that point in

the direction that data is flowing.

-)0-

leng t h ;

Ha

ci n

ss

cou t ......- " Wha t i s th e le ngth o f t he r ec t a ngl e? ";

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.

NOTE: You must include the iostrearn file in any program that llses c i n.

m

./"\

m

ad

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 .

V~----------------------~

uh a

Entering Multiple Values

M

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;

To Read Online & Download: WWW.ISSUU.COM/SHEIKHUHASSAN


Bismillah hiir Rehman nir Raheem-----------------------------Assalat o Wasalam o Alika Ya RasoolALLAH E/tpressions and Interactivity

Chapter 3

86

3 4 5

6 7 8 9

int main() { iot length, width,

area;

10

cout « cout « cout «

12

13 14

"This program calculates the area of a "i "rectangle.\n" ;

az

11

us uf

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 <iostream> using names pace std;

Yo

1 2

i

Program 3·2

"Enter the length a nd width of the rectangle ";

cout « "separated by a space. \n" ; cin » length » width ; area

17

cout «

18 19

return 0 ;

= length

*

width ;

Ri

15 16

"The area of the rectangle is .. «

}

area «

endl;

an

Program Output with Example Input Shown In Bold

This program calculates the area of a rectangle .

ss

Enter the length and width of the rectangle separated by a space . 10 20 [Enter] The area of the rectangle is 200

Ha

In the example output, the user entered 10 and 20, so 10 is stored in length and 20 is stored in width.

10 ~

ad

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 20

m

NOTE : The [Enter] key is pressed after the last number IS entered. V~----------------------~

m

cin will also read multiple values of different data types. Th is is shown in Program 3-3. Program 3-3

II This program demonstrates ho w cin can read multiple values

uh a

1 2 3

M

4 5

II of different data types. tinclude <iostrearn> using narnespace std;

To Read Online & Download: WWW.ISSUU.COM/SHEIKHUHASSAN


Bismillah hiir Rehman nir Raheem-----------------------------Assalat o Wasalam o Alika Ya RasoolALLAH 87

12

13 14

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 ;

az

15 16 17 18

f

us uf

9 10 II

int mai n ()

Yo

6 7 B

i

3.1 The cin Object

Ri

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

an

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]

Ha

ss

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

ad

t

m

cin begins reading here.

M

uh a

m

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.

To Read Online & Download: WWW.ISSUU.COM/SHEIKHUHASSAN


Bismillah hiir Rehman nir Raheem-----------------------------Assalat o Wasalam o Alika Ya RasoolALLAH Chapter 3

88

Expressions and Interactivity

us uf

i

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.

Yo

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

az

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.

Ri

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.

an

Program 3-4 shows how cin may be used to read a string into a character array. Program 3-4

ss

3 4

II This program demonstrates how cin can read a string into II a character array. tinc1ude <iostream> using namespace std;

5

6 7

int main() {

8

char name[21];

9 11

ad

cout « "What is your name? "; c in » name; cout « "Good morning " « name « return 0;

10

)

endl ;

m

12 13 14

Ha

1

2

m

Program Output with Example Input Shown In Bold What is your name? Charlie [Enter] Good morning Charlie

uh a

Let's examine the array definition in line 8:

M

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.

To Read Online & Download: WWW.ISSUU.COM/SHEIKHUHASSAN


Bismillah hiir Rehman nir Raheem-----------------------------Assalat o Wasalam o Alika Ya RasoolALLAH 89

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.

us uf

CD

i

3.1 The cin Object

Norice in lines 11 and 12 for rhe brackets and rhe size indicaror name are left our. name;

"Good morning " «

name «

endl:

Yo

cin »

cout «

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»

name(2l1;

// I ncorrect!

name [211 «

"Good morning " «

endl;

I IIncorrect !

az

cout «

Program 3-5 shows another example of using character arrays in a program.

Ri

Program 3-5

5

int main()

6

{

7 8 9

char first[l6],

an

II This program reads two strings into two character arrays. 'include <iostream> using narnespace std;

1

2 3 4

last(l6];

11

12 13 14

Ha

ss

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

}

Program Output with Example Input Shown In Bold

Johnny Jones (Enter]

m

Jones, Johnny

ad

Enter your first and last names and I will reverse them.

m

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:

uh a

Just as before, spaces separate the

twO

items.

M

/ ' \ 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__________--"

To Read Online & Download: WWW.ISSUU.COM/SHEIKHUHASSAN


Bismillah hiir Rehman nir Raheem-----------------------------Assalat o Wasalam o Alika Ya RasoolALLAH

~ 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

us uf

i

Chapler 3 Expressions and Interactivity

90

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

Yo

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;

az

AI 3. 14

Ri

BI 3 C) 0 0 ) Nothing. An error message is displayed.

A program has the follo w ing variable definitions .

3.6

l ong miles;

an

int feet; float inches;

ss

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

Ha

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 <iostream> using names pace std ; int main() {

ad

double first,

second, product:

m

cin » first » seco nd; product = first * second; cout « p r oduct; return 0 ;

m

}

M

uh a

3.8

Examme th e following program. 'include <ios tream> 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 ;

To Read Online & Download: WWW.ISSUU.COM/SHEIKHUHASSAN


Bismillah hiir Rehman nir Raheem-----------------------------Assalat o Wasalam o Alika Ya RasoolALLAH 91

3.2 Mathematical E.xpressions

3.9

us uf

i

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?

Complere [he following program skeleton so it asks for the user's weight (in pounds) and displays the equivalenc weight in kilograms.

int main() {

double pounds, kilograms;

az

II Write code here that prompts the user II to enter his or her weight and reads II the input into the pounds variable.

Yo

'include <iostream> using namespace std;

Ri

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;

an

)

ss

Mathematical Expressions

Ha

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

sum

ad

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:

= 21

+ 3;

m

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

m

statement, 3 is an expression .

number'" 3;

M

uh a

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;

To Read Online & Download: WWW.ISSUU.COM/SHEIKHUHASSAN


Bismillah hiir Rehman nir Raheem-----------------------------Assalat o Wasalam o Alika Ya RasoolALLAH 92

Chapter 3 Expressions and Interactivity

us uf

i

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 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.

Yo

Program 3-6 shows how mathematical expressions can be used with the cout object.

4

'include <iostream>

int main()

9

{

az

5 6 7 8

10

Ri

using names pace std;

double numerator, de nominator;

11

cout « COllt «

"This program shows the decimal value of "; "a fraction . \n";

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;

ss

an

12 13

Ha

21

endl;

)

ad

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

m

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.

uh a

()

m

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 : 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

M

unexpected resul ts otherw ise.

To Read Online & Download: WWW.ISSUU.COM/SHEIKHUHASSAN


Bismillah hiir Rehman nir Raheem-----------------------------Assalat o Wasalam o Alika Ya RasoolALLAH 93

3.2 Mathematical Expressions

us uf

i

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.

= 17

answer

+ x + 21 + y;

outcome

= 12

Yo

Some expressions are not that straightforward, however. Consider the following statement: + 6 I 3;

az

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.

Ri

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

+ 6 I 3 \ I 2 12 +

outcome outcome

= 14

ss

= 12

Ha

outcome

an

It could be diagrammed in the following way:

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.

(unary negation) â&#x20AC;˘ I ,

m

+

ad

Table 3-1 Prec::edence of Arithmetic Operators (Highest to Lowest)

m

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.

Some Simple Expressions and Their Values

uh a

Table 3-2

Ex pression

Value

5 + 2 * 4 10 I 2 -

M

8

13

3

2

+ 12 * 2 - 4

28 4

4+17%2 - 1 6

3

*

2 + 7

1

6

To Read Online & Download: WWW.ISSUU.COM/SHEIKHUHASSAN


Bismillah hiir Rehman nir Raheem-----------------------------Assalat o Wasalam o Alika Ya RasoolALLAH 94

Chapter 3 Expressions and Interactivity

us uf

i

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: 3 + 2

Yo

5 -

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:

az

«5-3)+2)

H ere is another example:

* 4

Ri

12 I 6

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)

Assodatlvlty of Arithmetic Operators

an

Table 3· 3 Operamr

Associativity

(una ry negation) I

Righr to left

ss

Left to right Left to right

Ha

+

Grouping with Parentheses

ad

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;

m

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,

More Simple Expressions and Their Values

m

Table 3·4

Expression

4

uh a

(5 + 2 )

10 I (5 - 3) 8 + 12 ,.. (6 - 2) + 17) ,

28

5 56

1

0

(2 + 7) I 3

9

M

" - 3) (6

2 -

Value

To Read Online & Download: WWW.ISSUU.COM/SHEIKHUHASSAN


Bismillah hiir Rehman nir Raheem-----------------------------Assalat o Wasalam o Alika Ya RasoolALLAH 95

3.2 Mathematical Expressions

us uf

i

Converting Algebraic Expressions to Programming Statements

Table 3-5 Algebraic and c++ Multiplication Expressions Algebraic Expression

Operatio n

68

6 times B

(3)(12 )

3

C++ Equiva lent B

3

• •

4

x • y

6

times 12 4 times x times y

12

az

4xy

Yo

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 .

x

Ri

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:

= a+b c x = (a

an

To convert this to a C++ statemen t, a + b will have to be enclosed in parentheses: + b) I Ci

ss

Table 3-6 shows more algebraic expressions and their C++ equivalents.

Table 3-6 Algebraic and c++ Expressions

Ha

Algebraic Ex pression

Y = 3~ 2

z = 3bc + 4 3x + 2

ad

a =

4a - 1

c ++ Expression

y_x/2· Jj z=J·b · c+4j a= (J '" x+Z) / (4 '" a- l)

m

No Exponents Please!

uh a

m

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:

M

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.

To Read Online & Download: WWW.ISSUU.COM/SHEIKHUHASSAN


Bismillah hiir Rehman nir Raheem-----------------------------Assalat o Wasalam o Alika Ya RasoolALLAH 96

Chapter 3

Expressions and Interactivity

/f

arguments

area = -00---- pow(4 . 0, 2 . 0)

Yo

16 . 0 return value

us uf

i

Figure 3路3

The statement area = pow (4.0, 2. 0 ) is equiva lent to the following alge braic sta tement: area

=4 2

X"

az

H ere is another examp le of a statement using the pow functio n. It assigns 3 rim es 6 3 to x: 3 * p o w(6. 0 , 3 . 0) ;

cout 芦

Ri

And the following statement displays the value of 5 raised to the power of 4: pow(S.O, 4.0);

Argumenl1

ss

an

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:

x -

Ha

pow function

Argument 2

y _

L -_ _ _---'

There are some guidelines that should be fo llo wed when the pow functio n is used . First,

= pow(4 , 0,

m

area

ad

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: 2 . 0);

m

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

uh a

Area = n r2

which is expressed in the program as

= 3.14159 * powtradius,

2.0) :

M

area

To Read Online & Download: WWW.ISSUU.COM/SHEIKHUHASSAN


Bismillah hiir Rehman nir Raheem-----------------------------Assalat o Wasalam o Alika Ya RasoolALLAH 3.2 Mathematical Expressions

6

using names pace std;

3

7

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;

az

12

13 14 15 16 17 1B

Ri

8

us uf

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 <iostream> linclude <cmath> II needed for pow function

Yo

1 2

i

Program } _7

97

)

Program Output with Example Input Sh.own in Bold

ss

an

This program calculates the area of a circle. What is the radius of the circle? 10 (Enter] The area is 314.159

area

= 3.14159

Ha

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 * radius * rad i us ;

m

ad

The pow function is useful, however, in operations that involve larger exponents.

m

In the Spotlight: Calculating an Average

uh a

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:

M

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;

To Read Online & Download: WWW.ISSUU.COM/SHEIKHUHASSAN


Bismillah hiir Rehman nir Raheem-----------------------------Assalat o Wasalam o Alika Ya RasoolALLAH Chapter 3 Expressions and Interactivity

98.

us uf

i

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.

Yo

Calculate the average by adding the three test scores and dividing the sum by 3. Display the average.

az

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;

Ri

The last step is to display the average. Program 3·8 shows the program.

Program 3-8

ss

an

1 II This program calculates the average 2 II of three -test scores . 3 ,include <iostream> 4 'include <cmath> 5 using namespace std;

13 14

IS 16

p

,. 18

20

·21

22

/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;

uh a

23 -l4 25

II Get cout « cin » cout « cin » cout « cin »

II To hold 'the scores

ad

12

double testl, testl, test3; double average;

m

10 11

m

B { 9

Ha

6 7 int main()

average «

endli

26 )

Program Output with Example Input Shown In Bold

M

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

To Read Online & Download: WWW.ISSUU.COM/SHEIKHUHASSAN


Bismillah hiir Rehman nir Raheem-----------------------------Assalat o Wasalam o Alika Ya RasoolALLAH 3.2 Mathematical Expressions

us uf

3.10

i

~ Checkpoint

99

Complete the table below by writing the value of each expression in the "Val ue" co lu mn.

Value

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 )

az

Yo

Expression 6 + 3 * 5

I 3

y

6x

a

2b + 4 c

x+2 X

Y=

Z

2

ss

Z 2 2

Ha

g =

2

an

Y = x

3.12

Ri

Write C++ expressions for the following algebraic expressions:

3. 11

Study the follo wing program and complete the table.

ad

'i nc lude <iostream> H nclude <cmath> usi ng names pace std,

int main () {

m

double value l, value2, va lue3 ;

M

uh a

m

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 ...

The Program Will Display Wha t Number (Stored in value3 )?

2 5

4. 3 6

To Read Online & Download: WWW.ISSUU.COM/SHEIKHUHASSAN


Bismillah hiir Rehman nir Raheem-----------------------------Assalat o Wasalam o Alika Ya RasoolALLAH Chapter 3 Expressions and Interactivity

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

i

3.13

us uf

100

Volume = 1t?-h

Yo

where 7t is 3.1415 9 r is the radius of the tan k h is the height of the tank .include <iostream> 'include <cmath>

int main() (

Ri

double volume, radius, height;

az

using namespace std ;

cout «

"This program will tell you the volume of\n"i

cout « cout «

" a cylinder - shaped fuel tank . \n"; "How tall is the tank? ";

cout «

cin »

height;

"What is the radius of the tank? Hi

radius ;

an

cin :»

II You must complete the program .

ss

)

Ha

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

ad

automatically convert them to th e same data type. This can affect the results of mathema tical expressions.

If an

m

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

m

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

uh a

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

M

double

float

unsigned long

long

unsigned int int

To Read Online & Download: WWW.ISSUU.COM/SHEIKHUHASSAN


Bismillah hiir Rehman nir Raheem-----------------------------Assalat o Wasalam o Alika Ya RasoolALLAH 3.3 When You Mix Apples and Oranges: Type Conversion

i

101

us uf

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.

Yo

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.

Ri

az

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.

years â&#x20AC;˘ interestRate

an

In the following exp ression, assume that years is an int and interestRate is a float:

ss

Before the multiplication takes place, years wil! be prommed to a float.

Ha

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;

ad

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. re~ults

in a fractional val ue being assigned

m

Watch out for situations where an expression to an integer variable. H ere is an example:

m

int x, y '" 4 ; float z = 2. 7: x = y * z;

uh a

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 .

M

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;

To Read Online & Download: WWW.ISSUU.COM/SHEIKHUHASSAN


Bismillah hiir Rehman nir Raheem-----------------------------Assalat o Wasalam o Alika Ya RasoolALLAH 102

Chapter 3 Expressions and Interactivity

us uf

i

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

Yo

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.

az

Overflow and Underflow

Ri

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.

a '" b *

an

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: Ci

If band c are set to values large enough, the mu ltiplication will prod uce a number tOO big

ss

to be stored in a . To prepa re for rhis, a shoul d have been defined as an int, or a long

into

Ha

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.)

2

II This program demonstrates integer overflow and underflow. 'include <iostream>

3

using namespace std ;

4

m

1

ad

Program 3-9

int main{)

6

{

7 S

II testVar is initialized with the maximum value for a short. short testVar ~ 32767;

uh a

9 10

m

5

11

II Display testVar. cout « testVar « endl;

12

13 14

M

15 16

II Add 1 to testVar to make it overf l ow . T 1; endl;

testvar = testvar cout « testVar «

To Read Online & Download: WWW.ISSUU.COM/SHEIKHUHASSAN


Bismillah hiir Rehman nir Raheem-----------------------------Assalat o Wasalam o Alika Ya RasoolALLAH 103

// Subtract 1 from testVar to make it underflow. testVar = testVar - Ii cout « testVar « endlj return Oi

18 19 20 21

us uf

17

i

3.4 Overflow and Underflow

)

Program Output

Yo

32767

-32768 32767

Ri

az

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.

an

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.

ss

• • •

Ha

Yo u can find our how your system reacts by compiling and running Program 3-10. Program 3-10

ad

1/ This program can be used to see how your system handles II float in g point overflow and under f low.

tinclude <iostream> using namespace stdj

m

1 2 3 4 5

int main() { f loat test ;

m

6 7 8 9

10

test

=

2 _Oe38 " 1000 j

Should overflow test-

cout «

l2 13

test - 2.0e-38 / 2.0e38; 1/ Should underflow test. cout « test « endl;

uh a

test «

//

11

return 0:

14

)

M

15

endl;

To Read Online & Download: WWW.ISSUU.COM/SHEIKHUHASSAN


Bismillah hiir Rehman nir Raheem-----------------------------Assalat o Wasalam o Alika Ya RasoolALLAH Chapter 3

Expressions and Interactivity

us uf

i

104

Type Casting

CONCEPT: Type cas ting allows yo u to perform ma nu al data type conversion.

Yo

A type cast expression lets you manually promote or demote a val ue. The general format of a type cast expression is static_cast<DdtaType>(Valuej

where Value is a variable or lireral value that you wish

[0

convert and

DdtdType

is the data

az

type you wish to convert Value roo Here is an example of coue that uses a type cast expresdouble number = 3 . 7; int val:

val

=

static_cast<int>( nurnberJ ;

Ri

Sion:

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

an

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.

ss

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

Ha

perMo nth - static_cast<double>(books) / months:

Program 3-11

7 8 9

ad

II This program uses a type cast to avoid integer division . 'include <iostream> using namespace std; int main() ( int books ; lnt months; double perHonth ;

m

1 2 3 4 5 6

II Number o f books to read II Number of months spent reading II Average number of books per month

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;

M

uh a

m

10 11 12 13

}

To Read Online & Download: WWW.ISSUU.COM/SHEIKHUHASSAN


Bismillah hiir Rehman nir Raheem-----------------------------Assalat o Wasalam o Alika Ya RasoolALLAH

105

us uf

i

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.

WARN I NG! In Program 3-1 1, the foJ1owing statement would still have resulred in integer division :

az

CD

Yo

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.

Ri

perMonth : static_cast<double>tbooks I months);

an

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 .

3

4

II This program uses a type cast expression to print a character II from a number. #include <iostream> using namespace std;

Ha

1

2

ss

Program 3· 12

5 7

8

int main ( ) ( lnt number

9

m

II Display t he value of the number variable . cout « number « end1;

m

II Displ ay the value of numbe r converted to II the c har data type. cout « static_ cast<c har >(number) « endl j return 0;

uh a

10 11 12 13 14 15 16 17

= 65;

ad

6

Program Output

M

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.

To Read Online & Download: WWW.ISSUU.COM/SHEIKHUHASSAN


Bismillah hiir Rehman nir Raheem-----------------------------Assalat o Wasalam o Alika Ya RasoolALLAH

Chapter 3 Expressions and Interactivity

i

106

us uf

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.

Yo

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

Ri

az

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.

=

(double)books / months;

an

perMonth

ss

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:

= in t( number);

Ha

val

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:

ad

perMonth = double(books) / months;

~

m

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 Assume the following variable definitions:

m

3. 14

iot a

m

5 , b _ 12;

M

uh a

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<int >(x)

To Read Online & Download: WWW.ISSUU.COM/SHEIKHUHASSAN


Bismillah hiir Rehman nir Raheem-----------------------------Assalat o Wasalam o Alika Ya RasoolALLAH

107

static_cast<int>(x) * static_cast<int>(z)

I)

static_cast<int>{x * z)

Jl Gtatic

cast<double>(stat~c_cast<int>(x l

us uf

H)

i

3.6 Named Constants

*

static_cast<int>(z)

3. 15

Yo

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 <iostream> using namespace std; int ma in()

az

{

Finish this program as specified above . return 0; II II

)

What will t he fo llowing program display? tinclude <iostream> using names pace std;

ss

int main()

an

3.16

Ri

char letter;

{

Ha

int integer l , integer2; double result;

«

m

)

ad

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;

m

Named Constants

uh a

CONCEPT: Literals m ay be given n ames that symbolica lly represent them in a p rogra m.

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;

To Read Online & Download: WWW.ISSUU.COM/SHEIKHUHASSAN


Bismillah hiir Rehman nir Raheem-----------------------------Assalat o Wasalam o Alika Ya RasoolALLAH

Chapter 3 Expressions and Interactivity

i

108

us uf

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?

Yo

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.

=

0.129;

Ri

const double INTEREST_RATE

az

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:

an

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.

Ha

ss

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;

ad

can be changed to read newAmount

= balance

* INTEREST_RATE;

uh a

m

m

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;

M

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.

To Read Online & Download: WWW.ISSUU.COM/SHEIKHUHASSAN


Bismillah hiir Rehman nir Raheem-----------------------------Assalat o Wasalam o Alika Ya RasoolALLAH 109

i

3.6 Named Constants

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 <iostream> II needed for pow function #include <cmath> using names pace std;

7

8

int main()

9

{

10 11

canst double PI = 3.14159; double area, radius;

az

12

Ri

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; )

an

13 14 15 16 17 18 19

Yo

1 2

us uf

Program 3-13

Ha

canst int SIZE ~ 21; char name [SIZE J i

ss

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:

ad

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.

m

If You Plan to Continue in Computer Science: The #define Directive

m

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 .

uh a

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

M

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 <iostream> finclude <cmath> II needed for pow function (program continues)

To Read Online & Download: WWW.ISSUU.COM/SHEIKHUHASSAN


Bismillah hiir Rehman nir Raheem-----------------------------Assalat o Wasalam o Alika Ya RasoolALLAH

6

(continued)

us uf

Program )·14

i

Chapter 3 Expressions and Interactivity

110

using namespace stdi

7

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

Yo

lnt main() {

az

10 11

'define PI 3 . 14159

)

Ri

8 9

an

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

*

pow(radius, 2.0);

Ha

area; PI

ss

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

wil l be modified by the preprocessor to read area; 3.14159 * pow(radius, 2.0);

If there had been a line that read

PI «

endl ;

ad

cout «

it wou ld have been modified to read 3.14159 «

m

cout «

endl;

It is important to realize the difference between const variables and constants created

M

uh a

m

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);

To Read Online & Download: WWW.ISSUU.COM/SHEIKHUHASSAN


Bismillah hiir Rehman nir Raheem-----------------------------Assalat o Wasalam o Alika Ya RasoolALLAH

3.6 Named Constants

i

111

us uf

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

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.

az

o

Yo

this state ment.

Checkpoint lowing literal values:

Ri

Write statements using the canst qualifier to create named constants for the fol -

3.17

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

an

Literal Va lue

9.8

ss

1609

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?

Ha

3.18

ad

'include <iastream> usi ng namespace std :

m

m

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()

uh a

(

canst int PER JAR int jars, pieces; double commission;

1860;

M

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 «

endl,

return 0; )

To Read Online & Download: WWW.ISSUU.COM/SHEIKHUHASSAN


Bismillah hiir Rehman nir Raheem-----------------------------Assalat o Wasalam o Alika Ya RasoolALLAH

i

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

us uf

112

linclude <iostream>

Yo

usi ng names pace std; int main() {

1/ Define a named con stant named CONVERSION II with the value 1.467 . double milesPerHour, feetPerSecond;

Ri

az

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.

"That is " « feet Per Second " feet per second. \n" i

an

cout « « return

OJ

ss

}

Ha

Multiple Assignment and Combined Assignment CONCEPT: Mu ltiple assignment means to assign the same value ro several variables with one statement.

ad

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: c

= b =

~

d

~

12i

m

a

m

T he value 12 will be assigned to each variable listed in the statement. 0:-

Combined Assignment Operators

uh a

Quire often, programs have assignment sta tementS of the following form: number

~

number + Ii

M

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.

To Read Online & Download: WWW.ISSUU.COM/SHEIKHUHASSAN


Bismillah hiir Rehman nir Raheem-----------------------------Assalat o Wasalam o Alika Ya RasoolALLAH

113

i

3.7 Multiple Assignment and Combined Assignment

(Assume x "" 6)

Statement

What It Does

x - x + 4;

Adds 4 to x

x x

x

-= • -= , •

10 3

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

az

x

Va lue o f x After the Statement

Yo

Table J -8

us uf

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.

x

60 3 2

Ri

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.

an

Table 3·9 Operator

Example Usage

Equivalent to

+.

X +-

5;

x

2;

Y = Y

-=

ss

Y

z *-= 10; a I=- b;

'= /=

Ha

,=

c %= 3;

.

x + 5 ,'

, =,

a

=a

c = c

2 ,'

10;

/ b,

3 ,'

ad

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

5 6 7

m

4

// 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 <iostream> using namespace std;

m

1 2 3

uh a

8 9

10 11

M

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)

To Read Online & Download: WWW.ISSUU.COM/SHEIKHUHASSAN


Bismillah hiir Rehman nir Raheem-----------------------------Assalat o Wasalam o Alika Ya RasoolALLAH

hpressions and \nterac.ti'Jity

Program 3-1 S

(continued)

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

az

30 31

"j

Yo

cout « "at the same time with the same beginning\n"; cout « "inventory . What was the beginning inventory? cin » beglnv;

"

20 21 22 23

/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

Ri

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

an

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 ,

43 44 4S 46

Ha

ss

42

47

i

Chapter 3

us uf

·''-1 4

)

Program Output with Example Input Shown In Bold One week ago, 3 new widget stor es opened

m

ad

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]

uh a

m

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:

M

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) ;

To Read Online & Download: WWW.ISSUU.COM/SHEIKHUHASSAN


Bismillah hiir Rehman nir Raheem-----------------------------Assalat o Wasalam o Alika Ya RasoolALLAH

3.7 Multiple Assignment and Combined Assignment

i us uf

which is different fro m result"" result

115

* a + Si

Table 3-10 shows other examples of such statements and their assignment statement equivalencies.

Equivalent to

Exam ple Usage b + 5;

x - x +( b+5)i

~

*

( 10

2) ;

-

c) ;

a " a I (b + c) ; c = c (d - 3) ;

Ri

az

(a

, ,

z *'" 10 - c; a /= b + c; c %- d - 3;

~

y

y

y-=a *2 ;

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:

to

the variables total,

an

K + ..,

Yo

Table 3-10

A) Add 6 to x.

C) Multipl y y by 4.

D) Divide total by

ss

B) Subtract 4 from amount. 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.

ad

Ha

E)

3,23

What will the following program display?

m

'i nclude <iostream> using namespace std; int main()

M

uh a

m

(

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 «

endl; endl;

endl;

return 0: )

To Read Online & Download: WWW.ISSUU.COM/SHEIKHUHASSAN


Bismillah hiir Rehman nir Raheem-----------------------------Assalat o Wasalam o Alika Ya RasoolALLAH

U6

us uf

i

Chapter 3 Expressions and Interactivity

Formatting Output

Yo

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:

Ri

az

720 720.0 720 . 00000000 7 . 2e+ 2 +720 . 0

an

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

7 8

ss

. 3 4 5

II This program displays three rows of numbers . iinclude <iostream> using namespace std ;

Ha

1 2

i nt main() { int num1 '"" 2897, num2 num4 -

num7

9

34, 390,

num3 837 , 5, numS - 7, num6 = 1623. num8 '=' 3456, num9 = 12;

ad

10

11

II Display the fi r st row of numbers cout « numl « " « num2 « "

12 13

I.

num3 «

end1 ;

II Display the second row of numbers cout « num4 « " « num5 « " «

num6 «

endl;

num9 «

endl;

m

14

«

15

18

19

}

«

uh a

20

m

II Display the third row of numbers « num8 « .. cout « num7 « " return 0;

17

Program Output 2897 5 837 34

M

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.

To Read Online & Download: WWW.ISSUU.COM/SHEIKHUHASSAN


Bismillah hiir Rehman nir Raheem-----------------------------Assalat o Wasalam o Alika Ya RasoolALLAH 3.8 Formatting Output

i

117

us uf

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;

value = 23; cout « "(H «

setw(5) «

value «

Ri

This will cause the following output:

")";

az

Yo

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:

23)

an

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.

ss

Program 3-17 shows how the numbers in Program 3·16 can be primed in columns that line up perfectly by using setw.

Ha

Program 3· 17

5 6

int main( )

7

(

ad

4

II This program displays three r ows of numbers_ 'inc lude <iostream> 'include <iomanip> II Required for setw using namespace std;

1 2 3

int numl = 2897, num2 = 5, num3 = 837, num6 num4 = 34, numS = 7, 1G 23, num7 390 , numS 3456, num9 12 ;

m

8 9 10

-

11

II Display the first row o f numbers cout « setw(6) « num1 « setw(6) « num2 « setw(G) « num3 « endlj

m

12

-

13

uh a

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

JI

M

~o

21 22 23

"

Oigp~ay

cout «

«

th e

third row of numbo r o

setw(6) « num7 « num8 « setw(6j «

setw(6) num9 « endl;

return OJ )

(program output conlinuel)

To Read Online & Download: WWW.ISSUU.COM/SHEIKHUHASSAN


Bismillah hiir Rehman nir Raheem-----------------------------Assalat o Wasalam o Alika Ya RasoolALLAH

3 ~ 17

(continued)

us uf

Program

i

Chapter 3 Expressions and Interactivily

118

Program Output

5

837

34 390

7 3456

1623 12

Yo

2897

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_"____________________________------------------------~

az

()

Notice how a setw manipu laror is used with each value because setw only establishes a

Ri

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 value" 18397; cout « setw(2) «

value;

an

following statement:

ss

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.

Ha

YOll

Program 3-18

4

5

II This program demonstrates the setw manipulator being II used with values of various data types .

'include <iostream> 'include <iomanip> using namespace std;

ad

1 2 3

9 10 11

uh a

12

int main() { int intValue - 3928; double doubleVa1ue = 91.5; canst int ARRAY_SIZE _ 14, char cStringvalue[ARRAY_SIZEI - "John J. Smith";

m

7

8

m

6

13 14

cout « "( " « cout « " ( " « cout « " ( " « return 0;

15 16

17

M

18

setw(5) « intValue « ")" « endl; setw(S) « doubleValue « "J" « endl; setw(16) «

cStringValue «

")'. «

endl;

)

To Read Online & Download: WWW.ISSUU.COM/SHEIKHUHASSAN


Bismillah hiir Rehman nir Raheem-----------------------------Assalat o Wasalam o Alika Ya RasoolALLAH 3.8 Formatting Output

i us uf

Program Output ( 3928)

(

11 9

91.5) John J. Smith )

.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.

an

Formatting Numbets with

Ri

The setprecision Manipulator

4 5

II This program demonstrates how setprecision rounds a II floating point value. linclude <iostream> 'include <iomanip> using names pace std:

Ha

3

ss

Program 3-19 1 2

6

7

i nt Illain()

8

( double quotient , number 1

ad

9

10

= 132 . 364,

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 15

16

17

number2

« « « «

«

26 . 91 ;

endl; endl; endl ; endl; e ndl;

uh a

)

m

m

13 1<

18 19

az

Yo

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 .

Program Output 4.91877

M

4 . 91BB 4. 91 9

' .~1

U

"

To Read Online & Download: WWW.ISSUU.COM/SHEIKHUHASSAN


Bismillah hiir Rehman nir Raheem-----------------------------Assalat o Wasalam o Alika Ya RasoolALLAH 120

Chapter 3 Expressions and Interactivity

us uf

i

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.

Yo

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;

setprecision(5) «

dollars «

endl;

II Displays 24.51 II Displays 24 . 5 1

az

cout «

Table 3·11 shows how setprecision affecrs the way various values are displayed.

Ri

Table 3-11 M anipula tor

28.92786

setprecision (3 )

28.9

21

setpreci. .. i.on (5)

21

109.5

setprecision (4)

34 .28596

setprecision(2)

an

Number

Value Displayed

109.5

3.

ss

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 .

Ha

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

ad

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 <iostream> 'include <ioma nip> using names pace std ;

m

1 2 3

6

intmain() {

9

double day1, day2, day3, total;

II Get cout « cin » cout « cin » cout « c,n »

the sa l es for each day.

uh a

10 11 12 13

m

7

8

,.

15

16

M

17

"

l~

20

"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;

To Read Online & Download: WWW.ISSUU.COM/SHEIKHUHASSAN


Bismillah hiir Rehman nir Raheem-----------------------------Assalat o Wasalam o Alika Ya RasoolALLAH 121

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 }

Input Shown In Bold 321 .57 [Enter] 269.62 [Enter] 307.77 [Enter]

Ri

Program Output with Example Enter the sales for day 1 : Enter the sales for day 2 : Enter the sales for day 3:

Sales Figures 32 1. 57

269.62

an

307.77

898.96

ss

Day 1. Day 2: Day 3; Total:

az

31

dayl « endl; day2 « endl; day3 « endl; total « end l ;

Yo

21 22 23 2.

us uf

i

3.8 Formatting Output

The fixed Manipulator

Ha

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:

ad

Program 3-20

1 . 4568e+OOS

2.0S61e+OOS

1.9865e+OOS 5.4994e+OOS

uh a

Day 1 : Day 2: Day 3: Total:

Input Shown In Bold 145678.99 [Enter] 205614_85 [Enter] 198645.22 [Enter]

m

Sales Figures

m

Program Output with Example Enter the sales for day l : Enter the sales for day 2 : Enter the sales for day 3:

M

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.

To Read Online & Download: WWW.ISSUU.COM/SHEIKHUHASSAN


Bismillah hiir Rehman nir Raheem-----------------------------Assalat o Wasalam o Alika Ya RasoolALLAH 122

Program 3- 21

llinclude <iomanip>

i nt main( ) (

double day!, d ay2, day), total;

.,

az

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

cout « cout « cout « cout « cout «

25

26

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;

)

«

Ha

24

ss

II Display the sales figures . cout « "\nSales Figures\n" i cout « ,, ------- - --- - - \n" ;

22 23

27 28 29 30 31

Yo

using namespace std;

Ri

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 <iostream>

an

1 2

us uf

i

Chapter 3 Expressions and lnteractivity

setw( 8)

endl;

endl; endl;

« tota l « endl;

Sales Figures

uh a

Day 3 : Total :

1321.87 1869.26 1403.77 4594.90

m

Day 1 : Day 2 :

m

ad

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]

The statement in line 25 uses the fixed manipulator:

M

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.

To Read Online & Download: WWW.ISSUU.COM/SHEIKHUHASSAN


Bismillah hiir Rehman nir Raheem-----------------------------Assalat o Wasalam o Alika Ya RasoolALLAH Formattin9 Output

1 23

i

3.B

double x = 123.4567; cout « setprecision(2) «

fixed «

x «

us uf

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. endl;

Yo

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

az

By default, f1oati ng-poim numbers are not displayed with trailing zeroes, and f1oating-

doubl e x = 123 . 4, Y = 456.0; cout « setprecision(6) « x « cout « y « endl;

Ri

point numbers that do not have a fractional part are not displayed with a decima l point. For example,look at the following code. endl ;

an

The cout statements will produce the following Output. 123 .4 456

Ha

ss

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;

ad

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

m

~

m

~ 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

uh a

Normally output is right justified. For example, look at the following code.

-

= 1.

783;

M

double x - 146.789, Y 24.2, , « « setw( 10) x« endl; cout « endl ; cout « setw(10) « y cout « setw(10) « , « endl:

To Read Online & Download: WWW.ISSUU.COM/SHEIKHUHASSAN


Bismillah hiir Rehman nir Raheem-----------------------------Assalat o Wasalam o Alika Ya RasoolALLAH

2,

is displayed in a pr ine field o f 10 spaces. The output of

us uf

Each of the variables, x, Y. and the cout statements is

i

Chapter 3 Expressions and Interactivity

12.

14 6.789 24.2 1 . 783

=

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;

az

dou b le x

The output of these cout statements is

Ri

146.789 24 . 2 1. 783

Yo

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.

an

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.

ss

Table 3-12

Descriptio n

setw(n)

Establishes a print field of n spaces.

fixed

D isplays float ing-point numbers in fixed poinr notation.

showpoint

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.

Ha

Stream M anipul ator

ad

setprecision (n)

Causes su bseq uent output to be left justified.

left

Causes subsequent output to be right just ified.

m

right

~ Checkpoint 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.

M

uh a

m

3.24

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.

To Read Online & Download: WWW.ISSUU.COM/SHEIKHUHASSAN


Bismillah hiir Rehman nir Raheem-----------------------------Assalat o Wasalam o Alika Ya RasoolALLAH 3.9 Formatted Input

us uf

i

Th e following program will nOt compile because the lines have been mixed up.

3.25

'include <iomanip> )

Yo

cout « person « endl; char person{ 151 = "Wolfgang Smith"; int main() cout « person « endl; (

az

'include <iostream> return 0 ; cout <<: left; using namespace std; cout « setw(20): cout « right:

When the lines are properly arranged the program should display the following:

Ri

wolfgang Smith Wolfgang Smith

an

Rearrange the lines in the correct order. Test the program by entering it on the compU[er, compiling it, and running it. 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 .

3.26

int main() (

s~d;

Ha

U$in9 namespace

ss

'include <iostream> 'include <iomanip>

canst double PI = 3 . 14159; double degrees, radians;

m

m

ad

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;

uh a

)

Formatted Input

M

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

To Read Online & Download: WWW.ISSUU.COM/SHEIKHUHASSAN


Bismillah hiir Rehman nir Raheem-----------------------------Assalat o Wasalam o Alika Ya RasoolALLAH 126

Chapter 3

Expressions and Interactivity

us uf

i

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.

Yo

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;

with cin.

Program 3-22

5 6 7

int main() {

a

an

iinclude <i omanip> using namespace s t d;

canst int SIZE: 5; char word[SIZE]i

9

cout « "Enter a word : " ; cin » setw(SIZE) » word;

14

return 0;

15

cout «

Ha

10 11 12 13

ss

'include <iostream>

3 4

Ri

II This program uses setw with the cin object. 2

"You entered " «

)

az

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

word «

endl ;

ad

Program Output with Example Input Shown In Bold Enter a word: Eureka [Enter] You entered Eure

m

m

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.

M

uh a

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.

To Read Online & Download: WWW.ISSUU.COM/SHEIKHUHASSAN


Bismillah hiir Rehman nir Raheem-----------------------------Assalat o Wasalam o Alika Ya RasoolALLAH 3.9 Formatted Input

• •

i

us uf

There are two important points to remember about the wa y cin handles field widths:

127

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.

Yo

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:

az

cin . getline(sentence, 20) ;

an

Ri

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.

ss

Program 3·23

II This program demonstrates ci n' s getline member function.

#include <iostream> using namespace std;

3 4

5

int main()

6

7

const int SIZE = 81 ; char sentence[SIzEJ;

8

ad

9 10 11

}

endl;

m

cout « "Enter a s e ntence: n; cin.getline(sentence, SIZE) ; cout « "You entered " « sentence « return 0 ;

12 13 14

Ha

1 2

uh a

m

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.

M

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.

To Read Online & Download: WWW.ISSUU.COM/SHEIKHUHASSAN


Bismillah hiir Rehman nir Raheem-----------------------------Assalat o Wasalam o Alika Ya RasoolALLAH

i

Chapter 3 Expressions and Interactivity

128

us uf

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

Using cin . get

Yo

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.

A limiting cha racteristic of the» operator w ith char variables

IS

az

tha t it requires a charac-

Ri

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.

an

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:

ss

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;

Ha

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.

3 4

II This program demonstrates cin.get .

'include <iostream> using namespace std ;

m

1 2

ad

Program 3-24

,

int main()

7

char

{

Chi

m

5

8

cout « "This program has paused. Press Enter to continue ."; cin.get(ch); cout « "Thank you! " « end1; return 0 ;

uh a

9 10 11 12 13

)

Program Output

M

This program has paused. Press Enter to continue. [Enter] Thank you!

To Read Online & Download: WWW.ISSUU.COM/SHEIKHUHASSAN


Bismillah hiir Rehman nir Raheem-----------------------------Assalat o Wasalam o Alika Ya RasoolALLAH 129

i

3.9 Formatted Input

us uf

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 exam-

Yo

ple, look at the following statements:

az

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";

an

Ri

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.

ss

Figure 3-6

Keyboard buffer 1

I

0

I

0

Ha

I

t

I[En'er)I

cin begins reading here.

m

m

ad

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

uh a

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:

M

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 . ) ;

To Read Online & Download: WWW.ISSUU.COM/SHEIKHUHASSAN


Bismillah hiir Rehman nir Raheem-----------------------------Assalat o Wasalam o Alika Ya RasoolALLAH Chapter 3 Expressions and lnteractivity

i

130

cin . ignore();

us uf

If no arguments arc used, cin will only skip the very next character. Here's an examp le:

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

II Skip the newline character.

cin. ignore ( ) i

cout «

Yo

int number; II Define an integer variable . cout « "Enter a number : "; cin » number; II Read an integer .

"Enter a character:

~;

cout «

/1 Read a character. "Thank You!" « endl ;

az

cin.get(ch)i

Ri

Focus on Object-Oriented Programming: More About Member Functions

ss

an

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.

Ha

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.

m

m

ad

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:

uh a

• • •

getline get

ignore

Calling an object's member function causes the object to perform some o perati on. For

M

exa mple, calli ng cin's getline member function causes cin to read a line o f input from the keyboard .

To Read Online & Download: WWW.ISSUU.COM/SHEIKHUHASSAN


Bismillah hiir Rehman nir Raheem-----------------------------Assalat o Wasalam o Alika Ya RasoolALLAH 13]

i

3.11 More Mathematical l ibrary Functjons

us uf

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 design your own objects, complete with member functions.

Yo

All of ci n's member funct ions are written in C++ code. In Chapter 13 you wil l learn to

az

More Mathematical Library Functions

CONCEPT: The C++ runtime library p rovides severa l fun ctions for pe rforming

Ri

complex mathemati cal operations.

an

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.

Example y : abs(X)i

cos

Y

exp

y = exp (x) ;

fmod

y =

m

fmod (x, z);

m y

uh a

log

log(x) i loglO(x) ;

10g10

Y

sin

y - sin(x) ;

sqrt

y -

tan

y = tan(x) ;

M

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.

ad

= cos(xl;

Description

Ha

Function abs

ss

Table 3-13

sqrt(x) ;

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.

To Read Online & Download: WWW.ISSUU.COM/SHEIKHUHASSAN


Bismillah hiir Rehman nir Raheem-----------------------------Assalat o Wasalam o Alika Ya RasoolALLAH

132

i

Chapter 3 Expressions and lnteractivity

cout « "Enter a number: "; cin » flum; s = sqrt(num) i

"The square root of " «

num «

" is " «

S «

endlj

Yo

cout «

us uf

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;

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

Ri

az

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.

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 <iostream> 'include <iomanip> /1 For setprecision 'include <cmath> // For the sqrt and pow funct ions using names pace stdj

ss

2 3

Ha

1

an

Program 3-25

8

int main() { double a, b,

12 13

.,

" ,. cout « "Enter the length of side » cin cout « "Enter the length of side b, , cin » b·, c = sqrt(pow{<l, 2.0) + pow{b , 2.0)) , cout « "The length of the hypotenuse is cout « setprecision(2) « c « endl: return 0,

.,

14 15

...

m

16 17 l8 19 20 )

...,

uh a

21

Ci

ad

11

m

9 10

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]

M

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,

calc ulates the square roar of the sum

sqrt(pow{a , 2 . 0) + pow(b , 2.0);

To Read Online & Download: WWW.ISSUU.COM/SHEIKHUHASSAN


Bismillah hiir Rehman nir Raheem-----------------------------Assalat o Wasalam o Alika Ya RasoolALLAH 3.11 More Mathematical Library Functions

i

133

us uf

Notice chat the following mathematical expression is used as the sqrt function's argument: pow(a, 2.0) + pow(b, 2 . 0)

Yo

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

y

:0

az

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: rand();

cout « cout « cout «

rand() « rand() « rand() «

endl; end1; end1;

an

Ri

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.

Ha

ss

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.

ad

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.

II This program demonstrates random numbers .

m

li nc lude <iostream> 'include <cstdlib> II For rand and srand iinclude <ctime> II For the time function using names pace stdi

uh a

1 2 3 4 5

m

Program 3-26

6

7 int main() B { 9 II Get the system time_ 10 unsigned seed time ( O) ; :0

M

11

12 13

II Seed the random number generator .

srand(seed);

14

(program continues)

To Read Online & Download: WWW.ISSUU.COM/SHEIKHUHASSAN


Bismillah hiir Rehman nir Raheem-----------------------------Assalat o Wasalam o Alika Ya RasoolALLAH Expressions and Interactivity

Program 3-26

i

Chapter 3

(continued)

us uf

134

/ I Display three random numbers . cout « rand ( ) « endl; cout « rand() « endl; cout « rand( ) « endl;

IS 16 17

18

o·,

return

19 20

Yo

)

Program Output 23861 20884

az

21941

y

~

Ri

NOTE : If you wish to limit the range of the random number, use the following formu la.

1 + rand() % maxRange;

an

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:

ss

This is how the sta tement works: Look at the following expression.

Ha

rand() % 100

ad

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.

Write a short description of each of the fo llowing func tions: cos

log

sin

exp

10g10

sqrt

m

3.27

m

~ Checkpoint

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

uh a

3.28

M

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

To Read Online & Download: WWW.ISSUU.COM/SHEIKHUHASSAN


Bismillah hiir Rehman nir Raheem-----------------------------Assalat o Wasalam o Alika Ya RasoolALLAH 3. 12 Focus on Debugging: Hand Tracing a Program

i

135

us uf

Write (I stMcmenr thar calculates the cosecant of rhe angle stored in the variable a, and sTores it in the variable y.

Yo

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.

Ri

az

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

an

1 II This program asks for three numbers, then 2 II displays the average of the numbers. 3 'include <iostream>

ss

4 using namespace std: 5 int main()

Ha

6 {

7

double num1, num2, num3, avgi

8

cout«

9

cin»

cin »

12

cout «

13

cin»

14

avg

num1; "Enter the second number ; ": num2;

"Enter the third number : ";

num3:

num1 + num2 + num3

uh a

~

avg

ad

11

num3

m

cout «

num2

"Enter the first number; ";

m

10

numl

15

cout «

16

return 0i

I 3:

"The average is .. «

avg «

endl;

M

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.

To Read Online & Download: WWW.ISSUU.COM/SHEIKHUHASSAN


Bismillah hiir Rehman nir Raheem-----------------------------Assalat o Wasalam o Alika Ya RasoolALLAH

i

Chapter 3 Expressions and Interactivity

136

us uf

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

(with hand trace chart filled)

Program 3 -27

1 II This program asks for three 2 II displays the average o f the

Ri

numbers, then numbers .

3 'include <iostrearn>

4 using na me space std;

an

5 int main ( ) 6 {

double nurnl , num2, nurn3, avg;

e

cout «

9

cin »

ss

7

10

cout «

11

ci n »

12

cout «

13

ci n »

14

avg

15

cout «

16

return 0,

. ..

Ha

"Enter the first number: nurn! ;

ad

nurn2 ; "Enter the th ird number :

m

.....

• nurn l + num2 + nurn3 I 3,

.

«

avg

1

,

«

endl;

nurn2

, ,

nurn3

avg

,

,

,

,

,

,

,

, ,

10

, ,

10

20

10

20

,

'0

20

30

10

20

30

.0

20

30

,

,

, I

40 40

uh a

m

"The average is

nurn!

10

"Enter the second number : " ;

nurn3;

az

Yo

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.

17

)

Do you see the error? By exa mi ning the statement that performs the math operation in

M

line 14, we find a mistake. The division operation rakes place before the addition opera-

tions, 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 .

To Read Online & Download: WWW.ISSUU.COM/SHEIKHUHASSAN


Bismillah hiir Rehman nir Raheem-----------------------------Assalat o Wasalam o Alika Ya RasoolALLAH Solvjn~j:

A Case Study

137

Focus on Problem Solving: A Case Study

us uf

i

3.13 Focus on Problem

Yo

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

az

Table 3-14 shows the variab les needed.

Table 3-14

Description A doubl e variable to ho ld the length of the crate, whic h is input by the user.

Ri

Variable length

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

an

width

calculated. cost

A double va ria ble to ho ld the cost of bu ilding the crate. The value stored in this variable

ss

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.

Ha

charge profit

ad

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).

m

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.

m

3. Display the data calcu lated in Step 2. A general hierarchy chart for this program is shown in Figure 3-7.

M

uh a

Figure 3-7

Calculale CraIe Volume, Cost, Price, and Profit.

I Gel Crate Dimensions.

Calculate Volume, Cost, Customer Charge. and Profit.

Display Calculated Data.

To Read Online & Download: WWW.ISSUU.COM/SHEIKHUHASSAN


Bismillah hiir Rehman nir Raheem-----------------------------Assalat o Wasalam o Alika Ya RasoolALLAH Chapter 3

Expressions and Interactivity

us uf

The "Get Crate Dimensions" step is shown in greater derail in Figure 3-8. Figure 3-8

Yo

Get Crate Dimensions.

I Get length.

i

138

Get Height.

az

Get Width.

Ri

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,

an

Customer Charge, and

ss

Profit.

Calculate the Crate's Volume.

Calculate the Customer Charge.

Calculate the Prolil Made.

Ha

Calculate the Crate's Cost.

The "Display Calculated Dam" step is shown in greater derail in Figure 3-10.

m

ad

Figure 3-10

Display Calculated Data.

Display the

Crate's Cost.

Display the Customer Charge.

Display the Prolit Made.

uh a

m

Display Ihe

Crate's Volume.

M

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

~he

c ra~ e .

crate's volume .

To Read Online & Download: WWW.ISSUU.COM/SHEIKHUHASSAN


Bismillah hiir Rehman nir Raheem-----------------------------Assalat o Wasalam o Alika Ya RasoolALLAH 3.13 Focus on Problem Solving: A Case Study

i

139

us uf

Display the cost of building the crate . Display the customer's charge for the crate . Display the profit made from the crate.

Calculations

Yo

The following formulas will be used to calcula te the crate's volume, cost, charge, and profit:

az

volume = length " width " height cOSt =volume" 0.23 charge:: volume " O.S profit = charge - COSt

The Program

Program 3 -28

II II 3 II 4 II

,

an

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 <iostream> j include <iomanip> using namespace std;

ss

5 6 7

6

19 20 21

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; /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;

M

uh a

22 23 24 25 26 27 28 29 30

double length, width, height, volume, cost, charge, profit;

ad

15

16 i7 18

{

m

13 14

int main()

m

10 11 12

shown in

Ha

1 2

IS

Ri

The last step is to expand the pseudocode into the final program, which Program 3-28.

(program continues)

To Read Online & Download: WWW.ISSUU.COM/SHEIKHUHASSAN


Bismillah hiir Rehman nir Raheem-----------------------------Assalat o Wasalam o Alika Ya RasoolALLAH Chapter 3

Expressions and Interactivity

Program )·28

i

(continued)

31

II calculate the crate's volume, the cost to produce it,

32

II the charge to the customer, and the profit. ~

volume

length * width * height ;

35

cost = volume * 0.23; charge = volume * 0.5:

36

profit

=

charge - cost;

Yo

33 34

37

38

II Display the calculated data .

39 40

cout cout cout cout cout

"Charge to customer : $ " « charge « $" « profit « end l ;

« " Profit: return 0;

)

Program Output with Example Input Shown In Bold Enter the dimensions of the crate (in fee t ): Length: 10 [Enter]

endl;

Ri

45

« «

"The volume of the crate is "i volume « " cubic feet . \n" ; "Cost to build: $" « cost « end!:

az

41 42 43 44

« «

us uf

140

Width : 8 [Enter]

an

Height: 4 [Enter]

ss

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

m

ad

Ha

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

m

Introduction to File Input and Output

M

uh a

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.

To Read Online & Download: WWW.ISSUU.COM/SHEIKHUHASSAN


Bismillah hiir Rehman nir Raheem-----------------------------Assalat o Wasalam o Alika Ya RasoolALLAH 3.14 Introduction to File Input and Output

i

us uf

There are always three steps thar must be taken when a file is used by a program!

141

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.

Yo

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

X

[ 10 [ 25 [ 40 [

:~:_t

I

Ri

Variables

az

Writing data to a file

y

25

z

40 r---------~

an

Data is copied from variables into the fife.

ss

When data is read from a file, it is copied from the file into variables. Figure 3-12 iIIustrares this.

Ha

Figure 3-12

Reading data from a tile

Variables

G

y

@J

z

B

m

m

ad

x

Data is copied from the file into variables.

uh a

Setting Up a Program for File Input/Output

M

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 <fstream>

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.

To Read Online & Download: WWW.ISSUU.COM/SHEIKHUHASSAN


Bismillah hiir Rehman nir Raheem-----------------------------Assalat o Wasalam o Alika Ya RasoolALLAH 142

Chapter 3 Expressions and lnteractivity

us uf

i

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.

Yo

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

az

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.

Ri

File Stream Data Typc of s t r eam

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 .

ss

NOTE: In this section we only discllss the of stream and i fstream types. The fstream type is covered in Chapter 12.

Ha

O

an

ifstream

~--------------------~

Here are example statemenrs that define of stream and ifstream objects: of stream out pu tFile; ifstream inputFile

m

ad

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.

m

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

uh a

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:

M

ifstream inputFile;

For example, the following statement uses i nputFi le to open a file named customer.dat: input File . open("customer.dat"};

To Read Online & Download: WWW.ISSUU.COM/SHEIKHUHASSAN


Bismillah hiir Rehman nir Raheem-----------------------------Assalat o Wasalam o Alika Ya RasoolALLAH 3.14 Introduction to File Input and Output

i

143

us uf

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. )

ollt putFile . open ("C : \ \data \ \i nventory .dat" )

Yo

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:

az

In this statemem, the file c : \data\inventory.dat is opened and linked with output File.

Ri

~ 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_. ________--'

i f stream inputF:ilej char' fileName [2'0 I ; cou t « "Enter l~he

an

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.

" j

ss

name of the file : cin » filenamel; inputFile . open dfileName) i

Ha

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

ad

file.

m

Closing a File

m

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:

M

uh a

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.

To Read Online & Download: WWW.ISSUU.COM/SHEIKHUHASSAN


Bismillah hiir Rehman nir Raheem-----------------------------Assalat o Wasalam o Alika Ya RasoolALLAH

i

Chapter 3 Expressions and Interactivity

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.

us uf

144

Calling the file strea m object's close member funct ion closes a fi le. Here is an example:

Yo

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.

outputFile «

"I love c+ + programming";

az

Assuming outputFile is a file stream object, the fo llowing statement demonstrates using the « operator £0 write a string to a file:

Ri

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: outputFile «

"Price: " «

price:

an

Writing Data to a File

ss

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.

,

ad

3 4 5 6

II This program writes data to a file. ' include <iostream> 'include <fstream> using namespace std:

int main () (

8 9

of stre am outputF ile: output File .open( "demofile. txt" ) ;

10

11

cout «

m

1 2

Ha

Progr am 3-29

" Now writing dat a to the file. \n" ;

,

m

12

II Write output File outputFile output File output File

13

"

uh a

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 ;

M

20 21 22

23

h

;

}

To Read Online & Download: WWW.ISSUU.COM/SHEIKHUHASSAN


Bismillah hiir Rehman nir Raheem-----------------------------Assalat o Wasalam o Alika Ya RasoolALLAH 3.14 Introduction to File Input and Output

i

145

us uf

Program Screen Output Now writing data to the file. Done.

Yo

Output to File demo file . txt Bach Beethoven Mozart Schubert

az

Reading Data from a File

inFile » in Program

name;

3 ~29,

Ri

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:

,

the pIe demofile.txt was created and the following list of names was

Bach

Beethoven Mozart Schubert

Reading Data

from a File

ss

-

an

stored there.

Program 3-30 demonso/ates the use of the» operator to read the names from the file and Program

Ha

store them in a variablf 3 ~ 30

II This program reads dtta from a file.

'include <iostream> linclude <fstream> using namespace std;

3 4

ad

1

2

5 6

m

11

inFile.open("demofile.txt"); cout « "Reading dat~ from the file. \n\n";

uh a

12 13

m

int main () { B ifstream inFile; 9 canst int SIZE = 81 ; 10 char name[SIZE]; 7

14 15

inFile »

16

cout «

II Read name 1 from the file

/1 Display name 1 (program continues)

M

17

name; name « endl;,

To Read Online & Download: WWW.ISSUU.COM/SHEIKHUHASSAN


Bismillah hiir Rehman nir Raheem-----------------------------Assalat o Wasalam o Alika Ya RasoolALLAH Chapter 3 Expressions and lnteractivity

Program 3-30 inFile »

18 20 21 22 23 24 25

i 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

name; name «

cout «

name; name

«

endl;

II Close t he file

inFile.close() ; cout « "\nDone.\n"; return 0;

az

2. 27 28 2. 30

e ndl;

cout «

us uf

,.

(continued)

Yo

146

)

Ri

Program Screen Output Reading data from the file . Bach

Beethoven

an

Mozart Schubert

ss

Done .

through the file.

Ha

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

ad

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.

h

\n

uh a

m

Figure 3· 13

m

Figure 3-13 shows the fi rst 5 bytes in the file:

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

M

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.

To Read Online & Download: WWW.ISSUU.COM/SHEIKHUHASSAN


Bismillah hiir Rehman nir Raheem-----------------------------Assalat o Wasalam o Alika Ya RasoolALLAH 3.14 Introduction to File Input and Output

3

4

i

I I This pr ogram reads

r~ctangle

us uf

Program 3-31

1 2

dimensions from a file.

'include <iostream> 'include <fstream> using namespace stdi

5

Yo

i nt mai n ( ) {

ifstream inFilej lnt length , width, area;

inFi1e. open ( "dimensi<?ns. txt" ) ; cout « "Reading dim'rns i ons o f 5 recta ng l es fr om the f i le. \ n\ nM;

11 12

13 14 15 16

II Process rectangle 1 inFile » length; inFile » width; a r ea = l ength * wi dtni cout « "Area of rec~angle 1: " «

area «

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;

area «

endl;

an

17 18 19 20 21

az

7 8 9 10

Ri

6

22 23

ss

24 25 26

Ha

27 28

29 30 31

ad

32 33 34

J5

endl;

m

36 37 38

II Process rectangle 5 inFile » length: infile » width: area = length * widt~; cout « "Area of rec}angle 5: " «

m

39 40 41 42

uh a

43

II Close the file inFile . c1ose(); cout« "\nDone. \ n"; return 0;

44

45 46 47

}

M

48

147

To Read Online & Download: WWW.ISSUU.COM/SHEIKHUHASSAN


Bismillah hiir Rehman nir Raheem-----------------------------Assalat o Wasalam o Alika Ya RasoolALLAH 148

Expressions and Interact;vity

i

Chapter 3

us uf

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

Yo

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:

"

length

10, width = 2

Ri

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

az

Rectangle

The program's output follows,

an

Program 3-31 Program Output

Reading dimensions of 5 rectangles from the file. rectangle 20 rectangle 2, 35 rectangle 3, 162 rectangle 4, 120

"

Are. of rectangle 5, 24

Done.

ss

of of of of

Ha

Area Area Area Area

ad

Review Questions and Exercises Short Answer

m

1. Assuming (he array description is defined as follows: char description{ 4 0];

m

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?

uh a

C) Will the following cin statement automatically stop reading input when the array

is filled? cin Âť

description;

M

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"

To Read Online & Download: WWW.ISSUU.COM/SHEIKHUHASSAN


Bismillah hiir Rehman nir Raheem-----------------------------Assalat o Wasalam o Alika Ya RasoolALLAH Review Questions and Exercises

i us uf

3. Assllme the arra y name is defined as follows:

name[2S] ;

char

149

Yo

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;

az

char section;

Write a single cin statement that will read input into each of these varia bles.

~nt

ma~n()

{ amou~t =

89 . 7; showpoint « fixe d; setJ (8) « amount «

return 0; 1

}

endl;

an

double cout « cout «

Ri

5. ~hat h~ader files r ust be included in the following program?

ss

6. Write a definition statement for a character array named city. It should be large enough to hold a string 30 characters in length.

Ha

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;

ad

pr ice = SIZB

m

8. Complete the fo Uotng table by writing the value of each expression in the Value column,

I

Expression

m

28 I 4 - 2 6 + 12 * 2 - 8 4 + B * 2

uh a

6+17%3-2 2

+

22

l 1

*

(8 + 7)

Value

(9 -

2

1)

(16+7)%2-1 12/(10-6)

*

(2

2) I 4

M

(19 - 3)

To Read Online & Download: WWW.ISSUU.COM/SHEIKHUHASSAN


Bismillah hiir Rehman nir Raheem-----------------------------Assalat o Wasalam o Alika Ya RasoolALLAH 150

a = 12x

z=5x+14y+6k

g=

,

Yo

y = x

us uf

9. Write C++ expressions for the following algebraic expressions:

i

Chapter 3 Expressions and Interactivity

h + 12 4k

az

c =

Ri

10. Assume a program has the following variable definitions;

iot units; float mass; double weight;

weight

=

mass * units;

an

and the fo llowing statement:

ss

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

Ha

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.

ad

11. Assume a program has the following variable definitions: int a, b = 2;

float c = 4.2;

m

and the following statement: a = b '" C;

m

What value will be stored in a? A) 8.4

uh a

B) 8

C) 0

M

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

To Read Online & Download: WWW.ISSUU.COM/SHEIKHUHASSAN


Bismillah hiir Rehman nir Raheem-----------------------------Assalat o Wasalam o Alika Ya RasoolALLAH

Review Questions and Exercises

i

us uf

13. Rewrite the following variable definition so the variable is a named constant.

ISl

int rate:

14. Complete the following table by writing statements with combined assignment opera-

Yo

tors in the right-hand column. The statements shou ld be equivalent to the statements in the left-hand column. Statements with Combined Assignment Operator

Statements with Assignment Operator x "" x + 5;

az

total = total + subtotal: dist '" dist / rep; ppl ppl" period: inv inv shrinkage;

Ri

num '" num \ 2;

15. Write a multiple assignment statement that can be used instead of the following group of assignment statements: east

= 1:

north = Itol,lth -

an

west = 1; 1; 1;

Ha

ss

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.

ad

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.

m

FIII-in-the-Blank

19. The _____ Iibraty function returns the cosine of an angle. 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.

M

uh a

m

20. The

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.

To Read Online & Download: WWW.ISSUU.COM/SHEIKHUHASSAN


Bismillah hiir Rehman nir Raheem-----------------------------Assalat o Wasalam o Alika Ya RasoolALLAH

i

Chapter 3 Expressions and lnteractivity

152

us uf

Algorithm Workbench

Yo

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.

az

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.

Ri

After you write the pseudocode algorithm, convert it to a complete C++ program.

Find the Errors 31. using namespace std; int main () {

an

Each of rhe following programs has some errors. Locate as many as yOll ca n.

ss

double number!, number2, sum:

Ha

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

ad

)

32. 'include <iostream> using namespace std;

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;

uh a

m

{

m

int main()

M

)

33. Hnclude <iostream> ; using namespace std ; int maine) {

const int numberl, number2, product:

To Read Online & Download: WWW.ISSUU.COM/SHEIKHUHASSAN


Bismillah hiir Rehman nir Raheem-----------------------------Assalat o Wasalam o Alika Ya RasoolALLAH

Review Questions and Exercises

i ;

Yo

)

H

us uf

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 <iostream>; using namespace std ; main

az

int number!, number2;

Ri

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

an

M

)

35. 'include <iostream> ;

ss

using namespace std , main {

Ha

double number, half;

eout « "Enter a number and I will divide it\n" cout « "in half for you . \n" cin » number! ; half =/ 2;

ad

cout « fixedpoint « return 0; )

showpoint «

half «

endl;

m

36. finclude <iostream> ; using names pace std ;

uh am

int main() {

char name, go;

cout « MEnter your name: "; ein » setw(20);

M

cin . getline » cout « ~Hi " « cout "Press the ein » go ;

153

name ; name « end!; key to end this progr.e.m.";

ENTER

return 0; )

To Read Online & Download: WWW.ISSUU.COM/SHEIKHUHASSAN


Bismillah hiir Rehman nir Raheem-----------------------------Assalat o Wasalam o Alika Ya RasoolALLAH

i

Chapter 3 Expressions and Interactivity

154

us uf

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.)

Yo

tinclude <iostream> using names pace std : int main ( ) (

double salary, monthly :

az

cout « "What is your annual sal ary? ": cin » salary ;

monthly - static_cast<int>(salary) I 12; cout « ~You r monthly wages arc " « monthly « return 0;

Ri

)

endl;

38. tinclude <iostream> using namespace std; int main{)

an

(

H

«

y «

Ha

x ,. y ,. Z : 4; x += 2: y -= 1; z *- 3: cout « x « " return 0;

ss

lon g x, y, Z;

)

• " «

z «

endl;

39. 'include <iostream> using namespace std :

ad

'defi ne WHO "Columbus "

canst int WHEN = 1492; cout « "In " « WHEN«

uh am

{

m

'define DI D "sailed" 'define WHAT "the ocean blue . " iot main()

« DID « return 0;

.... «

.. « WHO « WHAT « endl;

" ..

}

40. (Assume the user enters George Washington .) 'include <iostream> 'include <iomanip>

M

using namespace std;

int main( 1

To Read Online & Download: WWW.ISSUU.COM/SHEIKHUHASSAN


Bismillah hiir Rehman nir Raheem-----------------------------Assalat o Wasalam o Alika Ya RasoolALLAH ISS

us uf

const in SIZE - 20; char userlnput[SIZE]i cout « "What is your narne? "; cin » setw(SIZE) » userlnput; cout « MHello .. « userInput « return 0:

i

Review Questions and Exercises

endl;

}

Yo

41 . (Ass ume the user enters George Washington. ) tinclude <iostream> 'include <iomanip> using namespace std; int main()

az

{

Ri

canst in SIZE = 20: char userlnput{SIZE): cout « "What is your name ? ": cin.getline(uSerInput, SIZE): cout « "Hello " « userInput « return 0:

endl;

an

}

'include <iostrearn> tinclude <iomanip> using namespace std;

Ha

int main()

ss

42. (Assume the user enters 36720152. Use a calculator.)

{

long seconds; double minutes, hours, days, months, years:

ad

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

m

minu~es

-

seconds /

60;

M

uh a

m

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:

}

To Read Online & Download: WWW.ISSUU.COM/SHEIKHUHASSAN


Bismillah hiir Rehman nir Raheem-----------------------------Assalat o Wasalam o Alika Ya RasoolALLAH 156

Chapter 3 Expressions and Interactivity

us uf

i

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

Yo

per gallon 01 gas. 2. Stadium Seating

az

Scating Problem

3. Test Average

Ri

Solving the Stadium

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.

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.

an

4. Average Rainfall

ss

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:

Ha

The average rainfall for j une, j uly, and August is 6.72 inches. 5. Box Office

ad

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

m

Movie Name: Adult Tickets Sold:

Child Tickets Sold,

uh a

m

Gross Box Office Profit: Net Box Office Profit: Amount Paid to Distributor;

"Wheels of Fury" 382 127 $ 2673.00 $ 534.60 $ 2138.40

M

~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.

To Read Online & Download: WWW.ISSUU.COM/SHEIKHUHASSAN


Bismillah hiir Rehman nir Raheem-----------------------------Assalat o Wasalam o Alika Ya RasoolALLAH Review Questions and Exercises

i

157

us uf

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.

Yo

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.

az

9. Automobil e Costs

Ri

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

an

Write a program that converts Celsius tem pera tu res to Fahrenheit temperatures. T he form ula is 9 F=-C+32

ss

5

11. Currency

Ha

F is the Fahrenheit temperature and C is the Celsius temperature.

ad

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:

m

1 Dollar = 113.22 Yen 1 Dollar:= 0.6936 Euros twO

decimal places of

m

Format your currency amou nts in fixed-point notation, with precis ion, and be sure the decimal point is always displayed.

12. Monthly Sales Tax

M

uh a

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:

To Read Online & Download: WWW.ISSUU.COM/SHEIKHUHASSAN


Bismillah hiir Rehman nir Raheem-----------------------------Assalat o Wasalam o Alika Ya RasoolALLAH

us uf

S is the product sales and T is the tOral income (product sales plus sales tax).

The program should display a report similar to

$ 26572.89

Sa les: County Sales Tax:

$ 25068.76 $ 501. 38 $ 1002 . 75

State Sales Tax: Total Sales Tax:

$

Yo

Month: October Total Collected:

i

Chapter 3 Expressions and Interactivity

158

1504.13

13. Property Tax

Ri

az

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

15 . Math Tutor

Ha

ss

an

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.

247

m

+ 129

ad

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

m

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:

uh a

247

+ 129

376

M

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

To Read Online & Download: WWW.ISSUU.COM/SHEIKHUHASSAN


Bismillah hiir Rehman nir Raheem-----------------------------Assalat o Wasalam o Alika Ya RasoolALLAH 159

i

Review Questions and Exercises

us uf

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 4.25% 12 $ 1000 . 00 $ 43.34 $ 1043.34

Yo

Interest Rate : Times Compounded: principal: Interest: Amount in savings :

az

17. Monthly Payments The monthly payment on a loan may be calculated by the following formula:

,

«1 + Rate) - 1)

Ri

Payment = Rate" (l+Ratet • L

$ 10000.00

ss

Loan Amount: Monthly Interest Rate: Number of Payments; Monthly Payment : Amount Paid Back : Interest Paid:

an

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

36

332.14 $ $ 11957 . 15 $ 1957.15

Ha

18. Pizza Pi

l%

ad

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.

m

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.

m

To calculate the number of slices that may be taken from the pizza, you muSt know the fo llowing facts:

uh a

• • •

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:

M

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. ~~~~~~~~~~~~~

To Read Online & Download: WWW.ISSUU.COM/SHEIKHUHASSAN


Bismillah hiir Rehman nir Raheem-----------------------------Assalat o Wasalam o Alika Ya RasoolALLAH Chapter 3 Expressions and Interactivity

i

160

us uf

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?

Yo

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

az

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.

Ri

21. Saving Numbers to a File

For this assignment you will write two programs:

ss

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.

an

Program 1

Ha

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

ad

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

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.

uh a

m

• • •

m

Last Ill.ooth Joe purchased some stock in Acme Software, Inc. Here are the deta ils of the purchase:

M

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

To Read Online & Download: WWW.ISSUU.COM/SHEIKHUHASSAN


Bismillah hiir Rehman nir Raheem-----------------------------Assalat o Wasalam o Alika Ya RasoolALLAH 161

Review Que!>tiom, and Exercises

us uf

i

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.)

Yo

• • • • •

25. Word Game

• •

Ri

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

an

• •

az

Write a program that plays a word game with the user. The program should ask the user to emer the following:

After the user has entered these items, the program should display the following Story, inserting the user's input into the appropriate locations;

Ha

ss

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

ad

1. The Main Menu

m

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

uh a

m

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: •

M

• •

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.

To Read Online & Download: WWW.ISSUU.COM/SHEIKHUHASSAN


Bismillah hiir Rehman nir Raheem-----------------------------Assalat o Wasalam o Alika Ya RasoolALLAH

â&#x20AC;˘

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:

Yo

Serendipity Booksellers ' Ca$hier Module Date: 3/31/06 . Quantity of ~ook: 2 ISBN : 0-333¡90123-8

.

Title~

History of Scotland

19.95

az

Prjc~:

i

Expressions and lnteractivity

us uf

Chapter 3

Sere.ntlipity Booksellers

ss

Date: 3/31/06 Title .

.Qty ISBN

0-333-90123-8 History of Scotland

Ha

2

an

Ri

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:

Subtotal

Priclj

Total

$ 19.95 ' $' 39.90 . S 39.90

Tax

$ 2.39

Total

$ 42.29

ad

. Thank You for Shopping at Serendipity!

m

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.

m

3. The Inventory Database Menu

uh a

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.

M

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.

To Read Online & Download: WWW.ISSUU.COM/SHEIKHUHASSAN


Yo

us uf

i

Bismillah hiir Rehman nir Raheem-----------------------------Assalat o Wasalam o Alika Ya RasoolALLAH

JO

4. 11

The i f Statement

Focus on Software Engineering: Validating User Input More About Variable Definitions

Ri

Relational Operators

4 .1 4.2 4.3 4 .4 4 .5 4.6 4.7 4.8 49 4.10

az

o

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

logical Operators

ss

Menus

an

Nested i f Statements The if/else i f Statement

and Scope

Ha

Checking Numeric Ranges with Logical Operators

ad

Relational Operators

m

m

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.

M

uh a

• •

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

To Read Online & Download: WWW.ISSUU.COM/SHEIKHUHASSAN


Bismillah hiir Rehman nir Raheem-----------------------------Assalat o Wasalam o Alika Ya RasoolALLAH 164

Making Decisions

i

Chapter 4

us uf

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.

Yo

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

Ri

az

Greater than Less than Greater th an or equa l to Less tha n or equal to Equa l to Not equal to

1=

an

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

IS

ss

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 :

Ha

x < y

Table 4-2 shows examples of severa l relational expressions that compare the variables x and y. Table 4-2 Expression

~

m

Is x less than or equa l to y? Is x equa l to y? Is x not equal to y?

m

x "'''' y x != y

ad

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?

NOTE: All the relational operators have left-to-right associa tivity. Reca ll that

uh a

~ 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_,_,______________--"

M

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.

To Read Online & Download: WWW.ISSUU.COM/SHEIKHUHASSAN


Bismillah hiir Rehman nir Raheem-----------------------------Assalat o Wasalam o Alika Ya RasoolALLAH 165

i

4.1 Relational Operators

us uf

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: 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.

az

CD

::=

Yo

a

Ri

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 :

Bur the following is false:

ss

a >- 5

an

b >= a a >- c

a <=

C

b <= 10

Ha

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:

Bur the following is fa lse:

ad

b <= a

m

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 :

m

a 1"" b b !: c

uh a

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

M

Table 4 -3 shows other re lationa l exp ressions and their true or false values.

To Read Online & Download: WWW.ISSUU.COM/SHEIKHUHASSAN


Bismillah hiir Rehman nir Raheem-----------------------------Assalat o Wasalam o Alika Ya RasoolALLAH

(Assume X Is 10 and y is 7 .)

Expression )( <

us uf

Table 4 -3

Making Decisions

i

Chapter 4

166

Value

y

False, because x is nOt less than 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

Yo

x > y

What Is Truth?

az

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 -

Ri

gram ? How does a computer store true in memory? How does it Stor e fa lse?

an

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_,__~

ss

To illustra te t his more fully, look a t Program 4-1.

3 4 5 6

II This program displ ays the values of true and false states. 'include <iostream> using namespace std; int main ()

ad

1 2

Ha

Program 4-1

{

7

bool trueValue, falseVa l ue; = 10;

a

int x - 5, Y

m

9

10 11

trueValue - x < y; falseValue y == x;

=

m

12 13

cout « "True is " « trueVa lue « endl ; cout « ., False is ~ « falseValue « end l ; return 0 ;

14

uh a

15

16

)

Program Output

M

True is 1 False is 0

To Read Online & Download: WWW.ISSUU.COM/SHEIKHUHASSAN


Bismillah hiir Rehman nir Raheem-----------------------------Assalat o Wasalam o Alika Ya RasoolALLAH \67

i

4.1 Relational Operators

us uf

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

Yo

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.

=x

< y;

Ri

z

az

NOTE : Relational expressions have a higher precedence than the assignment operator. In the statement

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 x < y

cout « a

=x

>= Yi

cout « b

=Y

Displays 1 because x is greater tha n y.

(x > Y) i

a is assigned 1 because x is greater than or equal to y.

(x <=

ss

=

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

Ha

2

Outcome 2 is assigned 0 because x is not less than y.

an

Statement

When writing Statements such as these, it sometimes helps to enclose the rela tiona l expression in parentheses, such as:

ad

trueValue = (x < y); falseValue - (y m_ xli

m

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.

m

~ Checkpoint

M

uh a

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

To Read Online & Download: WWW.ISSUU.COM/SHEIKHUHASSAN


Bismillah hiir Rehman nir Raheem-----------------------------Assalat o Wasalam o Alika Ya RasoolALLAH 168

i

Chapter 4 Making Decisions

Indicate whether the following statements about relational expressions are correct or incorrect. A) x <=: y is the same as y > x .

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

Yo

4.3

B)

us uf

4.2

- - y is true?

z

! ..

Y a nd it is also true that x

is true?

What will the following program display?

#include <iostream> usi ng names pace std ; int main {

()

0, b "" 2, x = 4, Y

cout « cou t «

(a -- b) « endl; (a 1= y) « endl; (b <= X) « endl; (y > a) « end l ;

f

does that mean that

0;

Ha

ss

cout « return 0; }

Z

an

int a

cout «

!=

Ri

4.4

!= y

az

C) If it is true that x

The i f Statement

m

ad

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 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

uh a

The i f Statemem

m

-

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.

more than one path of execution, however. Many algorithms rcquire a program to exeCutc

M

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

To Read Online & Download: WWW.ISSUU.COM/SHEIKHUHASSAN


Bismillah hiir Rehman nir Raheem-----------------------------Assalat o Wasalam o Alika Ya RasoolALLAH 4.2 The i f Statement

i

169

us uf

Figure 4-1

II A program to calculate the area of a rectangle Step 1

Step3

Ii

I

Step 4 •• ,

int main() { double length, width, area ;

~ cout

SlepS

• Step 6 ,

i

c~n

«

"Ente r the lengt h of t he rect angle : " ;

» l ength j

az

'

cout « "Enter the width of the rectangle : cin » width ; ... area = length '* width ; area i, ; " «

area «

"j

eod 1

an

~:~~r~\ ;The

Ri

SteP. 2 ,

Yo

#include <iostream> using namespace std;

a

ss

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 <In accion being performed. If the answer to the question is no (or the condition IS fa lse), the program fl ow follows another path, which skips the action,

Ha

Figure 4-2

Is il cold outside?

Yes

Wear a coat. No

m

m

ad

1

uh a

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.

M

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.

To Read Online & Download: WWW.ISSUU.COM/SHEIKHUHASSAN


Bismillah hiir Rehman nir Raheem-----------------------------Assalat o Wasalam o Alika Ya RasoolALLAH 170

Making Decisions

i

Chapter 4

us uf

Figure 4-3

J Yes

Wear a coat.

Wear a hat.

az

No

Yo

Is it cold outside?

an

Ri

Wear gloves.

Ha

if (expression ) statement;

ss

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:

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

ad

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.

m

Program 4-2 1 2

II This program averages three test scores

3 4

'include <iomanip> usi ng names pace std ;

5 6

int main()

7

{

uh a

m

'include <iostream>

B 9

int scorel, score2, score3 ;

double average;

II To hold three test scores II To hold the average score

M

10

To Read Online & Download: WWW.ISSUU.COM/SHEIKHUHASSAN


Bismillah hiir Rehman nir Raheem-----------------------------Assalat o Wasalam o Alika Ya RasoolALLAH 1 71

17 18 19

20 2' 22

23

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

us uf

]5

16

Yo

13 14

II Get the three test scores . cout « "Enter 3 test scores and! will average them : " : cin » scorel » score2 » score):

II If the average is greater than 95, congratulate the user . if (average> 95) cout « "Congratulations ! That's a high score!\n"; return 0 ;

az

11 12

i

4.2 The i f Statement

"

Ri

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

an

Enter) test scores and I will average them: 100 100 100 [Enter] Your average is 100 . 0 Congratulations ! That · s a high score!

ss

Lines 2 '] and 22 ca use the congratulatory message to be primed:

Ha

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.

uh a

m

m

ad

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

M

Table 4-5 shows other examples of if staremenrs and their outcomes.

To Read Online & Download: WWW.ISSUU.COM/SHEIKHUHASSAN


Bismillah hiir Rehman nir Raheem-----------------------------Assalat o Wasalam o Alika Ya RasoolALLAH Making Decisions

i

Chapter 4

Table 4-5

us uf

172

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)

"Invalid number\n" ;

when value is greater than 32

Yo

cout «

Mu ltiplies payRate by 2 only w hen overTime is equa l to true

if (overTime

true) payRate *= 2;

az

Be Careful with Semicolons

Ri

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) ~ ~

an

stat e ment ;

Semicolon goes here.

Ha

ss

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

'include <iostream> 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;

uh a

5 6 7 8 9 10 11

ad

4

II This program demonstrates how a misplaced semicolon II prematurely terminate s an if statement.

m

2 3

m

1

12

13 14

Program Output

M

X is 0 and y is 10 x is greater tha n y

To Read Online & Download: WWW.ISSUU.COM/SHEIKHUHASSAN


Bismillah hiir Rehman nir Raheem-----------------------------Assalat o Wasalam o Alika Ya RasoolALLAH 173

us uf

Programming Style and the if Statement

i

4.2 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)

Yo

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:

Ri

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.

az

~ 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.____-'

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.

Ha

~

ss

an

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.

Comparing Floating-Point Numbers

m

m

ad

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

II This program demonstrates how floating - point II round-off errors can make equality operations unreliable . 'include <iostream> using namespace std;

uh a

1

2

3

4

M

5

(program continues)

To Read Online & Download: WWW.ISSUU.COM/SHEIKHUHASSAN


Bismillah hiir Rehman nir Raheem-----------------------------Assalat o Wasalam o Alika Ya RasoolALLAH Making Decisions

Program 4 -4 6 7

i

Chapter 4

(continued)

us uf

174

int ma i n() {

8

double a

9

double b

~

1.5;

1/ a is 1. 5 . 1/ b is 1.5 .

1. 5 ;

a += 0 . 0000000000000001; i f ( a == b)

11

12

cout«

13

14

"Both a and b are the same . \n";

else cout «

15

"a and b are not the same . \n" ;

return 0;

az

16 17 18

1/ Add a little to a .

Yo

10

}

Ri

Program Output

Bot h a and b are the same.

And Now Back to Truth

an

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.

Ha

ss

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-

m

m

ad

• •

uh a

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++:

M

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!";

To Read Online & Download: WWW.ISSUU.COM/SHEIKHUHASSAN


Bismillah hiir Rehman nir Raheem-----------------------------Assalat o Wasalam o Alika Ya RasoolALLAH 4.2 The i f Statement

175

i

a

if

us uf

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: (pow(a, b» cout « "It is True!" i

Yo

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.

az

Don't Confuse ;; With ;

i f (x :::: 2)

cout «

IICaution here! "It is True!" j

(==)

with the assignment

Ri

Earlier yOLl saw a warning nOt to confuse the equality operator operator ("'), as in the follow ing statemen t:

an

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

Ha

ss

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

, S

, 9 ]0

11 l~

i nt main () {

int scorel, score2, score3; double average;

14 15

II To hold three test scores II TO hold the average scor e

II Get the three test scores . cout « "En t er 3 test scores and I will average them : .. i cin » scorel » score2 » score3j

uh a

13

#include <iostream> #include <iomanip> us i ng namespace std ;

ad

4

m

3

II This program averages 3 test scores . The if statement II uses the = operator, but the == operator was intended.

m

2

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

M

17

"Your average is " «

averag .. «

end~;

20

(program continues)

To Read Online & Download: WWW.ISSUU.COM/SHEIKHUHASSAN


Bismillah hiir Rehman nir Raheem-----------------------------Assalat o Wasalam o Alika Ya RasoolALLAH

Program 4 -5

i

Making Decisions

(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;

Yo

)

us uf

Chapter 4

1 76

Program Output with Example Input Shown In Bold

az

Enter three test scores and I will average them: 809070 [Enter] Your average is 80.0 Congratulations! That's a perfect score !

Ri

Regardless of the average score, th is program will print the message congratulating the lIser on a perfeer score.

an

Flags

ss

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 .

Ha

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:

ad

bool hi ghscore = falsej

m

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.

m

if (average> 95) highscore = true;

uh a

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! ";

M

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 .

To Read Online & Download: WWW.ISSUU.COM/SHEIKHUHASSAN


Bismillah hiir Rehman nir Raheem-----------------------------Assalat o Wasalam o Alika Ya RasoolALLAH 4.4 Expanding the i f Statement

i

1 77

if (average> 95) highScore = 1;

II A nonzero value means true.

us uf

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.

Yo

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!" ;

az

You will find flag variables useful in many circumstances, and we will come back to them in furure chapters.

Ri

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.

an

Expanding the if Statement

Ha

ss

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:

ad

if (expression) {

m

)

m

statement; statement; II place as many statements here as necessary.

uh a

Program 4-6, another modificarion of the test-averaging program, demonstrates this type of if statement.

Program 4-6 1 2

3

M

4 5 6

II This program averages 3 test scores . II It demonstrates an if statement executing II a block of statements. Vinclude <iostream> 'include <iomanip> using names pace stdi

7

(program continues)

To Read Online & Download: WWW.ISSUU.COM/SHEIKHUHASSAN


Bismillah hiir Rehman nir Raheem-----------------------------Assalat o Wasalam o Alika Ya RasoolALLAH 178

Program 4-6

i

Chapter 4 Making Decisions

intmain ()

8 9

{

10

iot scorel, score2, scoreJ;

11

double average;

12 13

II To hold three test scores II To hold the average score

Yo

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;

20

CQut «

fixed «

cout «

"Your average is " «

showpoint «

setprecis i on(l) : average « endl;

az

18 19

/1 If the average is greater than 95, congratulate the user .

23 24

if (average> 95) {

27 28

)

29

retur n 0;

"You deserve a pat on the back!\n ";

)

ss

30

"Congratulations! \n" ; "That's a high score.\n";

an

cout « cout« cout «

Ri

21 22

25 26

us uf

(con tinued)

Program Output with Example Input Shown in Bold Your average is 100.0

Ha

Enter 3 test scores and I will average them : 100 100 100 [Enter] Congratulations! That's a hi~h score . You deserve a pat on the back!

ad

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

m

m

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.

uh a

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

M

~L-s_h_o_ul_d_b_e_i_nd_e_n_te_d_.________________________________________________-"

To Read Online & Download: WWW.ISSUU.COM/SHEIKHUHASSAN


Bismillah hiir Rehman nir Raheem-----------------------------Assalat o Wasalam o Alika Ya RasoolALLAH

4.4 Expanding the i f Statement

i

179

us uf

Don't forget the Braces!

Yo

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

, 7 8 9 10 11

az

4 5

II This program averages 3 test scores. The braces II were inadvertently left out of the if statement . 'include <iostreem> 'include <iomani p> using names pace std ;

int main () {

Ri

t 2 3

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

an

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

ss

17

Ha

18 19 20 21 22 23

24 25

26

27

ad

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;

}

m

Program Output with Example Input Shown In Bold Enter 3 test scores and I will average them: 8090 70 [Enter] Your average i6 80

uh am

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.

M

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~ :

To Read Online & Download: WWW.ISSUU.COM/SHEIKHUHASSAN


Bismillah hiir Rehman nir Raheem-----------------------------Assalat o Wasalam o Alika Ya RasoolALLAH

us uf

~

Making Decisions

i

Chapter 4

180

Checkpoint

TR UE or FALSE: Borh of [be followi ng if statements perform the same operation.

4.5

if (sales> 10000) commissionRate - 0 . 15;

if (calls rate 1.(

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 «

Ri

4.7

*=

az

4.6

Yo

if (sales> 10000) commissionRate = 0.15; TRUE or FALSE: Both of the fo llowing i f statements perform the same opera tion.

" hours qualifies for o v ertime . \n" ;

cout «

is e arning the maximum rate. \n" ;

> . 07)

ss

C) if (interestRate

an

B) balance = 1000; if (interestRate - . 07) cout « "This account

"This account earns a $10 bonus.\n";

bala nce += 10 . 0 ;

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.

Ha

4.8

Write an i f statement that assigns .20 to commission if sales is greater than or

equa l to 10000.00. 4.11

fers

to 50 if the flag variable max is

M

uh a

m

m

ad

Write an if statement that sets the variable set to true.

To Read Online & Download: WWW.ISSUU.COM/SHEIKHUHASSAN


Bismillah hiir Rehman nir Raheem-----------------------------Assalat o Wasalam o Alika Ya RasoolALLAH 4,5 The if/else Statement

us uf

i

181

The if/else Statement

Yo

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 )

Ri

The if/ .. l. "e Statement

az

statement Or block else statement or block

an

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

'include <iostrearn>

5

using nomespace stdi

6 7

int mai n ()

a { int number ;

9

ss

// 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 .

Ha

1

2 3 4

ad

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

m

m

)

uh a

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

M

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

To Read Online & Download: WWW.ISSUU.COM/SHEIKHUHASSAN


Bismillah hiir Rehman nir Raheem-----------------------------Assalat o Wasalam o Alika Ya RasoolALLAH 182

Chapter 4

Making Decisions

us uf

i

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.

Yo

Figure 4-6

I Indicate that the

Fa lse >-___ --,

az

True

, _ _ _ ~ nu mber % 2 == 0

Indicate thallhe number is odd.

Ri

number is even.

ss

an

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.

Ha

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.

ad

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.

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 <iostream>

m

1 2 3 4

m

Program 4-9

using namespace std;

9

int main(}

uh a

6 7 8

to {

11

double n uml , num2 , quotient;

M

t2

To Read Online & Download: WWW.ISSUU.COM/SHEIKHUHASSAN


Bismillah hiir Rehman nir Raheem-----------------------------Assalat o Wasalam o Alika Ya RasoolALLAH

4.5 The if/else Statement

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

{

25

2.

0)

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

}

28

else

29 30

{

Ri

27

az

24

quotient ~ nurol / num2: cout « "The quotient of " « numl « ~ divided by "; cout« num2 « " is " « quotient « ". \0 ";

31 32 33

1 return 0 ;

an

34 35

us uf

1/ Get the first number. cout « "Enter a number : "; cin » nurnl;

Yo

13

l4

I.

183

}

(When the user enters 0 for num2)

Ha

Enter a number: 10 [Enter] Enter another number : 0 [Enter]

ss

Program Output with Example Input Shown In Bold

Division by zero is not pos sible . Please run the program again and enter a number other than zero .

ad

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

~

m

divides numl by num2 and displays the resul t.

Checkpoint TRUE or FALSE: The following if/else statements cause the same output to display.

m

4.12

M

uh a

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";

To Read Online & Download: WWW.ISSUU.COM/SHEIKHUHASSAN


Bismillah hiir Rehman nir Raheem-----------------------------Assalat o Wasalam o Alika Ya RasoolALLAH Chapter 4

Making Oecisions

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.

us uf

i

4.13

Yo

184

iinc l ude <iostream>

using names pace std i int main()

az

{

double taxRate, saleAmount ; char residence;

an

Ri

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'

Ha

ss

saleAmount +; saleAmount * taxRatei cout « "The tota l is " « saleAmount; return 0; )

ad

Nested if Statements CONCEPT: To test more than one condition, an

if

statement can be nes ted in side

m

a nother if statement.

uh a

m

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

M

tests; we kno,"" th .. t the eUHorner docs not qualify (O( d lC s ped<l l inrcrcst nltc. If the

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.

To Read Online & Download: WWW.ISSUU.COM/SHEIKHUHASSAN


Bismillah hiir Rehman nir Raheem-----------------------------Assalat o Wasalam o Alika Ya RasoolALLAH

4.6 Nested i f Statements

False

Yo

us uf

i

185

True limp/eyed = 'Y'

az

Display ·You must be employed 10 qualify." False

Ri

r()Ccn'GraCl _ 'Y'

Display ' You quality tor the special interest rate ."

Ha

ss

an

Display ·You must have gradualed from ~lege in the past two years to qualify."

True

1 II This program demonstrates the nested if statement. 'include <iostream> using names pace std;

ad

2 3 4

int main()

6

{

9

10 11 13 14

M

15 16 17 18 19

II currently employed, y or II Recent graduate, Y or N

N

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";

uh a

12

char employed, recentGrad ;

m

7 8

m

5

cout «

H

;

"Are you employed? " ;

cin »

employed; cout « "Have you graduated from college .'; cout « "in the past t wo years? ,.; cin » recentGrad: (program continuel)

To Read Online & Download: WWW.ISSUU.COM/SHEIKHUHASSAN


Bismillah hiir Rehman nir Raheem-----------------------------Assalat o Wasalam o Alika Ya RasoolALLAH Making Dec.isions

Program 4 · 10

us uf

(confinued)

II Determine the user's loan qualifications. i f (employed -- 'Y' )

20 21 22

{

i f (recentGrad == 'Y' ) IINested i f {

24

cout « COllt «

25 26 27 28

)

29

r eturn 0,

.

"You qualify for the special " , " interest rate.\n";

Yo

23

)

)

az

30

i

Chapter 4

186

Program Output with Example Input Shown In Bold

Answer the following questions

Ri

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.

Answer the following queetions

with e ith er Y for Yes or N for No. Are you employed? Y [Enter]

an

Pro gram Output with Diffe rent Example Input Shown In Bo ld

ss

Have you graduated from college in the past two years? N [Enter]

Ha

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~

Program

3

uh a

4 5 6

II This program demonstrates the nested if statement . 'include <iostream> using namespace std;

m

1

2

4~ 11

m

ad

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.

7

,

B

M

10 11 12

13 1<

15 16

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 ";

To Read Online & Download: WWW.ISSUU.COM/SHEIKHUHASSAN


Bismillah hiir Rehman nir Raheem-----------------------------Assalat o Wasalam o Alika Ya RasoolALLAH

4.6 Nested i f Statement5

i

cout «

cin »

"in the past two years? ";

us uf

17 18

recentGrad;

/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

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

)

"You must be employed to qualify . \n" ;

an

cout «

return OJ

39

)

ss

.,

Ri

31

az

(

30

Yo

19

20 21

187

Program Output with Example Input Shown In Bold Answer the following questions

Ha

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

m

ad

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 .

m

Program Output with Different Example Input Shown In Bold

M

uh a

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.

To Read Online & Download: WWW.ISSUU.COM/SHEIKHUHASSAN


Bismillah hiir Rehman nir Raheem-----------------------------Assalat o Wasalam o Alika Ya RasoolALLAH Chapter 4

Making Decisions

us uf

Programming Style and Nested Decision Structures

i

188

Yo

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' ) {

==

' 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!

az

it (recentGrad

) {

cout « cout « cout «

"Yo u must

Ri

else /I Not a rece nt grad, but employed

.

have graduated from " ,

"college in the pa st two\ n" i "years to qualify . \n" i

an

) )

else II Not employed {

"You must be employed to qualify.\n" i

ss

cout « )

Ha

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') {

ad

1f (recentGrad "'''' ' Y') II Nested i f

r

ThiS 1f and else go together

m

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";

M

uh a

m

This

(

To Read Online & Download: WWW.ISSUU.COM/SHEIKHUHASSAN


Bismillah hiir Rehman nir Raheem-----------------------------Assalat o Wasalam o Alika Ya RasoolALLAH 189

i

4.6 Nested i f Statements

us uf

Testing a Series of Conditions

In the Spotlight: Multiple Nested Decision St ructures

az

Yo

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.

Ri

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: G rade

A

80-89

B

70-79 60-69 Below 60

C

an

Test Score 90 and above

D

ss

F

Ha

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:

ad

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.

M

uh a

m

m

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.

To Read Online & Download: WWW.ISSUU.COM/SHEIKHUHASSAN


Bismillah hiir Rehman nir Raheem-----------------------------Assalat o Wasalam o Alika Ya RasoolALLAH Chapter 4

Making Decisions

False

i

figure 4-9 Nested decision structure to determine a grade

True

Yo

score < 60

us uf

190

Display "Your

Fal.se

True

score

False

True

score

<80 score

Ri

Display ·Your

False

F.~

az

<70

grade is

True

grade is C.u

< 90

Ha

ss

an

Display ~Your grade Is A.--

Program 4-12

ad

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 <ios'tream>

m

4' using names pace std; 5 6 int main() 7 { ~ int testScore ; II To hold a numeric 10

If Get cout « cout«

~he

cin »

te~t

score

numeric teat score.

"Enter your numeric test score and I will\n "; "t"ell you the lett er grad.a you earnedl "I testScarei

uh a

11 17 13

m

9

,14

I)eterm~ne

the letter grade "

1>

I f

16

if (testScore < 60)

17

(

M

,.

19 20

cout «

"Your grade io F. \ n";

) el.se

To Read Online & Download: WWW.ISSUU.COM/SHEIKHUHASSAN


Bismillah hiir Rehman nir Raheem-----------------------------Assalat o Wasalam o Alika Ya RasoolALLAH 191

21

i

4.7 The if/else if Statement

i f (testScore < 70 ) {

cout «

2. 25 26

else

27

{

"Your grade is o. \n-";

}

2.

cout «

Yo

i f (testScore < ~o ) {

2' 30 31 32 33 3.

"Your" grade is c . \n";

}

else i f (testScore < '0)

}

~.\n";

cout «

"Y.our grade is

cout «

"Your grade is A. \n ";

else

3'

{

41

)

40

42 43 44

an

}

}

}

45

ss

return 0,

'6

.'

Ri

{

36 3.7 3.

az

{

35

47

us uf

{

22 23

}

Ha

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.

ad

Program Output with Different Example Input Shown In Bold

m

m

Enter your numeric test score and I will tell you the letter grade you earned: 84 [Enter] Your grade is B.

uh a

The if/else if Statement

M

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:

To Read Online & Download: WWW.ISSUU.COM/SHEIKHUHASSAN


Bismillah hiir Rehman nir Raheem-----------------------------Assalat o Wasalam o Alika Ya RasoolALLAH 192

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

)

Yo

else i f lexpressioD_2)

az

{

statemellt statement etc.

lnsert as malty else i t clauses as necessary

}

statement

statement

etc.

These stalemellls arc executed If

Ri

else {

us uf

i

Chapter 4 Making Decisions

nOlle of the expressions above are true.

an

)

Ha

ss

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.

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 .

m

()

ad

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.

m

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.

uh a

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 <iostream>

4 using namespace std;

M

5 6 int main() 7 ( 8 int testScore i

II To hold a numeric test score

To Read Online & Download: WWW.ISSUU.COM/SHEIKHUHASSAN


Bismillah hiir Rehman nir Raheem-----------------------------Assalat o Wasalam o Alika Ya RasoolALLAH 193

i

4.7 The if! else if Statement

11

12

13

us uf

9 10

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

21

22

23 24 25

Yo

19 20

az

17

18

// 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

Ri

IS 16

26

27

return 0;

28

an

Program Output with Example Input Shown in Bold

ss

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

Ha

Enter your numeric test score and I will tell you the letter grade you earned : 84 [Enter] Your grade i s a .

(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

m

m

..

ad

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:

uh a

else

cout «

"Your grade is A. \n" ;

If testScore is less [han 60, [he message "Your grade is

M

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";

;

To Read Online & Download: WWW.ISSUU.COM/SHEIKHUHASSAN


Bismillah hiir Rehman nir Raheem-----------------------------Assalat o Wasalam o Alika Ya RasoolALLAH 194

Chapter 4 Making Decisions

i

e l se i f (testScore < 70) cout « "Your grade is D. \n";

us uf

-+

else if (testScore < SO) cout « "Your grade is C.\n"i else i f (testScore < 90) cout « "Your grade is B. \n ",-

T he first

"Your grade is A. \n" ;

Yo

else cout «

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

az

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.

Ri

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

ss

an

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.

Ha

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 <iostream> 4 using names pace std;

ad

5

6 int main()

11 12 13 14

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: 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)

uh a

15 16

int testScore;

m

9 10

m

7 { 8

17 18

19

20

M

21

22

23

couto « "Your grade is C. \n" ; else if (teatScora < 90) cout « .. '{our grade is B. \n " ;

To Read Online & Download: WWW.ISSUU.COM/SHEIKHUHASSAN


Bismillah hiir Rehman nir Raheem-----------------------------Assalat o Wasalam o Alika Ya RasoolALLAH

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

Yo

return 0 ;

29 30

us uf

i

195

az

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 .

Ri

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:

an

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<lJ scro l!ing. Also, long statements tend to "wrap around" when primed on paper, making the code even more difficult to read .

ss

• •

Ha

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.

..... Menus

ad

4.8

m

m

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.

uh a

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.

M

3. Change a name in the \ist. 4. Print the list.

5. Qu it the program.

To Read Online & Download: WWW.ISSUU.COM/SHEIKHUHASSAN


Bismillah hiir Rehman nir Raheem-----------------------------Assalat o Wasalam o Alika Ya RasoolALLAH Chapter 4

Making Decisions

i

196

us uf

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.

Yo

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.

az

Program 4-15

// 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 <iostream> 5 'include <iomanip> 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

15

16 17

lB 19

for membersh i p rates ADULT -

4 0 . 0;

Ha

/1 Constan t s const doub le canst double canst double

14

ss

an

Ri

1 2 3 4

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;

ad

20 21 22 23

24

m

25

26 27

// Set the numeric output formatting. cout « fixed « showpoint « setPrec i s ion(2);

m

28 29 30

II Respond to the user's menu sel ection .

i~

33

{

uh a

31

32

3.

M 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

==

charges «

endl;

2)

(

To Read Online & Download: WWW.ISSUU.COM/SHEIKHUHASSAN


Bismillah hiir Rehman nir Raheem-----------------------------Assalat o Wasalam o Alika Ya RasoolALLAH 197

cout « "For how many months? "; cin » months;

41 42

43

charges

= months

44

cout «

"The total charges are $" «

* CHILD; charges «

endl;

charges «

endl;

4S

else if (choice

"

\

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)

az

48

==

(

cout«

55 56 57

"Program ending . \ n ";

)

Ri

else

"

Yo

46

{

59

cout «

"The valid choices are 1 through 4. Run the\n ,. ;

60

cout «

"program again and select one of those.\n" ;

61 62

return 0;

an

63

us uf

i

4.8 Menus

}

Health Club Membership Menu Standard Adult Membership Child Membe rship Senior Citizen Membership Quit the Program

Enter your choice : 3 [Enter]

Ha

1. 2. 3. 4.

ss

Program Output with Example Input Shown In Bold

ad

For how many months? 6 [Enter] The total charges are $180.00

m

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.

uh a

m

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

M

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

To Read Online & Download: WWW.ISSUU.COM/SHEIKHUHASSAN


Bismillah hiir Rehman nir Raheem-----------------------------Assalat o Wasalam o Alika Ya RasoolALLAH Making Decisions

4.17

i

Chapter 4

What will the following program display?

us uf

198

linclude <iostrearn> using namespace std; int main() (

funny

=

2

15;

Yo

int funny = 7 , serious serious \ 2 ;

i f (funny ! =

1)

{

funny = 0; serious'" 0 ;

az

}

else if (funny

2)

(

funny'" 10; = 10;

Ri

serious )

else {

funny

1;

an

serious" 1; }

cout «

f unny «

"" «

}

endl;

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.

Ha

4.18

serious «

ss

return 0;

fi nc l ud e <iostre am>

using names pace std ; {

ad

i n t main()

int nurnBooks, numcoupons;

cout «

"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

«

}

M

uh a

m

m

cin »

To Read Online & Download: WWW.ISSUU.COM/SHEIKHUHASSAN


Bismillah hiir Rehman nir Raheem-----------------------------Assalat o Wasalam o Alika Ya RasoolALLAH

199

i

4.9 logical Operators

us uf

If fhe customer purchases rhis many books

Th is many coupons arc given.

1 2

Yo

3 4

5

az

10

Ri

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

Logical Operators

4.9

-t

an

CONCEPT: Logical operators con nect two or morc relational expressions imo ODe or reverse the logic of an expression.

Table 4-6

Effect

AND

Connects two expressions into one. Borh expressions rhe overall expression to be true.

OR

m

NOT

&&

be tfue for

The ! operator reverses the "truth " of an expression. It makes a true expression false, and a false expression rrue .

Operator

uh a

The

mUSt

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.

m

/I

Meaning

ad

Operaror

Ha

ss

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 .

M

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.

To Read Online & Download: WWW.ISSUU.COM/SHEIKHUHASSAN


Bismillah hiir Rehman nir Raheem-----------------------------Assalat o Wasalam o Alika Ya RasoolALLAH Chapter 4

Making Decisions

us uf

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.

i

200

temperature > 0 && < 100

Yo

The expression must be rewritten as

temperature > 0 && temperature < 1 00

&&

az

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 .

Ri

Table 4-7 Expression true

&&

Value of Expression

false

fa ls e

false && true

to)

false (0) false (0) true (1)

an

false && false true && t r ue

ss

As the tab le shows, both sub-expressions must be true for the true value.

&&

ope rator to ret urn a

Ha

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,

Program 4-16

3

II This program demonstrates the finclude <iostre am> using names p ace std ;

uh a

4

5 6

7 8

,

M

10 J.1 12 13

&&

logical operator.

m

1 2

m

ad

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.

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" ;

To Read Online & Download: WWW.ISSUU.COM/SHEIKHUHASSAN


Bismillah hiir Rehman nir Raheem-----------------------------Assalat o Wasalam o Alika Ya RasoolALLAH 201

I'

20

/1 Determine the user ' s loan qualifications.

21

if (employed

22

{

cout « cout «

23 2. 25 26 27 28 2. 30

'Y' && recentGrad

==

Yo

15 16 17 18

us uf

cout « "Are you employed? H; cin » employed; cout « "Have you graduated from college "; cout « "in the past two years? "; cin » recentGracl ;

14

'Y')

"You qualify for the special " ; "interest rate . \n" ;

)

az

else {

cout «

"You must be employed and have\n" ; "graduated from col l ege in the\n" i "past two years to qualify.\ n";

Ri

cout « cout «

31

32 33

i

4.9 logical Operators

)

return 0 ; )

Are you employed? Y [Enter]

ss

with either Y for Yes or N for No .

an

Program Output with Example Input Shown In Bold Answer the following questions

Have you graduated from college in the past two years? N [Enter]

You must be employed and have

Ha

graduated from college in the past two years to qualify.

m

ad

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 .

m

Program Output with Example Input Shown In Bold

M

uh a

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.

To Read Online & Download: WWW.ISSUU.COM/SHEIKHUHASSAN


Bismillah hiir Rehman nir Raheem-----------------------------Assalat o Wasalam o Alika Ya RasoolALLAH

V

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

us uf

~

Making Decisions

i

Chapter 4

20 2

Operator

if (temperature < 20

cout ÂŤ

II

temperature> 100)

Yo

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;

"The temper ature is in the danger zone. ";

Ri

az

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.

temperature <

a II

> 100

ss

The expression must be rewn cten as

an

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 .

Ha

temp erature < 0 II temperature> 100

Table 4-8 shows a truth table for the Table 4-8

I I operator.

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)

m

ad

Expression

m

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.

uh a

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

M

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.

To Read Online & Download: WWW.ISSUU.COM/SHEIKHUHASSAN


Bismillah hiir Rehman nir Raheem-----------------------------Assalat o Wasalam o Alika Ya RasoolALLAH 20 3

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

int main() { double income; int years ;

Yo

9 10 11 1_

the job is more than 5 years . 'include <iostream> using namespace std ; lion

II Annual income II Years at t he current job

14 15 16

II Get the annual income cout « MWhat is your annual income? "; cin » income;

17

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 ;

an

19 19 21 21 22

,',

29

"3031

ss

25 26

Determine the user's loan qualifications. if (income >- 35000 II years> 5) cout« Myou qualify . \n" : else II

cout « cout «

Ha

2~

Ri

1'

az

~

6

us uf

i

4.9 Logical Operators

"You must earn at least $35,000 or have\n "; ., bee n employed for more than 5 years . \n" ;

return 0;

ad

32

m

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 .

uh am

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

M

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.

To Read Online & Download: WWW.ISSUU.COM/SHEIKHUHASSAN


Bismillah hiir Rehman nir Raheem-----------------------------Assalat o Wasalam o Alika Ya RasoolALLAH Making Decisions

i

Chapter 4

The I Operator

us uf

204

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:

Yo

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 -

~

Table 4-9 shows a ([urh tab le fo r the! operator.

Ri

Table 4-9

az

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?"

Expression

Value of the Expression

!true

false

(0)

! false

true

(1)

ss

an

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

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 <iostream> using names pace std;

Ha

1 2

12

13 14 15

II Annual income II Years at the current job

/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;

uh a

16 17

m

11

i nt main ( ) { double income; int years;

m

9 10

ad

7 8

18 19

20 21

M

22

II Determine the user's loan qual i f i cations.

To Read Online & Download: WWW.ISSUU.COM/SHEIKHUHASSAN


Bismillah hiir Rehman nir Raheem-----------------------------Assalat o Wasalam o Alika Ya RasoolALLAH 205

23 24 25

i f ( !( income >= 35000

II years> 5»

{

cout « cout «

26 )

else cout« return 0 ;

30 31

"You qualif y. \n";

)

az

The outpU t of Program 4-18 is the same as Program 4-17.

Yo

27 28 29

"You must earn at least $35,000 or have\n"; "been employed for more than 5 years . \n";

us uf

i

4.9 Logical Operators

Precedence and Associativity of Logical Operators

Ri

Table 4-10 shows the precedence of C++'s logical operators, from highest to lowest.

Table 4 -10 Logical Operators in Order of Precedence

an

&&

II

! (x !x

;> 2) ;> 2

Ha

ss

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:

m

ad

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!

m

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.

uh a

(a ;> b) && (x < y) == y) 11 (b > a)

(x

is the same as is the same as

a ;> b && x < y x==yllb;>a

M

The logical operaro rs have left-ro-rig hr associarivity. In rhe follOWing expression, a < b is evaluated before y """ z. a<blly==z

To Read Online & Download: WWW.ISSUU.COM/SHEIKHUHASSAN


Bismillah hiir Rehman nir Raheem-----------------------------Assalat o Wasalam o Alika Ya RasoolALLAH Chapter 4

Making Decisions

a < b

1I

y

==

z && m > j

The expression is equiva lent ro

II

((y==z)

&&

operator has

(rn>j))

Yo

(a<b)

&&

us uf

In the followlllg expression, y == z is evaluated first, however, because the higher precedence than II .

i

206

Checking Numeric Ranges with Logical Operators

az

CO NC EPT: Logical operators arc effective for determining whether a number is in or

out of a range.

Ri

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: (x >=

20 &&

cout «

<= 40)

K

x «

" is in the acceptab l e range . \n";

an

if

ss

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.

if (x < 20

cout «

II

Ha

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: x > 40)

x «

" is outside the acceptable range . \n";

ad

It's important nor to get the logIC of these logical operators confused. For example, the following i f statement would never test true:

m

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.

uh a

m

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

M

4.20

4.21

What is the disadvantage of llsing the && logical operator In Program 4-16 instead

of the nested

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.

To Read Online & Download: WWW.ISSUU.COM/SHEIKHUHASSAN


Bismillah hiir Rehman nir Raheem-----------------------------Assalat o Wasalam o Alika Ya RasoolALLAH

Logical Exp1:cssion

true true

&& &&

Result (true or fal se)

false true

false && true fa l se && false

II

true

Z07

on Software Engi neering: Validating User Input

false

Yo

true 11 true false II true fa l se II fa l se

i

Focu~

us uf

4.11

!true !false

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

Ri

a == 4 6 <~ c

az

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

an

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.

Ha

ss

4.24

Focus on Software Engineering: Validating User Input CONCEPT: As long as the user of a program enters bad input, the program will

ad

produce bad oUtpUI. Programs should be written to filter out bad input.

m

m

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:

uh a

M

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

To Read Online & Download: WWW.ISSUU.COM/SHEIKHUHASSAN


Bismillah hiir Rehman nir Raheem-----------------------------Assalat o Wasalam o Alika Ya RasoolALLAH 208

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 <iostream> 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 ;

"Enter your numeric test score and I will\n";

az

13

the numeric test score .

14

if (tes tScore < 0

16 l' 18 19

{

}

22

e lse

23

{

32

33

3. 3' 3. 37

3!! }

ss

Ha

30 31

re turn 0,

ad

28

29

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";

m

27

"in the range of 0 to 100 .\n";

an

cout «

2

,.

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

25

II

Ri

15

2.

Yo

,

us uf

i

Chapter 4 Making Decisions

m

Program Output with Example Input Shown in Bold

uh a

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

M

Enter your test score and I will tell you the letter grade you earned : 81 [Enter] Your grade is B

To Read Online & Download: WWW.ISSUU.COM/SHEIKHUHASSAN


Bismillah hiir Rehman nir Raheem-----------------------------Assalat o Wasalam o Alika Ya RasoolALLAH 209

us uf

i

4.12 M ore About Variable Definitions and Sc.ope

More About Variable Definitions and Scope to

rhe block in which it;s defined .

Yo

CONCEPT; The scope of a varjable is lim ired

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.

2 3

II This prog ram demonstrates late variable definition iinclude <iostream> using namespace std ;

4

int ma in() { 1/ Get the annua l income . cout « ·'What i s your annual income? ";

8

9

double income: cin »

10 11 12

income;

ss

/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

Ha

14 15 16 17

{

23 24 25 26

cout « cout «

)

return

Oi

m

}

"You must ear n at least $35 ,000 or have\n"; "been employed for more than 5 years . \n";

m

"

ad

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

27

II Variable de fi nition

an

5 6 7

Ri

1

az

Program 4 -20

uh a

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.

M

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.

To Read Online & Download: WWW.ISSUU.COM/SHEIKHUHASSAN


Bismillah hiir Rehman nir Raheem-----------------------------Assalat o Wasalam o Alika Ya RasoolALLAH 210

i

Chapter 4 Makjng Decisions

ProgrAm

4~ 21

'include <iostream>

3

using namespace std;

4 5 6

int main()

variable defined in

{

10

cin »

11 12

if (income >= 35000)

az

II Get the annual income. cout « ~What is your annual income? "; double income; /Ivariable definition

13 14

b~ock.

income;

Ri

7 S 9

(

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. "

18 19 20

(

26

)

27 28

) else

29

(

30

cout «

31 32 33

cout «

'''tou must earn at least $35,000 to\n"i "qualify. \n";

m

m

return 0: )

"you must have been employed tor\n··; "more than S years to qualify.\n~i

ad

cout « cout «

25

Ha

22 23 24

ss

if (years> S) cout « ftyou qualify. \n" ; else

21

an

«

17

34

an inner

Yo

1 II This program demonstrates a 2

us uf

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.

uh a

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.

M

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.

To Read Online & Download: WWW.ISSUU.COM/SHEIKHUHASSAN


Bismillah hiir Rehman nir Raheem-----------------------------Assalat o Wasalam o Alika Ya RasoolALLAH 211

i

4.12 More About Variable Definitions and Scope

us uf

Variables with the Same Name

Program 4-22 // This program uses two variables with the name number . 'include <iostream> using names pace stdi

1

2 3

,

Ri

az

i nt main( 1 ( /1 Define a variable named number. int number ;

5 6 7 S 9 10 11 12

Yo

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.

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;

"

15 16 17 lB

ss

an

13

)

cout « "'lour first number was " « return 0;

Ha

19

20 21 22

)

number «

endl;

m

ad

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

uh a

m

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.

to conmse one variable wi.th another.

M

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 Read Online & Download: WWW.ISSUU.COM/SHEIKHUHASSAN


Bismillah hiir Rehman nir Raheem-----------------------------Assalat o Wasalam o Alika Ya RasoolALLAH Chapter 4

Making Decisions

i

212

4 .25

us uf

Checkpoint

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 <iostream>

Yo

using namespace std ; lnt main() {

lnt first , second , result ;

cout «

" Now enter a positive integer ; " ;

=

first * second ; first « " times " «

«

r es ult « return 0 ;

" is "

Find and fix the errors in the fo llowing program:

ss

4.26

second «

endl ;

an

ff

Ri

ci n » second ; II II Write input val i d a t i on code

result cout «

az

cout « "Enter a negative integer : " ; cin » first ;

int main() {

cout «

Ha

'include <i ostream> using names pace std;

"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 ;

m

ad

«

m

}

M

uh a

4.27

What will the following program display if the lIser enters 40 for testl and 30 for test2? 'include <iostream> using namespace std j

int main (1 {

cout « "Enter your first test score , ". int testl ; ci n >::> test! ;

To Read Online & Download: WWW.ISSUU.COM/SHEIKHUHASSAN


Bismillah hiir Rehman nir Raheem-----------------------------Assalat o Wasalam o Alika Ya RasoolALLAH

213

"j

us uf

cout « "Enter your second test score: int test2; cin » test2 ; int sum = testl + test2: if (sum > 50)

i

4.1 3 Comparing Strings

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

az

)

Yo

(

Ri

Comparing Strings

C~strings.

an

CONCEPT: You mu st use the strcmp library function to compare

7 8 9

10

intmain() ( const int SIZE = 40; char firs tString [SIZE J, secondString[SIZEl:

ad

4 5 6

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 <io stream> using names p ace std;

m

1

2 3

4~23

Ha

Program

ss

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.

11

12

II Get two strings . cout « "Enter a string : M; ci n. getline(firstString, SIZE); cout « "Enter another string: " ; cin.getline (secondString, SIZE):

m

13

14

15

uh a

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

M

19 20 21 22 23

24

)

(program output continues)

To Read Online & Download: WWW.ISSUU.COM/SHEIKHUHASSAN


Bismillah hiir Rehman nir Raheem-----------------------------Assalat o Wasalam o Alika Ya RasoolALLAH Making Decisions

i

Chapter 4

214

us uf

(continued)

Yo

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 if (firstString

az

firstStri ng and secondString :

-= secondString)

Ri

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

ss

strcmp(stringl, string2) ;

an

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:

Ha

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 :

â&#x20AC;˘

If the two stnngs are identica l, strcmp retums O.

â&#x20AC;˘

If string! < string2, s t rcmp returns a nega tive number. If stringl > string2, strcmp returns a positive number.

â&#x20AC;˘

m

m

ad

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:

M

uh a

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.

To Read Online & Download: WWW.ISSUU.COM/SHEIKHUHASSAN


Bismillah hiir Rehman nir Raheem-----------------------------Assalat o Wasalam o Alika Ya RasoolALLAH 215

Program 4-24 1 2

II This program correctly tests two C-strings for equality II with the strcmp function.

3

jinclude <iostream>

4 5

tinc lude <cstri ng > using names pace std:

II Get two strings cout « "Enter a string: "; cin . getline(firstString, SIZE): cout « "Enter another string: "; cin . getline(secondString, SIZE):

az

int main() { canst int SIZE ~ 40; char firstStringlSIZEI, secondString(SIZE]:

Ri

7 8 9 10 11 12 13 14 15 16

Yo

6

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;

an

17 18

}

ss

24

us uf

i

4.13 Comparing Strings

Ha

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 .

m

ad

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.

uh a

m

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

M

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 <iostream> 'include <iomanip> tinclude <cstring> using namespace std; (program continues)

To Read Online & Download: WWW.ISSUU.COM/SHEIKHUHASSAN


Bismillah hiir Rehman nir Raheem-----------------------------Assalat o Wasalam o Alika Ya RasoolALLAH Making Decisions

(continued)

Program 4-25 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

« « «

22

cin »

az

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 . partNum;

Ri

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 .

" is not a valid part number . \ n";

Ha

partNum «

ss

an

if (strcmp(partNum, "S147-29A") ""', 0) cout « "The price is $" « APRICE «

34 35

Yo

8 9 10

i

Chapter 4

us uf

216

}

m

ad

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

m

Using ! with strcmp

uh a

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

M

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)

To Read Online & Download: WWW.ISSUU.COM/SHEIKHUHASSAN


Bismillah hiir Rehman nir Raheem-----------------------------Assalat o Wasalam o Alika Ya RasoolALLAH 4.13 Comparing Strings

i

2 17

us uf

Sorting Strings

Yo

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.

6 7

8 9 10

iinclude <iostream> 'include <cstring> using namespace std;

Ri

5

II This program uses the return value of strcmp to alphabetically II sort two strings entered by the user.

int main{) { const int SIZE = 30; char namel ( SIZE], name2!SIZEj i

11

II Ge t the first name . cout « "Enter a name (last name firs t) : "; cin . getline(namel, SIZE);

ss

12 13

14

Ha

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

ad

21 22

25

26 27 28

uh a

}

m

m

23 24

"

an

1

2 3 4

az

Program 4 -26

Program Output with Example Input Shown In Bold Enter a name (last name first): Smith, Richard [EnterJ

M

Enter another name : Jones, John [Enter1 Here a re the names sorted alphabetically: Jones, John Smi th, Richard

To Read Online & Download: WWW.ISSUU.COM/SHEIKHUHASSAN


Bismillah hiir Rehman nir Raheem-----------------------------Assalat o Wasalam o Alika Ya RasoolALLAH

~

Making Decisions

i

Chapter 4

Checkpoint 4.28

us uf

218

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" ) ;

DJ 4.29

Yo

C) strcmp ( "123", "ABC"); strcmp( "Sammy", "sally" 1;

Complete the if stateme ms in the fo llowing program skeleton.

az

'include <iostream> 'include <cst r ing>

using names pace std ; {

const int SIZE -

20;

char iceC ream[SIZE); cout « cout «

Ri

lnt main()

"What flavor of ice cream do you like best? " ;

an

"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";

ss

II II Finish the following if/else if statement

m

}

ad

Ha

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:

m

The Conditional Operator

M

uh a

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;

To Read Online & Download: WWW.ISSUU.COM/SHEIKHUHASSAN


Bismillah hiir Rehman nir Raheem-----------------------------Assalat o Wasalam o Alika Ya RasoolALLAH

219

x < 0 ? Y -

10 : z - 20;

us uf

Here is an example of a statement using the conditional operator:

i

4.14 The Conditional Operator

x < 0 ~

y =

?

10

z

=

20 ;

Yo

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:

NOTE : Since it takes three operands. the conditional operator is considered a

az

~L-t_e_rn_a_ry __o_p_e_ra_t_o_,______________________________________________________-"

Ri

The conditional expression above performs the same operation as the fo llowing if/else statement: if(x<O)

= 10;

y

else

20;

an

Z ..

ss

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.

Ha

figure 4-10

3rd Expression: Executes if the 1st

1st Expression: Expression to

expression is false.

be tested.

ad

"'-.x

< 0

10

/

z - 20;

2nd Expression : Executes if the 1st

m m

Y =

?

expression is true.

If it helps, you ca n put parentheses around the sub-expressions, as in the following:

uh a

(x < 0) ? (y

= 10)

: (z

= 20);

M

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 ;

To Read Online & Download: WWW.ISSUU.COM/SHEIKHUHASSAN


Bismillah hiir Rehman nir Raheem-----------------------------Assalat o Wasalam o Alika Ya RasoolALLAH

Chapter 4

Making Decisions

i

220

us uf

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;

Yo

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.

,

Ri

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 <iostream> 'include <iomanip> using namespace std; intrnain() (

10 11

const double PAY RATE = 50 . 0 ; double hours, charges;

ss

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:

Ha

14 15 16 17

18

19 )

ad

20

an

1 2 3 4 5

az

Program 4-27

Program Output with Example Input Shown in Bold How many hours were worked? 10 [Enter]

m

The charges are $500.00

Program Output with Eumple Input Shown In Bold

m

How many hours were worked? 2 [Enter] The charges are $250 . 00

uh a

Here is the statement in line 15, with the conditiona l expression:

M

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.");

To Read Online & Download: WWW.ISSUU.COM/SHEIKHUHASSAN


Bismillah hiir Rehman nir Raheem-----------------------------Assalat o Wasalam o Alika Ya RasoolALLAH

4.14 The Conditional Operator

i

221

us uf

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

()

is: Pass.

"

.,

Yo

cout « "Your grade

is ; F o i l . "i

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

4.30

az

Checkpoint

Rewrite the fo llowing if/else statements as conditional expressions:

Ri

A) if Ix > YI z ::: 1 i

e lse z

= 20i

B) i f (temp> 45)

= base

else

* 10 i

an

population

popu l ation::: base * 2; if (hours ~ 40)

ss

C)

wages *: 1.5;

Ha

else

wo<;es *- 1;

D ) if (result >= 0) cout «

"The res ul t is positive\n";

cout «

"The result is negative. \ n":

else

ad

The followi ng statements use cond itional expressions. Rewrite eac h wi rh an if I

4 .3 1

else statement. j

=

k > 90 ? 57 : 12 ;

factor = x >= 10 ? Y

m

A)

B)

*

22 : y

*

35;

C) total += count == 1 ? s ales : count * sales;

m

D ) cout« ((nurn % 2):,:: O)? "Even\n" : "Odd \n "):

What

will the fo llowing program display?

'include <iostrearn> using name s pace std ;

int main( )

I

M

uh a

4.3 2

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; }

To Read Online & Download: WWW.ISSUU.COM/SHEIKHUHASSAN


Bismillah hiir Rehman nir Raheem-----------------------------Assalat o Wasalam o Alika Ya RasoolALLAH 222

Making Decisions

The switch Statement

eXpreSS-lOn

Yo

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.

us uf

i

Chapter 4

az

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

switch (IntegerExpression) {

an

case ConstantExpression : II place one o r more II statements here

Ri

the format of the switch statement:

ss

case ConstantExpression : II place one or more II statements here

Ha

II case statements may be repeated as many II times as necessary

ad

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

m

â&#x20AC;˘ â&#x20AC;˘

M

uh a

m

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:

CI)

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. WARN I N G I The expression of each case statement in the block must be unique.

To Read Online & Download: WWW.ISSUU.COM/SHEIKHUHASSAN


Bismillah hiir Rehman nir Raheem-----------------------------Assalat o Wasalam o Alika Ya RasoolALLAH

223

i

4.15 The switch Statement

us uf

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

Program 4-28 shows how a simple switch statemenr works,

Program 4-28

3 4 5

' i nclude <iostream> using namespace std ;

6 7

i ntmain()

az

II The swi tch statement in this program tells the user something II he or she alre ady knows : the data just entered!

Ri

1

2

Yo

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.

(

8

char choice; cout « "Enter A, B, or C : ": cin » choice: switch (Choice)

10 11

12

cout « break; case 'B' ; cout « break; case 'c' : cout « break; default : cout « case

IS 16 17

"

19

20 21 22

}

"You entered A. \n"; "You entered B . \n"; "You entered C . \n"; "You

did not enter A, B, or C!\n";

return 0;

ad

23

'A' :

ss

(

Ha

13 14

an

9

)

m

Program Output with h .ample Input Shown in Bold Enter A, B, or C: B [Enter] You entered B ,

uh a

m

Program Output with Example Input Shown In Bold t;nter A, B , or C : F [Enter] You did not enter A, B, or C!

M

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,

To Read Online & Download: WWW.ISSUU.COM/SHEIKHUHASSAN


Bismillah hiir Rehman nir Raheem-----------------------------Assalat o Wasalam o Alika Ya RasoolALLAH 224

i

Chapter 4 Making Decisions

us uf

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 «

B . \n";

Yo

"You e ntered

"You entered C.\n";

"You did not enter A, B, or CJ\n"j

}

az

The case statements show rhe program where [Q start executing in the block and the break

Ri

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

an

need a b reak statemen t. Some programmers prefer to put one there anyway, for consistency.

2

II The switch statement in this program tells the user something II he or she already knows: the data just entered !

3 4

'include <io stream> using names pace std;

Ha

1

ss

Program 4-29 is a modi ficarion of Program 4-28, without the break sta[ements.

5

6

in t main()

7 8

{

,

ad

char choice; 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

m

10 11 12

(

,.

m

case 'A' : case ' B' : case ' C ' : default ;

}

21

return

uh a

19 20

22

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,.

)

M

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!

To Read Online & Download: WWW.ISSUU.COM/SHEIKHUHASSAN


Bismillah hiir Rehman nir Raheem-----------------------------Assalat o Wasalam o Alika Ya RasoolALLAH 4.15 The swi tch Statement

i

22.

us uf

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!

az

Yo

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

II This prog ram is carefully constructed to use the "fall through" II feature of the switch s tatement. 'include <iostream> using namespace std ;

Ri

1

2 3 4 5 7 8 9 10 11

{

int model Num ;

I I Model number

an

int main()

6

ss

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 ;

Ha

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 «

"\ tPicture-in-a-picture. \n" ; " \tStereo sound . \0" i "\ tRemote control . \0" ;

ad

19 20 21 22

m

23 24 25

"You can only choose the 100,":

"200, or 300.\0";

}

m

return 0;

26 27

uh a

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.

M

(program output continues)

To Read Online & Download: WWW.ISSUU.COM/SHEIKHUHASSAN


Bismillah hiir Rehman nir Raheem-----------------------------Assalat o Wasalam o Alika Ya RasoolALLAH Making Decisions

Program 4·10

i

Chapter 4

(continued)

us uf

226

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]

Yo

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 :

Ri

Program Output with Example Input Shown In Bold Our TVs come in three models :

az

Picture - in - a-picture. Stereo sound . Remote c ontrol.

The 100, 200, and 300 . Which do you wan t? 500 [Enter]

an

That model has the following features : You can only choose t he 100, 200, or 300 .

ss

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.

5

using namespace std ;

6 7

int main()

8

(

10 11 12

char feedGrade;

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 ;

uh a

13 14

m

9

ad

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 <iostream>

m

1 2

Ha

Program 4 -31

15

16 17 18 19

M

20 21

II Disp lay the price . switch (£eedGrade) {

case 'a ': case 'A' ; COllt « break ;

"30 cents

per pound . \n"

i

To Read Online & Download: WWW.ISSUU.COM/SHEIKHUHASSAN


Bismillah hiir Rehman nir Raheem-----------------------------Assalat o Wasalam o Alika Ya RasoolALLAH 227

case ' b' :

case

2.

"20 cents per pound.\n";

break;

26 27

28

"15 cents per pound,\n";

"That is an invalid choice, \n" ;

Yo

case 'c' : case ' C': cout« break; default: cout«

25

29 30 31

'B': cout«

us uf

22

23

i

4.15 The switch Statement

return 0: }

Ri

Program Output with Examp le Input Shown In Bold

az

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 .

an

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 case 'a': 'A':

cout« break;

"30

cents per pound. \n";

Ha

case

'A' .

ss

t he program falls through to the next case, which corresponds with

The same technique is used for' b' and' c ' .

Uling switch in Menu Systems

ad

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 pur-

m

Program 4 -12

m

chase. 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 ,

uh a

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 <iostream> 5 'include <iomanip> 6 using names pace std; 7

M

8 int main() 9 {

(program continues)

To Read Online & Download: WWW.ISSUU.COM/SHEIKHUHASSAN


Bismillah hiir Rehman nir Raheem-----------------------------Assalat o Wasalam o Alika Ya RasoolALLAH Making Decisions

Program 4 <J2

i

Cha pter 4

(confinued)

us uf

228

II Menu choice

10

iot choice;

11

iot months;

1/ Number o f months

12

double charges ;

II Monthly charges

13

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 ;

26

az

"\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" ;

« « «

Ri

2S

«

27

28 29

II Set the numeric output formatting . cout « fixed « showpoint « setprecision(2ji

an

30

1/ Respond to the user ' s menu selection . switch (choice)

33

{

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 ;

Ha

35 36

ss

31 32 34

Yo

I'

case 2 :

42 43

cout « "For how many months? cin » months ;

46

charges months • CHILD; cout « "The total char ges are $" « break ;

ad

case 3: cout « "For how man y months? " j cin » months; charge s = months • SENI OR; cout « "The tota l charges are $" « break ;

uh a

52

53 5' 55 56 57

charges «

endl j

charges «

endlj

"j

m

47

48 49 50 51

endl;

2

m

4' 45

c harges «

case 4; cout« break ;

"Program e nding . \n";

M

58

To Read Online & Download: WWW.ISSUU.COM/SHEIKHUHASSAN


Bismillah hiir Rehman nir Raheem-----------------------------Assalat o Wasalam o Alika Ya RasoolALLAH 229

default: cout « cout «

60 61

62

us uf

59

i

4.15 The switch Statement

"The valid choices are 1 through 4. Run the\n"; "program again and select one of those . \n";

)

63 return 0 ;

64

Yo

65 ) Program Output with Example Input Shown In Bold

Health Club Membersh i p Menu Standard Adult Membership Child Membership Senior Citizen Membership Quit the Program

az

1. 2. 3. 4.

Ri

Enter your choice : 2 [Enter] For how many months? 6 [Enter] The total charges are S120 . 00

4.33

an

~ Checkpoint

i f (temp == 100 ) x : 0;

ss

Explain why you cannot convert the follow ing if/else if statement into a switch statement.

x == 1;

else if

(rate < .1)

x = -1;

4.34

Ha

else if (population> 1000)

What is wro ng with the followi ng switch sta tement?

{

ad

switch (temp)

,

COllt « break; case temp -- 0 , cout « break ; case temp > 0 cout « break; < 0

m

case temp

"Temp is zero.\n"; "Temp is pos itive . \n";

m

,

"Temp is negative. \n";

)

M

uh a

4.35

What will the following program display?

#include <iostream> using namespace std; int main ( ) {

int funny funny switch

=

=

7 , serious - 15;

serious * 2 ; (funny)

To Read Online & Download: WWW.ISSUU.COM/SHEIKHUHASSAN


Bismillah hiir Rehman nir Raheem-----------------------------Assalat o Wasalam o Alika Ya RasoolALLAH

{

,

case 0

cout «

i

Making Decisions

"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;

)

return O·•

Yo

)

us uf

Chapter 4

230

az

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.

4.36

tinclude <iostream>

Ri

using namespace std; iot main() {

cout «

cin » II

an

iot userNum;

"Enter one of the numbers 1, 2, or 3: ";

userNum:

1/ Write the switch statement here.

ss

II return 0;

4.37

Ha

}

Rewrite the fo llowmg program. Use a switch statement instead of the if/else if statement.

ad

'inc~udQ <iostream> using namespace std;

int main() {

M

uh a

m

m

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";

)

To Read Online & Download: WWW.ISSUU.COM/SHEIKHUHASSAN


Bismillah hiir Rehman nir Raheem-----------------------------Assalat o Wasalam o Alika Ya RasoolALLAH 4. 16 Testing for F-iJe Open Errors

us uf

i

231

Testing for File Open Errors

CONCE.PT: When opening a file you can tes t the file stream object co determine if an

Yo

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:

az

ifstream inputFile ; inputFile .open ( "info. txt" ) ;

ifstream inputFile : inputF ile . open ( "customers. txt" ) ; if (!inputFile) cout «

an

{

Ri

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:

"Error opening file. \n";

)

open a file is with the fail member function, as

Ha

ifstream inputFile i

to

ss

Another way to detect a fa iled attempt shown in the followi ng code:

inputFile.open{"customers . txt~);

if (inputFile.fail()) {

"Error opening file . \n ";

ad

cout «

m

m

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.

uh a

of stream outputFile ; outputFile .open ( "customer. txt" ) ; if (outputFile.fail(»

M

{

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.

To Read Online & Download: WWW.ISSUU.COM/SHEIKHUHASSAN


Bismillah hiir Rehman nir Raheem-----------------------------Assalat o Wasalam o Alika Ya RasoolALLAH 232

i

Chapter 4 Making Decisions

us uf

Review Questions and Exercises Short Answer

1. Describe the dIfference between the if/else if statement and a series of if statements.

Yo

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.

az

operator works.

7. Why are the relational operators called relational?

Ri

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-or-

an

equal -ro, equa l, o r not-eq ual to operator is called a(n)

expression.

10. A relational expression is either ____ or ____

if statement regards an expression with the value

0 as _ _ _ __

Ha

12. The

ss

11. The value of a relational express ion is 0 jf the expression is _ ____ or 1 if the expression IS _ __ _ _

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 _ _ __

ad

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

m

16. The [railing else in an if/else i f Statement has a similar purpose as the _ _ _ _ _ section of a switch state ment.

m

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.

uh a

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.

M

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.

To Read Online & Download: WWW.ISSUU.COM/SHEIKHUHASSAN


Bismillah hiir Rehman nir Raheem-----------------------------Assalat o Wasalam o Alika Ya RasoolALLAH 233

Review Questions and Exercises

us uf

i

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 .

Yo

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? (12 > I) , _ _ __

A} t

t - 12 < 0), _ _ __ ( 3 · 2 ) ) ' _ __

D)

5)' _ _ __

15

t

_

Ri

qt-IS--

Algorithm Workbench 31. Write an

az

B)

if statement that assigns 100 to x when y is equal to

a to x when y is equal to 10. Otherwise it

an

32. Write an if/else srarement that assigns

O.

shou ld assign 1 to x.

33. Using the following chart, write an if/else if statement that assigns .10, .15, or .20

ss

to corrunission, depending on the value in sales.

Ha

Sales Up to $10,000 $10,000 to $15,000 Over $15,000

Commission Rate

10% 15% 20%

ad

34. Write an if statement that sets the variable hours to 10 when rhe flag variable minimum is set.

m

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.

m

36. Write an if statement that prints the message "The number is valid " if the variable grade is within the range 0 through 100.

uh a

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

M

title2 in alphabetical order.

40. Convert the following if/else if statement into a switch statement:

if (choice --

cout «

1)

fixed «

showpoint «

setprecision(2) ;

To Read Online & Download: WWW.ISSUU.COM/SHEIKHUHASSAN


Bismillah hiir Rehman nir Raheem-----------------------------Assalat o Wasalam o Alika Ya RasoolALLAH Making Decisions

}

else if (choice

:~

II

2

i

Chapter 4

choice

:~

3)

{

fixed «

else if (choice (

cout «

showpoint «

==

setprecision(4);

4)

fixed «

showpoint «

setprecision(6);

fixed «

showpoint «

setprecision(8)i

Yo

cout « }

}

else {

cout «

us uf

234

az

}

BI

q = x < y ? x

a + b,

2

C) x < y ? q = 0

q = l ',

"

y)

ss

if (x <

an

if Ix < y) 0, q else q =

Ri

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 ,•

q .. a + bi

else

2,

Ha

q "'" x •

U(x<y) q

else

::0

X

..

2;

q "" a -+ bi

42. T F F

The"" operator and the "'= operator perform the same operation. A variable defined in an inner block may not have the same name as a variable defined in the outer block.

m

43. T

ad

True or False

44. T

F

A conditionally executed statement should be indented one level from the i f

m

Statement.

45. T

uh a

46. T

F F

47. T F

M

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.

To Read Online & Download: WWW.ISSUU.COM/SHEIKHUHASSAN


Bismillah hiir Rehman nir Raheem-----------------------------Assalat o Wasalam o Alika Ya RasoolALLAH Review Questions and Exercises

i

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)

us uf

49. 50. 51. 52. 53.

2 35

F F

56. T

F

57.

T F

x == 5

II

3 z > 4

y >

7 <= x " 2 1'" Y x >= 0

1= 4

&&

Z

II

x <'" y

az

54. T 55. T

Yo

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:

Find the Errors

Each of the following programs has errors. Find as many as you can .

Ri

58. II Th i s program averages 3 test scores . II It uses the variable perfectScore as a flag . include <iostream> using namespace std;

an

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): {

ad

Ha

ss

«

m

cout « "congratulations!\n" : cout« "That's a perfect score.\n"; cout « .. You deserve a pat on the back! \n" : return 0 ;

m

}

59. II This program divides a user- supplied number by another II user-supplied number . It checks for division by zero .

uh a

'include <iostream> using namespace std ; int main()

M

{

double numl, num2, quotient; cout « "Enter a number : " ; cin » numl : cout « "Enter another number : " ;

To Read Online & Download: WWW.ISSUU.COM/SHEIKHUHASSAN


Bismillah hiir Rehman nir Raheem-----------------------------Assalat o Wasalam o Alika Ya RasoolALLAH Chapter 4

236

Making Oecisions

cout « else quotient

cout « cout « cout « return 0;

~ numl I num2; "The quotient of M divided by " «

quotient «

~

« numl « num2 « .. is Hi

endl;

)

M

;

Yo

"and enter a number besides zero.\n

us uf

num2i if (num2 "" ... 0) cout « "Division by zero is not possible. \n~ ; cout « ~Please run the program again ~ ;

i

cin »

60. II This program uses an if/else if statement to assign a

Ri

az

II letter grade (A, a, C, D, or F) to a numeric test Bcore. 'include <iostream> using namespace std: int maine 1 (

int testScore;

ss

an

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

« 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 ;

ad

cout else if cout else cout else if cout

Ha

else if (teatScore < 70) cout « "Your grade is D. \ 0"; else if (testScore < 80)

return 0;

m

)

61 . II This program tests two strings for equality.

uh am

tinclude <iostream> using nameapace std;

int main ( ) (

M

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 «

"The strings are the same . \n";

else

To Read Online & Download: WWW.ISSUU.COM/SHEIKHUHASSAN


Bismillah hiir Rehman nir Raheem-----------------------------Assalat o Wasalam o Alika Ya RasoolALLAH Review Questions and Exercises

i

"The strings are not the same.\n";

us uf

cout « return 0;

23 7

)

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.

Yo

'include <iostream> using namespace std; int main( ) {

{

Ha

ss

an

Ri

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;

az

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)

is D. \n";

is C . \n " ;

is B. \0" i

is A. \n ";

isn't valid\n";

ad

)

is F.\n";

63. The following statement should determine if x is not greater than 20. What is wrong

m

with it?

i f ilx > 20)

m

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?

II

count <- 100)

uh a

if (cou nt > - 0

65. T he followi ng statement should determine if count is outside the range of 0 through 100. What is wrong with it?

M

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:

To Read Online & Download: WWW.ISSUU.COM/SHEIKHUHASSAN


Bismillah hiir Rehman nir Raheem-----------------------------Assalat o Wasalam o Alika Ya RasoolALLAH Chapter 4

238

Making Decisions

us uf

i

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.

Yo

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

az

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

Ri

6/10/60

an

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

5. Body Mass Ind ex

Ha

ss

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. 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-

ad

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'

m

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

uh a

m

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

M

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

To Read Online & Download: WWW.ISSUU.COM/SHEIKHUHASSAN


Bismillah hiir Rehman nir Raheem-----------------------------Assalat o Wasalam o Alika Ya RasoolALLAH Review Questions and Exercises

23 9

7. Time Calculator

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.

az

CalculalOr

enter a number of seconds.

problem

Ri

Solving the Time

fO

Yo

Write a program that asks the user

us uf

i

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.

8. Sorted N ames

an

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

ss

Charlie 9. Math Tutor

Ha

Leslie

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:

ad

247 + 129

m

m

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

uh a

A software compa ny se lls a package that retails for $99. Quantity discounts are given according to the following table.

M

Quantity

10- 19

Di scount 20%

20-49

30%

50-99 100 or more

40% 50%

To Read Online & Download: WWW.ISSUU.COM/SHEIKHUHASSAN


Bismillah hiir Rehman nir Raheem-----------------------------Assalat o Wasalam o Alika Ya RasoolALLAH Chapter 4

240

Making Decisions

Input Validation: Make SIIre the number of units is greater than O. 11 . Book Club Points

us uf

i

Write a program that asks for the number of units sold and computes the total cost of the purchase.

Yo

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.

az

• • • •

Ri

\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:

ss

$.06 each for 40-59 checks $.04 each for 60 or more checks

an

$ .1 0 each for fewer than 20 checks $.08 each for 20-39 checks

Ha

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.

ad

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

m

The Fast Freight Shipping Company charges the followi ng rates:

m

Weight of Package (in Kilograms ) 2 Kg or less

Over 2 Kg but not more than 6 kg

uh a

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

M

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,

To Read Online & Download: WWW.ISSUU.COM/SHEIKHUHASSAN


Bismillah hiir Rehman nir Raheem-----------------------------Assalat o Wasalam o Alika Ya RasoolALLAH Review Questions and Exercises

us uf

i

1 4. Running the Race

241

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.

Yo

Input Validation: Be sure the names do not overflow the arrays. Only accept positive nllmbers (or the times.

15. Personal Best

az

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

Ri

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.

an

One gram of fat has 9 calories, so Calories from fa t = fat grams'" 9

ss

The percentage of calor ies from fat can be calcu lated as

Ha

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. .

ad

17. Spectral Analysis

1ÂŁ a scientist knows the wavelength of an electromagnetic wave, he or she can determine

M

uh a

@__

m

m

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

To Read Online & Download: WWW.ISSUU.COM/SHEIKHUHASSAN


Bismillah hiir Rehman nir Raheem-----------------------------Assalat o Wasalam o Alika Ya RasoolALLAH 242

Chapter 4

Making Decisions

Write a program that displays a menu allowing the L1ser to select air, water, or steel.

us uf

i

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.

Yo

19. The Speed of Sound in Gases

az

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 972.0

1,270.0

Ri

258.0

an

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

ss

was detected. The program should then report how far away (in meters) the source of the sound was from the detection loca tion.

Ha

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

m

ad

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.

m

Substance Ethyl a lcohol Mercury

uh a

Oxygen

Boiling Point r F)

- 173 -38 -362 32

172 676 -306 212

M

Water

Freezing Point (C F)

To Read Online & Download: WWW.ISSUU.COM/SHEIKHUHASSAN


Bismillah hiir Rehman nir Raheem-----------------------------Assalat o Wasalam o Alika Ya RasoolALLAH Review Questions and Exercises

us uf

i

21. Geometry Calculator

243

Write a program that displays the fonowing menu:

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):

Yo

Geometry calculator

dis~

az

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:

area

=

Ri

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: length * width

ss

area = base * height * .5

an

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:

If the user enters 4, the program should end.

22.

Long~Distan ce

Ha

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. Calls

ad

A !ong~ di stance carrier charges the fo llowing (ates for telephone calls; Rate per Minute

00,00-06,59

0.12 0.55 0.35

m

Starting Time of Call 07,00-1~,00

m

19,01-2359

uh a

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.

M

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<int>(num)

To Read Online & Download: WWW.ISSUU.COM/SHEIKHUHASSAN


Bismillah hiir Rehman nir Raheem-----------------------------Assalat o Wasalam o Alika Ya RasoolALLAH 244

Chapter 4

Making Decisions

i

23. In(ernct Servi ce Provider

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. For $19 .95 pcr month unlimi ted access is provided.

Yo

Package C:

us uf

An [merner service provider has three different subscription packages for its customers:

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 .

24 . Internet Ser vice Provider, Part 2

az

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.

25. Intern et Service Provider, Part 3

an

Ri

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.

Ha

ss

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

April

uh a

m

m

May

ad

Janua ry February March

November December

Hours

no 744

720 744 744

720 7 4'>

M

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.

To Read Online & Download: WWW.ISSUU.COM/SHEIKHUHASSAN


Bismillah hiir Rehman nir Raheem-----------------------------Assalat o Wasalam o Alika Ya RasoolALLAH 245

i

Review Questions and Exercises

us uf

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 out-

Yo

side the range of 1 through 4 is entered, the program should display an error message. Here is an example screen:

1. 2.

Cashier Module . Inventory Database Module

3: Report Module Exit

Enter Your Choice: S

Ri

4.

az

Serendipity Booksellers MaIn Menu

Please enter a number In the range 1-4.

an

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

ss

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

Ha

the user enters a number. Here is an example of the screen: Serendipity Booksellers Main Menu

1. 2.

Clshler Module Inventory Database Module

Report "'adule Exit

ad

3.

4.

You selected Item 3.

m

m

Enter Your Choice: 3

2. The Inventory Database Menu

uh a

You will make the same modifications to invrnenu . cpp that you made to main-

M

menu. cpp.

To Read Online & Download: WWW.ISSUU.COM/SHEIKHUHASSAN


Bismillah hiir Rehman nir Raheem-----------------------------Assalat o Wasalam o Alika Ya RasoolALLAH Chapter 4 Making Decisions

i

A. Modify (he invrnenu.cpp program so it val idates the user's input. If a value out~

us uf

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

Yo

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

az

Please enter a number In the range 1-5.

Ri

B. After the user input has been validated, add a switch statement thar branches to

an

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

Ha

ss

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

ad

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.

M

uh a

m

m

me nu . cpp

To Read Online & Download: WWW.ISSUU.COM/SHEIKHUHASSAN


Bismillah hiir Rehman nir Raheem-----------------------------Assalat o Wasalam o Alika Ya RasoolALLAH Review Questions and Exercises

us uf

i

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

az

Yo

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

Ri

please enter a number in the range 1- 7.

B. After the user input has been validated, add a switch statement that branches to

an

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:

ss

Serendipity Booksellers Reports

Ha

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

ad

Enter Your Choice: S

M

uh a

m

m

You selec:ted Item 5.

To Read Online & Download: WWW.ISSUU.COM/SHEIKHUHASSAN


M

uh a

m m

ad

Ha

ss

an

Ri

az

Yo

us uf

i

Bismillah hiir Rehman nir Raheem-----------------------------Assalat o Wasalam o Alika Ya RasoolALLAH

To Read Online & Download: WWW.ISSUU.COM/SHEIKHUHASSAN


az

Yo

us uf

i

Bismillah hiir Rehman nir Raheem-----------------------------Assalat o Wasalam o Alika Ya RasoolALLAH

Ri

TOPICS 5.1

Th e Increment and Decrement

5.7 5.B

5.2

Operators Introduction to lOOps:

5.9

5.J

The while Loop Using the while l oop for Input Validation

5.10 Focus on Software Engineering: Deciding Which loop to Use

5.4 5.5 5.6

The do- while l oop

Sentinels

an

Using a l OOp to Read Data from a I=ile

5.11 5.12

Nested Loops Breaking Out of a Loop

ss

Cou nters

Keeping a Running Total

5.13 The continue Statement

Ha

The for l oop

ad

The Increment and Decrement Operators

m

CONCEPT: ++ a nd -- are operators that add and subtract 1 from their operands.

m

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;

uh a

And num is decremented in both o f the fo llowing sta tements:

num

=

num - 1 ; t;

M

nurn -;;:

24.

To Read Online & Download: WWW.ISSUU.COM/SHEIKHUHASSAN


Bismillah hiir Rehman nir Raheem-----------------------------Assalat o Wasalam o Alika Ya RasoolALLAH 2 50

Looping

i

Chapter 5

us uf

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++; num:

Yo

And the following statement decrements num-- j

az

NOTE : The expression num++ is pronounced "num plus plus," and num- - is pronounced ( ) "-_"_"_"_"' __"' __'_ " _"_,_"' __i"__"_,_ .'_ ' ____________________________________________________________-'

Ri

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;

Program 5 - 1

II This program demonstra tes the iinclude <iostream> using names pace std ;

5 6 7 8

9 10 11

lnt main () { int num ... 4;

II Use postfix num++;

15

cout « cout «

"Now the variable num is " « num « "I will increment num a9ain . \n\n";

m

18 19

++ to increment num .

m

13 14

17

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

16

Ha

3

ad

,

++ and -- operators.

ss

1 2

an

In borh postfix and prefix mode, these operators add 1 ro or subtract J from their operand. Program 5-1 shows how they work.

1/ Use prefix ++ to increment num. ++n u mi

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 " ;

uh a

20 21 22

M

24 25

26

endl;

"Now the variable num is " « oum « "I will now decrement num. \0\0";

endl;

end l ;

27

To Read Online & Download: WWW.ISSUU.COM/SHEIKHUHASSAN


Bismillah hiir Rehman nir Raheem-----------------------------Assalat o Wasalam o Alika Ya RasoolALLAH 25 1

32

II Use prefix -- to increment num. --numi cout « "Now the variable num is " « return 0:

num «

us uf

28 29 30 31

i

5.1 The Increment and Decrement Operators

endl ;

}

Yo

Program Output The variable num is 4 I will now increment num.

az

Now the variable nurn i, 5 I will increment nurn again .

Now the variable nurn i , 6 I will now decrement num.

Ri

Now the var~able num is 5 I will decrement num again .

an

Now the variable num is 4

The Difference Between Postfix and Prefix Modes

num = 4: cout « num++;

Ha

ss

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:

ad

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.

m

m

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:

uh a

num '" 4 ; cout « ++num ;

Program 5-2 illustrates these dynamics further:

Program 5-2

M

1 2 3 ~

II This program demonstrates the prefix and postfix II modes of the increment and decrement operators, 'include <iostream> using names pace std: (program continues)

To Read Online & Download: WWW.ISSUU.COM/SHEIKHUHASSAN


Bismillah hiir Rehman nir Raheem-----------------------------Assalat o Wasalam o Alika Ya RasoolALLAH 252

(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

17 18 19

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

«

cout «

20 21

az

14 15 16

Yo

nurn <;< endl; num++ « endl:

cout «

13

?2

cout «

~-num

Ri

10 11 12

us uf

Program 5-2

i

Chapter 5 looping

return 0; }

an

Prog ram Output 4

4 5

ss

6

6

Ha

6 5 4

Let's ana lyze the statements in this program.

(0

line 8, nurn is initialized with the value 4,

ad

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.

m

m

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.

uh a

For another example, look at the following code:

M

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

To Read Online & Download: WWW.ISSUU.COM/SHEIKHUHASSAN


Bismillah hiir Rehman nir Raheem-----------------------------Assalat o Wasalam o Alika Ya RasoolALLAH 5.1 The Ir, crement an d Decrement Operators

i

253

us uf

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;

Yo

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

a - 2; b : 5;

*

c = a

cout «

b++ ;

a «

" " «

b

«

" " «

c,

Ri

az

The increment and decrement operators can also be used on variables in mathematical expressions. Consider the foll ow ing program segment:

an

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

c

=a *

ss

If the statement were changed ro read ++b ;

2 6 12

Ha

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

ad

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;

m

b = 5;

c=++(a*b);

/ / Error!

uh a

m

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.

M

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";

To Read Online & Download: WWW.ISSUU.COM/SHEIKHUHASSAN


Bismillah hiir Rehman nir Raheem-----------------------------Assalat o Wasalam o Alika Ya RasoolALLAH

Chapter 5 looping

i

254

us uf

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:

Yo

x = 10; i f (HX > 10)

cout «

"x is greater than 10. \n ";

Checkpoint 5. 1

az

What will the following program segments display? A) x = 2 ; y - x++; cout « x «

Ri

Yi

B) x = 2;

= ++X;

cout «

C) x

x «

y;

= 2;

y '" 4; cout «

x++ «

--y ;

y

=2

x

= 99;

ss

D) x = 2;

an

y

E)

Ha

* x++; cout « x « Yi i f (x++ < 100)

cout

"It

else cout «

is true ! \n" ;

"It is false! \n";

ad

F) x = 0;

"It

is true ! \n" ;

" It is false ! \n";

m

m

if (++x) cout « else cout «

uh a

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 pro-

M

gram. 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

To Read Online & Download: WWW.ISSUU.COM/SHEIKHUHASSAN


Bismillah hiir Rehman nir Raheem-----------------------------Assalat o Wasalam o Alika Ya RasoolALLAH 255

i

5.2 Introduction to Loops: The while Loop

us uf

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.

az

Yo

Figure 5 -1

Ri

True Expression)----j Statement(s)

an

False

Here is the general format of the while loop: (expression)

whi l e

ss

statement;

Ha

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.

ad

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.

m

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.

m

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.

uh a

If you wish the while loop to repeat a block of statements, its format is: while (expression)

M

{

statement; statement ;

II Pl ace as many statements here II as necessary.

)

To Read Online & Download: WWW.ISSUU.COM/SHEIKHUHASSAN


Bismillah hiir Rehman nir Raheem-----------------------------Assalat o Wasalam o Alika Ya RasoolALLAH

Chapter 5 looping

i

256

us uf

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 This program demonstrates a simple while loop .

,

using names pace std ;

5 6 7

int main() {

iot number: 1 ; while (number <= 5) {

11

cout «

12 13 14

number++ ;

~Hello\n" ;

)

cout « "That ' s a11!\n" ; ret urn 0 ;

an

15 16

az

10

' i nclude <iostream>

Ri

B 9

Yo

1 2 3

Program Output

ss

Hello

Ha

Hello Hello Hello Hello

That's all!

ad

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)

m

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:

m

cout « "Hello\n"; number++;

M

uh a

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.

To Read Online & Download: WWW.ISSUU.COM/SHEIKHUHASSAN


Bismillah hiir Rehman nir Raheem-----------------------------Assalat o Wasalam o Alika Ya RasoolALLAH 5.2 Introduction to Loops: The while Loop

i

257

Test this expression.

while (number <= 5) (

cout « "Hello\n"; number++;

If the expression is true, pertorm these statements.

~

Yo

j

us uf

Figure 5·2

)

az

L _ _ _ Afler executing the body of the loop, start over.

Figure 5-3

Ri

I True

an

number <= 5

Print "Hello"

Ha

ss

False

Add 1 to number

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. whi~e

Loop Is a Pretest Loop

ad

The

m

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;

m

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:

uh a

int number = 6; while (number <= 5) (

cout « "Hello\n"; number++;

M

)

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.

To Read Online & Download: WWW.ISSUU.COM/SHEIKHUHASSAN


Bismillah hiir Rehman nir Raheem-----------------------------Assalat o Wasalam o Alika Ya RasoolALLAH Chapter 5

Looping

i

258

us uf

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 conint number

Yo

tinues to repeat until the program is interrupted. Here is an exa mple of an infinite loop:

= Ii

while (number <= 5) {

cout «

"Hel10\n";

az

}

Ri

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; {

ss

cout « "Hello\n"; number++;

II This semicolon is an ERROR !

an

while (number <: 5);

}

Ha

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);

ad

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.

m

Don't Forget the Braces with a Block of Statements

uh a

m

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;

M

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.

To Read Online & Download: WWW.ISSUU.COM/SHEIKHUHASSAN


Bismillah hiir Rehman nir Raheem-----------------------------Assalat o Wasalam o Alika Ya RasoolALLAH 259

i

5.2 Introduction to l oops: The while loop

while (remainder : 1) II Error: Notice the assignment {

"i

Yo

cout « "Enter a number: cin » num; remainder: num % 2;

us uf

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.

)

Remember, any nonzero val ue is evaluated as true.

az

Programming Style and the while Loop !t's poss ible to create loops that look like this: 5)

{

cout «

"Hello\n" ; number++ i

Ri

while (number <=

}

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,

an

Ha

ss

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:

ad

Designing a Program with a while Loop

uh a

m

m

-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.

M

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.

To Read Online & Download: WWW.ISSUU.COM/SHEIKHUHASSAN


Bismillah hiir Rehman nir Raheem-----------------------------Assalat o Wasalam o Alika Ya RasoolALLAH 260

Looping

i

Chapter 5

us uf

3. After the loop fin;she~, tell the tecbnician thqt the temperature is acceptable and tQ c;heck it ag(lin in 1S minute~._

Program 5-4 1 1/ Tpis program as§ists ~ technician in the process 2 II of checking a substance's ~emperature.

az

3. tincluqe <iostxeam> . 4 using names pace s t d; 5

6 int

~ain()

Ri

7 1 B

II Maximum temperatur e II TQ hold the temperature

canst' double MAX TEMp:::: 1-02.5 ; double temperature;

9

10

d

15 16

"

j l As long as neoessary, instruct the technician

17 19

whil~

{

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;

Ha

cout « cou'l;: « ccut « cout «

19

1

ad

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

m

2.

2' 30" )

m

_return 0 ;

31

32

ss

II to adjust the thermostat . (temperature> MAx_TEMP )

an

12

I I Get. 'the ·current te:mperatur.e. oo"ut « UEnter t"e substance's Celsius temper ature: "; ci~ » temperature ;

H

Yo

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.

uh a

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 .

M

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.

To Read Online & Download: WWW.ISSUU.COM/SHEIKHUHASSAN


Bismillah hiir Rehman nir Raheem-----------------------------Assalat o Wasalam o Alika Ya RasoolALLAH 5.3 Using the while l oop for Input Validation

us uf

i

26 1

Using the while Loop for Input Validation

Yo

CONCEPT: Th e while loop can be used to create input routines that repeat unti l acceptable data is en tered.

az

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.

Ri

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:

an

cout « "Enter a number in the r ange 1-100 : " ; cin » number; whi l e (number < 1 I I number> 100) (

ss

cou t « "ERROR: Ente r a value in the range 1-100 : " ; cin » number ; )

Ha

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.

m

ad

Figure 5-4

j

M

uh a

m

Read the first value.

Isthe value invalid?

Yes

Display an error message.

Read another value.

No

To Read Online & Download: WWW.ISSUU.COM/SHEIKHUHASSAN


Bismillah hiir Rehman nir Raheem-----------------------------Assalat o Wasalam o Alika Ya RasoolALLAH

Chapter 5 l ooping

i

262

us uf

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 S-S

9 10 11

12 13 14

az

6 7

' i nclude <iostream>

using namespace std; int main( )

Ri

3 4 5

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.

{

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

an

1 2

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

{

Ha

m

II Get the number of players available. cout « ""How many players are available? .. ; cin » players;

32

II Validate the i nput. while (playe r s <= 0)

35

{

m

33 34

cout « "Please enter a positive number: cin » players;

uh a

36 37 38 39

teamPlayers > 15)

ad

)

2. 29 30 31

II

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

ss

15 16 17 18

I.

40

M

41 42

43

44

Yo

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.

"i

)

II Calculate the number of teams . numTeams = p l ayers I teamPlayersi

II Calculate the number of leftover players . leftOver = players % teamPlayers;

45

To Read Online & Download: WWW.ISSUU.COM/SHEIKHUHASSAN


Bismillah hiir Rehman nir Raheem-----------------------------Assalat o Wasalam o Alika Ya RasoolALLAH 5.4 Counters

Checkpoint

i

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" .

an

5.2

ss

~

Ri

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 .

Yo

}

az

sa

/1 Display the results. cout « "There will be " « numTeams « " teams with ": cout « leftOver « " players left over . \n "; return 0 ;

us uf

46 47 48 49

263

Ha

Counters

CONCEPT: A cou nler is a va riable thal is regularly incremented or decremented each t'ime a loop iterates.

m

ad

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.

// This program displays the numbers 1 through 10 and // thei r squares. 'include <iostream> using names pace stdi

7

(

uh a

m

1 2 J 4 5 6

8

intmain()

I : II Initialize the counter.

int num

~

cout «

"Number Number Squ a J:'ed\n";

9

M

10

(program continues)

To Read Online & Download: WWW.ISSUU.COM/SHEIKHUHASSAN


Bismillah hiir Rehman nir Raheem-----------------------------Assalat o Wasalam o Alika Ya RasoolALLAH

Looping

Program 5·6 11

cout «

while (nurn <= 10) {

endlj

Yo

"

17 18

" - -- - ------------ --- - ----- \ n"i

cout « nurn « "\t\t" « ( nurn * nurn) « num++; I/Inc remen t the counter.

15

us uf

(continued)

12 13

I.

i

Chapter 5

264

return 0 ; )

Program Output

Number Squared

1

az

Number

1

2

3

•5

Ri

9

I'25

3.

7 8 9 10

49

an

6'

ss

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

.A

Ha

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 . NOTE : It's important that num be properly initialized. Remember, variables defined

ad

~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,_.______________________________--'

m

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; ( n um • num) «

endl;

m

while (num++ < 10 ) cout « num « ,,\t\t" «

This code will produce the same outpu t as Program 5-6,

M

uh a

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.

To Read Online & Download: WWW.ISSUU.COM/SHEIKHUHASSAN


Bismillah hiir Rehman nir Raheem-----------------------------Assalat o Wasalam o Alika Ya RasoolALLAH 5.5 The do- while Loop

Figure S-S

num is compared to 10, then it is incremen ted. When l he cout statement

/

while (num++ <10) cout « num « "\t\t" «

(num * nurn) «

endl;

Yo

executes, num is 1 greater than il was in the relalionallesl.

us uf

i

26S

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

az

10. That's why the relational operaror is test, it will be lOin the cout statement.

Ri

The do-while Loop

an

CONCEPT: The do-while loop is a posttesf loop, whicb means its expression is tested after each iteration.

do

Ha

statement; while (expression);

ss

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 {

ad

Here is the format of the do-while loop when the body of the loop contains multiple statements:

m

m

statement; statement; II Place as many statements here /1 as necessary . } while (expressi on );

M

uh a

~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;

To Read Online & Download: WWW.ISSUU.COM/SHEIKHUHASSAN


Bismillah hiir Rehman nir Raheem-----------------------------Assalat o Wasalam o Alika Ya RasoolALLAH

Chapter 5 looping

i

266

us uf

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

endli

Yo

cout « x « while (x < 0);

Figure 5-6 illustrates the logic of the do-while loop.

az

Figure 5-6

Ri

Statemenl(s)

True

ss

False

r---'

an

Expression

to

make s ure the loop execu tes at least

Ha

You should use the do-w h ile loop when you want

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.

1 2 3

ad

Program 5-7 II This program averages 3 test scores . It repeats as 1/ many times as the user wishes_ 'include <i ostream> using namespace std;

int main()

7

{

int scorel, score2, score3; II Three scores double average ; II Average s c ore char again; II To hold Y or N input

uh a

9 10

m

m

4 5 6

11

12

M

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.

To Read Online & Download: WWW.ISSUU.COM/SHEIKHUHASSAN


Bismillah hiir Rehman nir Raheem-----------------------------Assalat o Wasalam o Alika Ya RasoolALLAH 267

average = (scorel + score2 + score3) I 3.0; cout « "The average is " « average « ". \n" ;

20 21

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; )

az

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]

Ri

Program Output Enter 3 scores The average is Do you want to Enter 3 scores The average is Do you want to

Yo

22 23 24 25 26 27

us uf

I.

i

5.5 The do-while Loop

an

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.

ss

Using do-while with Menus

Ha

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.

ad

1

. 7

m

4 'include <iostream> 5 'include <iomanip> 6 us i ng namespace std;

uh a

m

8 int main() ( i nt choice; 10 11 int months; 12 double charges; 13 14

M

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)

To Read Online & Download: WWW.ISSUU.COM/SHEIKHUHASSAN


Bismillah hiir Rehman nir Raheem-----------------------------Assalat o Wasalam o Alika Ya RasoolALLAH

us uf

(continued)

Program 5·8 19 20

i

Chapter 5 looping

268

II Set the numeric output formatting. cout « fixed « Showpoint « setprecision(2); do

23 24

{

30 31

32 33 34 35

36 37 38

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

II Respond to the user's menu selection .

41

switch (choice)

42 43

{

50 51 52

53 54 55 56 57

58 59 60

Ha

case 3: cout «

"For how many months? "; months; charges = months * SENIOR; cout « "The total charges are $" « charges « endl, break, cin »

uh a

61

case 2: cout « "For how many months? "; cin » months; charges - months * CHILD; cout « "The total charges are $" « charges « endl; break;

ad

""

m

46 47

"For how many months? ";

cin » months; charges = months * ADULT; cout « "The total charges are $" « charges « endl, break;

m

45

case 1 : cout «

ss

40

44

az

29

"\n\t\tHealth Club Membership Menu\n\n"; "1. Standard Adult Membership\n";

Ri

27 2B

1/ Display the menu and get a choice . cout « cout «

an

25 26

Yo

21 22

62

63 64 65

M

66

61 68

case 4 : cout «

"Program ending. \n" ,

To Read Online & Download: WWW.ISSUU.COM/SHEIKHUHASSAN


Bismillah hiir Rehman nir Raheem-----------------------------Assalat o Wasalam o Alika Ya RasoolALLAH

269

69

us uf

i

5.5 The do-while Loop

break;

70

}

71 72

}

73 74

return 0; )

Yo

75

while (choice 1= 4);

Program Output with Example Input Shown In Bold Health Club Membership Menu

Ri

az

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

an

Health club Membership Menu 1. Standard Adult Membership

Program ending.

Checkpoint 5.5

What will the following program segments d isplay? A)

ad

~

Ha

Enter your choice: 4 [Enter]

ss

2 . Child Membership 3 . Senior Citizen Membership 4 . Quit the Program

int count

~

10;

do

m

cout «

"Hello World\n":

while (count++ < 1);

M

uh a

m

B) int v = 0: do cout « v++; while (v < 5); C) lnt count ~ 0, funny do

1, serious = 0, l imit -

4;

{

funny+ +; serious +- 2 ; } while (count++ < limit); cout « funny « " .. « ser ious « cout « count « endl;

.. ";

To Read Online & Download: WWW.ISSUU.COM/SHEIKHUHASSAN


Bismillah hiir Rehman nir Raheem-----------------------------Assalat o Wasalam o Alika Ya RasoolALLAH

270

looping

us uf

i

Chapter 5

The for Loop

Yo

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.

az

The for Loop

Ri

-

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.

an

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.

ss

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 a single statement:

Ha

COli nt-controlled

for (initialization ; test ; update)

ad

statement ,.

J

The format of the for loop when it is used to repeat a block is

for (initialization; test,路 update)

m

{

M

uh a

m

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

To Read Online & Download: WWW.ISSUU.COM/SHEIKHUHASSAN


Bismillah hiir Rehman nir Raheem-----------------------------Assalat o Wasalam o Alika Ya RasoolALLAH

271

i

5.6 The for Loop

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'"

us uf

expression. Ir executes at the end of each iteration. Typica lly, this is a statemenr that increments the loop's counter variab le.

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.

!

Yo

Ri

Step 1: Perform the initialization expression.

az

Figure 5-7

1,

Step 2: Evaluate the test expression . If it is true, go 10 Slep 3.

1

Otherwise, terminate the loop.

an

for (count'" 1; count <'" 5; count++) cout « "Hello" « end l ;

1-

Step 3: Execute the body of the lOOp.

Ha

ss

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

ad

j

Assign 1 to

M

uh a

m

m

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

To Read Online & Download: WWW.ISSUU.COM/SHEIKHUHASSAN


Bismillah hiir Rehman nir Raheem-----------------------------Assalat o Wasalam o Alika Ya RasoolALLAH

272

Looping

i

Chapter 5

us uf

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;

1 2 3 4 5 6 7

a

Yo

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: 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

az

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.

{

,

ss

iot nurn;

cout «

10 11

12 13 14 15 16

an

int main()

"Number Number Squared\n" ; "-- - - -- ---- --------- ------\n" i

cout «

Ha

4 5 6 7 8

II This program displays the numbers 1 through 10 and II their squares. jinclude <iostream> using namespace stdi

for (nurn = 1; num <~ 10; num++) cout « num « "\t\t" « (num '" nurn) « return 0; )

Program Output

4

5 6 7

1

m

1 2 3

Number Squared

, 4

16

m

Number

25 36

"64

9

81

10

100

uh a

8

M

endl;

ad

1 2 ]

Ri

Program 5 -9

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

To Read Online & Download: WWW.ISSUU.COM/SHEIKHUHASSAN


Bismillah hiir Rehman nir Raheem-----------------------------Assalat o Wasalam o Alika Ya RasoolALLAH 5.6 The f or Loop

Step 1: Perlorm the initialization expression.

I

j for ( n um COllt

«

l; n urn <= lO ; nurn++) num « "\t\t" « l <num * num) «endl ; _

Yo

Step 2: Evaluate the test expression. It it is true, go to Step 3. Otherwise, terminate the loop.

us uf

i

Figure 5·9

2 73

Step 3 : Execute the body of the loop.

az

Step 4: Perform the update expression, then go back to Step 2.

Ri

Figure S-10

j Assign 1 to

Display num and num * nurn

Increment

nurn

ad

False

True

Ha

num <'" 10

ss

an

nurn

Using the :for Loop Instead of while or do- while

m

m

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.

uh a

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

M

Program 5-9 each have initialization, test) and update expressions.

To Read Online & Download: WWW.ISSUU.COM/SHEIKHUHASSAN


Bismillah hiir Rehman nir Raheem-----------------------------Assalat o Wasalam o Alika Ya RasoolALLAH Chapter S looping

2 74

us uf

i

Figure 5-11 Initialization expression Test expression

int nuro ~ 1; ~ while (nurn <= 10) {

cout «

"

nurn «

(nurn '* nurn) «

"\t\t" «

num++ ;

)

Yo

/

endl ;

t ,.,

for (nurn '"'

t

t

nurn <- 10; nurn ++) num « "\t\t" « (nurn

nurn) «

endl;

an

cout «

Update expression

Ri

Initialization Test expression expression

az

Update expression

The for Loop Is a Pretest Loop

Ha

ss

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;

ad

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.

m

Avoid Modifying the Counter Variable in the Body of the for Loop

m

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 :

uh a

when

for (x = 1; x <= 10; x++)

M

{

cout « X++i

x «

endl;

/ / wrong !

To Read Online & Download: WWW.ISSUU.COM/SHEIKHUHASSAN


Bismillah hiir Rehman nir Raheem-----------------------------Assalat o Wasalam o Alika Ya RasoolALLAH 5.6 The for loop

us uf

i

Other Forms of the Update Expression

275

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; [0

0:

Yo

And here is a loop that countS backward from 10 down for (oum ~ 10j num >= OJ num--) cout « num « endl ;

az

Defining a Variable in the for Loop's Initialization Expression

Ri

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;

an

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.

Ha

ss

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. <a 10;

count++)

count «

endlj

II ERROR!

ad

for (int count - 1; count cout « count « endl; cout « '·count is now ·· «

Creating a User Controlled for Loop

m

m

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.

uh a

Program 5-10 1

1/ This program demonstrates a user controlled for loop .

2 tinc l ude <iostream>

3

using namespace std;

5 6

i nt main()

M

• 7

{

int num;

II Loop counter variable (program conrinues)

To Read Online & Download: WWW.ISSUU.COM/SHEIKHUHASSAN


Bismillah hiir Rehman nir Raheem-----------------------------Assalat o Wasalam o Alika Ya RasoolALLAH Chapter 5 looping

Program 5-10

int maxValue;

II Max imum value to di splay

i

S

(continued)

us uf

276

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

,.15

cout «

"\nNumber

cout «

"-------------------------\n";

17 18 19

for (num : 1; num <= maxValue; num++) cout « num « "\t\t" « (num * num) «

20

return 0 ; )

2

1

1 4

3

9

4

,.

5

25

an

Number Squared

ss

Number

Ri

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]

endl;

az

2l

Number Squa r ed \n";

Yo

14

Ha

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;

ad

The for loop's rest expression then uses this value as rhe upper limit for [he control varia ble:

m

for (nurn = Ii nurn <= maxValue; num++)

In this loop, the nurn variable takes on the values 1 through maxvalue, and then the loop

m

terminates.

uh a

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

M

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

= 1;

x <= 5; x++)

I

To Read Online & Download: WWW.ISSUU.COM/SHEIKHUHASSAN


Bismillah hiir Rehman nir Raheem-----------------------------Assalat o Wasalam o Alika Ya RasoolALLAH 5.6 The for loop

«

x « " plus " « y " equals" « (x + y) endl;

i

«

us uf

cout «

This loop's initialization expression is =

1, Y "" 1

Yo

x

277

This initializes twO variables, x and y. The o utput produced by this loop is

3 plus 1 equals 4 plus 1 equals 5 5 plus 1 equals 6

two

int x, y;

Ix

=

{

cout

" « « «

Y

E

1; x <= 5; x++, y++)

x « .. plus equals " « endl;

)

ss

The loop's updare expression is

«y (x + y)

an

for

statements in the update expression. Here

Ri

We can further mod ify the loop to execute is an example;

az

1 plus 1 equals 2 2 plus 1 equals 3

x++, y++

Ha

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

ad

4 plus 4 equals 8 5 plus 5 equals 10

m

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

m

I I operatOrs.

uh a

Omitting the for Loop's Expressions

M

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;

To Read Online & Download: WWW.ISSUU.COM/SHEIKHUHASSAN


Bismillah hiir Rehman nir Raheem-----------------------------Assalat o Wasalam o Alika Ya RasoolALLAH Chapter 5 looping

i

278

us uf

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++; }

Yo

{

az

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";

an

Ri

Because chis loop has no way of scopping, it will display "Hello World\n" forever (or until something interrupts the program) .

,

ss

.In the Spotlight: Designing a Count-Controlled Loop with the for Statement

Ha

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:

ad

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';

M

uh a

m

m

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.

To Read Online & Download: WWW.ISSUU.COM/SHEIKHUHASSAN


Bismillah hiir Rehman nir Raheem-----------------------------Assalat o Wasalam o Alika Ya RasoolALLAH 5.6 Th.e for Loop

279

us uf

i

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.

8 (

II To hold speeds in kph II To ·hold s~eeds in mph

int kphi double mph;

9 ·10

11 12

"

II Display the table headings. « "KPB\tMPH\n";

16

cout cout

17

\"

"--------------\n·';

II Display the speeds. for (kph = 60 ; kph .<= 130; '-kph +=

2.0 21

{

22

II Calculate mph

2~

mph

0 . 6214;

II Displ ay the speeds in kph and mph. cout « kph « ' ·\t ·, « mph « endl;

25

26 27

} return 0;

ad

28 .29 .]{)

}

MPH

--------------

m

37.3 43 . 5 49.7 55 . 9

62 . 1

uh a

60 70 80 90 100 110 120 130

m

Program Output KPH

Ha

= kph *

.24

~O)

ss

Ig

«

an

1S

Ri

II Set the numeric out'put fOl:::matting. _ cout « fixed « showpoint « setpre:ci~i0n,<I);

l3

az

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 '<iomanip> 5 using namespace std; 6 7 int main( l

Yo

Program 5-11

M

6S . 4 74 .6 SO.8

To Read Online & Download: WWW.ISSUU.COM/SHEIKHUHASSAN


Bismillah hiir Rehman nir Raheem-----------------------------Assalat o Wasalam o Alika Ya RasoolALLAH

~

looping

i

Chapter 5

Checkpoint 5 .6

us uf

280

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 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

Yo

t hat you w ill use a counrer variable named c ount.

az

W hat will the fo llowing progra m segments displ ay? A) for (iot count: 0 ; count < 6 ; count ++) cout « (count + count);

Ri

B) for (i nt value = - 5; value < 5 ; v alue++) cout « va l ue ; C) iot x; for ( x -

5; x <c 14 ; x += 3)

an

cout « X « endl ; cout « x « endl ;

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.

Ha

ss

5.9

Keeping a Running Total CONCEPT: A nHltting total is a s um of n umbe rs that accumulates w ith each itera ti on

ad

of a loop. T he var iable used to keep the running rotal is called an accumulator.

m

m

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.

M

uh a

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.

To Read Online & Download: WWW.ISSUU.COM/SHEIKHUHASSAN


Bismillah hiir Rehman nir Raheem-----------------------------Assalat o Wasalam o Alika Ya RasoolALLAH 281

5.7 Keeping a Running Total

i

Logic for calculating a running total

us uf

Figure 5 -12

Yes (True)

Read the number

Add the number to the accumulator

Ri

Is there a number to read?

az

Yo

Set accumulator to 0

an

No

ss

(False)

Ha

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 com-

ad

pany'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

] 4

'include <iostream> ' include <iomanip> using names pace std;

uh a

5 6

II This program takes daily sales figures over a period of time II and calculates their total .

m

1 2

m

Program 5-12

7 8

9 10

intmain() {

int days; double total

= 0 . 0;

II Number of days If Accumulator , initialized with 0

II Get the number of days.

13

cout. ÂŤ

M

11 12

"For how many days do you have sales; figures? ";

(program cominues)

To Read Online & Download: WWW.ISSUU.COM/SHEIKHUHASSAN


Bismillah hiir Rehman nir Raheem-----------------------------Assalat o Wasalam o Alika Ya RasoolALLAH Chapter 5 Looping

Program 5·12 ci n »

14

i

(continued)

days;

15

,.

II Get the sales for each day and accumulate a total . for (int count ~ 1 ; count <= day s ; count++)

16 17

{ double sales;

20

cout «

11

cin »

total +.. sales ;

22

M

«

count «

" : ";

1/ Ac cumulate t he running total .

)

1/ Display the t otal sales. fixed « showpoint «

25 26

cout « cout «

27

az

23 24

setprecision(2);

"The total sales are S " «

total «

endl;

retur n 0 ; )

Program Output with Example Input Shown In Bold

Ri

28 29

"Enter t he sales f or day

sa les;

Yo

19

us uf

282

Enter the sal es f o r

day

4,

an

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] $1;2. )7 [lEnte r)

The total sales are $2448 . 15

ss

Enter the sales for day 5 ; 506.92 (Enter)

Ha

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.

ad

In the loop's initia lization express ion, in line 17, the variable count is defined and ini tial-

m

ized 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.

M

uh a

m

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 .

To Read Online & Download: WWW.ISSUU.COM/SHEIKHUHASSAN


Bismillah hiir Rehman nir Raheem-----------------------------Assalat o Wasalam o Alika Ya RasoolALLAH 5.8 Sentinels

us uf

i

283

Sentinels

C ONC EPT: A sentinel is a special va lue that marks the eo d of a list o f values. to

know in advan ce the number

Yo

Program 5-12, in the previous section, requi res the lIser

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.

Ri

az

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.

an

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

ss

5 6 7 8 9 10

1/ enters a series of point values , then -1 when finished. 'include <iostream> using namespace std; int main() {

int game - 1, pOints, total = 0;

II Game counter II To hold a number of points II Accumulator

ad

11

Ha

3 4

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;

16 17

m

{

20

total += points; game++ ; cout « "Enter the points for game" « ein » points;

uh a

21

22 23

24

I

25

cout « "\nThe total points are" « return 0 ;

26

M

";

while (points 1= -1)

IS 19

27

M.

m

13 14 15

game «

total «

": ";

endl;

)

(program output continues)

To Read Online & Download: WWW.ISSUU.COM/SHEIKHUHASSAN


Bismillah hiir Rehman nir Raheem-----------------------------Assalat o Wasalam o Alika Ya RasoolALLAH 284

Chapter 5 looping

Program 5- 13

us uf

i

(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]

Yo

"

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]

az

The total pOints are 34

an

Ri

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.

ss

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

Ha

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.

8

m

7 3 9 12

ad

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.

m

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.

uh a

Program 5-14

1

II This program displays five numbers in a file.

2 3

'include <iostream> ' include <f stream> using namespace std;

M

4

5 6 7

a

int main( l {

ifstream inputFilei

II File stream object

To Read Online & Download: WWW.ISSUU.COM/SHEIKHUHASSAN


Bismillah hiir Rehman nir Raheem-----------------------------Assalat o Wasalam o Alika Ya RasoolALLAH 5.9 Using a l oop to Read Data from a File

II To hold a value from the f ile

int count'" 1:

II Loop counter , initialized with 1

11

cout « else

14 15 16 17 18 19 20

"Error opening file . \n";

{

whi l e (count <= 5) {

/1 Read a number.

inputFile » number ; cout « number « endl:

II Display the number. /1 Inc~ement the counter.

count++;

21

az

)

II Close the file.

i nputFile.c l ose(); )

return 0 :

Ri

22 23 2. 25 26

II Open the file. II Test for errors.

inputFile . open("nurnbers.txt"Ji if (!inputFile)

13

Yo

12

i

int numberi

us uf

9 10

28'

)

ss

an

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.

Ha

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)

{

) {

endl;

m

else

ad

1/ Data was successfully read fr om the f il e. cout « "The data read from the file is " « number «

1/ No data was read from the file, COUt ~~ "Could nolo road an item f rom the f ile. \ n" ;

m

)

uh a

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)

M

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.

To Read Online & Download: WWW.ISSUU.COM/SHEIKHUHASSAN


Bismillah hiir Rehman nir Raheem-----------------------------Assalat o Wasalam o Alika Ya RasoolALLAH 286

Chapter 5 Looping

while (inputFile »

us uf

i

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: number)

{

cout «

number «

endl:

)

Yo

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 .

az

Program 5-15

1/ This pr ogram displays all of the numbers in a file . 'include <iostre arn>

3

'include <fstream>

4

using narnespace std;

Ri

1 2

5

intmain()

7

{

8

ifstream inputFile ;

g

lnt number:

II File stream object II To hold a v alue from the file

an

6

10

ss

inputFile. open ( "n umbers. txt" ) ; II Open the file. inputFile) II Test for errors. cout « "Error opening file. \n"; else

11

12

13 14 15

Ha

i f (I

16

while (inputFile »

17 18

{

19 20

}

cout «

end1;

II Re ad a number

II Display the number. II Close the file.

ad

inputFi1e.c1ose{ )i

21 22

return 0; )

m

23

number «

number)

m

~ Checkpoint 5.12

M

uh a

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;

To Read Online & Download: WWW.ISSUU.COM/SHEIKHUHASSAN


Bismillah hiir Rehman nir Raheem-----------------------------Assalat o Wasalam o Alika Ya RasoolALLAH 5.11 Neted l OOpS

287

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:

us uf

i

5.14

Yo

ifstream inputFilei input File . open ( "values. txt" ) ;

az

Write a loop that reads each number from the file and displays each number on the screen .

Ri

Focus on Software Engineering: Deciding Which Loop to Use

an

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.

ss

uh a

m

m

Ha

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.

ad

Nested Loops

M

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

To Read Online & Download: WWW.ISSUU.COM/SHEIKHUHASSAN


Bismillah hiir Rehman nir Raheem-----------------------------Assalat o Wasalam o Alika Ya RasoolALLAH 288

Chapter 5 l ooping

us uf

i

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: fixed «

couto fill( '0') i

for (int seconds cout «

right ;

= 0;

s e tw{2) «

seco nds < 60; seconds++ ) seconds «

end1;

Yo

cout «

az

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

Ri

th rough 60 minutes:

cout « fixed « right; cout.fill( ' O' ) ; for ( int minu t es = 0; minutes < 60; minutes++)

an

{

for (int seconds = 0 ; seconds < 60; seco nds++ ) {

minutes « seconds «

setw( 2 ) « setw( 2 ) «

ss

cout « cout « }

endl ;

Ha

}

.

. .

" . "

To make the simulated dock complete, an o ther va riable and loop can be added the hou rs:

to

{

ad

cou t « fixed « right ; cout . fi ll ( '0' I; for (int hours = 0 ; hours < 24 ; hours++) for (int minutes {

=

m

f or (int seconds

0 ; minutes < 60 ; minutes++ ) =

0 ; seconds < 60; seconds++)

m

{

cout « cout « cout «

setw(2) « setw(2) « setw( 2) «

hours « " :" ; minutes « ":"; seconds « end l;

}

uh a

}

}

The output of the previous program segment follows:

M

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 Read Online & Download: WWW.ISSUU.COM/SHEIKHUHASSAN

count


Bismillah hiir Rehman nir Raheem-----------------------------Assalat o Wasalam o Alika Ya RasoolALLAH 289

5.11 Nested l oops

us uf

i

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.

Yo

• • •

az

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.

1

Ri

Program 5-16

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 <iostream> 4 'include <iomanip> 5 using namespace std ; 6 7 int main( 1

ss

an

2

8 (

int numStudents, numTests ; double total , average;

13

22

23 24 25

ad

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;

m

17

18 19 20 21

Number of students Number of tests per student Accumulator for total scores Average test score

II Get the number of test scores per student . cout« "How many test scores does each student have? "i cin » numTests;

m

14 IS 16

II II II II

Ha

9 10 11 12

27

II Determine each student's average score . for (int stude nt : 1; student <= n umStude nts; student++)

28

{

uh a

26

2'30

31

M

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)

To Read Online & Download: WWW.ISSUU.COM/SHEIKHUHASSAN


Bismillah hiir Rehman nir Raheem-----------------------------Assalat o Wasalam o Alika Ya RasoolALLAH Chapter 5

Looping

Program 5- 16

i

(continved)

score; total += score;

35 36

cin » )

average = total I numTests; cout « "The average score for student " « cout « " is " « average « ".\n\o";

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)

Enter score 3 for student 1 : 97 [Enter]

The average score for student 1 is 86 . 7.

,,

92 [Enter]

Enter score 2 for student 2 , 88 [Enter] Enter score 3 for s tudent 2 , 94 [Enter]

, is

9 1. 3.

ss

The average score for student

an

Enter score 1 for student.

Ri

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]

az

40 41 42 43 }

Yo

37

38 39

us uf

290

Ha

Breaking Out of a Loop

CONCEPT: T he break statement causes a loop to terminate early.

ad

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.

m

CD

uh a

m

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.

M

The while loop in rhe following program segment appears break. statement causes it to StOp after the fifth iteration.

[Q

execure 10 rimes, bur [he

int count'" 0; while (count++ < 10) {

cout « count « if (count == 5) break;

endli

)

To Read Online & Download: WWW.ISSUU.COM/SHEIKHUHASSAN


Bismillah hiir Rehman nir Raheem-----------------------------Assalat o Wasalam o Alika Ya RasoolALLAH 5.12 Breaking Out of a l oop

291

us uf

i

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

7

'include <iostream> iinclud e <cmath> using names pace std; int main() {

double value; char choic e i

9

10 11 12

Ri

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

ss

20 21 22 23 24 25

return 0;

26 27

Yo

,

po~er5

az

4 5 6

II This program raises the user ' s number to the

II of 0 through 10.

an

2 3

Ha

,

}

uh a

m

m

ad

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]

M

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++ )

{

To Read Online & Download: WWW.ISSUU.COM/SHEIKHUHASSAN


Bismillah hiir Rehman nir Raheem-----------------------------Assalat o Wasalam o Alika Ya RasoolALLAH Chapter 5 looping

cout«

·It'j

i

292

us uf

i f (star == 10) break; )

cout «

endl;

)

Yo

The output of the program segment above is:

** •••••••••

........ .. "'** •• * .... _• _

.. " ........ ** •••

az

*_ ... ",,,,.,,* ...

Ri

The continue Statement

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.

ss

CD

an

CONCEPT: The continue statement ca uses a loop to stop its current iteration and begi n the next one.

Ha

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.

ad

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.

m

T he following program segment demonsrrates the lise of continue in a while loop:

int testval = 0;

m

while (testVal++ < 10)

M

uh a

{

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

To Read Online & Download: WWW.ISSUU.COM/SHEIKHUHASSAN


Bismillah hiir Rehman nir Raheem-----------------------------Assalat o Wasalam o Alika Ya RasoolALLAH 5.13 The continue Statement

293

us uf

is used to skip the part of the loop that calculates the charges fo r every third DVO .

.

5 using namespace std ; 6

az

11 12 13

II DVO counter II Number of DVDs rented II Accumulator II Current release, Y or N

Ri

9 10

int main ( ) { int dvdCount = Ii int numDVDs; double total = 0.0; char current;

14

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

{

if ( (dvdCount % 3)

22

{

==

0)

ss

21

an

7

Yo

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 <iostream> 4 iinclude <ioman ip>

cou t « "OVO t" « dvdCount « " is freel\n"; c o ntinue: // Immediately start the next itera tion

23 24 }

Ha

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

ad

31

32 33 34

m

m

II Disp lay the t otal. cout « fixed « showpoint « setprecision(2); cout« '·The total is $" « total « endl: return 0 ;

35

36 37 38

uh a

39 )

M

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=:.>

i

$2.50. If a customer rents severa l OVOs J eve ry th ird o ne is free. The continue statement

Case Stud y on CD: See the Loan Amortization Case Study on the Student CO.

To Read Online & Download: WWW.ISSUU.COM/SHEIKHUHASSAN


Bismillah hiir Rehman nir Raheem-----------------------------Assalat o Wasalam o Alika Ya RasoolALLAH Chapter 5 looping

i

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.

us uf

294

Yo

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 ?

az

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 ?

Ri

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?

an

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?

ss

Fill-in-the-Blank

to _ _ _ _

a val ue mea ns

Ha

11. To a value means to increase it by One, and to decrease it by one.

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

ad

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) _ _ __

m

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.

m

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.

uh a

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.

M

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.

To Read Online & Download: WWW.ISSUU.COM/SHEIKHUHASSAN


Bismillah hiir Rehman nir Raheem-----------------------------Assalat o Wasalam o Alika Ya RasoolALLAH Review Questions and Exercises

295

25. The _____ loop is ideal for situations that require a counter.

us uf

i

24. The -,-_ _ _ and _ _ _ _ loops wi ll not iterate at all if their test expressions are false to start with.

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)

Yo

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.

az

Algorithm Workbench

Ri

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

an

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

ss

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.

Ha

34. Write a nested loop that displays 10 rows of '#' characters. There should be 15 '#' cha racters in each row.

{

ad

35. Convert the following while loop to a do-while loop: int x .. 1 ; while (x > 0) cout « "e nter a number: "; cin » x;

m

)

36. Convert the following do -while loop to a while loop:

m

char sure;

M

uh a

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;

)

To Read Online & Download: WWW.ISSUU.COM/SHEIKHUHASSAN


Bismillah hiir Rehman nir Raheem-----------------------------Assalat o Wasalam o Alika Ya RasoolALLAH Chapter 5

296

Looping

= 50;

us uf

for (int x

i

38. Convert the fo llowing for loop to a while loop: x > OJ x-- )

(

cout «

x «

" seconds to go.\n";

)

True or False F

T he operand of the increment and decrement operarors can be any va lid

Yo

39. T

mathematica l expression.

40. T

F

The cout statement in the following program segment wi ll display 5: iot x - 5 ;

x++;

az

cout «

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-

an

loop's expressions may be omitted.

Ha

ss

for

Ri

41. T

ad

gle iteration of the o uter loop. To calcu late the total number of iterations of a nested loop, add the number of iterations of all the loops.

52. T

F

53. T

F

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.

m

m

The break sta tement causes a loop to stop the current iteration and begin the next one.

uh a

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 .

M

tinclude <iostream>

using namespace stdj

int main ( ) {

int num1

0, num2 : 10, result:

To Read Online & Download: WWW.ISSUU.COM/SHEIKHUHASSAN


Bismillah hiir Rehman nir Raheem-----------------------------Assalat o Wasalam o Alika Ya RasoolALLAH Review Questions and Exercises

i " " «

result;

)

57. II This program adds two numbers entered by the user .

Yo

'include <iostrearn> using narne space std;

us uf

numl++; result'" ++(nurnl + nurn2l; cout « nurnl « " " « num2 « return 0 ;

i nt main ( ) {

az

int nurn l, num2 ; char aga in ;

an

Ri

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 ; }

{

Ha

int main()

ss

58. I I This program uses a loop to ra i se a number to a power. ' i nclude <iostream> us i ng name s pace std ;

int nurn, bigNum, power , count ;

m

m

ad

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:

uh a

59. 1/ This program averages a set of numbers . ' include <iostream> using namespace std: int main() {

M

297

int numCount, total ; double average: cout « "How many numbers do you want to average? " ; cin » numCount ;

To Read Online & Download: WWW.ISSUU.COM/SHEIKHUHASSAN


Bismillah hiir Rehman nir Raheem-----------------------------Assalat o Wasalam o Alika Ya RasoolALLAH

Looping

i

Chapter 5

0; count < numCount; count++)

for (int count

us uf

298

{

int num; cout « "Enter a number : ft;

cin »

num;

total += nurn;

average = total / numCount; cout « "The average is « return 0 ;

average «

endl ;

}

This program displays the sum of two numbers.

az

60. II

Yo

count++; }

Ri

'include <iostream> using namespace std;

int main() {

int choice, numl, num2;

an

do {

cout «

"Enter a number: numl;

cout «

cin »

M;

"Enter another number: ";

ss

cin »

num2;

endl:

Ha

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 return 0 ;

= 1)

ad

61. II This program di splays the sum of the numbers 1-100. 'include <iostream>

m

using namespace std;

iot main() {

uh am

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

M

}

To Read Online & Download: WWW.ISSUU.COM/SHEIKHUHASSAN


Bismillah hiir Rehman nir Raheem-----------------------------Assalat o Wasalam o Alika Ya RasoolALLAH 299

i

Review Questions and Exercises

us uf

Programming Challenges 1. Sum of N umbers

Yo

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.

az

3. Ocean Levels

Ri

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

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.

Ha

Problem

5. Membership Fees Increase

ss

Solving the Calories BlImed

an

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.

6. Distance Traveled

The dista nce a vehicle navels can be calculated as follows: ~

speed * time

ad

distance

For example, if a trai n travels 40 miles per hour for 3 hou rs, the distance traveled is 120 mi les.

m

m

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:

uh a

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

M

I

Input Validation: Do not accept a negative number for speed and do not accept any /Jalue less than 1 for time trafJe/ed.

To Read Online & Download: WWW.ISSUU.COM/SHEIKHUHASSAN


Bismillah hiir Rehman nir Raheem-----------------------------Assalat o Wasalam o Alika Ya RasoolALLAH

Chapter 5 l ooping

i

300

us uf

7. Pennies for Pay

Yo

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

Ri

az

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.

an

Input Validation: If the user selects an item not on the menu, display an error message and display the menu again.

9. Hotel Occupancy

Ha

ss

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.

ad

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

~

m

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.

m

10. Average Rainfall

M

uh a

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.

To Read Online & Download: WWW.ISSUU.COM/SHEIKHUHASSAN


Bismillah hiir Rehman nir Raheem-----------------------------Assalat o Wasalam o Alika Ya RasoolALLAH Review Questions and Exercises

i

301

us uf

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.

Yo

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

Ri

13. The Greatest and Least of These

az

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.

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.

an

14. Student Line Up

A teacher has asked all her studen ts to line up single fi le according to their first name.

Ha

ss

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.

ad

15 . Payroll Report

m

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.

uh a

m

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.

M

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:

To Read Online & Download: WWW.ISSUU.COM/SHEIKHUHASSAN


Bismillah hiir Rehman nir Raheem-----------------------------Assalat o Wasalam o Alika Ya RasoolALLAH

Chapter 5

looping

i

302

us uf

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.

Yo

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

az

~

~ 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_.________________~

Ri

17. Sales Bar Chart

an

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. sales sales sales sales sales

for for for for for

store store store store store

"2,

1000 [Enter] 1200 [Enter]

ss

today's today's today's today's today's

3, 1800 [Enter] 4, 800 [Enter] 5, 1900 [Enter]

Ha

Enter Enter Enter Enter Enter

SALES BAR CHART

..

ad

(Each * ... $100) 1; -~~~芦 **. 2 : ************ 3: ******************

Store Store Store Store Store

4: ******** 5 : *******************

m

18. Population Bar Chart

m

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

uh a

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

M

(each路 represents 1,000

peop~e)

1900 ** 1920 **** 1940 *****

To Read Online & Download: WWW.ISSUU.COM/SHEIKHUHASSAN


Bismillah hiir Rehman nir Raheem-----------------------------Assalat o Wasalam o Alika Ya RasoolALLAH 303

i

Review Questions and Exercises

us uf

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.

Yo

20. Random Number Guessing Game

21. Random Number Guessing Game Enhancement

az

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.

Ri

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

ss

an

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

Ha

xxxxx

xxxxx xxxxx

If the user ente rs 8, [he program should display the follow ing:

ad

xxx xxx xx xxxxxxxx xxxxxxxx xxxxxxxx

m

xxxxxxxx

xxxxxxxx

m

xxxxxxxx xxxxxxxx

23. Panern Displays

M

uh a

Write a program that uses a loop to displa y Pattern A below, fo llowed by another loop that displays Pattern B.

To Read Online & Download: WWW.ISSUU.COM/SHEIKHUHASSAN


Bismillah hiir Rehman nir Raheem-----------------------------Assalat o Wasalam o Alika Ya RasoolALLAH

Pattern B

+

+++++++ +++

++

+++++++++

+++ ++++

++++++++ +++++++

+++++

++++++

++++++

+++++

++++

+++ ++

++++++++ +++++++++ ++++++++++

Yo

Pattern A

us uf

i

Chapter 5 l ooping

304

az

+

24. Using Files-Numeric Processing

A) The number of numbers in the fi le

Ri

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:

an

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

ss

numbers, and t he average of the n umbers.

25 . Using Files-Student Line Up

Ha

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

m

ad

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.

m

Serendipity Booksellers Software Development ProjectPart S: A Problem-Solving Exercise 1. Data Validation Modification

uh a

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.

M

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.

To Read Online & Download: WWW.ISSUU.COM/SHEIKHUHASSAN


Bismillah hiir Rehman nir Raheem-----------------------------Assalat o Wasalam o Alika Ya RasoolALLAH

i

Review Questions and Exercises

us uf

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.

Yo

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.

az

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,

M

uh a

m

m

ad

Ha

ss

an

Ri

add code that asks the cashier if another transaction is to be processed. If so, the program should repeat.

To Read Online & Download: WWW.ISSUU.COM/SHEIKHUHASSAN


M

uh am

m

ad

Ha

ss

an

Ri

az

Yo

us uf

i

Bismillah hiir Rehman nir Raheem-----------------------------Assalat o Wasalam o Alika Ya RasoolALLAH

To Read Online & Download: WWW.ISSUU.COM/SHEIKHUHASSAN


6.1

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

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

an

6.2 6.3 6.4 6.5

6.9

Ri

az

Yo

us uf

i

Bismillah hiir Rehman nir Raheem-----------------------------Assalat o Wasalam o Alika Ya RasoolALLAH

Program The return Statement

6.7 6.8

6.15 The exit ( ) Function 6.16 Stubs and Drivers

ss

6.6

as Parameters

ad

Ha

Returning a Value from a Function

Focus on Software Engineering: Modular Programming

m

CONCEPT: A program may be broken up into manageable fu nctions.

m

A function is a collection of statementS that performs a specific task. $0 far you have experi-

M

uh a

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

To Read Online & Download: WWW.ISSUU.COM/SHEIKHUHASSAN


Bismillah hiir Rehman nir Raheem-----------------------------Assalat o Wasalam o Alika Ya RasoolALLAH 308

Functions

i

Chapter 6

us uf

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.

In this program the problem has been divided into smaller problems, each of which is handled by a separate function.

This program has one long, complex function containing all althe statements necessary to solve a problem .

j

az

j int main ( ) sta tement;

statement ; 3tlltement ; statement; statement;

}

statement; s tatement : statement ;

Ri

int maine) {. statement ; s.tatement: statement:

{

..

main functIon . .

void function2_1) statement; statement; statement;

an

!

statement;

statement ;

function 2

Ha

ss

}

.

v:oid function3() {

statement ; s~,!ltement;

,..

function 3

statement: }

J

void function4 ( ) {

statement; stateme\'Lt; . statement; }

function 4 .

m

ad

statement ; statement ; statement ; statement ; statement; statement; statement; statement ; statement; statement; statement ; statement; statement; statement;

Yo

FI9ure 6 -1

M

uh a

m

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.

To Read Online & Download: WWW.ISSUU.COM/SHEIKHUHASSAN


Bismillah hiir Rehman nir Raheem-----------------------------Assalat o Wasalam o Alika Ya RasoolALLAH 6.2 Defining and Calli ng Functions

us uf

i

309

Defining and Calling Functions

Yo

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: 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.

Ri

az

Return type:

an

Figure 6-2 shows the definition of a simple func tion with the various partS labeled. Figure 6-2

~nt

..

,f

Function body

Ha

...

ss

Return type Parameter list (This one is empty) \ Function name/ main ()

/

cout «

'·Hello World\n";

return 0;

ad

}

The line in the definition that reads int main () is called the functioll header.

m

void Functions

You a lready know that a function can return a va lue. The main func tion in a ll of the proyO ll

m

gra m s

have seen in this book is declared to re turn an int va lue to t he o p er a t ing sys-

uh a

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.

M

void displayMessaqe() {

CQut «

"Hello from the function displayMessage. \n" ;

}

To Read Online & Download: WWW.ISSUU.COM/SHEIKHUHASSAN


Bismillah hiir Rehman nir Raheem-----------------------------Assalat o Wasalam o Alika Ya RasoolALLAH Chapter 6 Functions

i

3 10

us uf

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 .

Yo

Calling a Function

az

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.

] 2 3

Ri

Program 6-1

II This program has two functions: main and displayMessage ' inc lude <iostream> using namespace std i

4 6 7

ff ********************** * ****************** ff Definition of function di splayMessage *

an

5

fl This function d i sp lays a greeting .

void displayMessage() {

13

"

15 I.

17

"Hello from the function displayMessage. \n";

)

/1 ***************************************** II Function main //* ************************ **** ************

18

int main() {

cout « "Hello from main . \ n"; displayMessage(); cout « "Back i n fu nct ion main aga i n. \ n"; return 0 ;

m

21 22 23 24

25

)

m

19 20

Ha

cout «

12

ad

10 II

*

ss

8 9

uh a

Program Output

M

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();

To Read Online & Download: WWW.ISSUU.COM/SHEIKHUHASSAN


Bismillah hiir Rehman nir Raheem-----------------------------Assalat o Wasalam o Alika Ya RasoolALLAH 6.2 Defining and Calling Functions

311

Function Header - - ---+1 void displayMessage() Function Call I displayMessage() ;

us uf

i

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!

Yo

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.

~

az

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

Ri

~ L-J_;s_r_e_d_;_n_s;_d_e_r_h_e_p_a_r_e_n_r_he_s_e_s_._ _ __ _ _ _ _ __ __ _ _ _ _ _ __ _ _ _ _ _--'

ss

an

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.

Ha

~-----------------------~

ad

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.

m

Figure 6-3

void displayMessage ( )

M

uh a

m

(

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

)

To Read Online & Download: WWW.ISSUU.COM/SHEIKHUHASSAN


Bismillah hiir Rehman nir Raheem-----------------------------Assalat o Wasalam o Alika Ya RasoolALLAH 312

Chapter 6

Functions

us uf

i

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. linclude <io stream> using naroespace std;

Yo

2 3 4

/1** *************************************** 1/ Definition of function displayMessage * II This function displays a greeting. *

89 11-----.··_-_·_·_--_·_--------_·-·--_····_· 10

void dispiayMessage()

II

{

Ri

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

II Function main

an

19

20 21

"Hello from the function displayMessage . \n";

ss

,.

cout « }

Ha

12 13 14 15 16 17

az

5 6 7

}

m

m

ad

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

uh a

three functions: main, first , and second.

Program 6 -3

1 II This

program

has three functions: main, first ,

2

'include <iostream>

,

using names pace std;

M

3

and second .

To Read Online & Download: WWW.ISSUU.COM/SHEIKHUHASSAN


Bismillah hiir Rehman nir Raheem-----------------------------Assalat o Wasalam o Alika Ya RasoolALLAH 6.2 Defining and Calling Functions

7

8 9 10

i

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

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'

II**********************************~******

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;

32 33

34

35

Ha

ss

31

36

II Function main

26 27 28 29

an

2,

az

17

II~+~******************************~~~*****

Ri

15

16

us uf

6

Yo

,

313

)

m

ad

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

m

second:

uh a

first() i second ( ) ;

Each call statement causes the program to branch

to

a funct ion and then back

to

M

when the funct ion is finished. Figure 6-4 illustrates the pa ths taken by the program.

To Read Online & Download: WWW.ISSUU.COM/SHEIKHUHASSAN

main


Bismillah hiir Rehman nir Raheem-----------------------------Assalat o Wasalam o Alika Ya RasoolALLAH Chapter 6 Functions

314

void first( ) {

cout «

"I am oow inside eh_ function firs t .\n";

Yo

}

void second( I {

cout «

us uf

i

Figure 6 -4

"I am oow inside the function second.\n";

az

}

(

cout «

"I am starting

first();

second() ;

cout «

"Back

return 0,

function main . \n"

fUnction mo.in again . \n";

an

)

'0

'0

Ri

lnt maine )

Program 6 -4

Ha

ss

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.

1

II This program has t hree functions : main , deep , and deeper

2 3

using namespace std;

'include <iostream>

1/********** * **************·***************

7

II Definition of function deeper II This function displays a message.

8

//*********** * *************************** **

m

cout « )

"I am now inside the fUnction deeper.\n";

11**** ***** *** *** **** ***** ****** * ********** * * 11****** **** ********** *********** **********

uh a

I.

*

void deeper() (

12 13 14 15

*

m

9 10 11

ad

4 5

17

18

II Definition of function deep II This function displays a message .

M

19

To Read Online & Download: WWW.ISSUU.COM/SHEIKHUHASSAN


Bismillah hiir Rehman nir Raheem-----------------------------Assalat o Wasalam o Alika Ya RasoolALLAH 315

void deep() { cout «

23

"I am now inside the function deep. \n"; II call function deeper "Now I am back in deep . \n";

deeper(J: cout «

24

25 26

}

II Function main

29

1/*****************************************

30 31

lnt main()

32

{

Yo

27

2.

cout «

"1 am starting in function main.'n" : deep(); I I Call fu nction deep cout « "Back in function main again. \n": return 0;

az

Ri

33 34 3S 36

us uf

20 21 22

i

6.2 Defining and Calling Functions

37

ss

an

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.

Ha

The paths taken by the program are shown in Figure 6-5 . Figure 6-5

void deep() (

ad

",

cout « "r am now i nside funct.ion deep.\n··; deeper!) ; cout « "Now r am back in deep.\nH;

M

uh a

m

m

}

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 , }

To Read Online & Download: WWW.ISSUU.COM/SHEIKHUHASSAN


Bismillah hiir Rehman nir Raheem-----------------------------Assalat o Wasalam o Alika Ya RasoolALLAH

i

Chapter 6 Functions

3 16

6.1

us uf

~ Checkpoint Is the following a function header or a fu nction call? calcTotal ( ) i [s the following a function header or a funct ion call?

Yo

6.2

void showResults()

What will the output of the fol lowing program be if the user enters 10?

6.3

az

tinclude <iostream> using names pace stdi vo id funcl() (

"Able was I\n";

Ri

cout « )

void func2 ( ) {

cout «

"I saw Elba\n";

an

}

int main( ) {

(

Ha

ss

int input; cout « "Enter a number: " ., cin » input; i f ( input < 10 ) funcl(); func2() ; ) Al!".E"

{

ad

fund ( ) ;

funcl ();

)

return 0 ;

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.

M

uh a

m

6.4

m

)

linclude <iostream> using names pace std;

II You must write definitions for the two functions qualify II and noQualify.

To Read Online & Download: WWW.ISSUU.COM/SHEIKHUHASSAN


Bismillah hiir Rehman nir Raheem-----------------------------Assalat o Wasalam o Alika Ya RasoolALLAH 6.3 Function Prototypes

i

lnt main()

us uf

{

double salary; int years ; cout «

"This program will determine if you qualify\n";

cout «

"for our credit card. \n ";

cout « cout «

"What is your annual salary? ";

salary;

Yo

cout «

cln »

317

"How many years have you worked at your ";

"current job? "; cin » years; if (salary >= 17000.0 && years >= 2) qualify() ;

else

az

noQuality ( ) i

return 0;

Ri

)

Function Prototypes

an

CON C f. PT: A function prorotype eliminates the need ro place a fun ction definition before all calls to the fun ctio n. .

ss

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.

Ha

(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:

ad

void displayMessage();

m

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.

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.

M

uh a

CD

m

~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_.________________~

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.

To Read Online & Download: WWW.ISSUU.COM/SHEIKHUHASSAN


Bismillah hiir Rehman nir Raheem-----------------------------Assalat o Wasalam o Alika Ya RasoolALLAH 3 18

Chapter 6

Functions

II This program has three functions: main, first, and second. 'include <iostream> using namespace std;

1 2

3

/ 1 Function Prototypes

6

void first();

7

void second();

, 9 10

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";

11

12

13 14 15

)

17

void first()

24

(

cout «

25

~I

am now inside the function first.\n";

)

Ha

26 27 28 29

ss

21 22 23

an

1/'* ·** ******** ******** ******** *******' 1/ Definition of function first. * II This function displays a message . * 1/** *** ******* *****·***********········

18 19 20

Ri

return 0;

16

az

5

Yo

4

us uf

i

Program 6-5

1/**** **· · · · · ·******* ***·*·***********· II Definition of function second. * II Th i s function displays a message. •

30 31

II*~~*~ **** *********~* *********~*******

32

void second()

34 3S

(

ad

33

cout «

"1 am now inside the function second. \n";

Program Output

m

36

m

(The program's output is the same as the output of Program 6-3.)

uh a

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

M

'-"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____________________----~

To Read Online & Download: WWW.ISSUU.COM/SHEIKHUHASSAN


Bismillah hiir Rehman nir Raheem-----------------------------Assalat o Wasalam o Alika Ya RasoolALLAH 6.4 Sending Data jn to a Function

us uf

i

319

Sending Data into a Function

Yo

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:

az

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 " «

Ri

Functions and Arguments

nurn «

endl;

an

)

ss

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

Ha

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.

ad

Program 6·6

II This program demonstrates a function with a parameter.

'include <iostream> using names pace std ;

5 6

II Function Prototype void displayvalue(int);

7

8

intmo.in() {

uh a

9 10

m

, 3

m

1

2

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

M

14 15

)

(program continues)

To Read Online & Download: WWW.ISSUU.COM/SHEIKHUHASSAN


Bismillah hiir Rehman nir Raheem-----------------------------Assalat o Wasalam o Alika Ya RasoolALLAH Chapter 6 Functions

i

(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 «

--**-

Yo

I

Program 6-6

us uf

320

endl;

)

Program Output

Ri

az

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

an

its data type is required . The function prototype shown above cou ld optionally have been written as:

ss

void displayValue(int nurn);

However, the compiler ignores the name of the parameter variable in the fUllction prototype.

Ha

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

ad

.'.. ...'..

M

uh a

m

m

~

'~

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.

To Read Online & Download: WWW.ISSUU.COM/SHEIKHUHASSAN


Bismillah hiir Rehman nir Raheem-----------------------------Assalat o Wasalam o Alika Ya RasoolALLAH

6.4 Sending Da ta into a Function

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 ;

12

13

I.

15

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 **** **** *** *********** ************ **** ***** ***** *** * *****

an

16 17 IS

Ri

az

10 11

void displayValue ( int num) { cout « "The v alue is " «

ss

Yo

3

II This program demonstrates a function with a parameter. finclude <iostream> using namespace std;

num «

endl ;

Ha

1 2

us uf

i

321

)

WARNING ! When passing a variable as an argument, simply write the variable name

m

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:

uh a

CD

m

ad

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 .

displayValue(int x); II Error!

The functio n call should appear as

M

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);

To Read Online & Download: WWW.ISSUU.COM/SHEIKHUHASSAN


Bismillah hiir Rehman nir Raheem-----------------------------Assalat o Wasalam o Alika Ya RasoolALLAH

32

Functions

us uf

i

Chapter 6

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

Yo

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/ This program demonstrates a function with three parameters.

2

'include <iostream>

3

using names pace stdj

az

1

/1 Function Prototype void showSum(int, int, intI;

7 8 9

iot main() (

10

Ri

4

5 6

iot valuel, value2, value3;

an

11

12

II Get three integers. cout « "Enter three integers a nd I will display "i cout « "their sum: "; cin » va1ue1 » value2 » va1ue3;

ss

13 14 15 16

Ha

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 .

25

ad

24

II It uses three integer parameters . Thei r sum is displayed . • //

...•......•.•.••••••••••.•.•.•..........................••.•

26

void showsum(int numl, int num2, int num3)

28

{

"

)

cout «

(num1 + num2 + num3) «

endl;

m

30

m

27

Program Output with Example Input Shown In Bold

uh a

Enter three integers and I will display their sum: 487 [Enter] 19

M

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)

To Read Online & Download: WWW.ISSUU.COM/SHEIKHUHASSAN


Bismillah hiir Rehman nir Raheem-----------------------------Assalat o Wasalam o Alika Ya RasoolALLAH

323

CD

us uf

i

6.4 Sending Data into a Function

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:

Yo

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

az

In the funct ion call in line 18, the variables valuel, value2 , and value3 are pa ssed as arguments:

Ri

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.

an

Figure 6-7

ss

Function Call ---.- showSum(value 1, value2, value3)

I r

Ha

void showSum(int n! ml, int num2 , int num3) (

eout ÂŤ

(numl + num2 + num3) ÂŤ endl ;

}

ad

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:

m

showSum(5, 10, 15) ;

m

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

uh a

~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

M

~ 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'_.________________________________________~

To Read Online & Download: WWW.ISSUU.COM/SHEIKHUHASSAN


Bismillah hiir Rehman nir Raheem-----------------------------Assalat o Wasalam o Alika Ya RasoolALLAH

32

Functions

us uf

i

Chapter 6

Passing Data by Value

Yo

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

az

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

Ri

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 <iostream> using namespace std i

7 8 9 10

II Function Prototype void changeMe(int) i int main() (

11 12 13 14

int number

= 12;

ss

5 6

Ha

3 4

an

2 II

II Display the value in number . cout « "number is " « number «

endl ;

II II

16

Cal l changeMe, passing the value in number as an argument . changeMe(number)i

17

18

m

19

)

uh a

25 26 27 29

m

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

ad

15

29

II·· ················ •••••• • ••••••••••••••••••••••••••• •••••••••• II Definition of function changeMe. • II This function changes the v alue of the parameter myValue . • II •• •••••••••••••••••••••••••••••••••••••••••••••••••• ••••••••••

M

30

To Read Online & Download: WWW.ISSUU.COM/SHEIKHUHASSAN


Bismillah hiir Rehman nir Raheem-----------------------------Assalat o Wasalam o Alika Ya RasoolALLAH

325

31

void changeMe(int myValue)

32

{

us uf

i

6.5 Passing Data by Value

II Change the value of myvalue to O. myValue ~ 0 ;

33 34

II Display the value in myvalue . cout « "Now the value is " « myValue «

38

endl;

}

az

Program Output number is 12 Now the value is 0 Now back in main again, the value of number is 12

Yo

35

36 37

Ri

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.

an

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.

ss

Figure 6-8 illustrates that a pa rameter variable's storage location in memory is se parate from that of the original argument.

Ha

Figure 6-8

Original Argument

(in its memory location)

I~ Function Parameter (in its memory location)

12

m

m

ad

12

M

uh a

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_ ~_.__________________________________________________________~

To Read Online & Download: WWW.ISSUU.COM/SHEIKHUHASSAN


Bismillah hiir Rehman nir Raheem-----------------------------Assalat o Wasalam o Alika Ya RasoolALLAH

32

Functions

us uf

i

Chapter 6

Focus on Software Engineering: Using Functions in a Menu-Driven Program

In Chapters 4 and 5

YOll

Yo

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.

saw a menu-driven program that calculates the charges for a

az

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.

Ri

Program 6-10

II This is a menu-driven program that makes a function call II for each selection the user makes.

3

'include <iostream>

4

'include <iomanip>

5 6 7 8

using namespace std;

11

int main ( )

12 13

{

17

18 19

int choice; II Constants const doub l e const double const double

20

25

26 27

SENIOR

CHILD

--

30.0; 20.0;

do {

m

II Set up numeric output formatting. cout « fixed « showpoint « setprecision(2):

II Display the menu and get the user's choice . showMenu(): cin » choice;

uh a

28

for membership rates ADULT = 40.0;

m

21 22 23 24

II To hold a menu choice II To hold a number of months

int months;

ad

15 16

Ha

void showFees(double, i nt I;

ss

II Function prototypes void shoWMenU()i

9 10

14

an

1 2

M

"

To Read Online & Download: WWW.ISSUU.COM/SHEIKHUHASSAN


Bismillah hiir Rehman nir Raheem-----------------------------Assalat o Wasalam o Alika Ya RasoolALLAH

327

30

II Validate the menu selection.

31

while (choice < 1

32

{

cout «

cin »

"Please enter 1, 2, 3, or 4 : ";

choice;

35 36

}

37

if (choice 1= 4)

38 39

{

41

42 43 44 46 47

48 49 50 51

case 2 :

showFeeS(CHILD , months); break:

case 3 :

showFees(SENIOR, months);

an

45

Ri

II Display the membership fees. switch (choice) { case 1: showFees(ADULT, months); break;

}

52 53

} while (choice 1=

54

return 0;

az

II Get the number of months. cout « "For how many months? "i cin » months;

40

}

q)j

ss

55

choice> 4)

Yo

33

34

II

us uf

i

6.6 Focus on Software Engineering: Using Functions in a Menu-Driven Program

)

56

1/************************** ************************** ***** •• ****** II Definition of function showMenu which displays the menu. •

60 61

void showMenu()

{

"71

)

72 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 **************************************************** *************

uh a

73

"\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: " ,

m

70

« « « « « «

ad

cout cout cout cout cout cout

64 65 66 67 68

m

62 63

Ha

57 58

77

void showFees(double memberRate, int months)

78

{

M

79 80

81

cout « «

"The total charges are $" (memberRate * months) « endl;

} (program output continues)

To Read Online & Download: WWW.ISSUU.COM/SHEIKHUHASSAN


Bismillah hiir Rehman nir Raheem-----------------------------Assalat o Wasalam o Alika Ya RasoolALLAH

Functions

Program 6- 1 0

i

Chapter 6

(continued)

us uf

32

Program Output with Example Input Shown In Bold Health Club Membership Menu

Yo

1. Standard Adult Membership 2. Child Membership 3. senior Citizen Members hip 4. Quit the Program Enter your choice : 1 [Enter]

az

For how many months? 12 [Enter]

The total charges are $480.00

Ri

Health Club Membershi p Menu 1 . Standard Adult Membership 2. Child Membership

3. Senior Citizen Membership

an

4 . Quit the Program Enter your choice: 4 [Enter]

ss

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

Ha

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,

m

ad

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.

M

uh a

m

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.

To Read Online & Download: WWW.ISSUU.COM/SHEIKHUHASSAN


Bismillah hiir Rehman nir Raheem-----------------------------Assalat o Wasalam o Alika Ya RasoolALLAH

6.6 Focus on Sohware Engineering: Using Functions in a M enu-Driven Program

i us uf

~ Checkpoint 6.5

329

Ind ica te w hich of the foHowing is the function prototype, the function header, and the function call:

Yo

vo id showNum(double num) void showNum(double) i showNum(45 .67 );

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

az

6.6

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

Ri

is the o urput o f the following program?

'include <iostream> using namespace std;

an

void showOouble(int); II Function prototype

i nt main{) {

ss

i nt num ;

Ha

for (num : 0; nurn < 10: num++) s howDOuble(num ); return 0: )

II De£inition o f function showDouble. void showDouble(int value) {

6.9

value «

ad

cout «

)

" \t" «

(value '" 2) «

endl;

m

What is the o utp ut of the. following program?

m

'include <iostream> us ing namespace s td;

void funCl(double, intI : II Function prototype

M

uh a

int mai n() {

lo t x '" 0 ; double y '" 1 . 5;

cout «

x «

funcl(y, x) ; cout « x « " return O·,

«

y «

end1;

«

y

«

endl;

)

To Read Online & Download: WWW.ISSUU.COM/SHEIKHUHASSAN


Bismillah hiir Rehman nir Raheem-----------------------------Assalat o Wasalam o Alika Ya RasoolALLAH

Functions

i

Chapter 6

33

us uf

void funcl(double a, int b) (

cout « a « a = 0.0; b = 10;

cout «

a «

.. " «

b «

endl;

.. " «

b" «

endl;

Yo

)

The follow ing program skeleton asks for the number of hou( ~ you 've worked and your hourly pay rate. Jt then calculates and displays your wages. The funct ion showDollars, which you are to write, fo rma ts the output of the wages.

6. 10

az

linclude <iostream> using namespace std;

Ri

void showDollars(double) ; II Function prototype

int main() (

double payRate, hoursWorked, wages;

return 0;

Ha

)

ss

showDollars(wageS)i

an

cout « "How many hours have you worked? cin » hoursWorkedi cout « "What is your hourly pay rate? "; cin » payRatei wages m hoursWorked * payRate;

II You must write the definition of the function showDollars

ad

II here. It should take one parameter of the type double . II The function should display the message "Your wages are $n II fol l owed by the va l ue of the parameter . It should be d i splayed II with 2 p l aces of precision after t he decimal point, in fixQd II notation, and the decimal point should always display .

m

The return Statement lO

end immediately.

m

CONCEPT: T he r e turn sta tement ca uses a fu nction

When the last statemellt in a void fun ct ion has fin ished executing, the function terminates

uh a

and the program returns to the statement following the function ca ll. It's possible, however, to force a function to return before the last statement has been executed. When the return statement is encountered, the function immediately terminates and cOlltrol of the

M

program returns to the statement that called the function. This is demonstrated in Program 6-1 1. The function divide shows the quotient of argl divided by arg2. If arg2 IS set to zero, the function returns.

To Read Online & Download: WWW.ISSUU.COM/SHEIKHUHASSAN


Bismillah hiir Rehman nir Raheem-----------------------------Assalat o Wasalam o Alika Ya RasoolALLAH

6.7 The return Statement

i

'include <iostream>

4

using namespace std;

5 6 7

// Function prototype. void divide(double, double);

B 9

int main ()

Yo

II This program uses a function to perform division. If division // by zero is detected, the function returns.

3

{

az

double numl, num2i cout « "Enter two numbers and I will divide the first\n"; cout « "number by the second number : "; cin » numl » num2; divide(num1 , num2); return 0;

13 14 15

16 17

Ri

10 11 12

us uf

Program 6 -11

2

)

20 21

11**************************************************** *********** /1 Definition of function divide . * // Uses two parameters: argl and arg2. The function divides argl* II by arg2 and shows the result . If arg2 is zero, however, the * // function returns . * //********************************** • •••••••• ****.**** ***********

25 26

ss

24

an

18 19

22 'l

void div i de(double argl, double arg2)

28

{

29

if (arg2

30 31

{

=~

0 . 0)

Ha

27

33

)

34

cout «

ad

cout « "Sorry, I cannot divide by zero. \n" ; return;

32 35

331

"The quotient is " «

)

(argl / arg2) «

endl ;

m

m

Program Output with Example Input Shown In Bold Enter two numbers and I will divide the first number by the second number: 120 [Enter] Sorry , I cannot divide by zero.

M

uh a

In the example runn ing of the program, the user entered 12 and a as inpm. In line 16 the divide function was called, passing 12 into the argl pa rameter and 0 into the arg2 parameter. Inside the divide functio n, the i f statement in line 29 execu tes. Because arg2 is equa l to 0.0, the code in lines 31 and 32 execute. When the return statement in line 32 executes, the divide function immediately ends. Th is means the cout statement in line 34 does not execute. The program resumes at line 17 in the main function.

To Read Online & Download: WWW.ISSUU.COM/SHEIKHUHASSAN


Bismillah hiir Rehman nir Raheem-----------------------------Assalat o Wasalam o Alika Ya RasoolALLAH 33

Functions

us uf

i

Chapter 6

Returning a Value from a Function

CON (EPT: A fun ction may send a value back to the parr of the program rhat ca lled

Yo

the fun ction.

You've seen that data may be passed into a function by way of parameter variables. Data may also be returned from a function, back to the statement that called it. Functions that return a value are appropriately known as value-retttmillg functiotls.

az

The pow function, which you have already seen, is an example of a val ue-returning func-

tion. Here is an example:

-

ing Functions

Ri

VaJ ut'-Recurn-

double Xi x = pow(4 . 0, 2.0);

The second line in this code calls the pow funct ion, passing 4.0 and 2.0 as arguments. The function calculates the va lue of 4.0 raised ro the power of 2.0 and returns that va lue. The value, which is 16.0, is assigned to the x variable by [he = operaror.

ss

an

Although several arguments may be passed ioro a function, only one value may be returned from it. Think of a function as having multiple communication channels for recei ving data (para meters) , but on ly onc channel for sending data (the return value ). This is illustrated in Figure 6-9.

argument

argument

~

~

â&#x20AC;˘

Function

â&#x20AC;˘

Return value

ad

argument

Ha

Figure 6 -9

~

m

argument

uh a

m

NOTE: It is possible to return multiple values from a funct ion, bur they must be "packaged" in such a way that they are treated as a single value. Th is is a topic of Chapter 11.

M

Defining a Value-Returning Function When you are writing a value-returning function, you must decide what type of value the function will return. This is because you must specify the dara type of [he return va llie in the function header, and in the function prototype. Recall that a void function, which does not return a va lue, uses the key word void as its return type in the function header. A

To Read Online & Download: WWW.ISSUU.COM/SHEIKHUHASSAN


Bismillah hiir Rehman nir Raheem-----------------------------Assalat o Wasalam o Alika Ya RasoolALLAH 333

i

6.8 Returning a Value from a Function

us uf

value.recurning fu nction will ll se int, double, boo l, or any other valid data type in its header. Here is an example of a func tion that returns an int value: int sum(int numl, int nurn2) {

int result ;

Yo

result = numl + num2: return result ; )

az

The name of this function is sum. Notice in the function header that the return type is int, as illustrated in Figure 6-10. Figure 6路10

Ri

Return Type

j

int sum(int numl, int num2)

ss

an

T his code defines a function named sum tha t accepts twO int argumentS. The argumenrs are passed inro the parameter variables numl and num2. lnside the function, a variab le, result, is defined . Variables that are defined insi de a function are called local variables. After the variable definition, the pa rameter variables numl and num2 are added, and their sum is assigned to tbe result va riable. T he last statement in [he function is

Ha

return result;

T his Statement causes the function to end, and it sends the value of the result variable back to the statement that called the functio n. A val ue.returning function must have a return statement written in rhe following general format:

ad

return e xpression;

m

m

In the general format, expression is the value to be returned. It ca n be an y exp ress ion that has a value, such as a variab le, litera l, o r mathematical expression. T he value of [he expression is co nverted to [he data type that the function returns, and is sent back to the statement that called the func tion. In this case, the sum fu nction retur ns the value in the r e sult variab le.

uh a

However, we could have eliminated the r esult varia ble and returned the expresSIon numl + num2, as shown in the following code: int sum(i nt numl, int num2) {

return numl + num2;

M

)

When writ ing the prototype fo r a value-returning function, follow the same conventions tha t we have covered earlier. Here is rhe protOtype for rhe sum function: i nt surn(int , intI

j

To Read Online & Download: WWW.ISSUU.COM/SHEIKHUHASSAN


Bismillah hiir Rehman nir Raheem-----------------------------Assalat o Wasalam o Alika Ya RasoolALLAH

Functions

i

Chapter 6

Calling a Value-Returning Function Program 6-12 shows an example of how to ca ll the sum function. Program 6 -12 II This program US~S a function that returns a value. jinclude <iostream> using namespace std,

Yo

1 2 3 4

11

12

lnt main() { int valuel 20, value2 .. 40 , total;

II The first value 1/ The second value II To hold the total

13

an

/1 Call the sum function, passing the contents of 1/ valuel and value2 as arguments. Assign the return /1 value to the total variable . t otal ~ surn(valuel, value2)i

14 15 16 17 18

l'

21 22

value2 «

" is " «

retur n 0;

total «

Ha

}

24

and

ss

II Display the sum of the values . "The sum of " « valuel «

cout « «

20

23

az

7 8 9 10

II Function prototype int sum(int, int);

Ri

5 6

H

endl;

25

1/%****** ******************··*******··*****************

26 27

// Definition of function sum. This function returns // the sum of its two parameters.

28

1/** *** ********* ********************.* .************ ****

* *

ad

29

30

int sum(int numl, int num2)

31

{ }

m

return numl + num2;

32

33

us uf

334

m

Program Output The sum of 20 and 40 is 60

uh a

H ere is the statement in line 17 that calls the sum funct ion) passing valuel and value2 as arguments.

M

total

= sum{valuel,

value2);

This statement assigns the value returned by the sum function to the total variable. In this case) the function will return 60. Figure 6 ~ 11 shows how the arguments are passed into [he function and how a val lie is passed back from the function.

To Read Online & Download: WWW.ISSUU.COM/SHEIKHUHASSAN


Bismillah hiir Rehman nir Raheem-----------------------------Assalat o Wasalam o Alika Ya RasoolALLAH

6.8 Returning a Value from a Function

i

335

= sum(valuel,

value2)i

L------1~r-----,!

I

Yo

total

us uf

Figure 6 -11

int sum(int numl , int num2) { L _ _ _ _ _ _ _ _ _ __ _

return num + num:

}

an

int x = 10, Y = 15; double average; average = sum(x, y) I 2.0:

Ri

az

When you ca ll a va lue-returning function, you usua lly want to do something meaningful with the value it returns. Program 6-12 shows a function's return value being assigned to a variable. This is commonly how ret urn va lues are used, bu t you ca n do many other things with them. For example, the following code shows a mathematica l expression that uses a call to the sum function:

ss

In the last statement, the sum function is called with x and y as its arguments. The function's retu rn va lue, which is 25, is divided by 2.0. T he result, 12.5, is assigned to averllqe. Here is another example: sum(x , y) «

Ha

int x = 10, Y = lSi cout « "The sum is " «

endl;

This code sends the sum function's return value to cout so it can be displayed on the screen. T he message "T he sum is 25" will be displayed.

m

ad

Remember, a value-n::turning funct ion returns a value of a specific data type. You can use the function's return va lue anywhere that you can use a regular value of the same data type. Th is means that anywhere an int value can be used, a call to an int value-returning function can be used. Likewise, anywhere a double value can be used, a call to a double value-returning funct ion can be used. The same is true fo r all other data types.

uh a

m

Let's look at another exa mple. Program 6-13, which calcula tes the area of a circle, has two functions in addi tion to main. One of the functions is named square, and it returns the square of any number passed to it as an argument. The square function is called in a mathematical statement. The program also has a function named getRadius, which prompts the user to enter the circle's radius. The va lue entered by the lIser is returned from the function.

Program 6-13

M

1 2

3 4 5

II This proqram demonstrates two value-returning functiona . II The square functio n is called in a mathematica l statement .

'include <iostream> iinc l ude <iomanip> using namespace std;

6

(program continues)

To Read Online & Download: WWW.ISSUU.COM/SHEIKHUHASSAN


Bismillah hiir Rehman nir Raheem-----------------------------Assalat o Wasalam o Alika Ya RasoolALLAH

Program 6 -1 J

us uf

i

Chapter 6 functions

336

(continued)

7

//Function prototypes

8

double getRadius();

9

double square(double);

11

int main ( )

12

{

Yo

10

const double PI - 3 .14159; II Constant for pi 1/ To hold the circle's radius double radius; II To hold the circle ' s area double area;

13

14 15

l't7

cout «

20

22

II Get the radius of the circle. cout « "This program calculates the area of "; cout « "a circle. \0 " ;

23

radius - getRadius();

showpoint «

setprecision(2) ;

Ri

21

fixed «

az

II Set the numeric output formatting.

le 19

24

28

/1 Display the area.

29 30

cout «

31

-The area is • « return 0 ;

}

endl;

Ha

32

area «

ss

27

an

1/ Caculate the area of the circle. area - PI * square(radius);

25 26

33

1/** ·*****····.·.········.**·********.***··.·*** ••••••• *

34

II Definition of function getRadius. • II This function asks the user to enter the radius of • II the circle and then returns that number as a double .•

40 41 42

ad

38 39

11 ······ww*****.************************************* •••

double getRadius() {

double rad;

m

35 36 37

cout « "Enter the radius of the circle : H; cin » rad; return rad;

43

uh am

44 45

4. 47

49

1/* * ••••• ***.*** ••••••• **.*****.*.** •• *********.**.*.* **

49 50

1/ Definition of function square. * // This function accepts a double argument and returns *

51

II the square of the argument as a double .

52

//** •• *********** *************** •• **********************

*

53

double square(doUble number) {

M

54

55 56 57

return number * number; )

To Read Online & Download: WWW.ISSUU.COM/SHEIKHUHASSAN


Bismillah hiir Rehman nir Raheem-----------------------------Assalat o Wasalam o Alika Ya RasoolALLAH

337

us uf

i

6.8 Returning a Value from a Function

Program Output with Example Input Shown In Bold This program calculates the area of a circle. Enter the radius of the circle: 10 [Enter] The a rea is 314.16

az

Yo

First, look at the getRadius (unction defined in lines 39 through 46. The purpose of rhe function is to prompt the user to enter the radius of a circle. In line 41 the fu nction defines a loca l variable, rad. Lines 43 and 44 prompr the user to enter the ci rcle's radius, which is stored in the rad variable. In line 45 the value of rhe rad value is returned. The getRadius function is ca lled in [he main fun ction, in li ne 23. The value that is returned from the function is assigned to the radius variable.

an

Ri

Next look at the square function, which is defi ned in lines 54 through 57. When the fu nction is ca lled, a double argument is passed to ir. The fun ction stores the argument in the number paramete r. The return Statement in line 56 returns the val ue of the expression number * number, which is th e square of the number parameter. The square function is ca lled in the main function, in line 26, with the value of radiu s passed as an argument. The funcrion will rerurn the squ are of the radius variable, and that value will be used in the marhematical expression.

ss

Assuming the user has entered 10 as the radius, and this va lue is pa ssed as an argument to the square func tion, the square fun ction will return the value 100. Figure 6-12 il lustrates how the va lue 100 is passed back ro the mathema tical expression in line 26. The val ue 100 will rhen be used in the mathematica l expression.

Ha

Figure 6-12

a r ea - PI * square(radius);

100

I

double square(double number) {

return number * numberi

m

ad

I

M

uh a

m

Functions can return va lues of any type. Borh the getRadius and square functio ns in Program 6-13 retu rn a double. The sum function you saw in Program 6-12 returned an into When a sta tement calls a val ue-returning fun ction, it ShOldd properly hand le the rerum va lue. For example, if you assign the return value of the square fu nction ro a variable, the variable sho uld be a double. If the return va lue of the funct ion has a fractional ponion and you assign it to an int variable, the value will be truncated .

To Read Online & Download: WWW.ISSUU.COM/SHEIKHUHASSAN


Bismillah hiir Rehman nir Raheem-----------------------------Assalat o Wasalam o Alika Ya RasoolALLAH

Chapter 6 Functions

i

338

us uf

In the Spotlight: Using Functions

Yo

Your frien d Mich~e1 runs a' catering company. Some Qf the ingredients that his recipes require are measured in cups. When, he goes ~o the groc~ry Store to buy those,ingredients, however, they are sold (:Inly by the fluid ounce, He has asked YQU to write a simple pro· gram that converts cups ro fluid ounces. You design, the following algorithm:

1, Display an introductory screen that explains what the program 4oes .

az

. 2. Get the number of cups.

3. Convert the number of cups to fluid ounces and display the result.

.

· mainO

. .

.

.

.

getCups( )

...

.

. .

.

cupsToOunces (double cups)

.

ad

showlntro( )

Ha

ss

'

an

Hierarchy chart for the program

Figure 6 -13

Ri

This algorithrp lists the top leve! of'tasks that rhe program needs-to perform, and becomes the basis of the program's main function. The hierarchy chart shown in Figure 6-1 3 shows -how the program will broken down into functions.

showlnt':r;o-This funcrion will display a me.ssa'ge 'on ·the screen that explains what the program'does. ' getCups-This function will prompt the user to enter the: number of cups and then will cetu.r;n that value as a d014ble. cIlPsT,oOunces"":""This function will accept the" number o f cups ~s an argument and then 'return an equivalent number of fluid ounces ~s a double.

m

m

As shown in (he hierarchy chart, the main funct ion will ca ll three other funct ioAs. Here are suouuaries of those functions: '

uh a

6-14 shows the code for the pro:gram.

M

Progra~

To Read Online & Download: WWW.ISSUU.COM/SHEIKHUHASSAN


Bismillah hiir Rehman nir Raheem-----------------------------Assalat o Wasalam o Alika Ya RasoolALLAH

6.8 Returning a Value from a Function

i

339

us uf

Program 6-14 ·1 II This program conver·ts cups to fluid ounc·es. ~ iinclude <iostream> 3 'include <iomanip> '4 usipg namespace std;

5 6 II Function

Yo

pro~otypes

7 void showlntrO(); 8 double .qetCIlPS ( ) ; 9 double cupsToOunces(double); 10

II Display an intro screen . shQwlntrO()i

22:

II Get the number of cups. cups = getCups{);

ss

23 24

an

"

19 20 21

Ri

az

11 int wain () 12 { 13 II variables for the cups and oUnces. 14 d9uble cups, ounces; 15 16 (I Se-t up. numeric output form.atting. 17 cout <-< fixed « s .h owpoint « setprecision (1) ;

If Convert cups to fluid ounces. ounces '" cupsToOunces (c~ps) ;

27

Ha

26 26'

28

II Display the number of ounces.

29 30 31 32 33 }

cout « «

cup~

«

ounces «

" cups equals '! .. ounces.\n";

ad

return 0;

34 35 11*****"'*'*** * * * * *-* ****-li****** * * **** •••• 10****

,.

m

II The show~ntro function displays an • 37 I I il').t,roduc.tory screen. 3 • II**·****···**·***····*····~·**······**·****

. '39

m

40 void showlntro()

41 {

cout « « <-< «

42

"This prOSram converts measurements\n" (, in cups to fluid ounces . For your\n" "reference the formula i8:\n" . .. ' 1 cup'" 8 fluid ounces-\n\n" ;

uh a

.3

"45 .

46 }

."48. I I * ...

M

* * 1. * * * * * * * **.-** ~9 II The getCups function prompts the user • ?O· I I: to ent~ the n,u mher .of cups and then • 51 II re~urns that value as a double. • 52, 53

"'-'*'••• "'. * .............................. * * * * .... 'I

II*****··***·"'··~*****···***··*·*~*·********

(pro9ram continues)

To Read Online & Download: WWW.ISSUU.COM/SHEIKHUHASSAN


Bismillah hiir Rehman nir Raheem-----------------------------Assalat o Wasalam o Alika Ya RasoolALLAH

Chapter 6 Functions

us uf

i

340

(continued)

$4 double getc:::ups ( ) 5S { 56

double numCups;

57 sa 59

cin

60

return nu"mCups;

cout «

"Enter the number of cups: ";

Yo

»

numCu~si

.J }

•••

~5

II The cupsToounces.. function accepts a, II numb~r of cups as an argument and

6. II returns the equivalent number of fluid ~;

./ I ounces as a double.

• • •

"

70 double cupsToOunces(double

"1 ~- { ""'}2

nu~Cups)

return numCups .. 8 .0;

}

an

73

Ri

68, / flO",. ,.,.***'!<**** .. **,.,. .. ****ilr**** •.• ************

az

~2

=

8 fluid ounces

Ha

1 cup

ss

Program Output with Example Input Shown In Bold This program converts measurements in cups to fluid ounces . For your reference the formula is:

ad

Enter the number of cups: 2 [Enter] 2.0 cups equals 16.0 ounces.

m

Returning a Boolean Value

m

CONCEPT: Functions may return t.rue or £also vaJues.

uh a

Frequently there is a need for a function that tests an argument and returns a true or false value mdicating whether or not a condition exists. Such a function would return a bool value. For example, the following functio n accepts an int argument and returns true if the argument is wi thin the range of 1 through 100, or false otherwise. bool isValid(int number)

M

{

bool status;

if (number >: 1 && number <: 100) status """ true; else status '" false; return status;

To Read Online & Download: WWW.ISSUU.COM/SHEIKHUHASSAN


Bismillah hiir Rehman nir Raheem-----------------------------Assalat o Wasalam o Alika Ya RasoolALLAH

341

us uf

The following code shows an iflelse sta tement rhac uses a call to the function: int value '" 20; if (isVal id(value» cout « "The value is within range . \n " i el~e

"The val ue is out of range. \n" i

Yo

cout «

i

6.9 Returning a Boolean Value

When this code executes, the message "The value is within ra nge." will be displayed.

Program 6-15 shows another example. This program has a function na med isEven which returns true if irs a rgument is an even number. Otherwise, the funct ion returns false .

az

Program 6 -15

2

II This program uses a function that returns true or false. 'include <iostream>

3

u~~n9

4 5

name~pace

std i

II Function prototype bool iSEven(in t)i

7 8

int main()

9 10

an

6

{

iot val i

11 12

ss

II Get a number from the user . cout « "Enter an integer and I will tell you "; cout « "if it is even or odd: "i cin » val;

13

Ha

14 15

16

II Indic ate whether it is even or odd . if (iSEven(val» cout « val « is even.\n"; el se cout « val « is odd.\n"; re turn 0 ;

18 19 20 21

ad

17

}

m

22 23 24

Ri

1

*

29

II is o dd. The return v a lue is a bool.

30

II*******~******** · ****** ****************** **** * ****** ** ** *********

* *

uh a

m

II Definit i on of function isEven. This function accepts an II integer argument and tests it to be even or odd. The function II returns true if the argument is even or false if the argument

26

27 28 31

32 33

34 35

bool iSEven(int number) { boo l status: if (number' 2 == 0) status = t rue; II The number is even if there is no remainder. else status false; II Ot herwise, the number L8 odd. return status;

M

36 37 38

39 40

41

} (program output continues)

To Read Online & Download: WWW.ISSUU.COM/SHEIKHUHASSAN


Bismillah hiir Rehman nir Raheem-----------------------------Assalat o Wasalam o Alika Ya RasoolALLAH

342

Functions

Program 6路15

(continued)

Program Output with Example Input Shown In Bold

Yo

Enter an integer and I will tell you if i t is even or odd : 5 [Enter] 5 is odd.

us uf

i

Chapter 6

The isEven function is called in line 18, in the following statement: if (iSEven(val))

az

When the i f statement executes, isEven is ca lled with val as irs argumenr. If val is even, isEven returns true, otherwise it returns false.

~ Checkpoint

How many rerum values maya fu nction have ?

6.12

Write a header for a fUrlc t ion named distance. The function should return a

Ri

6.11

double and have two double parameters: rate and time.

6.13

Write a header for a functio n named days. The function sho uld return an lnt

an

and have three int parameters: years, months, and weeks . Write a header for a function named getKey . The function should return a char and use no parameters.

6.15

Write a header for a function named lightYears. The function should return a long and have one long parameter: miles .

Ha

ss

6.14

Local and Global Variables CONCEPT; A local variable is defined inside a function and is not accessible outside

ad

the function. A global variable is defined outside all fun cti ons and is accessible to all functions in its scope.

m

Local Variables

uh a

m

Variables defined inside a function are local to that function. They are hidden from the sta tements in other fu nctions, which normally cannot access them. Progra m 6-16 shows that because the variables defined in a function are hidden, other fun ctions may have sepa rate, distinct variables with the same name.

Program 6-16

4

II This program shows that variables defined in a function II are hidden from other functions. ' include <iostream> using namespace std;

5 6

void anotherFunccion(); II Function prototype

1

2

M

3

To Read Online & Download: WWW.ISSUU.COM/SHEIKHUHASSAN


i

Bismillah hiir Rehman nir Raheem-----------------------------Assalat o Wasalam o Alika Ya RasoolALLAH

Lot main()

{

/1 Local variable

10 11

lot num = 1;

12

cout « "In main, num is " « num « endl; anotherFunction(); cout « "Back in main, num is " « num « endl; return 0 i

13 14 lS

Yo

a

9

us uf

,

16

)

17 18 19

//~****************************************************

20 21

II It has a local variable, num, whose initi al value II is displayed.

22 23

//***** ***** * ******* ** ******* * ****** ** ***** * ***********

24

void anotherFunction()

25 26 27 28

{

29

)

Ri

iot num

= 20;

cout «

" In anotherFunction, num is " «

num «

an

II Local variab le

endl;

ss

Pr ogram Output

• • •

az

II Definition of anotherFunction

Ha

In main, num is 1 In anotherFunction, num is 20 Back in main, num is 1

ad

Even though there are two variables named num, the program can only "see" one of them at a time because they are in different funC[ion s. When the program is executing in main, the num variable defined in main is visible. When anotherFunction is ca lled, however, only variables defined inside it are visi ble. so (he num variable in main is hidden. Figure 6· 14 illustrares the closed nature of the twO fu ncrions. The boxes represent the scope of the variables.

m

Figure 6-14

int num :

Ii

....1-- --1--- only This nwn variable is visible in main.

L ____ _______--' Function anotherFunction

This num variable is visible L'~·n~t~n~u~m~-"':2~O~'~~==t-- only in anotherFunction.

M

uh a

m

Function main

To Read Online & Download: WWW.ISSUU.COM/SHEIKHUHASSAN


Bismillah hiir Rehman nir Raheem-----------------------------Assalat o Wasalam o Alika Ya RasoolALLAH

Chapter 6

Functions

us uf

i

344

Local Variable Lifetime

Yo

A functio n's local variables ex ist only whi le the function is executing. This is known as the lifetime of a local variable. When the function begins, its local variables and its para meter variables are created in memory, and when the funct ion ends, the local variables and parameter variables are destroyed. This means tha t any value sto red in a local variable is lost between calls to the function in which the va riable is declared.

Initializing Local Variables with Parameter Values

It is possible to use a parameter variable to initialize a local va riable. Sometimes this simpli.

az

fies the code in a function. For example, recal! the first version of the sum function we cussed earlier:

Ri

int sum(int num l , int num2)

int result ; result = numl + num2; return result;

an

}

dis~

ss

In the body of the fu nction, the result variable is defined and then a separate ass ignment statement assigns numl + num2 to result. We can combine these statemen ts into one, as shown in the following modified version of the function. int surn (i nt numl , i n t num2)

Ha

{

int result = numl + num2; return result ; }

ad

Because the scope of a parameter variable is the entire function in which it is declared, we can use parameter variables to initialize local variables.

Global Variables and Global Constants

uh a

m

m

A global variable is any variable defined outside all the functions in a program. The scope o f a global variable is the portion of the program from the variable definition to the end. T his mea ns that a global variable can be accessed by all functions that are defi ned after the global variable is defined. Program 6-17 shows twO funct ions, main a nd anotherFunction, thar access the same global va t路iable, num,

Program 6 -17

II This program shows that a global variable is visible

2

1/ to all the functions that appear in a program after

3 4 5

// the variable's declaration .

M

1

6 7

8

iinclude <iostream> using namespace std;

void anotherFunction()i II Function prototype II Global variable int num '" 2 ;

To Read Online & Download: WWW.ISSUU.COM/SHEIKHUHASSAN


Bismillah hiir Rehman nir Raheem-----------------------------Assalat o Wasalam o Alika Ya RasoolALLAH 6.10 Local and Global Variables

i int main()

11

{

12

cout « "In main, num is .. « num « endl; anotherFunction(): cout « "Back in main, num is .. « nurn « endl; return 0;

13

14 15 }

18 20 21

11***************************************************** II Definition of anotherFunction • II This function changes the value of the • II global var iable num . •

22

11**************************************************** ~

az

16 17

19

23 24

void anotherFunction()

25

{ M

Ha

In main, num is 2 In anotherFunction, num is 2 But, it is now changed to 50 Back in main, num is 50

ss

Program Output

an

}

Ri

cout « "In a notherFunction, num is « num « endl; nurn :: 50; cout « "But, it is now changed to " « num « endl;

26 27 28 29

us uf

10

Yo

345

In Program 6-17, num is defined outside of all the functions. Because its definition appears before the definitions of main and another Function, both funct ions have access ro it.

m

Program 6 -18

ad

Unless you explicitl y initialize numeric global variables. they ate automatically initialized to zero. Global character variables are initialized to NULL. " The variab le globalNum in Program 6-18 is never ser to any value by a statement, but because ir is global, it is automatically set to zero.

II This program has an uninitialized global variable .

linclude <iostream> using names pace std:

m

1

2 3 4

int globalNum; II Global variable, automatically set to zero

uh a

5 6 7

int main()

8

cout « "globalNum is " « return 0:

9 10

endl ;

}

M

11

globalNum «

(program output continues)

.. The NULL character is stored as ASCII code O.

To Read Online & Download: WWW.ISSUU.COM/SHEIKHUHASSAN


Bismillah hiir Rehman nir Raheem-----------------------------Assalat o Wasalam o Alika Ya RasoolALLAH Chapter 6

Functions

Program 6-18

i

346

us uf

(continued)

Program Output

globalNum is 0

Yo

Now that you've had a basic introduction to global variab les, I must warn you to restrict your use of them. When beginning students first learn to write programs wirh multiple functions, they are sometimes tempted to make all their variables global. T his is usually because global va riables can be accessed by any funct ion in the program without being passed as arguments. Although this approach might make a program easier to create, it usually causes problems later. T he reasons are as follows:

Global variables make debugging difficult. Any statement in a program can change the val ue of a global va riable. If you find that the wrong val ue is being srared in a global variable, you have ro track down every statement that accesses it ro determine where the bad value is coming from. In a program with thousands of li nes of code, this can be difficult. Functions that use global variables are usually dependent on those variables. [f you want to use such a function in a different program, most likely you will have to redesign it so it does not rely on the global va riable. Global var iables make a program hard to understand. A global variable ca n be modified by any statement in the program. If yo u are to understand any part of the program that lIses a global variable, you have to be aware of all the other pares of the program that access the global variable.

Ri

az

an

ss

In most cases, you should declare variables locally and pass them as arguments co the

Ha

functions that need to access them.

ad

Beca use of this, you should not use global variables fo r the conventional purposes of storing, manipu lating, and retrieving da ta. Instead, you should only use them as global C01lsla1lts, defining them with the canst mod ifier. Because a conStant cannOt be changed during program execution, you do not have to worry about a globa l constant's value getti ng corrupted.

m

m

Program 6-19 shows an example of how global constants might be used. T he program calculates an employee's gross pay, including overtime. In addition to main, this program has two functions! getBasePay and getOvertimepay. T he getBasePay function accepts the number of hours worked and returns the amount of pay for the non-overtime hours. T he getOvertimePay function accepts the number of hours worked and returns the amount of pay for the overtime hours, if any.

uh a

Program 6-19 1

II This program calculates gross pay.

2

'include <iostrearo> iinclude <iomanip> using namespace std;

M

3 4 5

6

7 8

II Global constants canst double PAY RATE ~ 22 . 55 ; const double BASE HOURS ~ 40 _0 ;

II Hourly pay rate II Max non-overtime hours

To Read Online & Download: WWW.ISSUU.COM/SHEIKHUHASSAN


Bismillah hiir Rehman nir Raheem-----------------------------Assalat o Wasalam o Alika Ya RasoolALLAH 6.10 Local and Global Variables

= 1 . 5;

// Overtime multiplier

12 13

// Function prototypes double getBasePay(double); double getOvertimePay(double};

14 15

int main()

16

{

19 20

21 22

II Hours worked II Base pay II Overtime pay II Total pay

II Get the number of hours worked . cout « ~How many hours did you work? cin » hours;

23 20

.,

26

II Get the amount of base pay . basePay = getBasePay(hours);

27 28

31 32 33

II Calculate the total pay. total Pay = basePay + overtime;

ss

34 35 36

an

II Get overtime pay, if any. if (hours> BASE_HOURS) overtime = getOvertimePay{hours);

29 30

Ri

25

az

double hours, basePay, overtime = 0 . 0 , totalPay;

17 18

Yo

10 11

i

const double OT MULTIPLIER

us uf

9

347

1/ Set up numeric output formatting. cout « setprecision(2 ) « fixed « showpoint;

Ha

37 38

39

II Display the pay . cout « "Base pay: $~ « basePay « endl; cout « "Overtime pay: .s" « overtime « endl; cout « "Total pay: .s" « totalPay « endl; return 0;

40 41

42

)

47 48 49

II The getBasePay function accepts the number of • II hours worked as an argument and returns the * II employee's pay for non- overtime hours. •

m

ad

43 44 45

m

50 11*····_····_--_·_··-.········.·.· ••••••••••••••••

51

double getBasepay(double hoursWorked)

53 54 55

{

uh a

52

56

57

M

58 59

60

double basepay: II To hold base pay

II Determine base pay. if (hoursworked > BASE_HOURS) basePay = BASE HOURS * PAY_RATE; else basePay & hoursworked • PAY_RATE; (program continues)

To Read Online & Download: WWW.ISSUU.COM/SHEIKHUHASSAN


Bismillah hiir Rehman nir Raheem-----------------------------Assalat o Wasalam o Alika Ya RasoolALLAH 48

Program 6-19

63

(continued)

us uf

61 62

i

Chapter 6 Functions

return basePaYi

)

66 67

//* ** ***************** ************ *** *************II The getOvertimePay function accepts the number * II of hours worked as an argument and returns the * II employee's overtime pay . * //*** **********************************************

68 69 70 71

double getOvertimepay(double hoursWorked)

72

{

double overtimePaY i II To hold overtime pay

74 75 76 77

II Determine overtime pay . if (hoursWorked > BASE_HOURS) {

overtimePay ~ (hoursWorked - BASE HOURS) * PAY RATE * OT_MULTIPLIER;

78 79 80

)

return overtimepaYi

an

else overtimepay : 0 . 0;

ss

81 82 83 84 85

Ri

73

az

65

Yo

64

)

Ha

Program Output with Example Input Shown In Bold How many hours did you work? 48 [Enter]

ad

Base pay: $902.00 overtime pay: $270 . 60 Total pay : $1172 . 60

m

m

Let's take a closer look at the program. Three global constants are defined in lines 7, 8, and 9. The PAY_RATE constant is set to the employee's hourly pay rate, which is 22.55. The BASE_HOURS consta nt is set to 40, which is the number o f hours an employee can work in a week without getting paid overtime. The aT_MULTIPLIER constant is set to 1.5, which is the pay rate multiplier for overtime hours. This means that the employee's ho urly pay rate is multiplied by 1.5 for a ll overtime hours.

M

uh a

Because these constants a re global, and are defined before all of the functions in the program, aU the functions may access them. For example, the getBasePay function accesses the BASE_HOURS constant in lines 57 and 58, and accesses the PAY_RATE constant in lines 58 and 60. The getOvertimePay functio n accesses the BASE_HOURS constant in lines 76 and 78. tbe PAY_RATE constant in line 79, and the aT_MULTIPLIER constant ill line 79.

Local and Global Variables with the Same Name

You cannot have twO loca l variables with the same name in the same function. This applies to parameter variab les as well. A parameter variable is, in essence, a local variable. So, YOll cannot give a parameter variable and a local variable in the same function the same name.

To Read Online & Download: WWW.ISSUU.COM/SHEIKHUHASSAN


Bismillah hiir Rehman nir Raheem-----------------------------Assalat o Wasalam o Alika Ya RasoolALLAH 6. 10 Local and Global Variables

349

Program 6 -20

1 2 3 4

II This program demonstrates how a local variable II can shadow the name of a global constant. 'include <iostream> using names pace std;

az

5

6 II Global constant. 7

canst int BIRDS = 500; II Function prototype void california();

11 12

int main()

13 14

(

cout «

"In main there are ., « « " birds . \n": cali f ornia {); return 0;

15 16

"

BIRDS

ss

17 19

an

9

Ri

8

10

II california function

22

11* *******************************************

23 24

void califor nia()

25 26

(

const int BIRDS = 10000 ; cout « "In california there are " « « " birds. \ n" ;

ad

"

Ha

20 21

27

Yo

us uf

i

However, you can have a local va riable or a pa rameter variable with the same name as a global variable, or a global constant. When you do, the name of the local or parameter variable shadows the name of the global va riable or global constant. This means that the global variable or constant's name is hidden by the name of the local or parameter variable. Foe example, look a t Program 6-20. This program has a global constant named BIRDS) set ro 500. The california function has a local consra nt named BIRDS, set to 10000.

BIRDS

m

29

m

Program Output In main there are 500 birds. In california there are 10000 birds.

M

uh a

When the program is executing in the main funct ion, the global consta nt BIRDS, which is set to 500, is visible. T he cout sta.tement in lines 14 and 15 displays " In main there ace 500 bi rds." (My apologies to fo lks living in Maine for the difference in spelling.) When th e program is exec uting in the california function, however, the local constant BIRDS shadows the global constant BIRDS. When the california function accesses BIRDS, it accesses the local constant. That is why the cout statement in lines 27 and 28 displays "In californ ia there a re 10000 birds."

To Read Online & Download: WWW.ISSUU.COM/SHEIKHUHASSAN


Bismillah hiir Rehman nir Raheem-----------------------------Assalat o Wasalam o Alika Ya RasoolALLAH

Chapter 6

Functions

us uf

i

350

Static Local Variables

Yo

\E a function is ca\\ed more than once in a program, the values stored in the funcrio n's local vadabfes do not persist between fUllction calls. Thjs is because the locaJ variables are destroyed when the fu nction terminates and arc then fe-created when the funcrion SWftS again. This is shown in Program 6-21.

II This program shows that local variables do not retain

II their value s between function calls. 'include <iostream> using namespace std;

6

II Function prototype void showLocal(); int main() {

11 12

IS 19 20 21 22 23 24 25 26 27

1/* ******** **** ************** ***************** ** * * **** ******* II Definition of function showLocal . .. /1 The initia l value of localNum, which is 5 , is displayed. * II The value of 1oca1Num is then cha nged to 99 before the * II function returns. * 11************** ************ *********** * * *** ********** *******

void showLOcal() {

int localNum = 5; II Local variable

cout « "localNum is " « localNum = 99; )

localNum «

endl;

m

28 29

ss

15 16 17

return 0 ; )

Ha

13 14

showLocal (); showLocal():

ad

9

10

m

, 7

Ri

4 5

an

3

az

1

2

Program Output

M

uh a

localNum is 5 localNum is 5

Even though in line 28 the last statement in the showLoeal function stores 99 in loca1Num, the variable is destroyed when the function returns . The next time the function is called, local Num is re·created and initialized to 5 again .

Sometimes it's desirable for a program to "remember" what value is stored in a local vari· able between function calls. This can be accomplished by maki ng the variable static.

To Read Online & Download: WWW.ISSUU.COM/SHEIKHUHASSAN


Bismillah hiir Rehman nir Raheem-----------------------------Assalat o Wasalam o Alika Ya RasoolALLAH 6.1 1 Static Local Variables

351

II This program uses a static local variable.

2

'include <iostream> us ing names pace std;

5

void showStatic() ; 1/ Function prototype

6 7

int main{)

8

{

10 11 12 13

II Ca l l the showStatic function five times . f or tint count : 0 ; count < 5; count++) showStatic(); return 0;

Ri

9

az

3 4

Yo

1

us uf

i

Static local variables a re nor destroyed when a function returns . They exist for rhe lifetime of the program, even tho ugh their scope is only the function in which they are defi ned . Program 6-22 demonstrates some characteristics of static local variables :

}

14

11******** **** *************************** *********** ** ******* ***

16

lS

II Definition of function showStatic . II statNum is a static local variable . Its value is displayed II and then incremented just before the f unction returns.

19

11**** ****** * ******* *********************** ******* **** ******* ** *

17

an

15

20 void showStatic() {

static int statNum;

23

cout « "statNum is " « statNum++;

25 }

statNum «

endl;

is 0 is 1 is 2 is 3 is 4

ad

Output

m

Program statNum statNum statNum statNum statNum

m

26 27

Ha

24

ss

21 22

In line 26 of Program 6·22, statNum is incremented in the showStatic function, and it

uh a

retains its va lue betweeo each function cal l. Notice that even though statNum is not explicitly initialized, it starts at zero. Li ke globa l variab les, all static loca l variables are initia lized to zero by default. (Of cou rse, you can pro vide your own initialization value, if necessary. ) If yo u do p rovide an initial ization va lue for a s t.a t.i.c loca l variab le, the initial ization only

M

occurs once. This is because initialization n o rmall y happens when the variable is created,

and static local variables are only created once during the running of a program. Pro-

g ram 6-23, which is a s light modification of Program 6-22, ill ustrates this point.

To Read Online & Download: WWW.ISSUU.COM/SHEIKHUHASSAN


Bismillah hiir Rehman nir Raheem-----------------------------Assalat o Wasalam o Alika Ya RasoolALLAH 352

i

Chapter 6 Functions

1

1/ This program shows that a static local variable is only

2 3

II initialized once . iinclude <iostream>

4

using namespace std;

us uf

Program 6 -2J

5

void showStatic(); /1 Function prototype

Yo

6 7 8

iot main( l

9

{

II call the showStatic function five times. for (int count ~ OJ count < 5; count++)

10 11 12

14 15

az

showStatic ( ) i

return 0;

!3 )

II statNum is a static local variable . Its value is displayed II and then incremented just before the function returns.

an

11-·-···-·_-*·*------*-*-***---------*-_····_------_··k.k_*_k __ void showStatic() {

24

static int statNum

~

5;

25

cout « "statNum is " « statNum++; )

Program Output S

• 7

ad

is is is is is

endl;

8

9

m

statNum statNum statNum statNum statNum

statNum «

Ha

26 27 28

* *

ss

20 21 22 23

Ri

__ .k __• " 11·*--····_···_-_·_-_···*··_----_·_**--------_·_------*kk /1 Definition of function showStatic .

17 18 19

Checkpoint

M

uh a

~

m

Even though the statement that defines statNum in line 24 initializes it to 5, the in itialization does not happen each time the function is called. If it did, the variable wou ld not be able to reta in its value between fUllction calls.

6.16

What is the difference between a static local variable and a global variable?

6.17

What is the output of the following program? 'include <iostream> using namespace std; void myFunc();

1/ Function prototype

int main()

To Read Online & Download: WWW.ISSUU.COM/SHEIKHUHASSAN


Bismillah hiir Rehman nir Raheem-----------------------------Assalat o Wasalam o Alika Ya RasoolALLAH 6.12 Default Argu ments

us uf

cout « var « myfun C() ; cout « v ar « return 0:

i

i nt var '" 100: end1; endl;

)

Yo

II Definition of function myFunc void myfunc ( ) (

int var

=

cout «

var «

353

50; endl;

az

)

What is the ou tput of the followi ng program?

Ri

6. 18

'i nclude <iostream> using names pace std;

void showVar() : II Function prototype

an

int main() {

ss

f or ( i nt c ou nt - 0 : count < 10 : count++) showVar ( ) ; return 0: )

{

Ha

II Definition of f unction showVar void showVar ( ) static int var = 10;

cout «

var «

endl:

)

ad

var+ + ;

m

Default Arguments

uh a

m

CON CEPT: Defau lt arguments are passed to parameters automatically if no argument is provided in the fun ction call .

It's possible to assign defa t/It argume,lts to function parameters. A defau lt argument is

passed to the para meter when the actual argument is left out of the fu nction call. The defa ult arguments are usua ll y listed in the function prorotype. Here is an example:

M

void showArea(double

=

20.0, double

~

10.0) :

Defa ult arguments are literal va lues or constants with an = operator in front of them, appearing after (he data types listed in a function prototype. Since parameter names are

optional in function prototypes, the exa mple prototype could also be declared as void showArea(double length

=

20.0 , double widt h = 10 . 0):

To Read Online & Download: WWW.ISSUU.COM/SHEIKHUHASSAN


Bismillah hiir Rehman nir Raheem-----------------------------Assalat o Wasalam o Alika Ya RasoolALLAH Chapter 6

Functions

us uf

i

In both example prototypes, the function showArea has cwo double parameters. The first is assigned the default argument 20.0 and the second is assigned the default argument 10.0. H ere is the definition of the function: void showArea{double length , double width) {

double area = length * width; cout « "The area is «area«

endl;

Yo

)

The default a rgument for length is 20.0 and (he default argument fo r width is 10.0. Because both parameters have default arguments, they may optionally be omitted in the

fu nction call, as shown here: showArea( );

Ri

az

In tillS function ca ll , both default arguments will be passed to the parameters. The param eter length will take the value 20.0 and width will take the value 10.0. The output of the func rion will be The area i s 200

an

The default argumenrs are only used when the actual arguments are omirred from the function call. In the call below, the first argument is specified, but the second is omitted: showArea(12.0);

The area is 120

ss

The value 12.0 will be passed to length, while the default value 10.0 will be passed to width. The Output of the fu nction will be

Ha

Of course, all the default arguments may be overridden. In the fu nction ca ll below, arguments are supplied fo r both parameters: shOWArea(12 . 0, 5.5) ;

The output of the function ca ll above will

be

ad

The area is 66

m

NOTE : If a function does not ha ve a prototype, defa ult arguments may be specified in the function header. The showArea function could be defined as fo llows: void showArea(double length

m

{

::=

20 . 0, double width " 10 . 0 )

double area : length * width; "The area is

«area«

endl;

uh a

cout «

M

CD

WAR NING ! A function's default arguments shou ld be assigned in the earliest occurrence of the function na me. This will usually be rhe function prototype.

Program 6·24 uses a function that displays asterisks on the screen. Arguments are passed to the func tion specifyin g how many co lumns and rows of asterisks to disp lay. Default argumentS are provided to d isplay one row of 10 asterisks.

To Read Online & Download: WWW.ISSUU.COM/SHEIKHUHASSAN


Bismillah hiir Rehman nir Raheem-----------------------------Assalat o Wasalam o Alika Ya RasoolALLAH 355

6.12 Default Arguments

us uf

i

Program 6 -24

1 II This program demonstrates default function arguments. 2

'include <iostream>

3

using namespace std ;

4

7 8 9 10 11 12 13 14 15 16

Yo

II Function prototype with default arguments void displayStars(int = 10, int = 1); lot main() {

II Use default values for cols and rows .

displayStars() ; cout « endl: displayStarS(S)i cout « endl; displayStars(7, 3): return 0;

II Use default value for rows.

az

6

II Use 7 f or cols and 3 for rows.

)

17 18

II

II This function displays a square made of asterisks.

11·····t .......................................•.......... void displayStars(int cols, int rows) {

II Nested loop. The outer loop controls the rows

27 28

II and the inner loop controls the columns . for ( int down = 0; down < rows; down++)

29

{

for (int across cout « "."; cout « endl;

30 31 32 33

Ha

26

=

0: across < cols; across++)

) )

•••••••

M

uh a

• *.**.* .***.**

m

••• *•

m

Program Output

ad

34

The def3u l t argument for cols is 10 and for rows is 1.*

an

21 22 23 24 25

II Definition of function displayStars.

ss

19 20

Ri

5

Although C ...... ·s dehw lt arguments are very convenient, they are not totally flexible in their use. When an argument is left o ur of a fu nction ca ll, all arguments that come after it must be {eft ou t as well. In the displaYStars fu nction in Program 6-24, it is not possible ro omit the argument for cols without also omitting the argument for rows. For example, the following function call would be illegal: displayStars(, 3); II Illegal function call.

To Read Online & Download: WWW.ISSUU.COM/SHEIKHUHASSAN


Bismillah hiir Rehman nir Raheem-----------------------------Assalat o Wasalam o Alika Ya RasoolALLAH Chapter 6

Functions

i

35

II Function prototype vo id calcPay(int empNum, double payRate, double hours

{

double wages;

= payRate

cout « cout « cout «

40 . 0);

* hours: fixe d « showpoint « setprecision(2): "Gross pay for employee number "; empNum « " is " « wages « endl:

az

wages

~

Yo

II Definition of function calcPay void calcPay(int empNum, double payRate, double hours)

us uf

It's possible for a function to have some pa rameters with defa ult arguments and some without. For example, in the following function (which displays an employee's gross pay ), only the last parameter has a default argument:

Ri

)

When call ing this function, arguments must always be specified for the first two parameters (empNum and payRate) si nce they have no default arguments. Here are exampJes of valid calls: calcpay(142, 12 . 00, 20);

II Use defau lt arg for 40 hours II Specify number of hours

an

calcPay(769. 15.75) ;

Ha

ss

When a function uses a mixture of parameters with and without default arguments, (he parameters with default arguments must be defined last. In the calcpay function, hours could not have been defined before either of the other pa rameters. The following protO" types are illegal: 40.0, doub le payRate);

=

40.0, int empNum, double payRate);

II Illegal prototype void calcPay(int empNum, double hours

ad

II Illegal prototype void calcPay(double hours

H ere is a summary of the important points about default arguments: The value of a default argument must be a literal value or a named constant. When an argument is left our of a function ca ll (because it ha s a default value), all the arguments that come after it must be left ou t too. When a function has a mixture of parameters both with and without default arguments, the parameters with defa ult arguments must be declared last.

m

• •

uh a

m

M

Using Reference Variables as Parameters

CONCEPT: When used as parameters, reference variables allow a fu nction 10 access th e parameter's original argument. Changes to the parameter are also made to the argument.

Earlier you saw that arguments are normally passed ro a function by value, and that the funct ion ca nnot change the source of the argument. c++ provides a special type of variable

To Read Online & Download: WWW.ISSUU.COM/SHEIKHUHASSAN


Bismillah hiir Rehman nir Raheem-----------------------------Assalat o Wasalam o Alika Ya RasoolALLAH 6.13 Using Reference Variables as Parameters

i

(0

the

us uf

called a reference variable that, when used as a function parameter, allows access original argument.

357

Yo

A reference variable is an alias for another variable. Any changes made to the reference variable are actually performed on the variable for which it is an alias. By using a reference variable as a parameter, a function may change a variable that is defined in another function . Reference variables are defined like regular variables, except you place an ampersand (&) in front of the name. For example, the following function definition makes the parameter refVar a reference variablc: void doubleNum(int &refVar)

az

(

refvar *= 2 ;

Ri

)

~L-N __O_T__E_: _T_h_c_v_a_r_ia_b_l_e _r_e_f _v _a__ r is_ c_a_I_1e_d_'_'a__ re_k_r_e_"_ce__' O __a_" _i_"_t _.'_' __________________--"

~

ss

void doubleNUm(int &);

an

This function doub les refVar by multiplying it by 2. Since refVar is a reference variable, this action is actuall y performed on the variable that was passed to the function as an argument. When prototyping a function with a reference variable, be sure to include the ampersand after the data typc. Here is the prototype for the doubleNum function:

NOTE: Some programmers prefer nOt to put a space between the data type and the

Ha

~L-_'"_'_p_e_'_',_"_d_"_T__h_e_fo __lI_o_w_i_"_g_p_'_O_,o_'_y_p_,_,_,_e_q_"_i_v_l , _e_"_,_,_o_,_h_e_o_"_e_a_b_o_v_'_'__________________--' void doubl eNum( i nt&);

NOTE: The ampersand must appear in both (he prowcype and the header of any function

ad

~

~ L-_th_a_t_u_,_e_s_a_r_e_fe_r_e_"_ce__v_a _ri_a_b_le_a_,__, _p_a_r_a _m_e_,e_r_"_I,_ d_ o_ e_,__n_o _, _a _p__ p,a_r__ in_r_h_e_f_u_n_c_r_io_n_c_a_'_I.______--"

m

Program 6路25

m

Program 6-25 demo nstrates how the doubleNum function works.

1

II This program uses a reference variable as a function

2

II parameter.

uh a

3 linclude <iostream> 4

using name s pace atd;

5

6

7 B

M

9

/1 Function prototype. The parameter is a reference variable . void doubl eNuffi(int &); iot main()

(program continues)

To Read Online & Download: WWW.ISSUU.COM/SHEIKHUHASSAN


Bismillah hiir Rehman nir Raheem-----------------------------Assalat o Wasalam o Alika Ya RasoolALLAH

Functions

i

Chapter 6

35

( lnt value

12 13 14

= 4;

15 16

cout « "In main, value is " « value « endl; cout « "Now calling doubleNum •.. " « endl; doubleNum(value): cout « "Now back in main. value is " « value «

17

return 0;

Yo

10 11

us uf

(continved)

endl;

18

19

1/***************************······*******************_*k_._

21

II Definition of doubleNum . /1 The parameter refVar is a reference variable. The value 1/ in refVar is doubled .

* * 1/****· ··********···*****·*·**** ***··* *** ******···**** .*****

25

26

void doubleNum (int &refVar)

27

{

refVar

*~

2;

an

)

Program Output

In main, value is 4 Now calling doubleNum ...

Ha

Now back in main . value is 8

ss

28 29

Ri

22 23 24

az

20

The parameter refVar in Program 6-25 "points" to the value variable in function main. W hen a program works wirh a reference variable, it is actually wo rking with the variable it references, or points to. This is illustrated in Figure 6- 15.

A;terence Variable

Original Argument 4

m

m

ad

Figure 6-15

uh a

Recall that function arguments a re normally passed by value, which means a copy of the argu m e nt's value is p;:tssed into t he param eter variable. When a reference parameter is lIsed, it is said that [he argument is passed by reference.

M

Program 6-26 is a modification of Program 6-25. TIle function getNum has been added. The function asks the user to enter a number, which is stO red in userNum. userNum is a refe rence to main's variable value.

To Read Online & Download: WWW.ISSUU.COM/SHEIKHUHASSAN


Bismillah hiir Rehman nir Raheem-----------------------------Assalat o Wasalam o Alika Ya RasoolALLAH

359

i

6.13 Using Reference Variables as Parameters

1 2 J

us uf

Program 6·26

II

This program uses reference variables as functio n parameters. <iostream> using namespace std; 'incl~ de

5 II 6 II

Yo

7 8

Function prototypes. Both f unctions use reference variables as parameters . void doubleNum(int &); voi d getNum(int &):

{

12 13

int value;

14

II

Get a number and store it in value. getNum(value) :

15 16 17 18

II Double the number stored in value . doubleNum(value):

Ri

int main()

11

az

9 10

19

II Dis p lay the res u lting number. cou t « "That value doubled is .. « return 0 i

21 22

23

an

20 }

26 27 28

29

//-** ***** -* * - - - *- - -**** - **** **-* * ** ********* ** * * ***** * **** * - * * II Definition of getNum . * II The parameter userNum is a reference variable. The user is * II asked to enter a number, which is stored in userNum. *

Ha

25

11 ·**·*························ ·**· ···*····*·········· •••• "._ ••

30 31

vo id getNum(int &userNum)

32 33

{

ad

cout « "Ent er a number : cin » userNum:

34

35

endl;

ss

24

value «

)

,.

m

36

"

11··***·*··* · ·_··_············_·····*·*·***·*-_··***** .*****

38

II Defi ni tion of do ubleNum. • II The parameter refVar is a reference variable. The value * 1/ in refvar is doubled . *

39 40

41

m

37

1/****** ****····*·*********************· *** ·.··*.·**** * ••• *.

uh a

42 43

void doubleNum (int &refVar)

44

{

45 46

refVar *= 2;

)

M

Program Output with Example Input Shown In Bold Enter a number: 12 (Enter]

That val ue doubled is 24

To Read Online & Download: WWW.ISSUU.COM/SHEIKHUHASSAN


Bismillah hiir Rehman nir Raheem-----------------------------Assalat o Wasalam o Alika Ya RasoolALLAH

1360

Functions

by reference. If you attempt ro pass a noovariable argument, slich as a litera!, a constant, or an expression, into a reference parameter, an erro r will result. Using the doubleNum fun ction as all example, the following statements w ill generate an error. NOTE: Only variables may be passed

II Error II Error

doubleNum( 5) i

doubleNum(userNum + 10);

Yo

()

us uf

i

Chapter 6

az

If a function uses more than one refercI1ce variable as a parameter, be sure to place the ampersand before each reference variable name. Here is the prototype and definition for a function tha t uses four reference variable parameters:

Ri

/1 Function prototype with four reference variables II as parameters . void addThree(int &, iot &, int &, int &); II Definition of addThree .

II All four parameters are reference variables . void addThree(int &sum, int &numl, int &num2, i nt &num3)

an

(

ss

cout « "Enter three i nteger values : " : cin » numl » num2 » num3 : sum - num! + num2 + num3; )

WARNING! Don't get carried away with usi ng reference variables as fu ncrion

Ha

CD

parameters. Any time you allow a function to alter a variable tha t's ou tside the function, you are creating potential debugging problems. Reference variables shou ld only be used as parameters when the situation reqllires them.

ad

Checkpoint

What kinds o f values ma y be specified as default arguments? Write the prototype and header for a function called compute. The function should have three parameters: an int, a double, and a long (n m necessarily in tha t order). The in t parameter should have a default argument of 5, and the long paramete r should have a default argument of 65536. T he double paramerer should not have a default argument.

m

m

6.19 6.20

uh a

6.21

M

6.22

Write the protOtype and header for a function called calculate. The funcrion should have three parameters: an int, a reference to a double, and a long (nor necessarily in tha[ order.) Only the int parameter shou ld have a default argument, which is 47. What is the output of rhe fo llowing program?

'include <iostream> using namespace std : void test{int

= 2,

int = 4, int

6);

To Read Online & Download: WWW.ISSUU.COM/SHEIKHUHASSAN


Bismillah hiir Rehman nir Raheem-----------------------------Assalat o Wasalam o Alika Ya RasoolALLAH 361

6.13 Using Reference Variables as Parameters

us uf

i

int main() {

test(); test(6) ; test(3, 9); test{l, 5, 7); return 0 ;

Yo

}

void test (int first, int second, int third) {

" " «

second «

" " «

third «

endl;

az

first + - 3; second += 6; third += 9; cout « first «

The following program asks the user to enter two numbers. What is the output of the program if the user enters 12 and 14?

Ri

6.23

'include <iostream> using namespace std;

int main() (

int x

= 0,

y

ss

an

void funcl(int &, int &); void func2(int &, int &, int &); void func3(int, int, int);

= o.

= 0; y «

«

z «

endl;

y «

«

z «

endl;

y «

«

z «

endl;

y «

«

z «

endl;

)

ad

Ha

cout « x « " « funcl(x, y) ; « cout « x « func2{x, y, z) ; COllt « x « " " « func3(x, y, z) ; cout « x « " " « return 0;

z

m

void funcl(int &a, int &b) {

m

cout « "Enter two numbers : "; cin » a » b;

}

void func2(int &a, i nt &b, int &c)

M

uh a

{

b++; c--;

a = b +

Ci

}

void func3(int a, int b, int c) {

a '" b -

Ci

}

To Read Online & Download: WWW.ISSUU.COM/SHEIKHUHASSAN


Bismillah hiir Rehman nir Raheem-----------------------------Assalat o Wasalam o Alika Ya RasoolALLAH

36

Functions

us uf

i

Chapter 6

Overloading Functions

Yo

CONCEPT: Two or more fu nctions may have the sa me name, as long as their parameter li sts are differenl.

an

Ri

az

Sometimes you will create two or more functions that perform the same opera ti on, but lise a different set of parameters or parameters of different data types. For instance, in Program 6-13 the re is a square fun ction that uses a double parameter. But, suppose YOLI also wanted a square function that works exclusively with integers, accepting a n int as irs argument. Both functions would do the same thing: return the square of their argument. The only difference is the data type involved in the operation. If you wefe to usc both these functions in the same program, you could assign a unique name to each function. For example, the funct ion that squa res an lnt might be named squarernt , and the one that sq uares a double might be named squareDoubl e. C++, however, allows you [0 overload function names. That means you may assign the same name to multiple functions, as long as their parameter lists are different. Program 6-27 uses twO overloaded square fLlnnions.

Program 6-27

ss

// This program uses overloaded functions . 'include <iostream> 'include <i omanip> using names pace std;

5

6 7 8

/1 Function prototypes int square(int); double squa re(doub l e);

Ha

1 2 3 4

in t main()

11

14

II Get an int and a double . cout « fixed « showpoint « setprecision(2) ; cout « "Enter an integer and a floating - point value: "; cin » userlnt » userFloat;

19 20 21 22 23

// Display their squares . cout « "Here are their squares: "; cout « s quare (userInt) « ., and" « return 0;

m

16 17 18

uh a

15

iot userlnt; doub le userFloat ;

m

12 13

ad

9

10

square(userFloat);

M

"25 26

27

28

29 30

11 **************************************************** ********** II Definition of overloaded function square . * II This function uses an int parameter, number. It returns the * 1/ square of number as an int o * //*********** ***** ************ **********************************

To Read Online & Download: WWW.ISSUU.COM/SHEIKHUHASSAN


Bismillah hiir Rehman nir Raheem-----------------------------Assalat o Wasalam o Alika Ya RasoolALLAH

6.14 Overloading Functions

us uf

i

363

31

36 37

38 39 40

41

int square(int number) ( return number * number; )

11******** ************ ******** *************** ********* *********** II Definition of overloaded function square. * II This function uses a double parameter, number . It returns * II the square of number as a double . * 11 ******************** ******************************** **** *******

Yo

32 33 34 3S

43

double square(douhle number)

44

{

return number * number;

45 }

Ri

46

az

42

an

Program Output with Example Input Shown In Bold Enter an integer and a floating-point value : 124.2 [Enter) Here are their squares: 144 and 17.64

H ere are the headers for the square fu nct ions used in Program 6路27:

ss

int square(int number)

double square(double number)

square (iot)

Ha

In C++, each function has a signature. The function signature is the name of the function and the data types of the funct ion's parameters in the pro per order. The square fUllctions in Program 6路27 would have the followi ng signa tures:

ad

square(douhle)

m

When an overloaded function is ca lled, C++ uses the function signature to distinguish it from other fu nctions with the same name. In Program 6-27, when an int a rgument is passed to square, the version of the function that has an iot parameter is ca lled. Likewise, when a double argument is passed to square, the version w ith a double parameter is called.

m

Note that rhe fu nction'S return va lue is nor parr of the signature. The following functions could not be used in the sa me program because their parameter lists aren't different. iot square(int number)

uh a

(

return number * number

)

M

double square{int number)

II Wrong! Parameter lists must differ

{

return number * number }

To Read Online & Download: WWW.ISSUU.COM/SHEIKHUHASSAN


Bismillah hiir Rehman nir Raheem-----------------------------Assalat o Wasalam o Alika Ya RasoolALLAH

Chapter 6 Functions

us uf

i

364

Overloading is also convenient when there are similar funcrions th at use a different number of parameters. For example, co nsider a program with funct ions that return the sum of integers. One returns the sum of two integers, anorher returns the su m of three integers, and yet another returns the sum of four integers. Here are their function headers:

int sum(int numl. i nt num2, i nt num3) iot sum(int numl, int num2 , int num3, int num4)

Yo

int sum(int numl, in t num2}

Because the number of parameters is different in each, they all may be used in the sa me pro-

az

gram. Program 6-28 is an example time uses tWO fu nctions, each named calcWeeklyPay, ro

Ri

determine an employee's gross weekly pay. One version of the function uses an int <lnd a double parameter, while {he other version only uses <I double pa ra meter.

Program 6-28

5

• 7

8 9 10 11

II Function prototypes void getChoice(char &); double calcweek lypay(i nt, double); double calcWeeklyPay(double);

12

int main()

13 14

{

"

17

char selection; i nt worked; dou bl e rate; dou ble yearly;

18

21 22 23 24

II Disp l ay the menu and get a sele ction . cout « "00 you want to calculate the weekly pay o f\n"; cout « "(H ) an hourly paid empl oyee, or \n" ; cout « "( 5 ) a s alar ied emp l oyee?\n"; getChoice(select ion);

uh a

25 26

II Se t numeric output formatting. cout « f ixed « showpoint « setprecision(2 )i

m

20

II Yearly sa l ar y

m

19

II Menu selection II Hours worked II Hourly pay rate

ad

15

an

3 4

II This program demonstrates overloaded functions to calculate II the gross wee k ly pay of hourly pa i d or salar ied employees . ' include <iostre am> ii nclude <ioma nip> using namespace std ;

ss

2

Ha

1

27

28

29

30 31

M

32 33

II Process the menu selection . switch (selection) { II Hourly paid employee case 'H' case 'h' : cou t « "How many hours were worked

"

,.

To Read Online & Download: WWW.ISSUU.COM/SHEIKHUHASSAN


Bismillah hiir Rehman nir Raheem-----------------------------Assalat o Wasalam o Alika Ya RasoolALLAH

365

cin » worked ;

34 35

c o ut «

36

ci n » r ate; cout « "The gross weekly pay i s $" , cout « calcweeklypay(worked, rate) « break;

40 41

If Sa l aried employee

42

case ' 5'

43 44

c a se '5'

45

cout « "What is the annua l salary? " i cin » year l y ; cout « "The gross weekl y pay i s $";

cout « br eak ;

46

47

calcwe eklyPay(yearly) «

}

return

OJ

50

51 52

53

e nd1 ;

Ri

48 49

endl ;

Yo

38

39

az

37

"What is the hourly pay rate? "i

us uf

i

6. 14 Overloading Funct ions

//************************ *** ***** ** ** *** * ************ . k.* * kk _ _ • 1/ Definit i on of functio n getChoice . I I The pa r ameter l etter is a reference t o a char . II Th i s function asks t he user fo r an H or an Sand returns 1/ t he val idated i nput .

58 59

vo i d getChoice(char &letter)

60

{

II

Get the u ser's selection . cout « "Enter your c hoice (H o r S) : "; cin » letter ;

62 63

Ha

61 6.

{

75

uh a

76 77 78 79

····································.···· ....•••• IIII·········.· Def i n i tion of overloaded function calcweek l yPay . II This function calculates t he gross weekly pa y of • II an hour l y paid employee . The parameter hours holds the • II number o f hours worked. The parameter payRate holds the • II hourly pay rate . The func t ion returns the weekly salary . •

m

73

}

)

I/w w• • • ••• • • • •• • ••• •• ••• • ••••••••••••••••••••••••• • ••• •••••••

(program continues)

M

80

..

m

cou t « "Please enter H or S : " cin » lett er ;

70

74

ad

II validate the select i o n. while (letter 1= 'H' && letter 1= 'h' && letter 1: '5' && let t er 1= 'S')

6S 66 67 68 69 71 72

ss

55

an

• • 56 • 57 11·············*········ __ ···_· __ ·_----·_· _- --------_·.k .. kkk k_ 54

To Read Online & Download: WWW.ISSUU.COM/SHEIKHUHASSAN


Bismillah hiir Rehman nir Raheem-----------------------------Assalat o Wasalam o Alika Ya RasoolALLAH

366

Functions

us uf

i

Chapter 6

(continued) 81

82

double calcWeeklyPay(int hours, double payRate)

8]

{

return hours * payRatei

84

Yo

85

86

89 90

91 92

1/****************************************** *** ********_k _*k_ II Definition of overloaded function calcWeeklyPay . * II This function calculates the gross weekly pay of * /1 a salaried employee. The parameter holds the employee's *

1/ annual salary. The function returns the weekly salary. * //******* **********************************************-*-*-*

az

87 88

94 95 96

double calcWeeklyPay(double annSalary) { return annSalary / 52;

97

)

Ri

9]

an

Program Output with Example Input Shown In Bold

Do you want to calculate the weekly pay of

Ha

ss

(H) an hourly paid employee, or (5) a salaried employee? Enter your choice (H or 5) : H [Enter] How many hours were worked? 40 [Enter] What is the hourly pay rate? 18.50 [Enter] The gross weekly pay is $740 . 00

Program Output with Example Input Shown In Bold

m

ad

Do you want to calculate the weekly pay of (H) an hourly paid employee , or (5) a salaried employee? Enter your choice (H or S): S [Enter] What is the annual salary? 68000.00 [Enter] The gross weekly pay is $1307.69

m

The exit() Function

M

uh a

CON CEPT: The exit () fun ction causes a program to termi nate, rega rdless of which function or control mechanism is executing.

A C ... + program stops executing when the return statement in function main is encountered. When other functions end, however, the program does not stop. Control of the program goes back to the place immediately following the function cal!. Sometimes it's convenient or even necessary to terminate a program in a function other than main. To accomplish this, the exit function is used. When the exit function is called, it causes the program to stOp, regardless of which function contains the call. Program 6-29 demonstrates its use.

To Read Online & Download: WWW.ISSUU.COM/SHEIKHUHASSAN


Bismillah hiir Rehman nir Raheem-----------------------------Assalat o Wasalam o Alika Ya RasoolALLAH 367

5 6

7

9 10

void function();

Yo

II This program shows how the exit funct i on causes a program II to stop execut i ng . 'include <iostream> jinclude <cstdlib> I I For e xit using namespace std;

1 2 3 4

II Function prototype

intmain () {

function ( ) ; return 0 ;

11

us uf

i

6.15 The exit() Function

II Thi s fun ction simply demonstrates that exit can be used II to termi nate a program from a function o ther than main .

18

// *~*** ****~*~*********** ******** ************ **** ************

az

12 13 14 15 16 17

)

Ri

11 ****** ********************** ************************ ******~

19

void func t ion () {

an

20 21

26 27

cout

<;<;

ss

cout« "This program terminates with the exit function . \n" , cout « "8ye !\n" ; ex i t(O), cout « "This mess age will never be displayed\n",

22 23 24 25

"becallse the progro m haa already terminated. \n" ;

Ha

}

Program Output

This program terminates with the exit function.

ad

Bye !

uh a

m

m

To use the e xit funct ion, be sure to include the cstdlib header fi le. Notice the function rakes an integer argument. This argument is the exit code you wish the program to pass back to the comp uter's operating system. This code is sometimes used o utside of the pro gram to indicate whether the program ended successfully or as the result o f a fa ilure. In Program 6-29, the exit cod e zero is passed, which commonly indica tes a successful exit. If you are unsure which code to use wi th the exit function, there are two named constams, EXIT_FAI LURE and EXIT_SUCCESS, defi ned in cstdlib for yOll ro use. The conStant EXIT_FAILURE is defined as the termination code that commonly n:preselHs an unsuccessfu l exit under the cu rrent operating system. Here is an exam pl e of its use: exit(EXIT_FAILURE);

T he constant EXIT_ SUCCESS is defined as the termination code cha r commonly represents

M

a successful exit under rhe current operating system. Here is an example: e xit(E XIT_5UCCESS) ;

~

NOTE: Generally, the exit code is important only if you know it will be tested outside the ~ L-_p_,o_g__,a_n_'_,_I_f_i_'_i,__n_o_,_u_,_e_d_,_j_u_,_,_p_'_'_'_'_'_"_o_,_O_'__E_X_I_T_-_S_U_C_C _E __S_S_,__________________________~

To Read Online & Download: WWW.ISSUU.COM/SHEIKHUHASSAN


Bismillah hiir Rehman nir Raheem-----------------------------Assalat o Wasalam o Alika Ya RasoolALLAH

Chapter 6

runctions

~

us uf

i

368

Checkpoint 6.24

What is the output of the follow ing program?

Yo

'include <iostream> 'include <cstdlib> using namespace std ; void sho'NVals (double , double) i lnt main() (

showVals(x,

4.5:

az

double x = 1 . 2, Y y);

Ri

return 0: }

void showVals(double pl. double p2J

endl: endl;

}

What is the output of the following program?

ss

6.25

an

cout « pI « exit(O)i cout « p2 «

Ha

jinclude <iostream> using namespace std ;

lnt manip(int); l nt manip(int, intI :

iot manip(int, double);

ad

int main ( )

lnt x

~

2, y= 4,

Zj

double a = 3.1; a)i

m

z = manip(x) + manip(x, y) + manip(y, cout « z « endl; return 0;

}

M

uh a

m

int manip(int val) (

return val + val * 2;

lnt manip(int vall , lot val2) (

return (vall + val2) * 2;

}

int manip(int vall, double va l 2) (

return vall * static_cast<int>(va12) ;

}

To Read Online & Download: WWW.ISSUU.COM/SHEIKHUHASSAN


Bismillah hiir Rehman nir Raheem-----------------------------Assalat o Wasalam o Alika Ya RasoolALLAH 6.16 Stubs and Drivers

us uf

i

369

Stubs and Drivers

Stubs and drivers are very helpful tools for test ing and debugging programs that use fun c-

Yo

tions. They allow you to rest the individual functions in a program, in isolation from the parts of the program that call the functions.

az

A stub is a du mmy function that is called instead of the actual function it represents. It usually displays a test message acknowledging that it was called, and nothing more. For example, if a stub were used for the showFees function in Program 6-10 (the modular hea lth club membership program), it might look like this: void showFees(double memberRate, int months) {

« «

«

"The showFees function was called wit h "the following arguments:\n" "memberRate : " « memberRate « endl "months: " « months « endl;

Ri

cout «

)

an

The following is an example output of the program if it were run with the stub instead of the actual showFees functio n. (A vcrSlon of the he<l lth club program using this stub func tion is on the Srudent CD. The program is named HealthClub..lithStub.cpp.)

ss

Heal th Club Membership Menu

Ha

1 . Standard Adult Membership 2 . Child Membership 3. Senior Citizen Membership 4. Quit the Program

ad

Enter your choice : 1 [Enter] For how many months? 4 [Enter] The showFees function was called with the following arguments :

m

membQrRate, 40.00 months: 4

Health Club Membership Menu

1 . Standard Adult Membership

m

2 . Child Membership

3. Senior Citizen Membership

uh a

4. Quit the Program

Enter your choice: 4 [Enter]

M

As YOll can see, by replacing an actual function with a stub, you ca n concenrrate your resting efforts on the parts of the program that call the function. Primarily, the stub allows

you to determine whether yo ur program is <:al!ing a funct ion when you expect it to, and co connJ'm that valid values are being passed to the function. If the stub represents a function that returns a value, then the stub should return a test value. This helps you confirm that the return value is being handled properly. When the parts of the program that call a function are debugged to your satisfacti on, you can move on to tesring and debugging the actu<ll functions themselves. This is where drillers become useful.

To Read Online & Download: WWW.ISSUU.COM/SHEIKHUHASSAN


Bismillah hiir Rehman nir Raheem-----------------------------Assalat o Wasalam o Alika Ya RasoolALLAH

Chapter 6 Functions

i

3 70

us uf

A driver is a program that tests a funcrion by simply calling it. I f the funcrion accepts arguments, the driver passes test data. If the function returns a value, the driver displays the rerurn value on the screen. This allows you to see how the function performs in isolation from the rest of the program it will eventually be pan of. Program 6-30 shows a driver for resting the showFees funcrion in (he health club membership program.

Yo

Program 6 -30

/1 This program is a driver for testing the showFees function. 'include <iostream> using namespace std;

/ / Prototype void showFees(double , intI;

8

int main()

9

{

10

II Constants for membership rates

11 12

canst double ADULT = 40 . 0 : canst double SENIOR = 30 . 0 ; canst double CHILD = 20.0;

an

13 14

// Perform a test for adult membership. cout « MTesting an adult membership ... \n~ « "Calling the showFees function with arguments .. « ADULT « .. and 10. \nM i showFeeS(ADULT, 10)i

ss

15 16 17 18

Ha

19 20

// Perform a test for senior citizen membership. cout « " \nTesting a senior citizen membership ... \n" « "Calling the showFees function with arguments " «SENIOR«" and 10 . \ n "i 5howFees{SENIOR, 10) ;

21 22 23

24 25

ad

26

II Perform a test for child membership . cout« "\nTesting a child membership . .. \n" « .. \nCalling the showFees function with arguments " « CHILD « " and 10 . \n"; showFees(CHILD , 10); return 0 :

29 30

uh am

)

m

27 28

31 32 33 34

Ri

,

az

1 2 3 4 S 6

35

1/·······································*·*.* •••• •••• •••••••••••••

36 38

// Definition of function showFees. The mernberRate parameter holds· II the monthly membership rate and the months parameter holds the. // number of months. The function displays the total charges. •

39

/1**************************************************** .* •••••••••••

37

40

M

41

42

43 44

void shoWFees{double rnemberRate , iot monthS) {

cout «

«

"The t 'o tal charges are $" {memberRate • months} « e ndl ;

45

To Read Online & Download: WWW.ISSUU.COM/SHEIKHUHASSAN


Bismillah hiir Rehman nir Raheem-----------------------------Assalat o Wasalam o Alika Ya RasoolALLAH Review Questions and Exercises

i

3 71

us uf

Program Output Testing an adult membership ...

Testing a senior citizen membership .. . Calling the showFees function with arguments 30 and 10 . The total charges are $300

Testing a child membership ...

az

calling the showFees function with arguments 20 and 10 . The total charges are $200

Yo

Calling the showFees function with arguments 40 and 10. The total charges are $400

Ri

As shown in Program 6~30, a driver can be used to thoroughly test a function . It can repeatedl y ca ll the function with different test values as arguments. When the flmction performs as desired, it can be placed into the actua l program it will be part of.

Case Study on CD, See High Adventure Travel Agency Pan 1 Case Study on the Student CD.

an

Review Questions and Exercises Short Answer

ss

1. Why do local variables lose their va lues between calls to the function in which they

are defined?

Ha

2. What is the difference between an argument and a parameter variable? 3. Where do you defi ne parameter variables? 4. If you arc writ ing a function that accepts an argument and you want to make sure the function cannot change the value of the argument, what do you do?

ad

5. When a functi on accepts multiple argumems, does it maner in w hat order the arguments are passed in?

m

6. How do you return a value from a functi on? 7. What is the advantage of breaking your app lication's code into severa l smal l procedures?

m

8. How wou ld a static local variable be useful?

uh a

9. Give an example where passing an argument by reference would be useful.

FIII路in路the路Blank

M

10. The is the part of a fun ction definition thar shows the fllnction name, return type, and parameter list. 11. If a functio n doesn't retu rn a value, the word _ _ _ _ will appear as its return type. 12 . Either a function's _ _ _ _ Ot irs _ _ _ _ m ust precede all calls to the fun ction.

13. Values that arc scm into a funct ion arc ca lled _ __ _

To Read Online & Download: WWW.ISSUU.COM/SHEIKHUHASSAN


Bismillah hiir Rehman nir Raheem-----------------------------Assalat o Wasalam o Alika Ya RasoolALLAH ~unc.tiom,

15. When only a copy of all argumenr is passed

to a

us uf

14. Special variables that hold copies of funct ion argumenrs a re called _ _ __

i

Chapte.r 6

372

funcrion, it is said ro be passed by

16. Aln) .,---___ climinares the need to place a fun ction definition before all calls to the function .

Yo

17. Aln) .,---___ variable is defined inside a function and is not accessible outside the function.

18.

variables are defin ed outside all functions and are accessibl e ro any function within their scope.

19.

va ria bles provide an easy wa y to sha re large amounts of data among all

az

the functions in a program .

Ri

20. Unless you explici tly initialize glo bal variables. they a re automa ti ca lly initialized to

21. If a funct io n has a local varia ble with the same name as a global variable, only the _ _ _ _ variable can be seen by the function. 22.

local va riables retai n their value between func tion ca lls.

arguments a re passed to parameters automatically if no a rgument is provided in the function call.

ss

24.

an

23. The _ _ _ _ statement ca uses a fun ction to end immedia tely.

25. When a function uses a mixture of parameters with and without defa ult arguments, the parameters with default arguments must be

defined ____

Ha

26. T he va lue of a defa ult argument must be a{n) _ _ __

27. When used as parameters, _ _ _ _ variables allow a function

to access the parame-

ter's original argument.

ad

28 . Reference varia bles are defined li ke regular variables, except there is a (n) _ __ _ on fro nt of the name.

29. Reference variables allow arguments to be passed by _ _ _ __

m

30. T he _ _ _ _ funct ion ca uses a program to term inate.

m

31. Two or more fu nctions may have the same name, as long as their _ _ _ _ are diffe rent.

Algorithm Workbench

uh a

32. Examine the following fun ction header, t hen write an example ca ll to the funct io n.

void showValue (int quantity)

M

33. The following statement calls a funct io n named half . The half function returns a value that is half that of the argument. Write the function.

result

=

half(number) ;

To Read Online & Download: WWW.ISSUU.COM/SHEIKHUHASSAN


Bismillah hiir Rehman nir Raheem-----------------------------Assalat o Wasalam o Alika Ya RasoolALLAH 373

Review Questions and Exercises

us uf

i

34. A program contains the following funct ion. int cube(int num) {

return num * num * num; )

Yo

Write a statement that passes the value 4 to this fu nction and assigns its rerum value to the variable resu lt.

35 . Write a functi on named timesTen that accepts an argument. When the funct ion is called , it should display the product of its argumenr multiplied rimes 10. 36. A progra m conta ins the fo llowing function . {

«

«

"Here are the values : " argl « " " « arg2 « " arg3 « endl;

Ri

cout «

az

void display{int argl, double arg2, char arg3)

)

int age; double income; char initial ;

an

Write a statement tha t ca lls the procedure and passes the following variables to it:

True or False

Ha

ss

37. Write a func tion named getNumber that uses a reference paramete r variable to accept an integer argument. The function should prompt the user to enter a number in rhe ra nge of l through 100. The input should be validated and sto red in the parameter variable.

F

Functions should be given names that reflect their purpose.

F

Function headers are terminated with a semico lon.

4 1. T

F

Function prototypes are terminated with a semicolon.

If other functions are defined before main, the program still sta n s executing

at function main. When a function terminates, it alwa ys branches back where it was called from .

m

F

ad

38. T 39. T 40. T

F

43. T

F

Arguments are passed to the funct ion parameters in the order they appea r in the function ca ll.

44. T 45 . T

F

The scope of a parameter is limited to the function which uses it.

F

46 . T

F

47. T 48. T

F

Changes to a function parameter always affect the original argument as well. In a func tion prototype, the names of the paramete r variables may be left Ollt. Many functions may have local va riables with the same name.

F

Overuse of global vari ables can lea d to problems.

f

Static local variables are not des(foyed when a fun ction returns.

F

All static local va riables arc initialized to - 1 by default.

M

uh a

m

42. T

49. T 50. T

to

main, rega rd less of

To Read Online & Download: WWW.ISSUU.COM/SHEIKHUHASSAN


Bismillah hiir Rehman nir Raheem-----------------------------Assalat o Wasalam o Alika Ya RasoolALLAH

Functiom

51. T

F

52. T

F

i

Chapter 6

Initialization of static local variables only ha ppens once, regardless of how many times the fu nction in which they are defined is ca lled .

us uf

37

When a function with default arguments is called and an argument is left out, all arguments that come after it must be left out as well.

F

It is not possible for a fU IlC(ion to have some parameters with default arguments and some without.

54. T 55. T

F

The exit function can only be called from main.

F

A stub is a dummy function that is called instead o f the actual function it rep-

resents.

Yo

53. T

az

Find the Errors

Each of the following functions has errors. Locate as many errors as you can.

Ri

56. void total(int valuel, value 2, value3) {

return value! + value2 + value3:

57. double average(int valuel, int value2, int value3)

an

{

double average;

= value 1

+ value2 + value3 I 3;

ss

average )

Ha

58. void are a (int length = 30 , int width) {

return length * width; )

59. void getValue(int value&) {

ad

cout « "Enter a value: "; cin » value&; )

m

60. (Overloaded functions) int getValue ( ) {

uh a

m

int inputValue; cout « "Ente r an integer : "; cin » inputValue; return inputValue;

)

double getValue()

M

{

double inputValue; cout « "Enter a floating - point number: .'; cin » inputValue; return inputValuei

)

To Read Online & Download: WWW.ISSUU.COM/SHEIKHUHASSAN


Bismillah hiir Rehman nir Raheem-----------------------------Assalat o Wasalam o Alika Ya RasoolALLAH Review Questions and Exercises

i

375

us uf

Programming Challenges 1. Markup

Write a program that asks the user to enter an item's wholesale cost and its ma rkup percentage. It should then display the item's reta il price. For exa mple:

wholesale cost is 5.00 and its markup percentage is 100%, then the price is 10.00. wholesale cost is 5.00 and its markup percentage is 50%. then the price is 7.50.

The program shou ld have a function named calcu late Retail that receives the wholesale cost and the markup pe rcentage as arguments. and returns the retail price ofthe item.

az

Solving th e Markup Problem

If an item's item 's retail If ao item's item's retail

Yo

2. Rectangle Area-Complete the Program

Ri

Input Validation: Do not accept negative values (o r either the wholesale cost o( the item or the -markup percentage.

Ha

getLength - This fun ction should ask the user to enter the rectangle's length. and then retu rn that value as a double. getWidth - This fu nctio n should ask the user to enter rhe recta ngle's widt h, and then return that va lue as a doub le. getArea - This function should accept the rectangle's length and width as arguments, and rermn the rectangle's area. The area is calculated by multipl ying the length by the width. di splayData - This fu nction should accept the rectangle's length, width, and area as arguments, and display them in an appropriate message on the screen .

ss

an

The Student CD contains a partia lly written program named AreaRectangle.cpp. Your job is to complete the program. When it is comp lete. the program will ask the user ro enter the width and length of a rectangle, and then display the rectangle's area . The program calls the following functio ns, which have not been written:

ad

3. Wi nning Division

double getSa les ( ) is passed the name of a division. lr asks the user for a division's quarterly sales figure, validates the input, then retu rns it. It should be called once for each division. void findHighest() is passed the four sales totals. It determines which is the largest and prints the name of the high gross ing division, along with its sa les figure.

m

m

Write a program that determines which of a company's four divisions (Northeast, Southeast, Northwest, and Southwest) had the greatest sales for a quarter. It shou ld include the following twO funct ions, which are called by main.

uh a

M

Input Validation: Do not accept dollar amounts less than $0.00.

To Read Online & Download: WWW.ISSUU.COM/SHEIKHUHASSAN


Bismillah hiir Rehman nir Raheem-----------------------------Assalat o Wasalam o Alika Ya RasoolALLAH

376

i

Chapter 6 Functions

us uf

4 . Safest Driving Area

Write a program that determines which of five geographic regions within a major city (north, south, cast, west, and central) had the fewest reported automobile accidents last year. It should have the following two functions, which are called by main. int getNumAccidents ( ) is passed the name of a region. It asks the user for the number of automobi le accidents reported in that region during the last year, va lidates the input, then returns it. It should be called once for each city region. void findLowest () is passed the five accident totals. it determines which is the smallest and prints the name of the region, along with its accident figure.

Yo

â&#x20AC;˘

â&#x20AC;˘

az

Input Validation: Do not accept an accident number that is less than O.

5. Falling Distance

Ri

When an object is falling because of grav ity, the following formuJa ca n be used to determine the distance the object falls in a specific time period:

an

The variables in the for mula are as follows: d is the distance in meters, g is 9.8, and t is the amount of time, in seconds, that the object has been falling.

6. Kinetic Energy

Ha

ss

Write a function named fallingDistance that accepts an object's falling time (in seconds) as an argument. The function should return the distance, in meters, that the object has fallen during that time interval. Write a program that demonstrates the function by calling it in a loop that passes the values 1 through 10 as arguments, and displays the return value.

ad

In physics, an object that is in motion is said to have kinetic energy. The fo llowing formula can be used to determine a moving object's kinetic energy:

m

The variables in the formula are as follows: KE is the kinetic energy, m is the object's mass in kilograms, and v is the object's velocity, in meters per second.

m

Write a function named kineticEnergy that accepts an object's mass (in kilograms) and velocity (in meters per second) as argumenrs. The funerion should return the amOunt of kinetic energy that the object has. Demonstrate the funcrion by calling it in a program thar asks rhe user to enter values for mass and velocity.

uh a

7. Celsius Temperature Table The formula for converting a temperature from Fahrenheit to Celsius is

M

C

= ~(F-32)

where F is the Fahrenheit remperarure and C is the Celsius temperature. Write a function named celsius that accepts a Fahrenheit temperature as an argument. The function should return the temperature, converted to Celsius. Demonstrate the function by calling it in a loop that displays a table of the Fahrenheit temperatures 0 rhrough 20 and their Celsius equivalents.

To Read Online & Download: WWW.ISSUU.COM/SHEIKHUHASSAN


Bismillah hiir Rehman nir Raheem-----------------------------Assalat o Wasalam o Alika Ya RasoolALLAH 377

Review Questions and Exercises

us uf

i

8. Coin Toss

Yo

Write a function named coinToss that simulates the rossing of a coin. When you ca ll the funct ion, it should generate a random number in the ra nge of J through 2. If the random number is 1, the function should display " heads." If the tandom number is 2, the functio n should display "ta ils." Demonstra te the function in a program that asks the user how many times the coin should be rossed, and then simulates the rossing of the coin that number of times.

9. Present Value

F = ---0

(1 + r)"

T he terms in the fo rm ula are as follows:

• •

ss

P is the present value, or the amount that you need to deposit today. F is the future value that you want in the account. (In this case, F is $10,000.) r is the annual interest rate. 11 is the number of years that you plan to let the money sit in the account.

an

Ri

P

az

Suppose you want to deposit a certain amoum of money into a savings account, and then leave it alone to draw interest for the next 10 years. At the end of 10 yea rs you wou ld like to have $10,000 in the account. How much do you need to deposit today to make rhat hap pen? You can use the following form ula, wh ich is known as the present value formu la, to find out:

Ha

Write a progra m that has a funct ion named presentValue that performs th is calcu l a~ rion . The function should accept the future value, annua l interest rate, and num ber of years as arguments. It should return the present value, which is the amount that you need to deposit today. Demonstrate the func tion in a program that lets the user experimenr with different values for the formula's terms.

10. Lowest Score Drop

void getScore () should ask the user for a test score, store it in a reference

parameter variable, and validare ir. Th is function should be called by mai n once for each of the five scores to be entered. void calcAverage() should calculate and display the average of the fou r highest scores. This func tion should be called just once by main, and shou ld be passed the five scores. .int:. fi nd Lowest:.() should find a nd return the lowest of the five sco res passed to it. It should be ca lled by calcAverage, which uses t he fu nction to determine which of the five scores to drop.

m

ad

Write a program t hat calc ula tes the average of a gro up of test scores, where the lowest sco re in the group is d ropped. It should use the follow ing functions:

m

uh a

M

Input Validation: Do 1lot accept test scores lower than 0 or higher than 100.

To Read Online & Download: WWW.ISSUU.COM/SHEIKHUHASSAN


Bismillah hiir Rehman nir Raheem-----------------------------Assalat o Wasalam o Alika Ya RasoolALLAH 378

Chapter 6

Functions

us uf

i

11. Star Search

A pa rticular ra lenr competition has five judges, each of whom awards a score between

o and 10 to each performer. Fractional scores, such as 8.3, are allowed . A performe r's final score is determined by dropping the highest and lowest score rece ived, then averaging the th ree remaining scores. Write a program that uses this method to calcu late a contestant's score. It should include rhe followi ng functions: void getJUdgeData ( ) sho uld ask the user fo r a judge's score, store it in a refer-

Yo

ence parameter va ria ble, and va lidate it:. T his function should be called by main once for each of the five judges. void calcScore ( ) shou ld calculate and d isplay rhe average of the three scores t hat remain after dropping the highest and lowest scores rhe performer received. This function shou ld be called just once by main, and should be passed the five scores.

az

Ri

T he last two functions, descri bed below, should be ca lled by calcScore, which uses the returned info rma tion to determi ne which of the scores to drop. • int findLowest ( ) sho uld find and return the lowest of the five scores passed to it. • int find Highest ( ) should fin d and return the highest of the five scores passed to it.

Input Validatio n; Do fl at accept judge scores lower than 0 or higher than 10.

an

12. Days Out

ss

Write a progra m that calcu lates the average nu mber of days a company's em ployees arc absent. T he progra m shou ld have the follOWing funct ions;

A functio n caJled by ma i n that asks the user for the nu mber of emp loyees in t he company. T his va lue sho u ld be returned as a n into (The function accepts no arguments.) A fllllCt io n cal led by main that accepts on e argumenr: rhe number of employees in rhe company. T be function shoul d ask the user to enter the number of days each emp loyee missed duri ng the past year. The total of these days sh ould be returned as an into A fu nction called by main that ra kes two arguments: the nu mber of em p loyees in the compa ny a nd the toral num ber of d ays absent for all em ployees d uring the yea r. T he fu nctio n should return, as a double, the averase number of d ays absent. (T his fu nction d ocs nOt perform sc reen Outp ut and does not ask t he LIseI' for inpur.)

Ha

m

ad

m

Inpllt Va/dation: Do not accept a nllmber less than 1 for the number of employees. Do not accept a 17egative ,wmber for the days any employee missed.

13. Order Status

M

uh a

T he Middletown Wholesale Cop per Wire Compa ny sells spools o f copper w iring for $100 each. Write a progra m that d isp lays the status of an orde r. T he progra m should have a functi on that asks for the follow ing d ata: • • •

The numbe r of spoo ls ordered. The number of spools in stock. Whether there are special shi pping and hand ling cha rges.

(Shipping a nd handling is normally $10 per spooL) If th ere are special charges, the program s hou ld ask fo r the specia l charges per spool.

To Read Online & Download: WWW.ISSUU.COM/SHEIKHUHASSAN


Bismillah hiir Rehman nir Raheem-----------------------------Assalat o Wasalam o Alika Ya RasoolALLAH 379

Review Questions and Exercises

• • •

The number of spools ready to ship from current stock. The number of spools on backorder (if the number ordered is greater than what is in stOck). Subtotal of the portion ready to ship (the number of spools ready to ship times $100). Tota l shipping and handling charges on the portion ready to ship. Tota l of the order ready to sh ip.

Yo

• •

us uf

i

The gathered data should be passed as argumentS to another function that displays

The shipping and hand ling parameter in the second function should have the defau lt argument to.OO.

az

[nput Validation: Do not accept numbers less than 1 for spools ordered. D o not accept a number less than 0 for spools in stock or shipping and handling charges. 14. Overloaded Hospital

The number of days spent in the hospital The daily rate Hospital medication charges Charges for hospital services (la b tests, etc. )

an

• • • •

Ri

Write a program that computes and displays the charges for a patient's hospital stay. First, the program should ask if the patient was ad mitted as an in- patient or an outpatient. If the patient was an in-patient, the following data should be entered:

Charges fo r hospital services (lab tests, etc.) H ospital medication charges

Ha

• •

ss

The progra m should ask for the following da ta if the patient was an out-patient:

The program should use two overloaded funct ions to calculate the total charges. One of the functions should accept arguments for the in-patient data, while the other fun ction accepts arguments for out-patient information. Both functions should return the tota l charges.

ad

Input Validation: Do not accept negative numbers for any data.

15. Population

m

m

In a popu lation, the birth rate is the percentage increase of the population due to births and the death rare is the percentage decrease of the popu lation due to deaths. Write a program that displays the size of a population for any number of yea rs. The program should ask for the fo llowing data ;

uh a

• • • •

The The The The

sca rting size of a population annual birth race annual death rate number of years to display

M

Write a function that calculates {he size of the population for a year. The form ul a is N = P + BP - DP

where N is the new population size, ra te, and 0 is the death rate.

P

is the previous population size,

B

is the bi rth

To Read Online & Download: WWW.ISSUU.COM/SHEIKHUHASSAN


Bismillah hiir Rehman nir Raheem-----------------------------Assalat o Wasalam o Alika Ya RasoolALLAH 380

Chapter 6 Functions

us uf

i

Input Validation: Do not accept numbers less than 2 {or the starting size. Do not accept negative numbers for birth rate or death rate. Do not accept numbers less than 1 for the number of years. 16. Transient Population

Modjfy Programming Challenge 13 to also consider the effect on population caused

az

Yo

by people moving into or out of a geographic area. Given as input a scarting population size, the annual birrh rate, the annua l death rate, the number of individuals who typically move into the area each year, and the number of individuals who typically leave the area each year, the program should project what the population will be numYears from now. You can either prompt the user to input a value for numYearS, or you can set it with in the program.

Input Validation: Do not accept nllmbers less than 2 for the starting size. Do not accept negative numbers for birth rate, death rate, arrivals, or departures.

Ri

1 7. Paint Job Estimator

ss

The number of gallons of paint required The hours of labor required T he cost of the pa int The labor charges The total cost of the paint job

Ha

• • • • •

an

A pa inting company has determined that for every 115 square feet of wa ll space, one ga Uon of paint and eight hours of labor will be required . The company charges $18.00 per hour for labor. Write a modular program that allows the user to enter the number of rooms that are to be painted and the ptice of the paint pe r gallon. It should also ask for the sq llare fee t of wall space in each room. It should then display the following data :

ad

Input validation: Do not accept a vallie less than 1 for the number of rooms. Do not accept a value less than $10.00 for the price of paint. Do not accept a negative value for square footage of wall space. 18. Using Files-Hospital Report

m

Modify Programming ChaUenge 14, Overloaded Hosp ital, to write the report it creates to a file. Print the contents of the file to hand in to your instructor.

m

19. Stock Profit The profit from the sale of a stock can be calculated as follows:

=((NS x SP) - sc) -

((NS x PP) + PC)

uh a

Profit

M

where NS is the number of shares, SP is the sale price per share, SC is the sale commission pa id, PP is the purchase price per share, and PC is the purchase commission paid. If [he calculation yields a positive value, then the sale of the stock resulted in a profit. If the calculation yields a nega tive number, then the sale resulted in a loss. Write a function that accepts as arguments the number of shares, the purchase price per share, the purchase commission paid, the sale price per share, and the sale commission paid. T he function should return the profit (or loss) from the sale of srock.

To Read Online & Download: WWW.ISSUU.COM/SHEIKHUHASSAN


Bismillah hiir Rehman nir Raheem-----------------------------Assalat o Wasalam o Alika Ya RasoolALLAH Review Questions and Exercises

381

us uf

i

Demonstrate the function in a program that asks the user to enter the necessary data and displays the amounr of the profit or loss. 20. Multiple Stock Sales

Use the function that you wrote for Programming Challenge 19 (Stock Profit)

In

a

21.

i~Prime

Yo

program [hat calculates the total profit or loss from the sale of multiple stocks. The program should ask the user for the number of stock sa les, and the necessa ry data for each stock sale. It should accumulate the profit or loss for each srock sale and then display the total. Function

az

A prime number is a number that is only evenly divisible by itself and 1. For example, the number 5 is prime because it can only be evenly divided by 1 and 5. The number 6, however, is not prime because it ca n be divided even ly by 1, 2, 3, and 6.

Ri

Write a function name isPrime, which takes an integer as an argllment and returns true if the argument is a prime number, or false otherwise. Demonstrate the function in a complete progra m. TIP: Recall that the % operator divides one number by another, and rcmrns the % num2,

the % operaror will

ss

22. Prime Number List

an

remainder of the division. In an expression such as numl return 0 if numl is even ly divisible by num2.

Ha

Use the iSPrime function that you wrote in Programming Challenge 21 in a program that stores a list of all the prime numbers from 1 through 100 in a file. 23. Rock, Paper, Scissors Game

Write a program that lets the user play the ga me of Rock, Paper, Scissors against the computer. The program should work as follows.

ad

When the program begins, a random number in the range of 1 through 3 is generated . If the number is 1J then the computer has chosen rock. U the number is 2, then the computer has chosen paper. If the number is 3, then the computer has chosen scissors. (Don 't disp lay the computer's choice yet. )

m

1.

M

uh a

m

2. The user enters his or her choice of "rock" , "pa per", or "scissors" at the keyboard. (YOll can use a menu if you prefer. ) 3. The computer's choice is displayed. 4. A winner is selected according to the following rules: •

• • •

If one player chooses rock and the other pia yet' chooses scissors, then rock wins. (The rock smashes the scissors.) If one player chooses scissors and the other player chooses paper, then scissors wins. (Scissors cuts paper.) If one player chooses paper and the other pla yer chooses rock, then paper wins. (Paper wraps rock.) If both players make the same choice, the game must be played again to determine the winner.

Be sure to divide the program into functions that perform each major task.

To Read Online & Download: WWW.ISSUU.COM/SHEIKHUHASSAN


Bismillah hiir Rehman nir Raheem-----------------------------Assalat o Wasalam o Alika Ya RasoolALLAH

i

Chapter 6 Functions

382

us uf

Group Project

24. Travel Expenses

This program should be designed and written by a ream of students. Here a re some suggestions: One student should design fun ction main, which will ca ll the other functi o ns in the program . The remainder of the functions will be designed by other members o f the tcam. The requirements of the program should be analyzed so each student is given

Yo

a bout the sa me work load. The parameters and return types of each function should be decided in advance.

• • •

az

Stubs and drivers should be used to t CS t a nd debug the program. The program can be implemented as a multifile program, or all the fun ctions can be cut a nd pasted into the main fil e.

Ri

H ere is the assignment: Write a program that calculates and displays the toral travel expenses of a busi nessperson on a rrip. The program should have func tions that ask for and return the following:

ss

• • •

Ha

• •

M

uh a

m

m

ad

• • •

The to tal number of days spenr on the trip T he rime of departure on the firsr day of the trip, a nd the rim e of arrival back home o n the last day of the rrip The amount of any round-trip airfare The amount of any car cenrais Miles d riven, if a private vehicle was used. Calculate [he vehicle expense as $0.27 per mile driven Parking fe es (The company allows up to $6 per day . Anything in excess of this must be paid by rhe employee.) Taxi fees, if a taxi was used anytime during the trip (The company allows up to $10 per day, for each day a taxi was used. Anything in excess of this must be paid by the employee.) Conference o r se mina r registration fees Hotel expenses (The compa ny allows up to $90 per night for lodging . Anything in eXCess of th is must be paid by rhe emp loyee.) The amount of each meal eaten. On rhe firsr day of rhe trip, breakfast is allowed as an expense if the time of departure is before 7 a.m. Lunch is allowed if rhe time of departure is before 12 noon. Ditmer is allowed on the first day if me rime of departure is before 6 p.m. On tbe last day of the trip, breakfast is allowed if me time of arrival is after 8 a.m. Lunch is allowed if the rime of arrival is after 1 p.m. Dinner is allowed on the last day if the time of arriva l is after 7 p.m. The program should o nly ask for the amounts of allowable meals. (The company allows up ro $9 for breakfast, $12 fo r lunch, and $16 for dinner. Anything in excess of this must be paid by the employee.)

an

• •

The program should ca lculate and display the total expenses incurred by the businessperson, the total allowable expenses for the trip, the excess that must be reimbursed by the busi nessperson, if any, and the amount saved by the bu sinessperson if the expenses were under the total allowed.

Input Validation: Do not accept negative numbers for any dollar amount or for miles drillen in a private vehicle. Do not accept numbers less than 1 for the number of days. Only accept valid times for the time of departure and the time of arrival.

To Read Online & Download: WWW.ISSUU.COM/SHEIKHUHASSAN


Bismillah hiir Rehman nir Raheem-----------------------------Assalat o Wasalam o Alika Ya RasoolALLAH 383

Review Questions and Exercises

us uf

i

Serendipity Booksellers Software Development ProjectPart 6 : A Problem-Solving Exercise 1. Function Name Change

It is now time to make one program from the separate files you have crea ted. Perform the follow ing functi on name changes: Change Cha nge Change Change

the the the the

name of funct ion main name of func tion main name of fun ction main name of funct ion main

in cashier. cpp to cashier. invmenu. cpp to invMenu. in bookinfo.cpp to booklnfo. in reports . cpp to r eports.

Yo

• • • •

Save each file after you have changed the name of its function main.

az

2. Development Strategy

Ri

You must now decide if you are going to develop the project as a multi-file program or simply merge all the functions listed above into the mainmenu. cpp fi le. (See Appendix K, Mulrisource file programs)

Multi-File Program

an

If you decide on the multi-file program approach, follow the directions in your com-

Sittgle-File Program

ss

piler manuals to create a project or "make files" for this progra m. The files that are part of the project are mainmenu . cpp, cashier. cpp, i nvrnenu . cpp, booki nfo . cpp, and reports. cpp. mainmenu. cpp will be the main file.

Ha

If you decide to merge the functio ns of this project into one fi le, simply use the cut and paste fea ture of your editOr to perform the following: •

ad

m

• •

Copy the cashier function in cashier. cpp and paste it into the mainmenu. cpp file. Copy the invMenu fu nction in invrnenu . cpp and paste it into the mainmenu. cpp file. Copy the booklnfo function in book info . cpp and paste it into the mainmenu . cpp file. Copy the reports function in reports . cpp and paste it into the mainmenu. cpp file.

m

3. Header File C reation

Multi-File Program

uh a

If you are developing a multi-file program, create the fo llowing header files: •

fi le should contain a fu nction prototype for the cashier iinclude directive in cashier. cpp that includes cashier . h. file should contain a function protOtype for the invMenu ,incl.ude directive in invrnenu . cpp that includes invmenu _h.

M

cashier . h: This funct ion. Place an invrnenu. h: This function. Place an

To Read Online & Download: WWW.ISSUU.COM/SHEIKHUHASSAN


Bismillah hiir Rehman nir Raheem-----------------------------Assalat o Wasalam o Alika Ya RasoolALLAH Functions

â&#x20AC;˘

bookinfo. h: This file should contain a function prototype for the bookInfo function. Place an Hnclude directive in bookinfo.cpp that includes bookinfo. h. reports. h: This fi le should contain a function prototype for the reports function. Place an finclude directive in reports. cpp that includes reports. h.

i

â&#x20AC;˘

us uf

Chapter 6

Yo

Single-File Program

If you are developing a single-file program, create a header file named mainmenu. h. I t should contain function prototypes for the following functions:

az

cashier invmenu bookinfo reports

Place a 'include statement in mainrnenu. cpp that includes mainmenu . h.

Ri

4. Switch Modification in main

Modify the switch statement in function main (of mainmenu.cpp) so that instead of displaying the number entered by the user, it calls

an

funcrion cashier if the user selects 1, function invMenu if the user selects 2, function reports if the user selects 3.

ss

S. Inventory Database Stub Functions

Ha

Add stub functions that will later perform operations selected from the Inventory Database Menu. The functions are void lookUpBook(). This function shou ld simply display the message "' You selected Look Up Book,"

ad

void addBook(). This function should simply display the message "' You selected Add Book," void editBook(). This function should simply display the message " You selected Edit Book."

m

void deleteBOok(). This function should simply display the message "You selected Delete Book. "

m

Multi-File Program:

uh a

If you are developing a multi -fi le program, add the functions above to the invmenu. cpp file. Add function prototypes for each fu nction to invmenu. h. Si,tgle-File Program;

If you are developing a single-file program) add the functions above to the main-

M

menu _cpp file. Add function prototypes for each function to [he mainmenu. h file.

To Read Online & Download: WWW.ISSUU.COM/SHEIKHUHASSAN


Bismillah hiir Rehman nir Raheem-----------------------------Assalat o Wasalam o Alika Ya RasoolALLAH

i

Review Questions and Exercises

us uf

6. Switch Modification in invMenu

Modify the switch statement in function invMenu so that instead of displaying the number entered by the user) it caUs

Yo

function lookUpBook if the user selects I, function addBook if the user selects 2, function edit Book if the user selects 3, function deleteBook if the user selects 4. 7. Report Stub Functions

az

Add stub functions that will later perform operations selected from the Reports Menu. The functions are void repListing(). This function should simply display the message "You selected Inventory Listing."

Ri

void repWholesale ( ). This function should simply display the message "You selected Inventory Wholesale Value."

an

void repRetail{). This function should simply display the message "You selected Inventory Retail Value." void repQty(). This function should simply display the message "You selected Listing By Quantity."

ss

void repCost ( ). This funct ion should simply display the message "You selected Listing By Cost." I

Ha

void repAge ( ). This function should simply display the message "You selected List-

ing By Age."

Multi-File Program:

ad

If you are developing a multi-file program, add the functions above to the reports. cpp file. Add function prototypes for each function to reports . h.

Single-File Program:

m

If you are developing a single-file program, add the functions above to the mainmenu . cpp file. Add fu nction prototypes for each function to the mainmenu. h file.

m

8. Switch Modification in r eports

M

uh a

Modify (he switch statement in function reports so instead of displaying the number entered by the user, it calls function repListing if the user selects I , function repWholesale if [he user selects 2, function r epRetail if the user selects 3, funct ion repQty if the user selects 4, function repCost if the user selects 5, function repAge if the user selects 6.

To Read Online & Download: WWW.ISSUU.COM/SHEIKHUHASSAN


M uh am

m

ad

Ha

ss

an

Ri

az

Yo

us

uf

i

Bismillah hiir Rehman nir Raheem-----------------------------Assalat o Wasalam o Alika Ya RasoolALLAH

To Read Online & Download: WWW.ISSUU.COM/SHEIKHUHASSAN