Issuu on Google+

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 c