PROGRAMMING LOG IC
AND DES IGN
COMPREHENSIVE VERSION
Copyright 2012 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part. Due to electronic rights, some third party content may be suppressed from the eBook and/or eChapter(s).
Editorial review has deemed that any suppressed content does not materially affect the overall learning experience. Cengage Learning reserves the right to remove additional content at any time if subsequent rights restrictions require it.
Copyright 2012 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part. Due to electronic rights, some third party content may be suppressed from the eBook and/or eChapter(s).
Editorial review has deemed that any suppressed content does not materially affect the overall learning experience. Cengage Learning reserves the right to remove additional content at any time if subsequent rights restrictions require it.
PROGRAMMING LOGIC
AND DESIGN
COMPREHENSIVE VERSION
JOYCE FARRELL
Australia • Brazil • Japan • Korea • Mexico • Singapore • Spain • United Kingdom • United States
SEV ENTH ED I T I ON
Copyright 2012 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part. Due to electronic rights, some third party content may be suppressed from the eBook and/or eChapter(s).
Editorial review has deemed that any suppressed content does not materially affect the overall learning experience. Cengage Learning reserves the right to remove additional content at any time if subsequent rights restrictions require it.
Copyright 2012 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part. Due to electronic rights, some third party content may be suppressed from the eBook and/or eChapter(s).
Editorial review has deemed that any suppressed content does not materially affect the overall learning experience. Cengage Learning reserves the right to remove additional content at any time if subsequent rights restrictions require it.
This is an electronic version of the print textbook. Due to electronic rights restrictions, some third party content may be suppressed. Editorial review has deemed that any suppressed content does not materially affect the overall learning experience. The publisher reserves the right to remove content from this title at any time if subsequent rights restrictions require it. For valuable information on pricing, previous editions, changes to current editions, and alternate formats, please visit www.cengage.com/highered to search by ISBN#, author, title, or keyword for materials in your areas of interest.
Programming Logic and Design,
Comprehensive version, Seventh Edition Joyce Farrell
Executive Editor: Marie Lee
Acquisitions Editor: Brandi Shailer
Senior Product Manager: Alyssa Pratt
Developmental Editor: Dan Seiter
Senior Content Project Manager: Catherine DiMassa
Associate Product Manager: Stephanie Lorenz
Associate Marketing Manager: Shanna Shelton
Art Director: Faith Brosnan
Text Designer: Shawn Girsberger
Cover Designer: Lisa Kuhn/Curio Press, LLC, www.curiopress.com
Image Credit: © Leigh Prather/Veer
Senior Print Buyer: Julio Esperas
Copy Editor: Michael Beckett
Proofreader: Kim Kosmatka
Indexer: Alexandra Nickerson
Compositor: Integra
© 2013 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, www.cengage.com/support.
For permission to use material from this text or product, submit all requests online at cengage.com/permissions.
Further permissions questions can be emailed to permissionrequest@cengage.com.
Library of Congress Control Number: 2012930593
ISBN-13: 978-1-111-96975-2
Course Technology 20 Channel Center Street Boston, MA 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: www.cengage.com/global
Cengage Learning products are represented in Canada by Nelson Education, Ltd.
To learn more about Course Technology, visit www.cengage.com/coursetechnology.
Purchase any of our products at your local college store or at our preferred online store: www.cengagebrain.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 registered trademarks of their respective manufacturers and sellers.
Unless otherwise credited, all art © Cengage Learning, produced by Integra.
Course Technology, a part of Cengage Learning, reserves the right to revise this publication and make changes from time to time in its content without notice.
Printed in the United States of America
1 2 3 4 5 6 7 16 15 14 13 12
Copyright 2012 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part. Due to electronic rights, some third party content may be suppressed from the eBook and/or eChapter(s).
Editorial review has deemed that any suppressed content does not materially affect the overall learning experience. Cengage Learning reserves the right to remove additional content at any time if subsequent rights restrictions require it.
Brief Contents
Preface . . . . . . . . . . . . . . . . . . xviii
CHAPTER 1 An Overview of Computers and Programming . 1
CHAPTER 2 Elements of High-Qual ity Programs . . . . . . 37
CHAPTER 3 Understanding Structure . . . . . . . . . . . 83
CHAPTER 4 Making Decisions . . . . . . . . . . . . . 121
CHAPTER 5 Looping . . . . . . . . . . . . . . . . . 169
CHAPTER 6 Arrays . . . . . . . . . . . . . . . . . . 213
CHAPTER 7 Fi le Handl ing and Appl ications . . . . . . . 257
CHAPTER 8 Advanced Data Handl ing Concepts . . . . . 305
CHAPTER 9 Advanced Modularizat ion Techniques . . . . 355
CHAPTER 10 Object-Oriented Programming . . . . . . . 407
CHAPTER 11 More Object-Oriented Programming Concepts . . . . . . . . . . . . . . . . . 449
CHAPTER 12 Event-Driven GUI Programming, Mult ithreading, and Animation . . . . . . . 491
CHAPTER 13 System Modeling with the UML . . . . . . . 523
CHAPTER 14 Using Relat ional Databases . . . . . . . . 555
APPENDIX A Understanding Numbering Systems and Computer Codes . . . . . . . . . . . 601
APPENDIX B Flowchart Symbols . . . . . . . . . . . . 611
APPENDIX C Structures . . . . . . . . . . . . . . . . 612
APPENDIX D Solving Diff icult Structuring Problems . . . . 614
v
Copyright 2012 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part. Due to electronic rights, some third party content may be suppressed from the eBook and/or eChapter(s).
Editorial review has deemed that any suppressed content does not materially affect the overall learning experience. Cengage Learning reserves the right to remove additional content at any time if subsequent rights restrictions require it.
APPENDIX E Creating Print Charts . . . . . . . . . . . 624
APPENDIX F Two Variat ions on the Basic Structures—case and do-while . . . 626
Glossary . . . . . . . . . . . . . . . . . 633
Index . . . . . . . . . . . . . . . . . . . 653
B R I E F C ON T EN T S
vi
Copyright 2012 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part. Due to electronic rights, some third party content may be suppressed from the eBook and/or eChapter(s).
Editorial review has deemed that any suppressed content does not materially affect the overall learning experience. Cengage Learning reserves the right to remove additional content at any time if subsequent rights restrictions require it.
Contents
Preface . . . . . . . . . . . . . . . . . . xviii
CHAPTER 1 An Overview of Computers and Programming . 1
Understanding Computer Systems . . . . . . . . . . . . . . . 2 Understanding Simple Program Logic . . . . . . . . . . . . . 5 Understanding the Program Development Cycle . . . . . . . . . 7 Understanding the Problem . . . . . . . . . . . . . . . . . 8 Planning the Logic . . . . . . . . . . . . . . . . . . . . . 9 Coding the Program . . . . . . . . . . . . . . . . . . . . 10 Using Software to Translate the Program into Machine Language . 10 Testing the Program . . . . . . . . . . . . . . . . . . . . 12 Putting the Program into Production . . . . . . . . . . . . . 13 Maintaining the Program . . . . . . . . . . . . . . . . . . 13
Using Pseudocode Statements and Flowchart Symbols . . . . . . 14 Writing Pseudocode . . . . . . . . . . . . . . . . . . . . 15 Drawing Flowcharts . . . . . . . . . . . . . . . . . . . . 16 Repeating Instructions . . . . . . . . . . . . . . . . . . . 17
Using a Sentinel Value to End a Program . . . . . . . . . . . . 19 Understanding Programming and User Environments . . . . . . . 22 Understanding Programming Environments . . . . . . . . . . 22 Understanding User Environments . . . . . . . . . . . . . . 24
Understanding the Evolution of Programming Models . . . . . . . 25 Chapter Summary . . . . . . . . . . . . . . . . . . . . . . 27 Key Terms . . . . . . . . . . . . . . . . . . . . . . . . . 28 Review Questions . . . . . . . . . . . . . . . . . . . . . . 31 Exercises . . . . . . . . . . . . . . . . . . . . . . . . . 33 Find the Bugs . . . . . . . . . . . . . . . . . . . . . . . 35 Game Zone . . . . . . . . . . . . . . . . . . . . . . . . 35 Up for Discussion . . . . . . . . . . . . . . . . . . . . . 36
vii
Copyright 2012 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part. Due to electronic rights, some third party content may be suppressed from the eBook and/or eChapter(s).
Editorial review has deemed that any suppressed content does not materially affect the overall learning experience. Cengage Learning reserves the right to remove additional content at any time if subsequent rights restrictions require it.
CHAPTER 2 Elements of High-Qual ity Programs . . . . . . 37
Declaring and Using Variables and Constants . . . . . . . . . . 38 Understanding Unnamed, Literal Constants and their
Data Types . . . . . . . . . . . . . . . . . . . . . . . 38 Working with Variables . . . . . . . . . . . . . . . . . . . 39 Naming Variables . . . . . . . . . . . . . . . . . . . . . 41 Assigning Values to Variables . . . . . . . . . . . . . . . . 42 Understanding the Data Types of Variables . . . . . . . . . . 43 Declaring Named Constants . . . . . . . . . . . . . . . . 44
Performing Arithmetic Operations . . . . . . . . . . . . . . . 45 Understanding the Advantages of Modularization . . . . . . . . . 48 Modularization Provides Abstraction . . . . . . . . . . . . . 49 Modularization Allows Multiple Programmers to
Work on a Problem . . . . . . . . . . . . . . . . . . . 50 Modularization Allows You to Reuse Work . . . . . . . . . . . 50
Modularizing a Program . . . . . . . . . . . . . . . . . . . 51 Declaring Variables and Constants within Modules . . . . . . . 55 Understanding the Most Common Configuration for Mainline Logic . 57
Creating Hierarchy Charts . . . . . . . . . . . . . . . . . . 61 Features of Good Program Design . . . . . . . . . . . . . . . 63 Using Program Comments . . . . . . . . . . . . . . . . . 64 Choosing Identifiers . . . . . . . . . . . . . . . . . . . . 66 Designing Clear Statements . . . . . . . . . . . . . . . . 68 Writing Clear Prompts and Echoing Input . . . . . . . . . . . 69 Maintaining Good Programming Habits . . . . . . . . . . . . 71
Chapter Summary . . . . . . . . . . . . . . . . . . . . . . 72 Key Terms . . . . . . . . . . . . . . . . . . . . . . . . . 73 Review Questions . . . . . . . . . . . . . . . . . . . . . . 76 Exercises . . . . . . . . . . . . . . . . . . . . . . . . . 79 Find the Bugs . . . . . . . . . . . . . . . . . . . . . . . 81 Game Zone . . . . . . . . . . . . . . . . . . . . . . . . 82 Up for Discussion . . . . . . . . . . . . . . . . . . . . . 82
CHAPTER 3 Understanding Structure . . . . . . . . . . . 83
The Disadvantages of Unstructured Spaghetti Code . . . . . . . 84 Understanding the Three Basic Structures . . . . . . . . . . . 86
viii
C O N T E N T S
Copyright 2012 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part. Due to electronic rights, some third party content may be suppressed from the eBook and/or eChapter(s).
Editorial review has deemed that any suppressed content does not materially affect the overall learning experience. Cengage Learning reserves the right to remove additional content at any time if subsequent rights restrictions require it.
Using a Priming Input to Structure a Program . . . . . . . . . . 95 Understanding the Reasons for Structure . . . . . . . . . . . 101 Recognizing Structure . . . . . . . . . . . . . . . . . . . 102 Structuring and Modularizing Unstructured Logic . . . . . . . . 105 Chapter Summary . . . . . . . . . . . . . . . . . . . . . 110 Key Terms . . . . . . . . . . . . . . . . . . . . . . . . 111 Review Questions . . . . . . . . . . . . . . . . . . . . . 112 Exercises . . . . . . . . . . . . . . . . . . . . . . . . 114 Find the Bugs . . . . . . . . . . . . . . . . . . . . . . 118 Game Zone . . . . . . . . . . . . . . . . . . . . . . . 118 Up for Discussion . . . . . . . . . . . . . . . . . . . . 119
CHAPTER 4 Making Decisions . . . . . . . . . . . . . 121
Boolean Expressions and the Selection Structure . . . . . . . 122 Using Relational Comparison Operators . . . . . . . . . . . 126 Avoiding a Common Error with Relational Operators . . . . . 129
Understanding AND Logic . . . . . . . . . . . . . . . . . 129 Nesting AND Decisions for Efficiency . . . . . . . . . . . . 132 Using the AND Operator . . . . . . . . . . . . . . . . . 134 Avoiding Common Errors in an AND Selection . . . . . . . . 136
Understanding OR Logic . . . . . . . . . . . . . . . . . . 138 Writing OR Decisions for Efficiency . . . . . . . . . . . . . 140 Using the OR Operator . . . . . . . . . . . . . . . . . . 141 Avoiding Common Errors in an OR Selection . . . . . . . . 143
Making Selections within Ranges . . . . . . . . . . . . . . 148 Avoiding Common Errors When Using Range Checks . . . . . 150
Understanding Precedence When Combining AND and OR Operators . . . . . . . . . . . . . . . . . . . . 154
Chapter Summary . . . . . . . . . . . . . . . . . . . . . 157 Key Terms . . . . . . . . . . . . . . . . . . . . . . . . 158 Review Questions . . . . . . . . . . . . . . . . . . . . . 159 Exercises . . . . . . . . . . . . . . . . . . . . . . . . 162 Find the Bugs . . . . . . . . . . . . . . . . . . . . . . 167 Game Zone . . . . . . . . . . . . . . . . . . . . . . . 167 Up for Discussion . . . . . . . . . . . . . . . . . . . . 168
ix
Copyright 2012 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part. Due to electronic rights, some third party content may be suppressed from the eBook and/or eChapter(s).
Editorial review has deemed that any suppressed content does not materially affect the overall learning experience. Cengage Learning reserves the right to remove additional content at any time if subsequent rights restrictions require it.
CHAPTER 5 Looping . . . . . . . . . . . . . . . . . 169
Understanding the Advantages of Looping . . . . . . . . . . 170 Using a Loop Control Variable . . . . . . . . . . . . . . . . 171 Using a Definite Loop with a Counter . . . . . . . . . . . . 172 Using an Indefinite Loop with a Sentinel Value . . . . . . . . 173 Understanding the Loop in a Program’s Mainline Logic . . . . 175
Nested Loops . . . . . . . . . . . . . . . . . . . . . . 177 Avoiding Common Loop Mistakes . . . . . . . . . . . . . . 183 Mistake: Neglecting to Initialize the Loop Control Variable . . . 183 Mistake: Neglecting to Alter the Loop Control Variable . . . . 185 Mistake: Using the Wrong Comparison with the Loop Control
Variable . . . . . . . . . . . . . . . . . . . . . . . 186 Mistake: Including Statements Inside the Loop
that Belong Outside the Loop . . . . . . . . . . . . . . 187 Using a for Loop . . . . . . . . . . . . . . . . . . . . . 192 Common Loop Applications . . . . . . . . . . . . . . . . . 194 Using a Loop to Accumulate Totals . . . . . . . . . . . . 194 Using a Loop to Validate Data . . . . . . . . . . . . . . . 198 Limiting a Reprompting Loop . . . . . . . . . . . . . . . 200 Validating a Data Type . . . . . . . . . . . . . . . . . . 202 Validating Reasonableness and Consistency of Data . . . . . 203
Chapter Summary . . . . . . . . . . . . . . . . . . . . . 205 Key Terms . . . . . . . . . . . . . . . . . . . . . . . . 205 Review Questions . . . . . . . . . . . . . . . . . . . . . 206 Exercises . . . . . . . . . . . . . . . . . . . . . . . . 209 Find the Bugs . . . . . . . . . . . . . . . . . . . . . . 211 Game Zone . . . . . . . . . . . . . . . . . . . . . . . 211 Up for Discussion . . . . . . . . . . . . . . . . . . . . 212
CHAPTER 6 Arrays . . . . . . . . . . . . . . . . . . 213
Storing Data in Arrays . . . . . . . . . . . . . . . . . . . 214 How Arrays Occupy Computer Memory . . . . . . . . . . . 214
How an Array Can Replace Nested Decisions . . . . . . . . . 216 Using Constants with Arrays . . . . . . . . . . . . . . . . 224 Using a Constant as the Size of an Array . . . . . . . . . . 224 Using Constants as Array Element Values . . . . . . . . . . 225 Using a Constant as an Array Subscript . . . . . . . . . . 225
x
C ON T E N T S
Copyright 2012 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part. Due to electronic rights, some third party content may be suppressed from the eBook and/or eChapter(s).
Editorial review has deemed that any suppressed content does not materially affect the overall learning experience. Cengage Learning reserves the right to remove additional content at any time if subsequent rights restrictions require it.
Searching an Array for an Exact Match . . . . . . . . . . . . 226 Using Parallel Arrays . . . . . . . . . . . . . . . . . . . . 230 Improving Search Efficiency . . . . . . . . . . . . . . . . 234
Searching an Array for a Range Match . . . . . . . . . . . . 237 Remaining within Array Bounds . . . . . . . . . . . . . . . 241 Using a for Loop to Process Arrays . . . . . . . . . . . . . 244 Chapter Summary . . . . . . . . . . . . . . . . . . . . . 245 Key Terms . . . . . . . . . . . . . . . . . . . . . . . . 246 Review Questions . . . . . . . . . . . . . . . . . . . . . 246 Exercises . . . . . . . . . . . . . . . . . . . . . . . . 249 Find the Bugs . . . . . . . . . . . . . . . . . . . . . . 253 Game Zone . . . . . . . . . . . . . . . . . . . . . . . 253 Up for Discussion . . . . . . . . . . . . . . . . . . . . 255
CHAPTER 7 Fi le Handl ing and Applicat ions . . . . . . . 257
Understanding Computer Files . . . . . . . . . . . . . . . 258 Organizing Files . . . . . . . . . . . . . . . . . . . . . 259
Understanding the Data Hierarchy . . . . . . . . . . . . . . 260 Performing File Operations . . . . . . . . . . . . . . . . . 261 Declaring a File . . . . . . . . . . . . . . . . . . . . . 261 Opening a File . . . . . . . . . . . . . . . . . . . . . 262 Reading Data from a File . . . . . . . . . . . . . . . . . 262 Writing Data to a File . . . . . . . . . . . . . . . . . . 264 Closing a File . . . . . . . . . . . . . . . . . . . . . . 264 A Program that Performs File Operations . . . . . . . . . . 264
Understanding Sequential Files and Control Break Logic . . . . 267 Understanding Control Break Logic . . . . . . . . . . . . 268
Merging Sequential Files . . . . . . . . . . . . . . . . . . 273 Master and Transaction File Processing . . . . . . . . . . . 281 Random Access Files . . . . . . . . . . . . . . . . . . . 290 Chapter Summary . . . . . . . . . . . . . . . . . . . . . 292 Key Terms . . . . . . . . . . . . . . . . . . . . . . . . 293 Review Questions . . . . . . . . . . . . . . . . . . . . . 295 Exercises . . . . . . . . . . . . . . . . . . . . . . . . 299 Find the Bugs . . . . . . . . . . . . . . . . . . . . . . 302 Game Zone . . . . . . . . . . . . . . . . . . . . . . . 302 Up for Discussion . . . . . . . . . . . . . . . . . . . . 303
xi
Copyright 2012 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part. Due to electronic rights, some third party content may be suppressed from the eBook and/or eChapter(s).
Editorial review has deemed that any suppressed content does not materially affect the overall learning experience. Cengage Learning reserves the right to remove additional content at any time if subsequent rights restrictions require it.
CHAPTER 8 Advanced Data Handl ing Concepts . . . . . 305
Understanding the Need for Sorting Data . . . . . . . . . . . 306 Using the Bubble Sort Algorithm . . . . . . . . . . . . . . . 307 Understanding Swapping Values . . . . . . . . . . . . . . 308 Understanding the Bubble Sort . . . . . . . . . . . . . . 309 Sorting a List of Variable Size . . . . . . . . . . . . . . . 318 Refining the Bubble Sort to Reduce Unnecessary
Comparisons . . . . . . . . . . . . . . . . . . . . . 322 Refining the Bubble Sort to Eliminate Unnecessary
Passes . . . . . . . . . . . . . . . . . . . . . . . 324 Sorting Multifield Records . . . . . . . . . . . . . . . . . 326 Sorting Data Stored in Parallel Arrays . . . . . . . . . . . 326 Sorting Records as a Whole . . . . . . . . . . . . . . . 328
Using the Insertion Sort Algorithm . . . . . . . . . . . . . . 329 Using Multidimensional Arrays . . . . . . . . . . . . . . . . 333 Using Indexed Files and Linked Lists . . . . . . . . . . . . . 340 Using Indexed Files . . . . . . . . . . . . . . . . . . . 340 Using Linked Lists . . . . . . . . . . . . . . . . . . . . 342
Chapter Summary . . . . . . . . . . . . . . . . . . . . . 345 Key Terms . . . . . . . . . . . . . . . . . . . . . . . . 346 Review Questions . . . . . . . . . . . . . . . . . . . . . 347 Exercises . . . . . . . . . . . . . . . . . . . . . . . . 350 Find the Bugs . . . . . . . . . . . . . . . . . . . . . . 352 Game Zone . . . . . . . . . . . . . . . . . . . . . . . 353 Up for Discussion . . . . . . . . . . . . . . . . . . . . 354
CHAPTER 9 Advanced Modularization Techniques . . . . 355
Using Methods with No Parameters . . . . . . . . . . . . . 356 Creating Methods that Require Parameters . . . . . . . . . . 358 Creating Methods that Require Multiple Parameters . . . . . 364
Creating Methods that Return a Value . . . . . . . . . . . . 366 Using an IPO Chart . . . . . . . . . . . . . . . . . . . 372
Passing an Array to a Method . . . . . . . . . . . . . . . . 373 Overloading Methods . . . . . . . . . . . . . . . . . . . 380 Avoiding Ambiguous Methods . . . . . . . . . . . . . . . 383
Using Predefined Methods . . . . . . . . . . . . . . . . . 386
xii
C O N T E N T S
Copyright 2012 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part. Due to electronic rights, some third party content may be suppressed from the eBook and/or eChapter(s).
Editorial review has deemed that any suppressed content does not materially affect the overall learning experience. Cengage Learning reserves the right to remove additional content at any time if subsequent rights restrictions require it.
Method Design Issues: Implementation Hiding, Cohesion, and Coupling . . . . . . . . . . . . . . . . . . . . . . 388 Understanding Implementation Hiding . . . . . . . . . . . 388 Increasing Cohesion . . . . . . . . . . . . . . . . . . . 388 Reducing Coupling . . . . . . . . . . . . . . . . . . . 389
Understanding Recursion . . . . . . . . . . . . . . . . . . 390 Chapter Summary . . . . . . . . . . . . . . . . . . . . . 395 Key Terms . . . . . . . . . . . . . . . . . . . . . . . . 396 Review Questions . . . . . . . . . . . . . . . . . . . . . 397 Exercises . . . . . . . . . . . . . . . . . . . . . . . . 400 Find the Bugs . . . . . . . . . . . . . . . . . . . . . . 404 Game Zone . . . . . . . . . . . . . . . . . . . . . . . 404 Up for Discussion . . . . . . . . . . . . . . . . . . . . 405
CHAPTER 10 Object-Oriented Programming . . . . . . . 407
Principles of Object-Oriented Programming . . . . . . . . . . 408 Classes and Objects . . . . . . . . . . . . . . . . . . . 408 Polymorphism . . . . . . . . . . . . . . . . . . . . . 412 Inheritance . . . . . . . . . . . . . . . . . . . . . . . 413 Encapsulation . . . . . . . . . . . . . . . . . . . . . . 414
Defining Classes and Creating Class Diagrams . . . . . . . . 415 Creating Class Diagrams . . . . . . . . . . . . . . . . . 417 The Set Methods . . . . . . . . . . . . . . . . . . . . 420 The Get Methods . . . . . . . . . . . . . . . . . . . . 421 Work Methods . . . . . . . . . . . . . . . . . . . . . 422
Understanding Public and Private Access . . . . . . . . . . . 424 Organizing Classes . . . . . . . . . . . . . . . . . . . . 428 Understanding Instance Methods . . . . . . . . . . . . . . 429 Understanding Static Methods . . . . . . . . . . . . . . . 434 Using Objects . . . . . . . . . . . . . . . . . . . . . . . 436 Chapter Summary . . . . . . . . . . . . . . . . . . . . . 440 Key Terms . . . . . . . . . . . . . . . . . . . . . . . . 440 Review Questions . . . . . . . . . . . . . . . . . . . . . 442 Exercises . . . . . . . . . . . . . . . . . . . . . . . . 445 Find the Bugs . . . . . . . . . . . . . . . . . . . . . . 447 Game Zone . . . . . . . . . . . . . . . . . . . . . . . 447 Up for Discussion . . . . . . . . . . . . . . . . . . . . 447
xiii
Copyright 2012 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part. Due to electronic rights, some third party content may be suppressed from the eBook and/or eChapter(s).
Editorial review has deemed that any suppressed content does not materially affect the overall learning experience. Cengage Learning reserves the right to remove additional content at any time if subsequent rights restrictions require it.
CHAPTER 11 More Object-Oriented Programming Concepts 449
Understanding Constructors . . . . . . . . . . . . . . . . 450 Default Constructors . . . . . . . . . . . . . . . . . . . 450 Nondefault Constructors . . . . . . . . . . . . . . . . . 453 Overloading Methods and Constructors . . . . . . . . . . . 453
Understanding Destructors . . . . . . . . . . . . . . . . . 456 Understanding Composition . . . . . . . . . . . . . . . . . 458 Understanding Inheritance . . . . . . . . . . . . . . . . . 459 Understanding Inheritance Terminology . . . . . . . . . . . 462 Accessing Private Fields and Methods of a Parent Class . . . 465 Using Inheritance to Achieve Good Software Design . . . . . 470
An Example of Using Predefined Classes: Creating GUI Objects . 472 Understanding Exception Handling . . . . . . . . . . . . . . 473 Drawbacks to Traditional Error-Handling Techniques . . . . . 473 The Object-Oriented Exception-Handling Model . . . . . . . . 475 Using Built-in Exceptions and Creating Your Own Exceptions . . 477
Reviewing the Advantages of Object-Oriented Programming . . . 479 Chapter Summary . . . . . . . . . . . . . . . . . . . . . 479 Key Terms . . . . . . . . . . . . . . . . . . . . . . . . 480 Review Questions . . . . . . . . . . . . . . . . . . . . . 482 Exercises . . . . . . . . . . . . . . . . . . . . . . . . 485 Find the Bugs . . . . . . . . . . . . . . . . . . . . . . 489 Game Zone . . . . . . . . . . . . . . . . . . . . . . . 489 Up for Discussion . . . . . . . . . . . . . . . . . . . . 490
CHAPTER 12 Event-Driven GUI Programming, Mult ithreading, and Animation . . . . . . . 491
Understanding Event-Driven Programming . . . . . . . . . . . 492 User-Initiated Actions and GUI Components . . . . . . . . . . 495 Designing Graphical User Interfaces . . . . . . . . . . . . . 498 The Interface Should Be Natural and Predictable . . . . . . . 498 The Interface Should Be Attractive, Easy to Read, and
Nondistracting . . . . . . . . . . . . . . . . . . . . 499 To Some Extent, It’s Helpful If the User Can Customize Your
Applications . . . . . . . . . . . . . . . . . . . . . 500 The Program Should Be Forgiving . . . . . . . . . . . . . 500 The GUI Is Only a Means to an End . . . . . . . . . . . . . 500
xiv
C O N T E N T S
Copyright 2012 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part. Due to electronic rights, some third party content may be suppressed from the eBook and/or eChapter(s).
Editorial review has deemed that any suppressed content does not materially affect the overall learning experience. Cengage Learning reserves the right to remove additional content at any time if subsequent rights restrictions require it.
Developing an Event-Driven Application . . . . . . . . . . . . 501 Creating Storyboards . . . . . . . . . . . . . . . . . . 502 Defining the Storyboard Objects in an Object Dictionary . . . . 502 Defining Connections Between the User Screens . . . . . . . 503 Planning the Logic . . . . . . . . . . . . . . . . . . . . 504
Understanding Threads and Multithreading . . . . . . . . . . 509 Creating Animation . . . . . . . . . . . . . . . . . . . . 512 Chapter Summary . . . . . . . . . . . . . . . . . . . . . 515 Key Terms . . . . . . . . . . . . . . . . . . . . . . . . 516 Review Questions . . . . . . . . . . . . . . . . . . . . . 517 Exercises . . . . . . . . . . . . . . . . . . . . . . . . 520 Find the Bugs . . . . . . . . . . . . . . . . . . . . . . 520 Game Zone . . . . . . . . . . . . . . . . . . . . . . . 521 Up for Discussion . . . . . . . . . . . . . . . . . . . . 522
CHAPTER 13 System Modeling with the UML . . . . . . . 523
Understanding System Modeling . . . . . . . . . . . . . . . 524 What Is the UML? . . . . . . . . . . . . . . . . . . . . . 525 Using UML Use Case Diagrams . . . . . . . . . . . . . . . 527 Using UML Class and Object Diagrams . . . . . . . . . . . . 533 Using Other UML Diagrams . . . . . . . . . . . . . . . . . 537 Sequence Diagrams . . . . . . . . . . . . . . . . . . . 537 Communication Diagrams . . . . . . . . . . . . . . . . 538 State Machine Diagrams . . . . . . . . . . . . . . . . . 539 Activity Diagrams . . . . . . . . . . . . . . . . . . . . 540 Component and Deployment Diagrams . . . . . . . . . . . 542 Profile Diagrams . . . . . . . . . . . . . . . . . . . . 544 Diagramming Exception Handling . . . . . . . . . . . . . 544
Deciding When to Use the UML and Which UML Diagrams to Use . 546 Chapter Summary . . . . . . . . . . . . . . . . . . . . . 547 Key Terms . . . . . . . . . . . . . . . . . . . . . . . . 548 Review Questions . . . . . . . . . . . . . . . . . . . . . 549 Exercises . . . . . . . . . . . . . . . . . . . . . . . . 552 Find the Bugs . . . . . . . . . . . . . . . . . . . . . . 553 Game Zone . . . . . . . . . . . . . . . . . . . . . . . 553 Up for Discussion . . . . . . . . . . . . . . . . . . . . 554
xv
Copyright 2012 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part. Due to electronic rights, some third party content may be suppressed from the eBook and/or eChapter(s).
Editorial review has deemed that any suppressed content does not materially affect the overall learning experience. Cengage Learning reserves the right to remove additional content at any time if subsequent rights restrictions require it.
CHAPTER 14 Using Relat ional Databases . . . . . . . . 555
Understanding Relational Database Fundamentals . . . . . . . 556 Creating Databases and Table Descriptions . . . . . . . . . . 558 Identifying Primary Keys . . . . . . . . . . . . . . . . . . 560 Understanding Database Structure Notation . . . . . . . . . . 563 Working with Records within Tables . . . . . . . . . . . . . 564 Creating Queries . . . . . . . . . . . . . . . . . . . . . 565 Understanding Relationships between Tables . . . . . . . . . 568 Understanding One-To-Many Relationships . . . . . . . . . . 569 Understanding Many-To-Many Relationships . . . . . . . . . 569 Understanding One-To-One Relationships . . . . . . . . . . 573
Recognizing Poor Table Design . . . . . . . . . . . . . . . 574 Understanding Anomalies, Normal Forms, and Normalization . . 576 First Normal Form . . . . . . . . . . . . . . . . . . . . 578 Second Normal Form . . . . . . . . . . . . . . . . . . 579 Third Normal Form . . . . . . . . . . . . . . . . . . . 582
Database Performance and Security Issues . . . . . . . . . . 585 Providing Data Integrity . . . . . . . . . . . . . . . . . 585 Recovering Lost Data . . . . . . . . . . . . . . . . . . 586 Avoiding Concurrent Update Problems . . . . . . . . . . . 586 Providing Authentication and Permissions . . . . . . . . . . 586 Providing Encryption . . . . . . . . . . . . . . . . . . . 587
Chapter Summary . . . . . . . . . . . . . . . . . . . . . 587 Key Terms . . . . . . . . . . . . . . . . . . . . . . . . 589 Review Questions . . . . . . . . . . . . . . . . . . . . . 591 Exercises . . . . . . . . . . . . . . . . . . . . . . . . 594 Find the Bugs . . . . . . . . . . . . . . . . . . . . . . 598 Game Zone . . . . . . . . . . . . . . . . . . . . . . . 598 Up for Discussion . . . . . . . . . . . . . . . . . . . . 598
APPENDIX A Understanding Numbering Systems and Computer Codes . . . . . . . . . . . . 601
APPENDIX B Flowchart Symbols . . . . . . . . . . . . . 611
APPENDIX C Structures . . . . . . . . . . . . . . . . . 612
xvi
C O N T E N T S
Copyright 2012 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part. Due to electronic rights, some third party content may be suppressed from the eBook and/or eChapter(s).
Editorial review has deemed that any suppressed content does not materially affect the overall learning experience. Cengage Learning reserves the right to remove additional content at any time if subsequent rights restrictions require it.
APPENDIX D Solving Diff icult Structuring Problems . . . . 614
APPENDIX E Creating Print Charts . . . . . . . . . . . . 624
APPENDIX F Two Variat ions on the Basic Structures—case and do-while . . . . . . . . . . . . . . . 626
Glossary . . . . . . . . . . . . . . . . . . 633
Index . . . . . . . . . . . . . . . . . . . . 653
xvii
Copyright 2012 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part. Due to electronic rights, some third party content may be suppressed from the eBook and/or eChapter(s).
Editorial review has deemed that any suppressed content does not materially affect the overall learning experience. Cengage Learning reserves the right to remove additional content at any time if subsequent rights restrictions require it.
Preface
Programming Logic and Design, Comprehensive, Seventh 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, Seventh 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 gives students a solid foundation in 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 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 advantages of object-oriented thinking.
xviii
Copyright 2012 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part. Due to electronic rights, some third party content may be suppressed from the eBook and/or eChapter(s).
Editorial review has deemed that any suppressed content does not materially affect the overall learning experience. Cengage Learning reserves the right to remove additional content at any time if subsequent rights restrictions require it.
Chapter 12 explores additional object-oriented programming issues: event-driven GUI programming, multithreading, and animation. Chapter 13 discusses system design issues and details the features of the Unified Modeling Language. Chapter 14 is a thorough introduction to important database concepts that business programmers should understand.
The first three appendices give students summaries of numbering systems, flowchart symbols, and structures. Additional appendices allow students to gain extra experience with structuring large unstructured programs, creating print charts, and understanding posttest loops and case structures.
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:
l It is written and designed to be non-language specific. The logic used in this book can be applied to any programming language.
l The examples are everyday business examples; no special knowledge of mathematics, accounting, or other disciplines is assumed.
l The concept of structure is covered earlier than in many other texts. Students are exposed to structure naturally, so they will automatically create properly designed programs.
l Text explanation is interspersed with both flowcharts and pseudocode so students can become comfortable with these logic development tools and understand their interrelationship. Screen shots of running programs also are included, providing students with a clear and concrete image of the programs’ execution.
l 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 programs.
Organization and Coverage
xix
Copyright 2012 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part. Due to electronic rights, some third party content may be suppressed from the eBook and/or eChapter(s).
Editorial review has deemed that any suppressed content does not materially affect the overall learning experience. Cengage Learning reserves the right to remove additional content at any time if subsequent rights restrictions require it.
Features This text focuses on helping students become better programmers and understand the big picture in program development through a variety of key features. In addition to chapter Objectives, Summaries, and Key Terms, these useful features will help students regardless of their learning style.
The use of flowcharts is excellent. This is a must-have book for learning programming logic before tackling the various languages.
—Lori Selby, University of Arkansas at Monticello
FLOWCHARTS, figures, and illustrations provide
learning experience. the reader with a visual
VIDEO LESSONS help explain important chapter concepts. Videos are part of the text’s enhanced CourseMate site.
NOTES provide additional information— for example, another location in the book that expands on a topic, or a common error to watch out for.
xx
Copyright 2012 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part. Due to electronic rights, some third party content may be suppressed from the eBook and/or eChapter(s).
Editorial review has deemed that any suppressed content does not materially affect the overall learning experience. Cengage Learning reserves the right to remove additional content at any time if subsequent rights restrictions require it.
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 through the enhanced CourseMate site.
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.
xxi
Copyright 2012 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part. Due to electronic rights, some third party content may be suppressed from the eBook and/or eChapter(s).
Editorial review has deemed that any suppressed content does not materially affect the overall learning experience. Cengage Learning reserves the right to remove additional content at any time if subsequent rights restrictions require it.
Assessment
The material is very well written, clearly presented, and up to date. All explanations are very solid, and Farrell’s language is clean, cogent, and easy to follow.
—Judy Woodruff, Indiana University-Purdue University Indianapolis
EXERCISES provide opportunities to practice concepts. These exercises
to explore logical programming concepts. Each exercise can
pseudocode, or both. In addition, instructors can assign the exercises as programming problems to be coded and executed in a particular programming language.
REVIEW QUESTIONS test student comprehension of the major ideas and techniques presented. Twenty questions follow each chapter.
xxii
Copyright 2012 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part. Due to electronic rights, some third party content may be suppressed from the eBook and/or eChapter(s).
Editorial review has deemed that any suppressed content does not materially affect the overall learning experience. Cengage Learning reserves the right to remove additional content at any time if subsequent rights restrictions require it.
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 the CourseMate available for this text. These files are also available to instructors through the Instructor Resources CD and login.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.
ESSAY QUESTIONS present personal and ethical issues that programmers must consider. These questions can be used for written assignments or as a starting point for classroom discussion.
xxiii
Copyright 2012 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part. Due to electronic rights, some third party content may be suppressed from the eBook and/or eChapter(s).
Editorial review has deemed that any suppressed content does not materially affect the overall learning experience. Cengage Learning reserves the right to remove additional content at any time if subsequent rights restrictions require it.
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. In this edition, all explanations have been carefully reviewed to provide the clearest possible instruction. Material that previously was included in margin notes has most frequently been incorporated into the main text, giving the pages a more streamlined appearance. All the chapters in this edition contain new programming exercises. All Sixth Edition exercises that have been replaced are available on the Instructor Resources CD and through login. cengage.com so instructors can use them as additional assigned exercises or as topics for class discussions.
l Clear explanations. The language and explanations in this book have been refined over seven editions, providing the clearest possible explanations of difficult concepts.
l Emphasis on structure. More than its competitors, this book emphasizes structure. Chapter 3 provides an early picture of the major concepts of structured programming, giving students an overview of the principles before they are required to consider program details.
l Emphasis on modularity. From the second chapter, 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. This edition uses modularization early, using global variables instead of local passed and returned values, and saves parameter passing for later when the student has become more adept.
l Methods as black boxes. The use of methods is consistent with the languages in which the student is likely to have first programming experiences. In particular, this book emphasizes using methods as black boxes, declaring all variables and constants as local to methods, and passing arguments to and receiving returned values from methods as needed.
l Objectives. Each chapter begins with a list of objectives so 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.
l Pseudocode. This book includes numerous examples of pseudocode, which illustrate correct usage of the programming logic and design concepts being taught.
l Chapter summaries. Following each chapter is a summary that recaps the programming concepts and techniques covered in the chapter. This feature provides a concise means for students to review and check their understanding of the main points in each chapter.
l Key terms. Each chapter lists key terms and their definitions; the list appears in the order the terms are encountered in the chapter. Along with the chapter summary, the
xxiv
P R E F A C E Other Features of the Text
Copyright 2012 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part. Due to electronic rights, some third party content may be suppressed from the eBook and/or eChapter(s).
Editorial review has deemed that any suppressed content does not materially affect the overall learning experience. Cengage Learning reserves the right to remove additional content at any time if subsequent rights restrictions require it.
list of key terms provides a snapshot overview of a chapter’s main ideas. A glossary at the end of the book lists all the key terms in alphabetical order, along with working definitions.
CourseMate The more you study, the better the results. Make the most of your study time by accessing everything you need to succeed in one place. Read your textbook, review flashcards, watch videos, and take practice quizzes online. CourseMate goes beyond the book to deliver what you need! Learn more at www.cengage.com/coursemate.
The Programming Logic and Design CourseMate includes:
l Video Lessons. Designed and narrated by the author, videos in each chapter explain and enrich important concepts.
l Two Truths & A Lie and Debugging Exercises. Complete popular exercises from the text online!
l An interactive eBook with highlighting and note-taking, flashcards, quizzing, study games, and more!
Instructors may add CourseMate to the textbook package, or students may purchase CourseMate directly at www.cengagebrain.com.
Instructor Resources The following teaching tools are available to the instructor on a single CD-ROM. Many are also available for download through our Instructor Companion Site at login.cengage.com.
l Electronic 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.
l PowerPoint Presentations. This text provides PowerPoint slides to accompany each chapter. Slides are included to guide classroom presentation, to make available to students for chapter review, or to print as classroom handouts. Instructors may customize the slides, which include the complete figure files from the text, to best suit their courses.
l Solutions. Solutions to review questions and exercises are provided to assist with grading.
xxv
Instructor Resources
Copyright 2012 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part. Due to electronic rights, some third party content may be suppressed from the eBook and/or eChapter(s).
Editorial review has deemed that any suppressed content does not materially affect the overall learning experience. Cengage Learning reserves the right to remove additional content at any time if subsequent rights restrictions require it.
l ExamView�. This textbook is accompanied by ExamView, a powerful testing software package that allows instructors to create and administer printed, LAN-based, and Internet exams. ExamView includes hundreds of questions that correspond to the text, enabling students to generate detailed study guides that include page references for further review. The computer-based and Internet testing components allow students to take exams at their computers, and the components save the instructor time by grading each exam automatically. These test banks are also available in Blackboard and Angel compatible formats.
Additional Offerings You have the option to bundle software with your text. Please contact your Cengage Learning sales representative for more information.
l PAL Guides. Together with Programming Logic and Design, these brief books, or PAL guides, provide an excellent opportunity to learn the fundamentals of programming while gaining exposure to a programming language. Readers will discover how real code behaves within the context of the traditionally language-independent logic and design course. PAL guides are available for C++, Java, and Visual Basic; please contact your sales rep for more information on how to add the PAL guides to your course.
l Microsoft� Office Visio� Professional 2010, 60-day version. Visio 2010 is a diagramming program that allows users to create flowcharts and diagrams easily while working through the text, enabling them to visualize concepts and learn more effectively.
l Visual LogicTM software. Visual Logic is a simple but powerful tool for teaching programming logic and design without traditional high-level programming language syntax. Visual Logic uses flowcharts to explain the essential programming concepts discussed in this book, including variables, input, assignment, output, conditions, loops, procedures, graphics, arrays, and files. Visual Logic also interprets and executes flowcharts, providing students with immediate and accurate feedback. Visual Logic combines the power of a high-level language with the ease and simplicity of flowcharts.
Acknowledgments I would like to thank all of the people who helped to make this book a reality, especially Dan Seiter, Development Editor. After seven editions, Dan still finds ways to improve my explanations so that we can create a book of the highest possible quality. Thanks also to Alyssa Pratt, Senior Product Manager; Brandi Shailer, Acquisitions Editor; Catherine DiMassa, Senior Content Project Manager; and Green Pen QA, Technical Editors. I am grateful to be able to work with so many fine people who are dedicated to producing quality instructional materials.
xxvi
P R E F A C E Acknowledgments
Copyright 2012 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part. Due to electronic rights, some third party content may be suppressed from the eBook and/or eChapter(s).
Editorial review has deemed that any suppressed content does not materially affect the overall learning experience. Cengage Learning reserves the right to remove additional content at any time if subsequent rights restrictions require it.
I am indebted to the many reviewers who provided helpful and insightful comments during the development of this book, including Linda Cohen, Forsyth Tech; Andrew Hurd, Hudson Valley Community College; George Reynolds, Strayer University; Lori Selby, University of Arkansas at Monticello; and Judy Woodruff, Indiana University–Purdue University Indianapolis.
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
xxvii
Acknowledgments
Copyright 2012 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part. Due to electronic rights, some third party content may be suppressed from the eBook and/or eChapter(s).
Editorial review has deemed that any suppressed content does not materially affect the overall learning experience. Cengage Learning reserves the right to remove additional content at any time if subsequent rights restrictions require it.
Copyright 2012 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part. Due to electronic rights, some third party content may be suppressed from the eBook and/or eChapter(s).
Editorial review has deemed that any suppressed content does not materially affect the overall learning experience. Cengage Learning reserves the right to remove additional content at any time if subsequent rights restrictions require it.
Copyright 2012 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part. Due to electronic rights, some third party content may be suppressed from the eBook and/or eChapter(s).
Editorial review has deemed that any suppressed content does not materially affect the overall learning experience. Cengage Learning reserves the right to remove additional content at any time if subsequent rights restrictions require it.
Copyright 2012 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part. Due to electronic rights, some third party content may be suppressed from the eBook and/or eChapter(s).
Editorial review has deemed that any suppressed content does not materially affect the overall learning experience. Cengage Learning reserves the right to remove additional content at any time if subsequent rights restrictions require it.
Copyright 2012 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part. Due to electronic rights, some third party content may be suppressed from the eBook and/or eChapter(s).
Editorial review has deemed that any suppressed content does not materially affect the overall learning experience. Cengage Learning reserves the right to remove additional content at any time if subsequent rights restrictions require it.
Copyright 2012 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part. Due to electronic rights, some third party content may be suppressed from the eBook and/or eChapter(s).
Editorial review has deemed that any suppressed content does not materially affect the overall learning experience. Cengage Learning reserves the right to remove additional content at any time if subsequent rights restrictions require it.
CHAPTER 1 An Overview of Computers and Programming
In this chapter, you will learn about:
Computer systems
Simple program logic
The steps involved in the program development cycle
Pseudocode statements and flowchart symbols
Using a sentinel value to end a program
Programming and user environments
The evolution of programming models
Copyright 2012 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part. Due to electronic rights, some third party content may be suppressed from the eBook and/or eChapter(s).
Editorial review has deemed that any suppressed content does not materially affect the overall learning experience. Cengage Learning reserves the right to remove additional content at any time if subsequent rights restrictions require it.
Understanding Computer Systems 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.
l 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 large mainframe computers, laptops, and even smaller computers that are embedded into products such as cars and thermostats, but the types of operations performed by different-sized computers are very similar. When you think of a computer, you often think of its physical components first, but for a computer to be useful, it needs more than devices; a computer needs to be given instructions. Just as your stereo equipment does not do much until you provide music, computer hardware needs instructions that control how and when data items are input, how they are processed, and the form in which they are output or stored.
l Software is computer instructions that tell 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 word-processing 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:
l Application software comprises all the programs you apply to a task, such as word- processing programs, spreadsheets, payroll and inventory programs, and even games.
l System software comprises the programs that you use to manage your computer, including operating systems such as Windows, Linux, or UNIX.
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:
l Input—Data items enter the computer system and are placed in memory, where they can be processed. Hardware devices that perform input operations include keyboards and mice. Data items include all the text, numbers, and other raw material that are entered into and processed by a computer. In business, many of the data items used are facts and figures about such entities as products, customers, and personnel. However, data can also include items such as images, sounds, and a user’s mouse movements.
l 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.
2
C H A P T E R 1 An Overview of Computers and Programming
Copyright 2012 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part. Due to electronic rights, some third party content may be suppressed from the eBook and/or eChapter(s).
Editorial review has deemed that any suppressed content does not materially affect the overall learning experience. Cengage Learning reserves the right to remove additional content at any time if subsequent rights restrictions require it.
l 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 that has been processed and output. Sometimes you place output on storage devices, such as disks or flash media. 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.
When you write a program, you usually type its instructions using a keyboard. When you type program instructions, they are stored in computer memory, which is a computer’s temporary, internal storage. Random access memory, or RAM, is a form of internal, volatile memory. Programs that are currently running and data items that are currently being used are stored in RAM for quick access. Internal storage is volatile—its contents are lost when the computer is turned off or loses power. Usually, you want to be able to retrieve and perhaps modify the stored instructions later, so you also store them on a permanent storage device, such as a disk. Permanent storage devices are nonvolatile—that is, their contents are persistent and are retained even when power is lost. If you have had a power loss while working on a computer, but were able to recover your work when power was restored, it’s not because the work was still in RAM. Your system has been configured to automatically save your work at regular intervals on a nonvolatile storage device.
After a computer program is typed using programming language statements and stored in memory, it must be translated to machine language that represents the millions of on/off circuits within the computer. Your programming language statements are called source code, and the translated machine language statements are object code.
Each programming language uses a piece of software, called a compiler or an interpreter, to translate your source code into machine language. Machine language is also called binary language, and is represented as a series of 0s and 1s. The compiler or interpreter that translates your code tells you if any programming language component has been used incorrectly. Syntax errors are relatively easy to locate and correct because your compiler or interpreter highlights them. If you write a computer program using a language such as C++
3
Understanding Computer Systems
Copyright 2012 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part. Due to electronic rights, some third party content may be suppressed from the eBook and/or eChapter(s).
Editorial review has deemed that any suppressed content does not materially affect the overall learning experience. Cengage Learning reserves the right to remove additional content at any time if subsequent rights restrictions require it.
but spell one of its words incorrectly or reverse the proper order of two words, the software lets you know that it found a mistake by displaying an error message as soon as you try to translate the program.
Although there are differences in how compilers and interpreters work, their basic function is the same—to translate your programming statements into code the computer can use. When you use a compiler, an entire program is translated before it can execute; when you use an interpreter, each instruction is translated just prior to execution. Usually, you do not choose which type of translation to use—it depends on the programming language. However, there are some languages for which both compilers and interpreters are available.
After a program’s source code is successfully translated to machine language, the computer can carry out the program instructions. When instructions are carried out, a program runs, or executes. In a typical program, some input will be accepted, some processing will occur, and results will be output.
Besides the popular, comprehensive programming languages such as Java and C++, many programmers use scripting languages (also called scripting programming languages or script languages) such as Python, Lua, Perl, and PHP. Scripts written in these languages usually can be typed directly from a keyboard and are stored as text rather than as binary executable files. Scripting language programs are interpreted line by line each time the program executes, instead of being stored in a compiled (binary) form. Still, with all programming languages, each instruction must be translated to machine language before it can execute.
TWO TRUTHS & A LIE Understanding Computer Systems
In each Two Truths and a Lie section, two of the numbered statements are true, and one is false. Identify the false statement and explain why it is false.
1. Hardware is the equipment, or the devices, associated with a computer. Software is computer instructions.
2. The grammar rules of a computer programming language are its syntax.
3. You write programs using machine language, and translation software converts the statements to a programming language.
. s1 dna s0 si hci h w, egaugnal eni hca mot st ne met at s eht str evnoc )r et er pr et ni r or eli p moc a dell ac( mar gor p noi t al snart a dna, avaJ r o ci saBl ausi V sa hcus egaugnal gni mmar gor p a gni su s mar gor p eti r wuoY. 3# si t ne met at s esl af ehT
4
C H A P T E R 1 An Overview of Computers and Programming
Copyright 2012 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part. Due to electronic rights, some third party content may be suppressed from the eBook and/or eChapter(s).
Editorial review has deemed that any suppressed content does not materially affect the overall learning experience. Cengage Learning reserves the right to remove additional content at any time if subsequent rights restrictions require it.
Understanding Simple Program Logic A program with syntax errors cannot be fully translated and cannot execute. A program with no syntax errors is translatable and can execute, but it still might contain logical errors and produce incorrect output as a result. For a program to work properly, you must develop correct logic; that is, you must write program instructions in a specific sequence, you must not leave any instructions out, and you must not add extraneous instructions.
Suppose you instruct someone to make a cake as follows:
Get a bowl Stir Add two eggs Add a gallon of gasoline Bake at 350 degrees for 45 minutes Add three cups of flour
The dangerous cake-baking instructions are shown with a Don’t Do It icon. You will see this icon when the book contains an unrecommended programming practice that is used as an example of what not to do.
Even though the cake-baking instructions use English language syntax correctly, the instructions are out of sequence, some are missing, and some instructions belong to procedures other than baking a cake. If you follow these instructions, you will not make an edible cake, and you may end up with a disaster. Many logical errors are more difficult to locate than syntax errors—it is easier for you to determine whether eggs is spelled incorrectly in a recipe than it is for you to tell if there are too many eggs or if they are added too soon.
Just as baking directions can be provided in Mandarin, Urdu, or Spanish, program logic can be expressed correctly in any number of programming languages. Because this book is not concerned with a specific language, the programming examples could have been written in Visual Basic, C++, or Java. For convenience, this book uses instructions written in English!
After you learn French, you automatically know, or can easily figure out, many Spanish words. Similarly, after you learn one programming language, it is much easier to understand several other languages.
Most simple computer programs include steps that perform input, processing, and output. Suppose you want to write a computer program to double any number you provide. You can write the program in a programming language such as Visual Basic or Java, but if you were to write it using English-like statements, it would look like this:
input myNumber set myAnswer = myNumber * 2 output myAnswer
Don’t Do It Don't bake a cake like this!
5
Understanding Simple Program Logic
Copyright 2012 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part. Due to electronic rights, some third party content may be suppressed from the eBook and/or eChapter(s).
Editorial review has deemed that any suppressed content does not materially affect the overall learning experience. Cengage Learning reserves the right to remove additional content at any time if subsequent rights restrictions require it.
The number-doubling process includes three instructions:
l The instruction to input myNumber is an example of an input operation. When the computer interprets this instruction, it knows to look to an input device to obtain a number. When you work in a specific programming language, you write instructions that tell the computer which device to access for input. For example, when a user enters a number as data for a program, the user might click on the number with a mouse, type it from a keyboard, or speak it into a microphone. Logically, however, it doesn’t matter which hardware device is used, as long as the computer knows to accept a number. When the number is retrieved from an input device, it is placed in the computer’s memory in a variable named myNumber. A variable is a named memory location whose value can vary— for example, the value of myNumber might be 3 when the program is used for the first time and 45 when it is used the next time. In this book, variable names will not contain embedded spaces; for example, the book will use myNumber instead of my Number.
From a logical perspective, when you input, process, or output a value, the hardware device is irrelevant. The same is true in your daily life. If you follow the instruction “Get eggs for the cake,” it does not really matter if you purchase them from a store or harvest them from your own chickens—you get the eggs either way. There might be different practical considerations to getting the eggs, just as there are for getting data from a large database as opposed to getting data from an inexperienced user working at home on a laptop computer. For now, this book is only concerned with the logic of operations, not the minor details.
l The instruction set 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.
l 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 to appear on the monitor (which might be a flat-panel plasma screen or a cathode-ray tube), 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 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.
6
C H A P T E R 1 An Overview of Computers and Programming
Copyright 2012 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part. Due to electronic rights, some third party content may be suppressed from the eBook and/or eChapter(s).
Editorial review has deemed that any suppressed content does not materially affect the overall learning experience. Cengage Learning reserves the right to remove additional content at any time if subsequent rights restrictions require it.
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 hexadecimal number. Appendix A contains information on this numbering system.
TWO TRUTHS & A LIE Understanding Simple Program Logic
1. A program with syntax errors can execute but might produce incorrect results.
2. Although the syntax of programming languages differs, the same program logic can be expressed in different languages.
3. Most simple computer programs include steps that perform input, processing, and output.
. stl user t cerr ocni ecudor pt hgi mt ub, et ucexe nac sr orr e xat nys on hti w mar gor p a; et ucexet onnac sr orr e xat nys hti w mar gor p A. 1# si t ne met at s esl af ehT
Understanding the Program Development Cycle A programmer’s job involves writing instructions (such as those in the doubling program in the preceding section), but a professional programmer usually does not just sit down at a computer keyboard and start typing. Figure 1-1 illustrates the program development cycle, which can be broken down into at least seven steps:
1. Understand the problem.
2. Plan the logic.
3. Code the program.
4. Use software (a compiler or interpreter) to translate the program into machine language.
5. Test the program.
6. Put the program into production.
7. Maintain the program.
7
Understanding the Program Development Cycle
Copyright 2012 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part. Due to electronic rights, some third party content may be suppressed from the eBook and/or eChapter(s).
Editorial review has deemed that any suppressed content does not materially affect the overall learning experience. Cengage Learning reserves the right to remove additional content at any time if subsequent rights restrictions require it.
Understanding the Problem Professional computer programmers write programs to satisfy the needs of others, called users or end users. Examples of end users include a Human Resources department that needs a printed list of all employees, a Billing department that wants a list of clients who are 30 or more days overdue on their payments, and an Order department that needs a Web site to provide buyers with an online shopping cart. Because programmers are providing a service to these users, programmers must first understand what the users want. When a program runs, you usually think of the logic as a cycle of input-processing-output operations, but when you plan a program, you think of the output first. After you understand what the desired result is, you can plan the input and processing steps to achieve it.
Suppose the director of Human Resources says to a programmer, “Our department needs a list of all employees who have been here over five years, because we want to invite them to a special thank-you dinner.” On the surface, this seems like a simple request. An experienced programmer, however, will know that the request is incomplete. For example, you might not know the answers to the following questions about which employees to include:
l Does the director want a list of full-time employees only, or a list of full- and part-time employees together?
l Does she want to include people who have worked for the company on a month-to- month contractual basis over the past five years, or only regular, permanent employees?
l Do the listed employees need to have worked for the organization for five years as of today, as of the date of the dinner, or as of some other cutoff date?
l What about an employee who worked three years, took a two-year leave of absence, and has been back for three years?
Understand the problem
Test the program
Put the program into production
Maintain the program
Plan the logic
Translate the code
Write the code
Figure 1-1 The program development cycle
8
C H A P T E R 1 An Overview of Computers and Programming
Copyright 2012 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part. Due to electronic rights, some third party content may be suppressed from the eBook and/or eChapter(s).
Editorial review has deemed that any suppressed content does not materially affect the overall learning experience. Cengage Learning reserves the right to remove additional content at any time if subsequent rights restrictions require it.
The programmer cannot make any of these decisions; the user (in this case, the Human Resources director) must address these questions.
More decisions still might be required. For example:
l What data should be included for each listed employee? Should the list contain both first and last names? Social Security numbers? Phone numbers? Addresses?
l Should the list be in alphabetical order? Employee ID number order? Length-of-service order? Some other order?
l Should the employees be grouped by any criteria, such as department number or years of service?
Several pieces of documentation are often provided to help the programmer understand the problem. Documentation consists of all the supporting paperwork for a program; it might include items such as original requests for the program from users, sample output, and descriptions of the data items available for input.
Fully understanding the problem may be one of the most difficult aspects of programming. On any job, the description of what the user needs may be vague—worse yet, users may not really know what they want, and users who think they know frequently change their minds after seeing sample output. A good programmer is often part counselor, part detective!
Watch the video The Program Development Cycle, Part 1.
Planning the Logic The heart of the programming process lies in planning the program’s logic. During this phase of the process, the programmer plans the steps of the program, deciding what steps to include and how to order them. You can plan the solution to a problem in many ways. The two most common planning tools are flowcharts and pseudocode. Both tools involve writing the steps of the program in English, much as you would plan a trip on paper before getting into the car or plan a party theme before shopping for food and favors.
You may hear programmers refer to planning a program as “developing an algorithm.” An algorithm is the sequence of steps necessary to solve any problem.
In addition to flowcharts and pseudocode, programmers use a variety of other tools to help in program development. One such tool is an IPO chart, which delineates input, processing, and output tasks. Some object-oriented programmers also use TOE charts, which list tasks, objects, and events.
The programmer shouldn’t worry about the syntax of any particular language during the planning stage, but should focus on figuring out what sequence of events will lead from the available input to the desired output. Planning the logic includes thinking carefully about all
9
Understanding the Program Development Cycle
Copyright 2012 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part. Due to electronic rights, some third party content may be suppressed from the eBook and/or eChapter(s).
Editorial review has deemed that any suppressed content does not materially affect the overall learning experience. Cengage Learning reserves the right to remove additional content at any time if subsequent rights restrictions require it.
the possible data values a program might encounter and how you want the program to handle each scenario. The process of walking through a program’s logic on paper before you actually write the program is called desk-checking. You will learn more about planning the logic throughout this book; in fact, the book focuses on this crucial step almost exclusively.
Coding the Program After the logic is developed, only then can the programmer write the source code for a program. Hundreds of programming languages are available. Programmers choose particular languages because some have built-in capabilities that make them more efficient than others at handling certain types of operations. Despite their differences, programming languages are quite alike in their basic capabilities—each can handle input operations, arithmetic processing, output operations, and other standard functions. The logic developed to solve a programming problem can be executed using any number of languages. Only after choosing a language must the programmer be concerned with proper punctuation and the correct spelling of commands—in other words, using the correct syntax.
Some experienced programmers can successfully combine logic planning and program coding in one step. This may work for planning and writing a very simple program, just as you can plan and write a postcard to a friend using one step. A good term paper or a Hollywood screenplay, however, needs planning before writing—and so do most programs.
Which step is harder: planning the logic or coding the program? Right now, it may seem to you that writing in a programming language is a very difficult task, considering all the spelling and syntax rules you must learn. However, the planning step is actually more difficult. Which is more difficult: thinking up the twists and turns to the plot of a best-selling mystery novel, or writing a translation of an existing novel from English to Spanish? And who do you think gets paid more, the writer who creates the plot or the translator? (Try asking friends to name any famous translator!)
Using Software to Translate the Program into Machine Language Even though there are many programming languages, each computer knows only one language—its machine language, which consists of 1s and 0s. Computers understand machine language because they are made up of thousands of tiny electrical switches, each of which can be set in either the on or off state, which is represented by a 1 or 0, respectively.
Languages like Java or Visual Basic are available for programmers because someone has written a translator program (a compiler or interpreter) that changes the programmer’s English-like high-level programming language into the low-level machine language that the computer understands. When you learn the syntax of a programming language, the commands work on any machine on which the language software has been installed. However, your commands then are translated to machine language, which differs in various computer makes and models.
10
C H A P T E R 1 An Overview of Computers and Programming
Copyright 2012 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part. Due to electronic rights, some third party content may be suppressed from the eBook and/or eChapter(s).
Editorial review has deemed that any suppressed content does not materially affect the overall learning experience. Cengage Learning reserves the right to remove additional content at any time if subsequent rights restrictions require it.
If you write a programming statement incorrectly (for example, by misspelling a word, using a word that doesn’t exist in the language, or using “illegal” grammar), the translator program doesn’t know how to proceed and issues an error message identifying a syntax error. Although making errors is never desirable, syntax errors are not a major concern to programmers, because the compiler or interpreter catches every syntax error and displays a message that notifies you of the problem. The computer will not execute a program that contains even one syntax error.
Typically, a programmer develops logic, writes the code, and compiles the program, receiving a list of syntax errors. The programmer then corrects the syntax errors and compiles the program again. Correcting the first set of errors frequently reveals new errors that originally were not apparent to the compiler. For example, if you could use an English compiler and submit the sentence The dg chase the cat, the compiler at first might point out only one syntax error. The second word, dg, is illegal because it is not part of the English language. Only after you corrected the word to dog would the compiler find another syntax error on the third word, chase, because it is the wrong verb form for the subject dog. This doesn’t mean chase is necessarily the wrong word. Maybe dog is wrong; perhaps the subject should be dogs, in which case chase is right. Compilers don’t always know exactly what you mean, nor do they know what the proper correction should be, but they do know when something is wrong with your syntax.
Watch the video The Program Development Cycle, Part 2.
When writing a program, a programmer might need to recompile the code several times. An executable program is created only when the code is free of syntax errors. After a program has been translated into machine language, the machine language program is saved and can be run any number of times without repeating the translation step. You only need to retranslate your code if you make changes to your source code statements. Figure 1-2 shows a diagram of this entire process.
11
Understanding the Program Development Cycle
Copyright 2012 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part. Due to electronic rights, some third party content may be suppressed from the eBook and/or eChapter(s).
Editorial review has deemed that any suppressed content does not materially affect the overall learning experience. Cengage Learning reserves the right to remove additional content at any time if subsequent rights restrictions require it.
Testing the Program A program that is free of syntax errors is not necessarily free of logical errors. A logical error results when you use a syntactically correct statement but use the wrong one for the current context. For example, the English sentence The dog chases the cat, although syntactically perfect, is not logically correct if the dog chases a ball or the cat is the aggressor.
Once a program is free of syntax errors, the programmer can test it—that is, execute it with some sample data to see whether the results are logically correct. Recall the number-doubling program:
input myNumber set myAnswer = myNumber * 2 output myAnswer
If you execute the program, provide the value 2 as input to the program, and the answer 4 is displayed, you have executed one successful test run of the program.
However, if the answer 40 is displayed, maybe the program contains a logical error. Maybe the second line of code was mistyped with an extra zero, so that the program reads:
input myNumber set myAnswer = myNumber * 20 output myAnswer
Placing 20 instead of 2 in the multiplication statement caused a logical error. Notice that nothing is syntactically wrong with this second program—it is just as reasonable to multiply a number by 20 as by 2—but if the programmer intends only to double myNumber, then a logical error has occurred.
Write and correct the program code
Compile the program
Executable program
Data that the program uses
List of syntax error
messages
Program output
If there are no syntax errors
If there are syntax errors
Figure 1-2 Creating an executable program
Don’t Do It The programmer typed 20 instead of 2.
12
C H A P T E R 1 An Overview of Computers and Programming
Copyright 2012 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part. Due to electronic rights, some third party content may be suppressed from the eBook and/or eChapter(s).
Editorial review has deemed that any suppressed content does not materially affect the overall learning experience. Cengage Learning reserves the right to remove additional content at any time if subsequent rights restrictions require it.
The process of finding and correcting program errors is called debugging. You debug a program by testing it using many sets of data. For example, if you write the program to double a number, then enter 2 and get an output value of 4, that doesn’t necessarily mean you have a correct program. Perhaps you have typed this program by mistake:
input myNumber set myAnswer = myNumber + 2 output myAnswer
An input of 2 results in an answer of 4, but that doesn’t mean your program doubles numbers—it actually only adds 2 to them. If you test your program with additional data and get the wrong answer—for example, if you enter 7 and get an answer of 9—you know there is a problem with your code.
Selecting test data is somewhat of an art in itself, and it should be done carefully. If the Human Resources department wants a list of the names of five-year employees, it would be a mistake to test the program with a small sample file of only long-term employees. If no newer employees are part of the data being used for testing, you do not really know if the program would have eliminated them from the five-year list. Many companies do not know that their software has a problem until an unusual circumstance occurs—for example, the first time an employee has more than nine dependents, the first time a customer orders more than 999 items at a time, or when the Internet runs out of allocated IP addresses, a problem known as IPV4 exhaustion.
Putting the Program into Production Once the program is thoroughly tested and debugged, it is ready for the organization to use. Putting the program into production might mean simply running the program once, if it was written to satisfy a user’s request for a special list. However, the process might take months if the program will be run on a regular basis, or if it is one of a large system of programs being developed. Perhaps data-entry people must be trained to prepare the input for the new program, users must be trained to understand the output, or existing data in the company must be changed to an entirely new format to accommodate this program. Conversion, the entire set of actions an organization must take to switch over to using a new program or set of programs, can sometimes take months or years to accomplish.
Maintaining the Program After programs are put into production, making necessary changes is called maintenance. Maintenance can be required for many reasons: for example, because new tax rates are legislated, the format of an input file is altered, or the end user requires additional information not included in the original output specifications. Frequently, your first programming job will require maintaining previously written programs. When you maintain the programs others have written, you will appreciate the effort the original programmer put into writing clear
Don’t Do It The programmer typed "+" instead of "*".
13
Understanding the Program Development Cycle
Copyright 2012 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part. Due to electronic rights, some third party content may be suppressed from the eBook and/or eChapter(s).
Editorial review has deemed that any suppressed content does not materially affect the overall learning experience. Cengage Learning reserves the right to remove additional content at any time if subsequent rights restrictions require it.
code, using reasonable variable names, and documenting his or her work. When you make changes to existing programs, you repeat the development cycle. That is, you must understand the changes, then plan, code, translate, and test them before putting them into production. If a substantial number of program changes are required, the original program might be retired, and the program development cycle might be started for a new program.
Watch the video The Program Development Cycle, Part 3.
TWO TRUTHS & A LIE Understanding the Program Development Cycle
1. Understanding the problem that must be solved can be one of the most difficult aspects of programming.
2. The two most commonly used logic-planning tools are flowcharts and pseudocode.
3. Flowcharting a program is a very different process if you use an older programming language instead of a newer one.
. segaugnal f or eb mun yna gni su det ucexe eb nac mel bor p gni mmar gor p a evl os ot depol eved ci gol ehT. snoi t cnuf dr adnat s r eht o dna, snoi t ar epot upt uo, gni ssecor p ci t e mhti r a, snoi t ar epot upni el dnah nac hcae —sei tili bapac ci sabri eht ni ekil a eti uq er a segaugnal gni mmar gor p, secner effi d ri eht eti pseD. 3# si t ne met at s esl af ehT
Using Pseudocode Statements and Flowchart Symbols When programmers plan the logic for a solution to a programming problem, they often use one of two tools: pseudocode (pronounced sue-doe-code) or flowcharts.
l Pseudocode is an English-like representation of the logical steps it takes to solve a problem. Pseudo is a prefix that means false, and to code a program means to put it in a programming language; therefore, pseudocode simply means false code, or sentences that appear to have been written in a computer programming language but do not necessarily follow all the syntax rules of any specific language.
l A flowchart is a pictorial representation of the same thing.
14
C H A P T E R 1 An Overview of Computers and Programming
Copyright 2012 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part. Due to electronic rights, some third party content may be suppressed from the eBook and/or eChapter(s).
Editorial review has deemed that any suppressed content does not materially affect the overall learning experience. Cengage Learning reserves the right to remove additional content at any time if subsequent rights restrictions require it.
Writing Pseudocode You have already seen examples of statements that represent pseudocode earlier in this chapter, and there is nothing mysterious about them. The following five statements constitute a pseudocode representation of a number-doubling problem:
start input myNumber set myAnswer = myNumber * 2 output myAnswer
stop
Using pseudocode involves writing down all the steps you will use in a program. Usually, programmers preface their pseudocode with a beginning statement like start and end it with a terminating statement like stop. The statements between start and stop look like English and are indented slightly so that start and stop stand out. Most programmers do not bother with punctuation such as periods at the end of pseudocode statements, although it would not be wrong to use them if you prefer that style. Similarly, there is no need to capitalize the first word in a sentence, although you might choose to do so. This book follows the conventions of using lowercase letters for verbs that begin pseudocode statements and omitting periods at the end of statements.
Pseudocode is fairly flexible because it is a planning tool, and not the final product. Therefore, for example, you might prefer any of the following:
l Instead of start and stop, some pseudocode developers would use other terms such as begin and end.
l Instead of writing input myNumber, some developers would write get myNumber or read myNumber.
l Instead of writing set myAnswer = myNumber * 2, some developers would write calculate myAnswer = myNumber times 2 or compute myAnswer as myNumber doubled.
l Instead of writing output myAnswer, many pseudocode developers would write display myAnswer, print myAnswer, or write myAnswer.
The point is, the pseudocode statements are instructions to retrieve an original number from an input device and store it in memory where it can be used in a calculation, and then to get the calculated answer from memory and send it to an output device so a person can see it. When you eventually convert your pseudocode to a specific programming language, you do not have such flexibility because specific syntax will be required. For example, if you use the C# programming language and write the statement to output the answer to the monitor, you will code the following:
Console.Write(myAnswer);
The exact use of words, capitalization, and punctuation are important in the C# statement, but not in the pseudocode statement.
15
Using Pseudocode Statements and Flowchart Symbols
Copyright 2012 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part. Due to electronic rights, some third party content may be suppressed from the eBook and/or eChapter(s).
Editorial review has deemed that any suppressed content does not materially affect the overall learning experience. Cengage Learning reserves the right to remove additional content at any time if subsequent rights restrictions require it.
Drawing Flowcharts Some professional programmers prefer writing pseudocode to drawing flowcharts, because using pseudocode is more similar to writing the final statements in the programming language. Others prefer drawing flowcharts to represent the logical flow, because flowcharts allow programmers to visualize more easily how the program statements will connect. Especially for beginning programmers, flowcharts are an excellent tool to help them visualize how the statements in a program are interrelated.
You can draw a flowchart by hand or use software, such as Microsoft Word and Microsoft PowerPoint, that contains flowcharting tools. You can use several other software programs, such as Visio and Visual Logic, specifically to create flowcharts. When you create a flowchart, you draw geometric shapes that contain the individual statements and that are connected with arrows. (Appendix B contains a summary of all the flowchart symbols you will see in this book.) You use a parallelogram to represent an input symbol, which indicates an input operation. You write an input statement in English inside the parallelogram, as shown in Figure 1-3.
Arithmetic operation statements are examples of processing. In a flowchart, you use a rectangle as the processing symbol that contains a processing statement, as shown in Figure 1-4.
To represent an output statement, you use the same symbol as for input statements—the output symbol is a parallelogram, as shown in Figure 1-5. Because the parallelogram is used for both input and output, it is often called the input/output symbol or I/O symbol.
Some software programs that use flowcharts (such as Visual Logic) use a left-slanting parallelogram to represent output. As long as the flowchart creator and the flowchart reader are communicating, the actual shape used is irrelevant. This book will follow the most standard convention of using the right-slanting parallelogram for both input and output.
To show the correct sequence of these statements, you use arrows, or flowlines, to connect the steps. Whenever possible, most of a flowchart should read from top to bottom or from left to right on a page. That’s the way we read English, so when flowcharts follow this convention, they are easier for us to understand.
To be complete, a flowchart should include two more elements: terminal symbols, or start/ stop symbols, at each end. Often, you place a word like start or begin in the first terminal symbol and a word like end or stop in the other. The standard terminal symbol is shaped like a racetrack; many programmers refer to this shape as a lozenge, because it resembles the shape of the medication you might use to soothe a sore throat. Figure 1-6 shows a complete flowchart for the program that doubles a number, and the pseudocode for the same problem.
input myNumber
Figure 1-3 Input symbol
set myAnswer = myNumber * 2
Figure 1-4 Processing symbol
output myAnswer
Figure 1-5 Output symbol
16
C H A P T E R 1 An Overview of Computers and Programming
Copyright 2012 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part. Due to electronic rights, some third party content may be suppressed from the eBook and/or eChapter(s).
Editorial review has deemed that any suppressed content does not materially affect the overall learning experience. Cengage Learning reserves the right to remove additional content at any time if subsequent rights restrictions require it.
You can see from the figure that the flowchart and pseudocode statements are the same— only the presentation format differs.
Programmers seldom create both pseudocode and a flowchart for the same problem. You usually use one or the other. In a large program, you might even prefer to write pseudocode for some parts and to draw a flowchart for others.
When you tell a friend how to get to your house, you might write a series of instructions or you might draw a map. Pseudocode is similar to written, step-by-step instructions; a flowchart, like a map, is a visual representation of the same thing.
Repeating Instructions After the flowchart or pseudocode has been developed, the programmer only needs to: (1) buy a computer, (2) buy a language compiler, (3) learn a programming language, (4) code the program, (5) attempt to compile it, (6) fix the syntax errors, (7) compile it again, (8) test it with several sets of data, and (9) put it into production.
“Whoa!” you are probably saying to yourself. “This is simply not worth it! All that work to create a flowchart or pseudocode, and then all those other steps? For five dollars, I can buy a pocket calculator that will double any number for me instantly!” You are absolutely right. If this were a real computer program, and all it did was double the value of a number, it would not be worth the effort. Writing a computer program would be worthwhile only if you had many numbers (let’s say 10,000) to double in a limited amount of time—let’s say the next two minutes.
start
Flowchart Pseudocode
stop
input myNumber
output myAnswer
set myAnswer = myNumber * 2
start input myNumber set myAnswer = myNumber * 2 output myAnswer stop
Figure 1-6 Flowchart and pseudocode of program that doubles a number
17
Using Pseudocode Statements and Flowchart Symbols
Copyright 2012 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part. Due to electronic rights, some third party content may be suppressed from the eBook and/or eChapter(s).
Editorial review has deemed that any suppressed content does not materially affect the overall learning experience. Cengage Learning reserves the right to remove additional content at any time if subsequent rights restrictions require it.
Unfortunately, the program represented in Figure 1-6 does not double 10,000 numbers; it doubles only one. You could execute the program 10,000 times, of course, but that would require you to sit at the computer and run the program over and over again. You would be better off with a program that could process 10,000 numbers, one after the other.
One solution is to write the program shown in Figure 1-7 and execute the same steps 10,000 times. Of course, writing this program would be very time consuming; you might as well buy the calculator.
A better solution is to have the computer execute the same set of three instructions over and over again, as shown in Figure 1-8. The repetition of a series of steps is called a loop. With this approach, the computer gets a number, doubles it, displays the answer, and then starts again with the first instruction. The same spot in memory, called myNumber, is reused for the second number and for any subsequent numbers. The spot in memory named myAnswer is reused each time to store the result of the multiplication operation. However, the logic illustrated in the flowchart in Figure 1-8 contains a major problem—the sequence of instructions never ends. This programming situation is known as an infinite loop—a repeating flow of logic with no end. You will learn one way to handle this problem later in this chapter; you will learn a superior way in Chapter 3.
start input myNumber set myAnswer = myNumber * 2 output myAnswer input myNumber set myAnswer = myNumber * 2 output myAnswer input myNumber set myAnswer = myNumber * 2 output myAnswer …and so on for 9,997 more times
Don’t Do It You would never want to write such a repetitious list of instructions.
Figure 1-7 Inefficient pseudocode for program that doubles 10,000 numbers
18
C H A P T E R 1 An Overview of Computers and Programming
Copyright 2012 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part. Due to electronic rights, some third party content may be suppressed from the eBook and/or eChapter(s).
Editorial review has deemed that any suppressed content does not materially affect the overall learning experience. Cengage Learning reserves the right to remove additional content at any time if subsequent rights restrictions require it.
TWO TRUTHS & A LIE Using Pseudocode Statements and Flowchart Symbols
1. When you draw a flowchart, you use a parallelogram to represent an input operation.
2. When you draw a flowchart, you use a parallelogram to represent a processing operation.
3. When you draw a flowchart, you use a parallelogram to represent an output operation.
. noi t ar epo gni ssecor p at neser per ot el gnat cer a esu uoy ,tr ahcwolf a war d uoy neh W. 2# si t ne met at s esl af ehT
Using a Sentinel Value to End a Program The logic in the flowchart for doubling numbers, shown in Figure 1-8, has a major flaw—the program contains an infinite loop. If, for example, the input numbers are being entered at the keyboard, the program will keep accepting numbers and outputting their doubled values forever. Of course, the user could refuse to type any more numbers. But the program cannot progress any further while it is waiting for input; meanwhile, the program is occupying computer memory and tying up operating system resources. Refusing to enter any more numbers is not a practical solution. Another way to end the program is simply to turn off the