Tải bản đầy đủ (.pdf) (849 trang)

c++ for engineers and scientists

Bạn đang xem bản rút gọn của tài liệu. Xem và tải ngay bản đầy đủ của tài liệu tại đây (31.73 MB, 849 trang )

Colin Dean
You knew you were a Computer Science major when…
I had that feeling when, somewhat on a whim, I proposed to Westminster’s
information systems department that they lend me nine new, unused computers
in order to build a Folding@Home cluster in the Unix Lab. They approved, and that
cluster ran 24/7 for about six months. (
One piece of advice for fi rst year students:
Ask questions. Don’t be afraid to virtually inundate a professor with questions.
Remember, it’s your education—get what you want out of it. If a professor is
too busy to help you, fi nd another one to help. Don’t share your code with
classmates—don’t even let them look at it unless you get permission from a
professor: it’s against every school’s academic integrity policies. And fi nally, learn
at least one weird (read: non-major) language like Scheme, Smalltalk, Prolog, or
even Haskell. You never know when it might come in handy.
If you could have dinner with a famous computer scientist, living or dead, who
would you choose?
Tim Berners-Lee, the father of the World Wide Web. His creation has changed
more lives directly than just about any other technology has. It’s enabled
the dissemination of vast amounts of knowledge and enabled collaboration
throughout the world.
What technology blogs do you read on a regular basis?
I fi nd myself on Ars Technica, A List Apart, and The Daily WTF most often, as well as
Engadget and a few politics and technology blogs.
Where do you see yourself in ten years?
I hope to be running my own successful Internet-based company and
contemplating a doctorate, and perhaps holding public offi ce.
Colin Dean of Volant, PA graduated with a B.S. in
Computer Science from Westminster College in
New Wilmington, PA in May 2007. He completed his
M.S. in Business Education in July 2008 at Robert


Morris University and is employed as a developer in
Pittsburgh, PA.
Spotlight on Careers in Computing
C
++
for Engineers and Scientists
Third Edition
Gary J. Bronson
G.J. Borse
Contributing Editor
Lehigh University
Australia • Brazil • Japan • Korea • Mexico • Singapore • Spain • United Kingdom • United States
C
++
for Engineers and Scientists, Third
Edition
Gary J. Bronson
Managing Editor: Marie Lee
Acquisitions Editor: Amy Jollymore
Senior Product Manager: Alyssa Pratt
Developmental Editor: Lisa M. Lord
Content Product Manager: Matt Hutchinson
Marketing Manager: Bryant Chrzan
Editorial Assistant: Julia Leroux-Lindsey
Art Director: Marissa Falco
Compositor: GEX Publishing Services
© 2010 Course Technology, Cengage Learning
ALL RIGHTS RESERVED. No part of this work covered by the copyright
herein may be reproduced, transmitted, stored or used in any form or by
any means graphic, electronic, or mechanical, including but not limited to

photocopying, recording, scanning, digitizing, taping, Web distribution,
information networks, or information storage and retrieval systems, except
as permitted under Section 107 or 108 of the 1976 United States Copyright
Act, without the prior written permission of the publisher.
For product information and technology assistance, contact us at
Cengage Learning Customer & Sales Support, 1-800-354-9706
For permission to use material from this text or product, submit all
requests online at www.cengage.com/permissions
Further permission questions can be e-mailed to

ISBN-13: 978-0-324-78643-9
ISBN-10 : 0-324-78643-3
Course Technology
20 Channel Center Street
Boston, Massachusetts 02210
USA
Cengage Learning is a leading provider of customized learning solutions
with office locations around the globe, including Singapore, the United
Kingdom, Australia, Mexico, Brazil, and Japan. Locate your local office at:
international.cengage.com/region
Cengage Learning products are represented in Canada by Nelson
Education, Ltd.
For your lifelong learning solutions, visit www.cengage.com
Purchase any of our products at your local college store or at our preferred
online store www.ichapters.com
Some of the product names and company names used in this book have
been used for identification purposes only and may be trademarks or regis-
tered trademarks of their respective manufacturers and sellers.
Any fictional data related to persons or companies or URLs used through-
out this book is intended for instructional purposes only. At the time this

book was printed, any such data was fictional and not belonging to any real
persons or companies.
The programs in this book are for instructional purposes only.
They have been tested with care but are not guaranteed for any particular
intent beyond educational purposes. The author and the publisher do not
offer any warranties or representations, nor do they accept any liabilities
with respect to the programs.
Printed in the United States of America
12345671413121110
BRIEF TABLE OF CONTENTS
Part 1
Fundamentals of C++ Programming
1
Chapter 1
Preliminaries 3
Chapter 2
Problem Solving Using C++ 43
Chapter 3
Assignment, Formatting, and Interactive Input 103
Chapter 4
Selection Structures 177
Chapter 5
Repetition Statements 231
Chapter 6
Modularity Using Functions 293
Chapter 7
Arrays 373
Chapter 8
I/O Streams and Data Files 439
Chapter 9

Completing the Basics 489
Part 2
Object-Oriented Programming
551
Chapter 10
Introduction to Classes 553
Chapter 11
Class Functions and Conversions 597
Brief Table of Contents 3
Part 3
Data Structures
663
Chapter 12
Pointers 665
Chapter 13
Structures 707
Part 4
Additional Topics
749
Chapter 14
Numerical Methods 751
Chapter 15
Bit Operations 787
Appendix A
Operator Precedence Table 801
Appendix B
ASCII Character Codes 803
Appendix C
Floating-Point Number Storage 805
Appendix D

Command-Line Arguments 809
Index 815
4 Brief Table of Contents
CONTENTS
Part 1
Fundamentals of C++ Programming
1
Chapter 1
Preliminaries 3
1.1 Preliminary One: Unit Analysis 4
Engineering and Scientific Units 6
1.2 Preliminary Two: Exponential and Scientific Notations 10
Using Scientific Notation 11
1.3 Preliminary Three: Software Development 14
Phase I: Development and Design 15
Phase II: Documentation 19
Phase III: Maintenance 19
Backup 20
1.4 Preliminary Four: Algorithms 22
1.5 A Closer Look: Software, Hardware, and Computer Storage 28
Machine Language 28
Assembly Languages 28
Low- and High-Level Languages 29
Procedural and Object Orientations 30
Application and System Software 30
The Development of C++ 31
Computer Hardware 33
Computer Storage 34
1.6 Common Programming Errors 37
1.7 Chapter Summary 37

Chapter 2
Problem Solving Using C++ 43
2.1 Introduction to C++ 43
The main() Function 46
The cout Object 48
2.2 Programming Style 53
Comments 55
2.3 Data Types 58
Integer Data Types 59
Determining Storage Size 62
Signed and Unsigned Data Types 64
Floating-Point Types 65
2.4 Arithmetic Operations 68
Expression Types 70
Integer Division 71
Negation 71
Operator Precedence and Associativity 72
2.5 Variables and Declaration Statements 76
Declaration Statements 78
Multiple Declarations 81
Memory Allocation 83
Displaying a Variable’s Address 85
Contents 5
2.6 A Case Study: Radar Speed Traps 90
2.7 Common Programming Errors 94
2.8 Chapter Summary 95
Chapter 3
Assignment, Formatting, and Interactive Input 103
3.1 Assignment Operations 103
Coercion 107

Assignment Variations 108
Accumulating 110
Counting 111
3.2 Formatting Numbers for Program Output 117
3.3 Using Mathematical Library Functions 131
Casts 135
3.4 Program Input Using cin 139
A First Look at User-Input Validation 143
3.5 Symbolic Constants 149
Placement of Statements 151
3.6 A Case Study: Acid Rain 158
3.7 A Closer Look: Programming Errors 164
3.8 Common Programming Errors 167
3.9 Chapter Summary 167
Chapter 4
Selection Structures 177
4.1 Selection Criteria 178
Relational Operators 178
Logical Operators 181
A Numerical Accuracy Problem 183
4.2 The if-else Statement 184
Compound Statements 187
Block Scope 190
One-Way Selection 191
Problems Associated with the if-else Statement 193
4.3 Nested if Statements 199
The if-else Chain 201
4.4 The switch Statement 208
4.5 A Case Study: Solving Quadratic Equations 213
4.6 A Closer Look: Program Testing 220

4.7 Common Programming Errors 222
4.8 Chapter Summary 223
Chapter 5
Repetition Statements 231
5.1 Basic Loop Structures 232
Pretest and Posttest Loops 232
Fixed-Count Versus Variable-Condition Loops 233
5.2 while Loops 234
5.3 Interactive while Loops 245
Sentinels 251
break and continue Statements 253
The Null Statement 254
6 Contents
5.4 for Loops 256
5.5 A Closer Look: Loop Programming Techniques 268
Technique 1: Interactive Input in a Loop 268
Technique 2: Selection in a Loop 269
Technique 3: Evaluating Functions of One Variable 270
Technique 4: Interactive Loop Control 273
5.6 Nested Loops 276
5.7 do while Loops 281
Validity Checks 283
5.8 Common Programming Errors 285
5.9 Chapter Summary 286
Chapter 6
Modularity Using Functions 293
6.1 Function and Parameter Declarations 294
Function Prototypes 295
Calling a Function 296
Defining a Function 297

Placement of Statements 302
Function Stubs 302
Functions with Empty Parameter Lists 303
Default Arguments 305
Reusing Function Names (Overloading) 305
Function Templates 306
6.2 Returning a Single Value 313
Inline Functions 319
6.3 Returning Multiple Values 324
Passing and Using Reference Parameters 324
6.4 A Case Study: Rectangular to Polar Coordinate Conversion 333
6.5 Variable Scope 346
Scope Resolution Operator 349
Misuse of Globals 351
6.6 Variable Storage Categories 354
Local Variable Storage Categories 355
Global Variable Storage Categories 358
6.7 Common Programming Errors 362
6.8 Chapter Summary 364
Chapter 7
Arrays 373
7.1 One-Dimensional Arrays 374
Input and Output of Array Values 378
7.2 Array Initialization 384
7.3 Declaring and Processing Two-Dimensional Arrays 388
Larger Dimensional Arrays 392
7.4 Arrays as Arguments 394
Internal Array Element Location Algorithm 401
7.5 A Case Study: Statistical Analysis 404
7.6 The Standard Template Library (STL) 410

7.7 A Closer Look: Sear ching and Sorting 418
Search Algorithms 418
Big O Notation 425
Sort Algorithms 426
7Contents
7.8 Common Programming Errors 432
7.9 Chapter Summary 433
Chapter 8
I/O Streams and Data Files 439
8.1 I/O File Stream Objects and Methods 440
Files 440
File Stream Objects 441
File Stream Methods 442
8.2 Reading and Writing Character-Based Files 454
Reading from a Text File 456
Standard Device Files 461
Other Devices 462
8.3 Random File Access 465
8.4 File Streams as Function Arguments 468
8.5 A Case Study: Pollen Count File Update 472
8.6 A Closer Look: The iostream Class Library 479
File Stream Transfer Mechanism 479
Components of the iostream Class Library 480
In-Memory Formatting 482
8.7 Common Programming Errors 483
8.8 Chapter Summary 484
Chapter 9
Completing the Basics 489
9.1 Exception Handling 490
9.2 Exceptions and File Checking 496

Opening Multiple Files 500
9.3 The string Class 504
string Class Functions 505
String Input and Output 507
String Processing 511
9.4 Character Manipulation Functions 522
Character I/O 526
A Second Look at User-Input Validation 531
9.5 Input Data Validation 533
9.6 A Closer Look: Namespaces and Creating a Personal Library 541
9.7 Common Programming Errors 546
9.8 Chapter Summary 546
Part 2
Object-Oriented Programming
551
Chapter 10
Introduction to Classes 553
10.1 Abstract Data Types in C
++
(Classes) 553
Abstract Data Types 555
Class Construction 556
Terminology 563
8 Contents
10.2 Constructors 567
Calling Constructors 570
Overloaded and Inline Constructors 570
Destructors 574
10.3 A Case Study: Constructing a Room Object 576
10.4 A Closer Look: Object Identification and the Unified Modeling Language (UML) 582

Representing Problems with Models 583
Class and Object Diagrams 585
Relationships 588
10.5 Common Programming Errors 592
10.6 Chapter Summary 593
Chapter 11
Class Functions and Conversions 597
11.1 Assignment 597
Copy Constructors 602
Base/Member Initialization 605
11.2 Additional Class Features 607
Class Scope 607
Static Class Members 607
Friend Functions 612
11.3 Operator Functions 616
Operator Functions as Friends 623
11.4 Data Type Conversions 625
Built-in to Built-in Conversion 626
Built-in to Class Conversion 626
Class to Built-in Conversion 628
Class to Class Conversion 630
11.5 A Case Study: Random Numbers and Simulations 635
Scaling 636
Elevator Simulation 637
11.6 Class Inheritance 645
Access Specifications 647
11.7 Polymorphism 653
11.8 Common Programming Errors 658
11.9 Chapter Summary 658
Part 3

Data Structures
663
Chapter 12
Pointers 665
12.1 Addresses and Pointers 666
Storing Addresses 667
Using Addresses 667
Declaring Pointers 668
References and Pointers 671
12.2 Array Names as Pointers 677
Dynamic Array Allocation 682
12.3 Pointer Arithmetic 686
Pointer Initialization 689
12.4 Passing Addresses 690
Passing Arrays 695
Advanced Pointer Notation 699
9Contents
12.5 Common Programming Errors 702
12.6 Chapter Summary 704
Chapter 13
Structures 707
13.1 Single Structures 708
13.2 Arrays of Structures 714
13.3 Structures as Function Arguments 718
Passing a Pointer 721
Returning Structures 724
13.4 Linked Lists 727
13.5 Dynamic Data Structure Allocation 735
13.6 Unions 742
13.7 Common Programming Errors 744

13.8 Chapter Summary 745
Part 4
Additional Topics
749
Chapter 14
Numerical Methods 751
14.1 Introduction to Root Finding 751
14.2 The Bisection Method 755
14.3 Refinements to the Bisection Method 761
Regula Falsi Method 762
Modified Regula Falsi Method 764
Summary of the Bisection Methods 769
14.4 The Secant Method 770
14.5 Introduction to Numerical Integration 774
14.6 The Trapezoidal Rule 775
Computational Form of the Trapezoidal Rule Equation 776
Example of a Trapezoidal Rule Calculation 777
14.7 Simpson’s Rule 779
Example of Simpson’s Rule as an Approximation to an Integral 781
14.8 Common Programming Errors 783
14.9 Chapter Summary 783
Chapter 15
Bit Operations 787
15.1 The AND Operator 788
15.2 The Inclusive OR Operator 790
15.3 The Exclusive OR Operator 793
15.4 The Complement Operator 795
15.5 Different-Size Data Items 795
15.6 The Shift Operators 796
15.7 Chapter Summary 799

Appendix A
Operator Precedence Table 801
Appendix B
ASCII Character Codes 803
10 Contents
Appendix C
Floating-Point Number Storage 805
Appendix D
Command-Line Arguments 809
Index 815
11Contents
This page intentionally left blank
PREFACE
The C++ programming language, which includes C as a proper subset, has become the
preeminent programming language in the engineering and scientific fields. For most
engineers and scientists, however, using the full potential of C++, which is a hybrid language
containing both structured and object-oriented features, involves a gradual refinement of
programming skills from a structured approach to an object-oriented one. One reason for this
is that many engineering and scientific problems can be solved efficiently and conveniently
by using only C++’s structured elements.
The refinement approach, from structural to object-oriented programming, is the one
C++ for Engineers and Scientists, Third Edition, takes. Therefore, like the first two editions, this
new edition begins by providing a strong foundation in structured programming. This
foundation is then expanded to a complete object orientation in a pedagogically sound and
achievable progression. Additionally, to keep it current with the current ANSI/ISO C++
standard, this edition has several important changes and added features, including the
following:
• Restructuring Part One to include both arrays and files, which allows using Part One
as the basis for a complete semester course in C++
• Adding more than 40 new engineering and scientific exercises that incorporate the

fields of electrical engineering, mechanical engineering thermodynamics, structural
engineering, numerical applications, physics, heat transfer, chemistry, and fluid
mechanics
• Adding a section on performing a unit analysis
• Adding a new introduction to the Standard Template Library
• Adding a section that introduces the fundamentals of the Unified Modeling
Language (UML)
• Restructuring the case studies throughout the book to emphasize specific engineer-
ing or scientific applications
• Adding end-of chapter programming projects that supplement the exercises at the
end of each section
• Labeling all exercises and programming projects as to application type
The following features have been retained from the second edition:
• Fundamentals of software engineering are discussed from both procedural and
object-oriented viewpoints.
• Common Programming Errors sections have been retained. These sections antici-
pate problems that novice C++ programmers encounter.
• The ANSI/ISO C++ iostream library and namespace mechanism are used in all
programs.
• Exception handling is discussed in a complete section, with practical applications of
exception handling included throughout the book.
• The new C++ string class is covered.
• A thorough discussion is included of input data validation and functions to check the
numerical data type of input items and to allow reentering invalid numerical types.
In practical terms, this book has been written to support both a one- and two-semester
technical C++ programming course; the only prerequisite is that students should be familiar
Preface 13
with fundamental algebra. This book is constructed to be flexible enough so that professors
can mold the book to their preferences for topic presentations. This flexibility is achieved in
the following ways.

Excluding Chapter 1, which includes computer literacy material for those who require
this background, Part One presents the basic structured syntax, flow control, and modularity
topics needed for a thorough understanding of C++’s structural features. With the topics of
arrays (Chapter 7) and files (Chapter 8) having been moved to Part One, this part now
provides a comprehensive one-semester course. As Chapters 7 and 8 have been written
specifically to depend only on Chapters 1 through 6, their order of presentation in the
classroom is entirely up to the professor’s discretion. With time permitting, the basics of
classes, introduced in Chapter 10, can also be covered to complete a one-semester course.
Additionally, depending on time and inclination, the numerical techniques discussed in
Chapter 14 can be presented at any point after Part One has been completed. Figure 1
illustrates this one-semester topic dependency.
An important feature of this book is that Part Two, on object-oriented programming, and
Part Three, on data structures, are interchangeable. So if you want to cover object-oriented
programming early, follow a Part One–Part Two–Part Three progression. On the other hand,
if you want to continue with additional structured programming reinforcement and discuss
object-oriented programming at the end of the course or the start of a second semester, follow
the sequence Part One–Part Three–Part Two. In either case, the material on arrays in
Chapter 7, files in Chapter 8, classes in Chapter 10, and numerical techniques in Chapter 14
can be introduced at any time after covering the first six chapters. Figure 2 shows the topic
dependency chart for the complete book and illustrates the flexibility of introducing different
topics under the umbrella of procedural programming, object-oriented programming, and
data structures.
Part One
Introduction
Chapter 1
Chapters
2 to 6
and 9
Arrays
Chapter 7

Files
Chapter 8
Objects
Chapter 10
Figure 1 Topic dependency for a one-semester course
14 Preface
Distinctive Features of This Book
Writing Style One thing I have found to be essential in my own classes is that after the
professor sets the stage in class, the assigned book must continue to encourage, nurture, and
assist students in acquiring and “owning” the material. To do this, the book must be written
in a manner that makes sense to students. My primary concern, and one of the distinctive
features of this book, is that it has been written for students. Therefore, I believe the writing
style used to convey the concepts is one of the most important aspects of this book.
Modularity To produce readable and maintainable programs, modularity is essential. C++,
by its nature, is a modular language. Therefore, the connection between C++ functions and
modules is made early in Chapter 2 and sustained throughout the book. Similarly, the idea
of parameter passing into modules is discussed early in Chapter 3, using C++’s mathematical
library. Explaining these concepts early introduces students to function and argument passing
as natural programming techniques. With the introduction of object-oriented programming
techniques in Chapter 10, students can build on the basic concept of encapsulating both data
and functions, which strengthens this modular emphasis.
Software Engineering Rather than simply introduce students to programming in C++,
this book introduces students to the fundamentals of software engineering from both a
structured and object-oriented viewpoint. Chapter 1 introduces the software development
procedure, which incorporates one of this book’s main themes: emphasizing problem-solving
techniques. Therefore, the importance of understanding and defining a problem, selecting
and refining a solution, and understanding the relationship between analysis, design, coding,
and testing is stated early and followed through with practical examples in all subsequent
case studies.
Case Studies Starting with Chapter 2, most chapters contain a case study. These case

studies demonstrate and reinforce effective problem solving in the context of the software
Chapter 1
Literacy
Topics
Part One
Procedural
Programming
Part Two
(Chapters 10 and 11)
Object-Oriented
Programming
Part Three
(Chapters 12 and 13)
Data Structures
Part Four
(Chapters 14 and 15)
Figure 2 Topic dependency chart
15Preface
development procedure explained in Chapter 1 and are extended to object-oriented
development when classes are introduced in Chapter 10.
Program Testing Every C++ program in this book has been compiled and run successfully
and has been quality assurance tested with Microsoft Visual C++ .NET. Source code for all
programs can be found on the Course Technology Web site (www.cengage.com/coursetechnology).
Using the source code permits students to experiment with and extend the existing programs
and modify them more easily, as required for a number of end-of-section exercises.
Pedagogical Features
To facilitate the goal of making C++ accessible as a first-level course, the following
pedagogical features have been incorporated into this book.
End-of-Section Exercises Almost every section in the book contains numerous and
diverse skill-building and programming exercises. Each exercise is identified as to type

(practice, desk check, and so forth) or application (such as electrical engineering, heat
transfer, environmental, and so on). Additionally, solutions to all exercises are provided in the
Instructor Downloads section on www.cengage.com/coursetechnology.
End-of-Chapter Programming Projects Each chapter includes several programming
projects that combine all elements of C++ covered in previous sections and chapters. Projects
are identified as to type (practice, desk check, and so forth) or application (electrical
engineering, heat transfer, environmental, and so on).
Common Programming Errors and Chapter Summary Each chapter ends with a sec-
tion on common programming errors and a summary of the main topics covered in the
chapter.
Enrichment Sections Given the many different emphases that can be used in teaching
C++, several chapters include an enrichment section called “A Closer Look.” These sections
allow you to provide varying emphases with different students in C++ classes.
Point of Information Boxes These boxes present additional clarification of commonly
used or difficult concepts, such as abstraction, lvalues and rvalues, values versus
identities, flags, and stream formatting. In addition, many Point of Information boxes explain
alternative and advanced programming techniques, useful technical points, programming
tips, and programming tricks used by professional programmers.
Pseudocode Descriptions Pseudocode is used throughout the book. Flowchart symbols
are introduced but are used only in illustrating flow-of-control constructs.
Engineering and Scientific Disciplines Many chapters have a box at the end with
information on several engineering and scientific fields, such as electrical, chemical, mechani-
cal, and aeronautical engineering.
16 Preface
Appendixes This book includes four appendixes on operator precedence, ASCII character
codes, floating-point number storage, and command-line arguments. Additionally, Course
Technology provides tutorials for using various C++ compilers at www.cengage.com/coursetechnology.
Supplemental Materials
The following supplemental materials are available when this book is used in a classroom
setting:

Electronic Instructor’s Resources. The Instructor’s Resources that accompany this book
include the following:
• Additional instructional material to assist in class preparation, including suggestions
for lecture topics
• Solutions to all the end-of-chapter materials, including the programming projects
ExamView௡. This book is accompanied by ExamView, a powerful testing software
package that allows instructors to create and administer printed, computer (LAN-based), and
Internet exams. ExamView includes hundreds of questions that correspond to the topics
covered in this book, enabling students to generate detailed study guides that include page
references for further review. These computer-based and Internet testing components allow
students to take exams at their computers and save instructors time because each exam is
graded automatically. The Test Bank is also available in WebCT and Blackboard formats.
PowerPoint Presentations. This book comes with Microsoft PowerPoint slides for each
chapter. They are included as a teaching aid for classroom presentations, to make available
to students on the network for chapter review, or to be printed for classroom distribution.
Instructors can add their own slides for additional topics they introduce to the class.
Source Code. The source code for this book is available at www.cengage.com/coursetechnology
and is also available on the Teaching Tools CD.
Solution Files. The solution files for all programming exercises and projects are available
at www.cengage.com/coursetechnology and on the Teaching Tools CD.
17Preface
To Rochelle, Jeremy, David, and Matthew Bronson
Acknowledgments
The writing of this third edition is a direct result of the success (and limitations) of the
previous two editions. In this regard, my most heartfelt acknowledgment and appreciation is
to the instructors and students who found the previous editions to be of service in their
quests to teach and learn C++.
Next, I would like to thank Alyssa Pratt, my Senior Product Manager at Course
Technology. In addition to her continuous faith and encouragement, her ideas and partner-
ship were instrumental in creating this book. After the writing process was completed, the

task of turning the final manuscript into a book depended on many people other than myself.
For this, I especially want to thank my developmental editor, Lisa Lord, who provided an
outstanding job. Her editing so dovetailed with both the spirit and idiosyncrasies of my own
writing style that it was an absolute pleasure working with her. She stayed true to what I was
attempting to achieve while patiently going through both the technical and grammatical
content. A truly incredible feat! This editing was supplemented by the equally detailed work
of my colleague, Professor Joan Zucker Hoffman, with structural engineering applications
provided by Professors Andy Gregg and Al Branchi and moral support provided by Dr. John
Becker of the Theology Department. Finally, I would like to thank the testers at Course
Technology’s MQA Department as well as GEX Publishing Services, especially the interior
designer, and Camille Kiolbasa, the copyeditor. The dedication of this team of people was
extremely important to me and I am very grateful to them.
The following reviewers provided extensive, extremely useful, and detailed information and
corrections that made this edition better and more accurate. No matter how careful I was, each
reviewer pointed out something that I missed or could be stated better. I am very thankful to
them. Naturally, all errors rest squarely on my shoulders, but these reviewers made the load
much easier: Hyder Ali, California State University, Northridge, and Robert Baird, Salt Lake
Community College. In addition, I’d like to thank the following instructors who reviewed the
proposal for this edition and offered valuable feedback: Randy Bower, Jacksonville University;
Helen Darcey, Cleveland State Community College; Akira Kawaguchi, The City College of New
York; Cynthia Lester, Tuskegee University; and Sherman Wong, Baruch University.
As with the first edition, special acknowledgement goes to Dr. G.J. Borse of Lehigh
University, who provided material that was adapted for this book. Specifically, his contribu-
tion includes almost all of Chapter 14, which Dr. Borse graciously permitted me to adapt from
his FORTRAN 77 text (copyright held by PWS Publishing). I would also like to acknowl-
edge, with extreme gratitude, the wonderful academic environment for learning and teaching
created at Fairleigh Dickinson University—starting with the President, Dr. Michael Adams,
followed through in the academic departments by the university and campus provosts, Dr.
Joseph Kiernan and Dr. Kenneth Greene, and finally to the direct encouragement and
support provided by my dean, Dr. William Moore, and my chairperson, Dr. Paul Yoon.

Without their support, this book could not have been written.
Finally, I deeply appreciate the patience, understanding, and love provided by my friend,
wife, and partner, Rochelle.
Gary Bronson
2009
18 Preface
Part
One
Fundamentals of C++
Programming
1 Preliminaries
2 Problem Solving
Using C++
3 Assignment, Formatting,
and Interactive Input
4 Selection Structures
5 Repetition Statements
6 Modularity Using Functions
7 Arrays
8 I/O Streams and Data Files
9 Completing the Basics
Although C++ is an object-oriented
language, it was developed as an
extension to C, a procedural-oriented
language. As such, C++ is a hybrid
language having both procedural and
object features. Because of this hybrid
nature, not only is it possible to write a
complete C++ program using just
procedural code, but also it’s

impossible to write an object-oriented
program in C++ that doesn’t include
procedural elements. Therefor e, a
proper start to learning C++ requires
familiarity with its procedural aspects.
This page intentionally left blank
Chapter
1
Preliminaries
1.1 Preliminary One: Unit Analysis
1.2 Preliminary Two: Exponential
and Scientific Notations
1.3 Preliminary Three: Software
Development
1.4 Preliminary Four: Algorithms
1.5 A Closer Look: Software,
Hardware, and Computer
Storage
1.6 Common Programming Errors
1.7 Chapter Summary
Programming scientific and engineering applications requires a number of basic skills, both in
understanding the underlying applications and in understanding the fundamentals of the programming
process itself. On the applications side, a knowledge of numerical measurements and their corresponding
units, as well as a familiarity with performing calculations, are assumed. Using consistent sets of units
and knowing how to convert between units is a basic prerequisite of these applications.
Additionally, the programming process assumes the programmer starts with a preliminary set of
skills. As you develop your programming abilities in C++, a clear understanding of how programs are
developed, in general, is important. This understanding includes what constitutes a “good” program
and what an algorithm is.
This chapter covers these preliminary requirements and can be used as an introduction or a review.

1.1 Preliminary One: Unit Analysis
In all fields of study, using consistent and correct units when making computations is crucial.
As a simple example, consider calculating the area of a rectangle by using this formula:
Area = length × width [Eq. 1-1]
When using this formula, the units for length and width must be the same. Therefore,
if the length is given as 2 feet and the width as 3 inches, at least one of these units must be
converted to ensure that both length and width are in the same units before the area is
calculated. Converting the length to inches, the rectangle’s area is computed as follows:
Area ft
in
ft
in in=






×=2
12
1
336
2
[Eq. 1-1a]
Similarly, if you choose to convert the width from 3 inches to its equivalent feet, the
calculation becomes the following:
Area ft in
ft
in
ft=×







=23
1
12
025
2
.
[Eq. 1-1b]
In the same manner, if one side of the rectangle is given in centimeters and the other in
meters, a conversion is necessary to compute the area.
Notice that in Equations 1-1a and 1-1b, units for both length and width as well as units
for the conversion factor ([12 in/1 ft] in Eq. 1-1a and [1 ft/12 in] in Eq. 1-1b) are included in
the formula. The reason is that the terms for units can be multiplied and divided to provide
the final unit result. In many cases, this technique is a powerful one for selecting a correct
conversion factor and ensuring that a computation is being calculated correctly.
To see why, continue with the area example. Use Eq. 1-1a, but include only the unit
terms, which yields the following:
Area f t
in
ft
in=







×
[Eq. 1-1c]
Now a unit of ft divided by a unit of ft is 1. That is, you can cancel the ft units in
Eq. 1-1c as follows, which yields the final units as in multiplied by in,orin
2
, which is a correct
unit for the area:
Area ft
in
ft
in in=
///






×=
2
Including only the units and conversion factors in an equation, and canceling out
corresponding units in the numerator and denominator, is referred to as performing a
unit
analysis
. As an example of a unit analysis for selecting a correct form of a conversion factor,
assume you need to convert miles (symbol mi) to kilometers (symbol km), and you have the
information that 1 kilometer = 0.6214 miles. As a conversion factor, this equality can be
written as either of the following fractions:

1
0 6214
0 6214
1
or
km
mi
mi
km.
.
Deciding which conversion factor to use in converting miles to kilometers is easy when
you consider units. To see why, try both factors with miles, canceling the units that occur
4 Preliminaries
in both the numerator and denominator and concerning yourself only with the final
resulting units:
mi
km
mi
km×






=
1
0 6214.
and
mi

mi
km
mi
km
×






=
0 6214
1
2
.
.
Because the first factor (1 km/0.6214 mi) provides the correct final units of kilometers,
it’s the form of the conversion factor that must be applied to convert miles to kilometers.
For a slightly more complicated example of performing a unit analysis for selecting
correct conversion factors, consider converting days to seconds. You can determine the correct
form of each conversion factor easily by including the units with each conversion factor, as
you change days to hours, then hours to minutes, and finally minutes to seconds, performing
each conversion one at a time and canceling units as you proceed with each conversion, as
follows:
24 hr
day
×
days
1st conversion:

days to hours
(cross out the days)
The next conversion changes the units of hours to minutes, using the conversion factor
60 min/hr, as follows:
60 min
hr
24 hr
day
×
1st conversion:
days to hours
(cross out the days)
2nd conversion:
hours to minutes
(cross out the hours)
×
days
5Chapter 1
Preliminary One: Unit Analysis

×