PROGRAMMING LOGIC
AND DESIGN
COMPREHENSIVE
NINTH EDITION
PROGRAMMING LOGIC
AND DESIGN
COMPREHENSIVE
JOYCE FARRELL
Australia • Brazil • Japan • Korea • Mexico • Singapore • Spain • United Kingdom • United States
Programming Logic and Design,
Comprehensive
Ninth Edition
Joyce Farrell
Senior Product Director:
Kathleen McMahon
Product Team Leader: Kristin McNary
Associate Product Manager: Kate Mason
Senior Content Developer: Alyssa Pratt
Senior Content Project Manager:
Jennifer Feltri-George
© 2018 Cengage Learning®
ALL RIGHTS RESERVED. No part of this work covered by the
copyright herein may be reproduced or distributed in any form
or by any means, except as permitted by U.S. copyright law,
without the prior written permission of the copyright owner.
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 permissions questions can be emailed to
permissionrequest@cengage.com
Manufacturing Planner: Julio Esperas
Art Director: Diana Graham
Library of Congress Control Number: 2016959742
Production Service/Composition:
SPi Global
ISBN: 978-1-337-10207-0
Cover Photo:
Colormos/Photodisc/Getty Images
Cengage Learning
20 Channel Center Street
Boston, MA 02210
USA
Unless otherwise noted all items © Cengage Learning.
Cengage Learning is a leading provider of customized learning
solutions with employees residing in nearly 40 different countries and sales in more than 125 countries around the world.
Find your local representative at www.cengage.com.
Cengage Learning products are represented in Canada by
Nelson Education, Ltd.
To learn more about Cengage Learning Solutions, visit
www.cengage.com
Purchase any of our products at your local college store or at
our preferred online store www.cengagebrain.com
Printed in the United States of America
Print Number: 01 Print Year: 2018
Brief Contents
v
Pref ace ���������� ����� � ����� ��� � ����� ��� ��� ������ � ����� xvi
CHAPTER 1
An Over view of Computers and Programmi ng � �� 1
CHAPTER 2
Elem en t s o f Hi gh- Qual i ty Programs ����� ��� � �� ��� � 38
CHAPTER 3
U n der s t an din g Structure ��� �� ��� � ��� �� ��� ��� � �� ��� � 87
CHAPTER 4
M akin g Decis i ons ��� � �� ��� ���� �� ��� � ��� �� ��� ��� � �� �� 124
CHAPTER 5
Lo o pin g � ������ ����� ��� � �� ��� ���� �� ��� � ��� �� ��� ��� � �� �� 176
CHAPTER 6
Ar r ays ��� ������ ����� ��� � �� ��� ���� �� ��� � ��� �� ��� ��� � �� �� 227
CHAPTER 7
F ile Han dlin g and Appl i cati ons��� ��� �� ��� ��� � �� �� 272
CHAPTER 8
Advan ced Data Handl i ng Concepts ��� � �� � �� � �� � �� 321
CHAPTER 9
Advan ced M o dul ari z ati on Techni ques ����� � �� �� 366
CHAPTER 10
Object -Or ien t ed Programmi ng ����� ��� ��� ��� ��� �� 420
CHAPTER 11
M o re Object -Ori ented Programmi ng
Co n cept s ��� ����� ��� ��� ���� ����� ������ ��� ��� ��� ��� ��� �� 464
CHAPTER 12
Even t -Dr iven G UI Programmi ng,
M u lt it h readin g, and Ani mati on����� ��� ��� ��� ��� �� 507
APPENDIX A
U n der s t an din g Numberi ng Sy stems
an d Co m pu t er Codes ��� �� ��� ���� �� ������ ��� ������ �� 539
APPENDIX B
So lvin g Dif f icul t Structuri ng Probl ems ��� � �� �� 547
Glo s s ar y ��� ����� ��� ��� ������ ��� ��� � �� ��� ��� � ��� �� ��� � � 556
In dex��� ������ ��� ����� ��� ��� ��� ���� �� ���� ����� � ����� ��� �� 571
Contents
vii
Pref ace ���������� ����� � ����� ��� � ����� ��� ��� ������ � ����� xvi
CHAPTER 1
An Over view of Computers and Programmi ng � �� 1
Understanding Computer Systems��������������������������������������� 2
Understanding Simple Program Logic���������������������������������� 5
Understanding the Program Development Cycle��������������������� 8
Understanding the Problem ��������������������������������������������� 8
Planning the Logic ��������������������������������������������������������10
Coding the Program �����������������������������������������������������10
Using Software to Translate the Program into Machine
Language ������������������������������������������������������������������11
Testing the Program �����������������������������������������������������12
Putting the Program into Production��������������������������������13
Maintaining the Program������������������������������������������������14
Using Pseudocode Statements and Flowchart Symbols ���������15
Writing Pseudocode ������������������������������������������������������15
Drawing Flowcharts ������������������������������������������������������17
Repeating Instructions ��������������������������������������������������19
Using a Sentinel Value to End a Program�����������������������������20
Understanding Programming and User Environments ������������23
Understanding Programming Environments�����������������������23
Understanding User Environments�����������������������������������25
Understanding the Evolution of Programming Models������������27
Chapter Summary �����������������������������������������������������������28
Key Terms�����������������������������������������������������������������������29
Exercises �����������������������������������������������������������������������32
CHAPTER 2
Elem en t s o f Hi gh- Qual i ty Programs ����� ��� � �� ��� � 38
Declaring and Using Variables and Constants�����������������������39
Understanding Data Types ���������������������������������������������39
Understanding Unnamed, Literal Constants�����������������������39
Working with Variables ��������������������������������������������������40
Understanding a Declaration’s Data Type��������������������������41
CONTENTS
Understanding a Declaration’s Identifier ���������������������������42
Assigning Values to Variables �����������������������������������������45
Declaring Named Constants��������������������������������������������46
Performing Arithmetic Operations ��������������������������������������47
The Integer Data Type ���������������������������������������������������50
Understanding the Advantages of Modularization �����������������51
Modularization Provides Abstraction��������������������������������52
Modularization Helps Multiple Programmers to Work
on a Problem��������������������������������������������������������������53
Modularization Allows You to Reuse Work��������������������������53
Modularizing a Program ������������������������������������������������54
Declaring Variables and Constants within Modules�����������������58
Understanding the Most Common Configuration
for Mainline Logic�����������������������������������������������������������60
Creating Hierarchy Charts ���������������������������������������������64
Features of Good Program Design��������������������������������������66
Using Program Comments ���������������������������������������������67
Choosing Identifiers������������������������������������������������������69
Designing Clear Statements��������������������������������������������71
Writing Clear Prompts and Echoing Input��������������������������72
Maintaining Good Programming Habits��������������������������������74
Chapter Summary �����������������������������������������������������������75
Key Terms�����������������������������������������������������������������������76
Exercises �����������������������������������������������������������������������79
viii
CHAPTER 3
U n der s t an din g Structure ��� �� ��� � ��� �� ��� ��� � �� ��� � 87
The Disadvantages of Unstructured Spaghetti Code��������������88
Understanding the Three Basic Structures ��������������������������90
The Sequence Structure ������������������������������������������������90
The Selection Structure��������������������������������������������������91
The Loop Structure ������������������������������������������������������92
Combining Structures ���������������������������������������������������93
Using a Priming Input to Structure a Program�����������������������99
Understanding the Reasons for Structure��������������������������� 106
Recognizing Structure���������������������������������������������������� 107
Structuring and Modularizing Unstructured Logic ��������������� 110
Chapter Summary ��������������������������������������������������������� 115
Key Terms��������������������������������������������������������������������� 115
Exercises ��������������������������������������������������������������������� 117
CHAPTER 4
CONTENTS
M ak in g Decis ions ��� � �� ��� ���� �� ��� � ��� �� ��� ��� � �� �� 124
The Selection Structure�������������������������������������������������� 125
Using Relational Comparison Operators ���������������������������� 129
Avoiding a Common Error with Relational Operators��������� 133
Understanding AND Logic������������������������������������������������ 134
Nesting AND Decisions for Efficiency ���������������������������� 137
Using the AND Operator ���������������������������������������������� 139
Avoiding Common Errors in an AND Selection������������������ 141
Understanding OR Logic ������������������������������������������������� 143
Writing OR Selections for Efficiency ������������������������������ 145
Using the OR Operator ������������������������������������������������ 147
Avoiding Common Errors in an OR Selection������������������� 147
Understanding NOT Logic������������������������������������������������ 153
Avoiding a Common Error in a NOT Expression ��������������� 154
Making Selections within Ranges ������������������������������������� 155
Avoiding Common Errors When Using Range Checks ������� 157
Understanding Precedence When Combining
AND and OR Operators��������������������������������������������������� 160
Understanding the case Structure ���������������������������������� 163
Chapter Summary ��������������������������������������������������������� 165
Key Terms��������������������������������������������������������������������� 166
Exercises ��������������������������������������������������������������������� 167
CHAPTER 5
Lo o pin g � ������ ����� ��� � �� ��� ���� �� ��� � ��� �� ��� ��� � �� �� 176
Appreciating the Advantages of Looping ��������������������������� 177
Using a Loop Control Variable������������������������������������������ 179
Using a Definite Loop with a Counter������������������������������ 179
Using an Indefinite Loop with a Sentinel Value ���������������� 181
Understanding the Loop in a Program’s Mainline Logic������ 183
Nested Loops ��������������������������������������������������������������� 185
Avoiding Common Loop Mistakes ������������������������������������ 190
Mistake: Failing to Initialize the Loop Control Variable ������ 190
Mistake: Neglecting to Alter the Loop Control Variable������ 191
Mistake: Using the Wrong Type of Comparison When
Testing the Loop Control Variable ������������������������������� 192
Mistake: Including Statements Inside the Loop Body
that Belong Outside the Loop ������������������������������������� 194
Using a for Loop ���������������������������������������������������������� 199
Using a Posttest Loop ��������������������������������������������������� 201
Recognizing the Characteristics Shared
by Structured Loops ���������������������������������������������������� 203
ix
CONTENTS
Common Loop Applications��������������������������������������������� 205
Using a Loop to Accumulate Totals ������������������������������� 205
Using a Loop to Validate Data��������������������������������������� 209
Limiting a Reprompting Loop ��������������������������������������� 209
Validating a Data Type ������������������������������������������������ 212
Validating Reasonableness and Consistency of Data��������� 213
Comparing Selections and Loops������������������������������������� 214
Chapter Summary ��������������������������������������������������������� 218
Key Terms��������������������������������������������������������������������� 218
Exercises ��������������������������������������������������������������������� 220
x
CHAPTER 6
Ar r ays ��� ������ ����� ��� � �� ��� ���� �� ��� � ��� �� ��� ��� � �� �� 227
Storing Data in Arrays���������������������������������������������������� 228
How Arrays Occupy Computer Memory��������������������������� 228
How an Array Can Replace Nested Decisions��������������������� 231
Using Constants with Arrays ������������������������������������������� 238
Using a Constant as the Size of an Array������������������������ 238
Using Constants as Array Element Values ���������������������� 239
Using a Constant as an Array Subscript ������������������������� 239
Searching an Array for an Exact Match������������������������������ 240
Using Parallel Arrays������������������������������������������������������ 244
Improving Search Efficiency������������������������������������������ 248
Searching an Array for a Range Match������������������������������ 250
Remaining within Array Bounds���������������������������������������� 255
Understanding Array Size��������������������������������������������� 255
Understanding Subscript Bounds ���������������������������������� 255
Using a for Loop to Process an Array������������������������������ 258
Chapter Summary ��������������������������������������������������������� 260
Key Terms��������������������������������������������������������������������� 261
Exercises ��������������������������������������������������������������������� 261
CHAPTER 7
F ile Han dlin g and Appl i cati ons��� ��� �� ��� ��� � �� �� 272
Understanding Computer Files ���������������������������������������� 273
Organizing Files ��������������������������������������������������������� 274
Understanding the Data Hierarchy������������������������������������ 275
Performing File Operations ��������������������������������������������� 277
Declaring a File Identifier��������������������������������������������� 277
Opening a File������������������������������������������������������������ 278
Reading Data from a File and Processing It��������������������� 278
Writing Data to a File��������������������������������������������������� 281
Closing a File������������������������������������������������������������� 281
CONTENTS
A Program that Performs File Operations������������������������ 282
Understanding Control Break Logic ���������������������������������� 285
Merging Sequential Files ������������������������������������������������ 290
Master and Transaction File Processing ���������������������������� 299
Random Access Files������������������������������������������������������ 308
Chapter Summary ��������������������������������������������������������� 309
Key Terms��������������������������������������������������������������������� 310
Exercises ��������������������������������������������������������������������� 312
CHAPTER 8
Advan ced Data Handl i ng Concepts ��� � �� � �� � �� � �� 321
Understanding the Need for Sorting Data��������������������������� 322
Using the Bubble Sort Algorithm��������������������������������������� 324
Understanding Swapping Values������������������������������������ 324
Understanding the Bubble Sort ������������������������������������� 325
Sorting Multifield Records ���������������������������������������������� 340
Sorting Data Stored in Parallel Arrays ��������������������������� 340
Sorting Records as a Whole������������������������������������������ 341
Other Sorting Algorithms ������������������������������������������������ 342
Using Multidimensional Arrays������������������������������������������ 345
Using Indexed Files and Linked Lists��������������������������������� 351
Using Indexed Files ���������������������������������������������������� 352
Using Linked Lists ������������������������������������������������������ 353
Chapter Summary ��������������������������������������������������������� 356
Key Terms��������������������������������������������������������������������� 357
Exercises ��������������������������������������������������������������������� 358
CHAPTER 9
Advan ced M o dul ari z ati on Techni ques ����� � �� �� 366
The Parts of a Method ��������������������������������������������������� 367
Using Methods with no Parameters ���������������������������������� 368
Creating Methods that Require Parameters������������������������ 371
Creating Methods that Require Multiple Parameters ��������� 377
Creating Methods that Return a Value������������������������������� 379
Using an IPO Chart������������������������������������������������������ 384
Passing an Array to a Method������������������������������������������ 386
Overloading Methods������������������������������������������������������ 394
Avoiding Ambiguous Methods ��������������������������������������� 397
Using Predefined Methods ���������������������������������������������� 400
Method Design Issues: Implementation Hiding, Cohesion,
and Coupling��������������������������������������������������������������� 402
Understanding Implementation Hiding ���������������������������� 402
Increasing Cohesion ��������������������������������������������������� 403
Reducing Coupling������������������������������������������������������ 404
Understanding Recursion������������������������������������������������ 405
xi
CONTENTS
Chapter Summary ��������������������������������������������������������� 410
Key Terms��������������������������������������������������������������������� 411
Exercises ��������������������������������������������������������������������� 412
xii
CHAPTER 10
Object -Or ien t ed Programmi ng ����� ��� ��� ��� ��� �� 420
Principles of Object-Oriented Programming������������������������ 421
Classes and Objects ��������������������������������������������������� 421
Polymorphism ������������������������������������������������������������ 424
Inheritance ���������������������������������������������������������������� 426
Encapsulation ������������������������������������������������������������ 426
Defining Classes and Creating Class Diagrams ������������������ 428
Creating Class Diagrams ��������������������������������������������� 430
The Set Methods��������������������������������������������������������� 433
The Get Methods��������������������������������������������������������� 434
Work Methods������������������������������������������������������������ 435
Understanding Public and Private Access��������������������������� 437
Organizing Classes��������������������������������������������������������� 440
Understanding Instance Methods ������������������������������������� 441
Understanding Static Methods������������������������������������������ 447
Using Objects ��������������������������������������������������������������� 448
Passing an Object to a Method ������������������������������������� 449
Returning an Object from a Method ������������������������������� 450
Using Arrays of Objects ���������������������������������������������� 453
Chapter Summary ��������������������������������������������������������� 455
Key Terms��������������������������������������������������������������������� 456
Exercises ��������������������������������������������������������������������� 458
CHAPTER 11
M o re Object -Ori ented Programmi ng
Co n cept s ��� ����� ��� ��� ���� ����� ������ ��� ��� ��� ��� ��� �� 464
Understanding Constructors ������������������������������������������� 465
Default Constructors��������������������������������������������������� 466
Non-default Constructors��������������������������������������������� 468
Overloading Instance Methods and Constructors ������������� 469
Understanding Destructors ��������������������������������������������� 472
Understanding Composition��������������������������������������������� 474
Understanding Inheritance ���������������������������������������������� 475
Understanding Inheritance Terminology��������������������������� 478
Accessing Private Fields and Methods
of a Parent Class������������������������������������������������������ 481
Overriding Parent Class Methods in a Child Class������������ 486
CONTENTS
Using Inheritance to Achieve Good Software Design��������� 486
An Example of Using Predefined Classes:
Creating GUI Objects ��������������������������������������������������� 487
Understanding Exception Handling������������������������������������ 488
Drawbacks to Traditional Error-Handling Techniques��������� 489
The Object-Oriented Exception-Handling Model���������������� 491
Using Built-in Exceptions and Creating
Your Own Exceptions ������������������������������������������������ 493
Reviewing the Advantages of Object-Oriented Programming 494
Chapter Summary ��������������������������������������������������������� 495
Key Terms��������������������������������������������������������������������� 496
Exercises ��������������������������������������������������������������������� 497
CHAPTER 12
Even t -Dr iven G UI Programmi ng,
M u lt it h readin g, and Ani mati on����� ��� ��� ��� ��� �� 507
Understanding Event-Driven Programming ������������������������� 508
User-Initiated Actions and GUI Components������������������������ 511
Designing Graphical User Interfaces��������������������������������� 514
The Interface Should Be Natural and Predictable������������� 514
The Interface Should Be Attractive, Easy to Read,
and Nondistracting ��������������������������������������������������� 515
To Some Extent, It’s Helpful If the User Can Customize
Your Applications������������������������������������������������������ 516
The Program Should Be Forgiving ��������������������������������� 516
The GUI Is Only a Means to an End��������������������������������� 516
Developing an Event-Driven Application������������������������������ 517
Creating Wireframes ��������������������������������������������������� 518
Creating Storyboards��������������������������������������������������� 518
Defining the Storyboard Objects in an Object Dictionary��� 519
Defining Connections Between the User Screens������������� 520
Planning the Logic ������������������������������������������������������ 520
Understanding Threads and Multithreading ������������������������ 525
Creating Animation��������������������������������������������������������� 528
Chapter Summary ��������������������������������������������������������� 531
Key Terms��������������������������������������������������������������������� 532
Exercises ��������������������������������������������������������������������� 533
xiii
CONTENTS
xiv
APPENDIX A
U n der s t an din g Numberi ng Sy stems
an d Co m pu t er Codes ��� �� ��� ���� �� ������ ��� ������ �� 539
APPENDIX B
So lvin g Dif f icul t Structuri ng Probl ems ��� � �� �� 547
Glo s s ar y ��� �������� ��� ������ ��� ��� � �� ��� ��� � ��� �� ��� � � 556
In dex��� ������ ��� ����� ��� ��� ��� ���� �� ���� ����� � ����� ��� �� 571
Preface
xvi
Programming Logic and Design, Comprehensive, Ninth Edition, provides the beginning
programmer with a guide to developing structured program logic. This textbook assumes
no programming language experience. The writing is nontechnical and emphasizes
good programming practices. The examples are business examples; they do not assume
mathematical background beyond high school business math.
Additionally, the examples illustrate one or two major points; they do not contain so
many features that students become lost following irrelevant and extraneous details. The
examples in this book have been created to provide students with a sound background in
logic, no matter what programming languages they eventually use to write programs. This
book can be used in a stand-alone logic course that students take as a prerequisite to a
programming course, or as a companion book to an introductory programming text using
any programming language.
Organization and Coverage
Programming Logic and Design, Comprehensive, Ninth Edition, introduces students to
programming concepts and enforces good style and logical thinking. General programming
concepts are introduced in Chapter 1.
Chapter 2 discusses using data and introduces two important concepts: modularization
and creating high-quality programs. It is important to emphasize these topics early so
that students start thinking in a modular way and concentrate on making their programs
efficient, robust, easy to read, and easy to maintain.
Chapter 3 covers the key concepts of structure, including what structure is, how to
recognize it, and most importantly, the advantages to writing structured programs. This
chapter’s content is unique among programming texts. The early overview of structure
presented here provides students a solid foundation for thinking in a structured way.
Chapters 4, 5, and 6 explore the intricacies of decision making, looping, and array
manipulation. Chapter 7 provides details of file handling so that students can create
programs that process a significant amount of data.
In Chapters 8 and 9, students learn more advanced techniques in array manipulation and
modularization. Chapters 10 and 11 provide a thorough, yet accessible, introduction to concepts and terminology used in object-oriented programming. Students learn about classes,
objects, instance and static class members, constructors, destructors, inheritance, and the
Organization and Coverage
P R E FA C E
advantages of object-oriented thinking. Chapter 12 explores some additional
object-oriented programming issues: event-driven GUI programming, multithreading,
and animation.
Two appendices instruct students on working with numbering systems and providing
structure for large programs.
Programming Logic and Design combines text explanation with flowcharts and pseudocode
examples to provide students with alternative means of expressing structured logic.
Numerous detailed, full-program exercises at the end of each chapter illustrate the concepts
explained within the chapter, and reinforce understanding and retention of the material
presented.
Programming Logic and Design distinguishes itself from other programming logic books in
the following ways:
•• It is written and designed to be non-language specific. The logic used in this book can
be applied to any programming language.
•• The examples are everyday business examples: no special knowledge of mathematics,
accounting, or other disciplines is assumed.
•• The concept of structure is covered earlier than in many other texts. Students are
exposed to structure naturally, so that they will automatically create properly designed
programs.
•• Text explanation is interspersed with both flowcharts and pseudocode so that students
can become comfortable with these logic development tools and understand their interrelationship. Screen shots of running programs also are included, providing s tudents
with a clear and concrete image of the programs’ execution.
•• Complex programs are built through the use of complete business examples. Students
see how an application is constructed from start to finish, instead of studying only
segments of a program.
xvii
Features
xviii
This text focuses on helping students become better programmers, as well as helping them
understand the big picture in program development through a variety of features. Each
chapter begins with objectives and ends with a list of key terms and a summary; these
useful features will help students organize their learning experience.
Using a Priming Input to Structure a Program
FLOWCHARTS, figures,
and illustrations provide
the reader with a visual
learning experience.
start
Declarations
num originalNumber
num calculatedAnswer
not eof?
No
Don’t Do It
This logic is structured,
but flawed. When the user
inputs the eof value, it will
incorrectly be doubled and
output.
Yes
input
originalNumber
stop
calculatedAnswer =
originalNumber * 2
output
calculatedAnswer
Figure 3-17
105
THE DON’T DO IT ICON illustrates
how NOT to do something—for
example, having a dead code
path in a program. This icon
provides a visual jolt to the student,
are NOT to be emulated and making
students more careful to recognize
problems in existing code.
Structured but incorrect solution to the number-doubling problem
tested. Instead, a result is calculated and displayed one last time before the loop-controlling
test is made again. If the program was written to recognize eof when originalNumber is 0,
then an extraneous answer of 0 will be displayed before the program ends. Depending on
the language you are using and on the type of input being used, the results might be worse:
The program might terminate by displaying an error message or the value output might
be indecipherable garbage. In any case, this last output is superfluous—no value should be
doubled and output after the eof condition is encountered.
As a general rule, a program-ending test should always come immediately after an input
statement because that’s the earliest point at which it can be evaluated. Therefore, the best
solution to the number-doubling problem remains the one shown in Figure 3-16—the
structured solution containing the priming input statement.
C9275_Chapter03_hr.indd 105
11/15/16 2:07 PM
F E AT U R E S
Understanding Simple Program Logic
• The instruction myAnswer = myNumber * 2 is an example of a processing operation.
In most programming languages, an asterisk is used to indicate multiplication, so this
instruction means “Change the value of the memory location myAnswer to equal the
value at the memory location myNumber times two.” Mathematical operations are not the
only kind of processing operations, but they are very typical. As with input operations,
the type of hardware used for processing is irrelevant—after you write a program, it can
be used on computers of different brand names, sizes, and speeds.
xix
7
VIDEO LESSONS help
• In the number-doubling program, the output myAnswer instruction is an example of an
output operation. Within a particular program, this statement could cause the output
explain important chapter
to appear on the monitor (which might be a flat-panel plasma screen or a smartphone
concepts. Videos are part
display), or the output could go to a printer (which could be laser or ink-jet), or the
output could be written to a disk or DVD. The logic of the output process is the same no
of the text’s MindTap. matter what hardware device you use. When this instruction executes, the value stored
in memory at the location named myAnswer is sent to an output device. (The output
value also remains in computer memory until something else is stored at the same
memory location or power is lost.)
Watch the video A Simple Program.
Computer memory consists of millions of numbered locations where data can be stored. The memory
location of myNumber has a specific numeric address, but when you write programs, you seldom need
to be concerned with the value of the memory address; instead, you use the easy-to-remember name
you created. Computer programmers often refer to memory addresses using hexadecimal notation,
or base 16. Using this system, they might use a value like 42FF01A to refer to a memory address.
Despite the use of letters, such an address is still a number. Appendix A contains information about the
hexadecimal numbering system.
TWO TRUTHS & A LIE
Understanding Simple Program Logic
NOTES provide
additional information—
2. Although the syntax of programming languages differs, the same program
for example, another
logic can be expressed in different languages.
3. Most simple computer programs include steps that location
perform input,in the book that
processing, and output.
expands on a topic, or a
common error to avoid.
1.
A program with syntax errors can execute but might produce incorrect
results.
The false statement is #1. A program with syntax errors cannot execute;
a program with no syntax errors can execute, but might produce incorrect results.
TWO TRUTHS & A LIE mini quizzes
appear after each chapter section, with
answers provided. The quiz contains
three statements based on the preceding
section of text—two statements are
true and one is false. Answers give
immediate feedback without “giving away”
answers to the multiple-choice questions
and programming problems later in
the chapter. Students also have the option
to take these quizzes electronically
MindTap.
C9275_Chapter01_hr.indd 7
8/23/16 7:50 PM
Assessment
PROGRAMMING EXERCISES provide
opportunities to practice chapter material.
These exercises increase in difficulty and
allow students to explore logical programming concepts. Most exercises can be
completed using flowcharts, pseudocode,
or both. In addition, instructors can assign
the exercises as programming problems
to be coded and executed in a particular
programming language.
xx
CHAPTER 1
An Overview of Computers and Programming
Exercises
Review Questions
32
1.
Computer programs also are known as ____________.
a. data
b. hardware
2.
The major computer operations include ____________.
a.
b.
c.
d.
3.
input, processing, and output
hardware and software
sequence and looping
CHAPTER 4
spreadsheets, word processing, and data communications
6.
c. hardware
Programming Exercises
d. machine languages
A programming language’s rules are its ____________.
a. syntax
b. logic
5.
Making Decisions
Visual Basic, C++, and Java are all examples of computer ____________.
a. operating systems
b. programming languages
4.
c. software
d. information
1.
c.170format
d. options
Assume that the following variables contain the values shown:
numberBig = 100
numberMedium = 10
numberSmall = 1
wordBig = “Constitution”
wordMedium = “Dance”
wordSmall = “Toy”
The most important task of a compiler or interpreter is to ____________.
For each of the following Boolean expressions, decide whether the statement is
true, false, or illegal.
a. create the rules for a programming language
b. translate English statements into a language such as Java
a. numberBig > numberSmall
c. translate programming language statements into machine language
b. numberBig < numberMedium
d. execute machine language programs to perform useful tasks c. numberMedium = numberSmall
d. numberBig = wordBig
e. numberBig = "Big"
f. wordMedium > wordSmall
g. wordSmall = “TOY”
Which of the following pairs of steps in the programming process is in the
h. numberBig = 2000
a. code the program, plan the logic
j. numberBig > numberMedium + numberSmall
b. test the program, translate it into machine language
k. numberBig > numberMedium AND numberBig < numberSmall
c. put the program into production, understand the problem
l. numberBig = 100 OR numberBig > numberSmall
d. code the program, translate it into machine language
m. numberBig < 10 OR numberSmall > 10
n. numberBig = 300 AND numberMedium = 10 OR numberSmall = 1
o. wordSmall > wordBig
p. wordSmall > wordMedium
Which of the following is temporary, internal storage?
a. CPU
b. hard disk
REVIEW QUESTIONS test
7.
student comprehension of the
major ideas and techniques
presented. Twenty questions
follow each chapter.
c. keyboard
d. memory
2.
Design a flowchart or pseudocode for a program that accepts two numbers from
a user and displays one of the following messages: First is larger, Second is larger,
Numbers are equal.
3.
Design a flowchart or pseudocode for a program that accepts three numbers from
a user and displays a message if the sum of any two numbers equals the third.
4.
Cecilia’s Boutique wants several lists of salesperson data. Design a flowchart or
pseudocode for the following:
C9275_Chapter01_hr.indd 32
11/25/16 6:08 PM
a.
A program that accepts one salesperson’s ID number, number of items sold
in the last month, and total value of the items and displays data message only
if the salesperson is a high performer—defined as a person who sells more
than 200 items in the month.
b. A program that accepts the salesperson’s data and displays a message only if
the salesperson is a high performer—defined a person who sells more than
200 items worth at least $1,000 in the month.
C9275_Chapter04_hr.indd 170
11/25/16 6:17 PM
ASSESSMENT
PERFORMING MAINTENANCE
Exercises
exercises ask students to modify
working
logic based on new
c. Modify the softball program so that it also computes a gross production
average
(GPA) for each player.This
A GPA is calculated by multiplying a player’s
requested
specifications.
on-base percentage by 1.8, then adding the player’s slugging percentage, and
activity then
mirrors
real-world
tasks
dividing by four.
that
arechart
likely
10. students
Draw the hierarchy
and to
design the logic for a program for Arnie’s
Appliances. Design a program that prompts the user for a refrigerator model
encounter
in
their
first
programming
name and the interior height, width, and depth in inches. Calculate the
jobs.refrigerator capacity in cubic feet by first multiplying the height, width, and
xxi
85
depth to get cubic inches, and then dividing by 1728 (the number of cubic inches
in a cubic foot). The program accepts model names continuously until “XXX” is
entered. Use named constants where appropriate. Also use modules, including
one that displays End of job after the sentinel is entered for the model name.
Performing Maintenance
1.
A file named MAINTENANCE02-01.txt is included with your downloadable
student files. Assume that this program is a working program in your
organization and that it needs modifications as described in the comments (lines
that begin with two slashes) at the beginning of the file. Your job is to alter the
program to meet the new specifications.
Find the Bugs
1.
Your downloadable files for Chapter 2 include DEBUG02-01.txt, DEBUG02-02.
txt, and DEBUG02-03.txt. Each file starts with some comments that describe
the problem. Comments are lines that begin with two slashes (//). Following the
comments, each file contains pseudocode that has one or more bugs you must
find and correct.
2.
Your downloadable files for Chapter 2 include a file named DEBUG02-04.jpg that
contains a flowchart with syntax and/or logical errors. Examine the flowchart,
and then find and correct all the bugs.
Game Zone
1.
For games to hold your interest, they almost always include some random,
unpredictable behavior. For example, a game in which you shoot asteroids loses
some of its fun if the asteroids follow the same, predictable path each time you
play. Therefore, generating random values is a key component in creating most
C9275_Chapter02_hr.indd 85
DEBUGGING EXERCISES are
included with each chapter because
examining programs critically and
closely is a crucial programming skill.
Students can download these exercises
at www.cengagebrain.com and through
MindTap. These files are also available
to instructors through sso.cengage.com.
GAME ZONE EXERCISES are included
at the end of each chapter. Students can
create games as an additional entertaining
way to understand key programming
concepts.
11/25/16 6:22 PM
P R E F A C E
MindTap
Other Features of the Text
This edition of the text includes many features to help students become better programmers and understand the big picture in program development.
xxii
•• Clear explanations. The language and explanations in this book have been refined over
eight editions, providing the clearest possible explanations of difficult concepts.
•• Emphasis on structure. More than its competitors, this book emphasizes
structure. Chapter 3 provides an early picture of the major concepts of structured
programming.
•• Emphasis on modularity. From the second chapter onwards, students are encouraged
to write code in concise, easily manageable, and reusable modules. Instructors have
found that modularization should be encouraged early to instill good habits and
a clearer understanding of structure.
•• Objectives. Each chapter begins with a list of objectives so that the student knows the
topics that will be presented in the chapter. In addition to providing a quick reference to
topics covered, this feature provides a useful study aid.
•• Chapter summaries. Following each chapter is a summary that recaps the programming concepts and techniques covered in the chapter.
•• Key terms. Each chapter lists key terms and their definitions; the list appears in the
order that the terms are encountered in the chapter. A glossary at the end of the book
lists all the key terms in alphabetical order, along with their working definitions.
MindTap
MindTap is a personalized learning experience with relevant assignments that guide students in analyzing problems, applying what they have learned, and improving their thinking. MindTap allows instructors to measure skills and outcomes with ease.
For instructors: Personalized teaching becomes yours with a learning path that is built with
key student objectives. You can control what students see and when they see it. You can use
MindTap as-is, or match it to your syllabus by hiding, rearranging, or adding content.
For students: A unique learning path of relevant readings, multimedia, and activities is created to guide you through basic knowledge and comprehension of analysis and application.
For both: Better outcomes empower instructors and motivate students with analytics and
reports that provide a snapshot of class progress, the time spent in the course, engagement
levels, and completion rates.
The MindTap for Programming Logic and Design includes coding labs in C11, Java, and
Python, study tools, videos, and interactive quizzing, all integrated into an eReader that
includes the full content of the printed text.
Acknowledgments
P R E FA C E
Instructor Resources
The following teaching tools are available to the instructor for download through our
Instructor Companion Site at sso.cengage.com.
•• Instructor’s Manual. The Instructor’s Manual follows the text chapter by chapter to
assist in planning and organizing an effective, engaging course. The manual includes
learning objectives, chapter overviews, lecture notes, ideas for classroom activities, and
abundant additional resources. A sample course syllabus is also available.
•• PowerPoint Presentations. This text provides PowerPoint slides to accompany each
chapter. Slides are included to guide classroom presentations, and can be made available
to students for chapter review, or to print as classroom handouts.
•• Solutions. Solutions to review questions and exercises are provided to assist with grading.
•• Test Bank®. Cengage Learning Testing Powered by Cognero is a flexible, online system
that allows you to:
•• author, edit, and manage test bank content from multiple Cengage Learning
solutions,
•• create multiple test versions in an instant, and
•• deliver tests from your LMS, your classroom, or anywhere you want.
Additional Options
•• Visual Logic™ software. Visual Logic is a simple but powerful tool for teaching
rogramming logic and design without traditional high-level programming language
p
syntax. Visual Logic also interprets and executes flowcharts, providing students with
immediate and accurate feedback.
Acknowledgments
I would like to thank all of the people who helped to make this book a reality, especially
Alyssa Pratt, Jennifer Feltri-George, Kristin McNary, Kate Mason, and all the other
professionals at Cengage Learning who made this book possible. Thanks, too, to my
husband, Geoff, and our daughters, Andrea and Audrey, for their support. This book, as
were all its previous editions, is dedicated to them.
–Joyce Farrell
xxiii
CHAPTER
An Overview
of Computers
and Programming
1
Upon completion of this chapter, you will be able to:
Describe computer systems
Understand simple program logic
List the steps involved in the program development cycle
Write pseudocode statements and draw flowchart symbols
Use a sentinel value to end a program
Understand programming and user environments
Describe the evolution of programming models
CHAPTER 1
An Overview of Computers and Programming
Understanding Computer Systems
2
A computer system is a combination of all the components required to process and store
data using a computer. Every computer system is composed of multiple pieces of hardware
and software.
•• Hardware is the equipment, or the physical devices, associated with a computer.
For example, keyboards, mice, speakers, and printers are all hardware. The devices
are manufactured differently for computers of varying sizes—for example, large
mainframes, laptops, and very small devices embedded into products such as
telephones, cars, and thermostats. The types of operations performed by differentsized computers, however, are very similar. Computer hardware needs instructions
that control its operations, including how and when data items are input, how they are
processed, and the form in which they are output or stored.
•• Software is computer instructions that tells the hardware what to do. Software is programs,
which are instruction sets written by programmers. You can buy prewritten programs that
are stored on a disk or that you download from the Web. For example, businesses use wordprocessing and accounting programs, and casual computer users enjoy programs that play
music and games. Alternatively, you can write your own programs. When you write software
instructions, you are programming. This book focuses on the programming process.
Software can be classified into two broad types:
•• Application software comprises all the programs you apply to a task, such as wordprocessing programs, spreadsheets, payroll and inventory programs, and games. When
you hear people say they have “downloaded an app onto a mobile device,” they are
simply using an abbreviation of application software.
•• System software comprises the programs that you use to manage your computer,
including operating systems such as Windows, Linux, or UNIX for larger computers
and Google Android and Apple iOS for smartphones.
This book focuses on the logic used to write application software programs, although many
of the concepts apply to both types of software.
Together, computer hardware and software accomplish three major operations in most programs:
•• Input: Data items enter the computer system and are placed in memory, where they can be
processed. Data items include all the text, numbers, and other raw material that are entered
into and processed by a computer. Hardware devices that perform input operations
include keyboards and mice. In business, many of the data items used are facts and figures
about such entities as products, customers, and personnel. Data, however, also can include
items such as images, sounds, and a user’s mouse or finger-swiping movements.
•• Processing: Processing data items may involve organizing or sorting them, checking
them for accuracy, or performing calculations with them. The hardware component
that performs these types of tasks is the central processing unit, or CPU. Some devices,
such as tablets and smartphones, usually contain multiple processors, and efficiently
using several CPUs requires special programming techniques.
Understanding Computer Systems
•• Output: After data items have been processed, the resulting information usually is sent
to a printer, monitor, or some other output device so people can view, interpret, and use
the results. Programming professionals often use the term data for input items, but use
the term information for data items that have been processed and output. Sometimes
you place output on storage devices, such as your hard drive, flash media, or a
cloud-based device. (The cloud refers to devices at remote locations accessed through
the Internet.) People cannot read data directly from these storage devices, but the
devices hold information for later retrieval. When you send output to a storage device,
sometimes it is used later as input for another program.
You write computer instructions in a computer programming language such as Visual Basic,
C#, C++, or Java. Just as some people speak English and others speak Japanese, programmers
write programs in different languages. Some programmers work exclusively in one language,
whereas others know several and use the one that is best suited to the task at hand.
The instructions you write using a programming language are called program code; when
you write instructions, you are coding the program.
Every programming language has rules governing its word usage and punctuation. These
rules are called the language’s syntax. Mistakes in a language’s usage are syntax errors. If
you ask, “How the geet too store do I?” in English, most people can figure out what you
probably mean, even though you have not used proper English syntax—you have mixed up
the word order, misspelled a word, and used an incorrect word. However, computers are
not nearly as smart as most people; in this case, you might as well have asked the computer,
“Xpu mxv ort dod nmcad bf B?” Unless the syntax is perfect, the computer cannot interpret
the programming language instruction at all.
Figure 1-1 shows how the statement that displays the word Hello on a single line on a
computer monitor looks in some common programming languages. Notice that the syntax
of some languages require that a statement start with an uppercase letter, while the syntax
of others does not. Notice that some languages end statements with a semicolon, some with
a period, and some with no ending punctuation at all. Also notice that different verbs are
used to mean display, and that some are spelled like their like English word counterparts,
while others like cout and System.out.println are not regular English words. The different
formats you see are just a hint of the various syntaxes used by languages.
Language
Statement that displays Hello on a single line
Java
System.out.println(“Hello);
C++
cout