Homework

profileKoqe.2020
re.pdf

Buy. Rent. Access.

Access student data fles and other study tools on cengagebrain.com.

For detailed instructions visit http://solutions.cengage.com/ctdownloads/

Store your Data Files on a USB drive for maximum eff ciency in organizing and working with the fles.

Macintosh users should use a program to expand WinZip or PKZip archives. Ask your instructor or lab coordinator for assistance.

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

E I G H T H E D I T I O N

PROGRAMMING LOGIC

AND DESIGN

COMPREHENSIVE VERSION

J O Y C E F A R R E L L

Australia Brazil Japan Korea Mexico Singapore Spain United Kingdom United States

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

Copyright 2015 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, Eighth Edition Joyce Farrell

Senior Product Manager: Jim Gish

Senior Content Developer: Alyssa Pratt

Development Editor: Dan Seiter

Content Project Manager: Jennifer Feltri-George

Product Assistant: Gillian Daniels

Senior Market Development Manager: Eric La Scola

Marketing Manager: Gretchen Swann

Art Director: Cheryl Pearl, GEX Publishing Services

Text Designer: GEX Publishing Services

Cover Designer: GEX Publishing Services

Image Credit: © Kasia/Shutterstock.com

Manufacturing Planner: Julio Esperas

Copyeditor: Michael Beckett

Proofreader: Lisa Weidenfeld

Indexer: Alexandra Nickerson

Compositor: Integra

© 2015 Cengage Learning.

WCN: 02-200-203

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 e-mailed to [email protected].

Library of Congress Control Number: 2013956197

ISBN-13: 978-1-285-77671-2

Cengage Learning 200 First Stamford Place, 4th Floor Stamford, CT 06902 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.

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.

Microsoft product screenshots used with permission from Microsoft Corporation.

Unless otherwise credited, all art and tables © 2015 Cengage Learning, produced by Integra.

Cengage Learning reserves the right to revise this publication and make changes from time to time in its content without notice.

Printed in the U nited States of America

1 2 3 4 5 6 7 17 16 15 14 13

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

iii

Brief Contents

Preface . . . . . . . . . . . . . . . . . . . ix

C HAP T E R 1 An Overview of Computers and Programming . . 1 C HAP T E R 2 Elements of High-Quality Programs . . . . . . 38 C HAP T E R 3 Understanding Structure . . . . . . . . . . . 87 C HAP T E R 4 Making Decisions . . . . . . . . . . . . . 125 C HAP T E R 5 Looping . . . . . . . . . . . . . . . . . 177 C HAP T E R 6 Arrays . . . . . . . . . . . . . . . . . . 226 C HAP T E R 7 File Handling and Applications . . . . . . . 274 C HAP T E R 8 Advanced Data Handling Concepts . . . . . 321 C HAP T E R 9 Advanced Modulariza tion Techniques . . . . 371 C HAP T E R 1 0 Object-Oriented Prog ramming . . . . . . . 427 C HAP T E R 1 1 More Object-Oriented Programming

Concepts . . . . . . . . . . . . . . . . . 471 C HAP T E R 1 2 Event-Driven GUI Progra mming,

Multithreading, and Animation . . . . . . . 514 C HAP T E R 1 3 System Modeling with the UML . . . . . . . 547 C HAP T E R 1 4 Using Relational Databases . . . . . . . . 579 A PP E N D I X A Understa nding Numbering Systems

and Computer Codes . . . . . . . . . . . . 625

A PP E N D I X B Solving Difficult Structuring Problems . . . . 633

A PP E N D I X C Creating Print Charts . . . . . . . . . . . 642

A PP E N D I X D Two Variations on the Basic Structures— case and do-while . . . . . . . . .644

Glossary . . . . . . . . . . . . . . . . . 651

Index . . . . . . . . . . . . . . . . . . . 667

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

iv

Contents

Preface . . . . . . . . . . . . . . . . . . . ix

C HAP T E R 1 An Overview of Computers and Programming . . 1

Understanding Computer Systems . . . . . . . . . . . . . . . . 2 Understanding Simple Program Logic . . . . . . . . . . . . . . 5 Understanding the Program Development Cycle . . . . . . . . . . 7 Using Pseudocode Statements and Flowchart Symbols . . . . . . 14 Using a Sentinel Value to End a Program . . . . . . . . . . . . 20 Understanding Programming and User Environments . . . . . . . 23 Understanding the Evolution of Programming Models . . . . . . . 26 Chapter Summary . . . . . . . . . . . . . . . . . . . . . . 28 Key Terms . . . . . . . . . . . . . . . . . . . . . . . . . 28 Exercises . . . . . . . . . . . . . . . . . . . . . . . . . 31

C HAP T E R 2 Elements of High-Quality Programs . . . . . . 38

Declaring and Using Variables and Constants . . . . . . . . . . 39 Performing Arithmetic Operations . . . . . . . . . . . . . . . 47 Understanding the Advantages of Modularization . . . . . . . . . 51 Modularizing a Program . . . . . . . . . . . . . . . . . . . 54 Creating Hierarchy Charts . . . . . . . . . . . . . . . . . . 64 Features of Good Program Design . . . . . . . . . . . . . . . 66 Chapter Summary . . . . . . . . . . . . . . . . . . . . . . 75 Key Terms . . . . . . . . . . . . . . . . . . . . . . . . . 76 Exercises . . . . . . . . . . . . . . . . . . . . . . . . . 79

C HAP T E R 3 Understanding Structure . . . . . . . . . . . 87

The Disadvantages of Unstructured Spaghetti Code . . . . . . . 88 Understanding the Three Basic Structures . . . . . . . . . . . 90 Using a Priming Input to Structure a Program . . . . . . . . . . 99 Understanding the Reasons for Structure . . . . . . . . . . . .106 Recognizing Structure . . . . . . . . . . . . . . . . . . . .107 Structuring and Modularizing Unstructured Logic . . . . . . . . .110 Chapter Summary . . . . . . . . . . . . . . . . . . . . . .116 Key Terms . . . . . . . . . . . . . . . . . . . . . . . . .116 Exercises . . . . . . . . . . . . . . . . . . . . . . . . .117

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

v

C HAP T E R 4

C HAP T E R 5

C HAP T E R 6

Making Decisions . . . . . . . . . . . . . 125

Boolean Expressions and the Selection Structure . . . . . . . .126 Using Relational Comparison Operators . . . . . . . . . . . .131 Understanding AND Logic . . . . . . . . . . . . . . . . . .135 Understanding OR Logic . . . . . . . . . . . . . . . . . . .145 Understanding NOT Logic . . . . . . . . . . . . . . . . . .156 Making Selections within Ranges . . . . . . . . . . . . . . .157 Understanding Precedence When Combining AND and OR

Operators . . . . . . . . . . . . . . . . . . . . . . . .163 Chapter Summary . . . . . . . . . . . . . . . . . . . . . .166 Key Terms . . . . . . . . . . . . . . . . . . . . . . . . .167 Exercises . . . . . . . . . . . . . . . . . . . . . . . . .168

Looping . . . . . . . . . . . . . . . . . 177

Understanding the Advantages of Looping . . . . . . . . . . .178 Using a Loop Control Variable . . . . . . . . . . . . . . . . .180 Nested Loops . . . . . . . . . . . . . . . . . . . . . . .186 Avoiding Common Loop Mistakes . . . . . . . . . . . . . . .192 Using a for Loop . . . . . . . . . . . . . . . . . . . . . .201 Common Loop Applications . . . . . . . . . . . . . . . . . .203 Comparing Selections and Loops . . . . . . . . . . . . . . .213 Chapter Summary . . . . . . . . . . . . . . . . . . . . . .217 Key Terms . . . . . . . . . . . . . . . . . . . . . . . . .217 Exercises . . . . . . . . . . . . . . . . . . . . . . . . .218

Arrays . . . . . . . . . . . . . . . . . . 226

Storing Data in Arrays . . . . . . . . . . . . . . . . . . . .227 How an Array Can Replace Nested Decisions . . . . . . . . . .230 Using Constants with Arrays . . . . . . . . . . . . . . . . .239 Searching an Array for an Exact Match . . . . . . . . . . . . .241 Using Parallel Arrays . . . . . . . . . . . . . . . . . . . . .246 Searching an Array for a Range Match . . . . . . . . . . . . .253 Remaining within Array Bounds . . . . . . . . . . . . . . . .257 Using a for Loop to Process an Array . . . . . . . . . . . . .261 Chapter Summary . . . . . . . . . . . . . . . . . . . . . .262 Key Terms . . . . . . . . . . . . . . . . . . . . . . . . .263 Exercises . . . . . . . . . . . . . . . . . . . . . . . . .263

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

C O N T E N T S

C HAP T E R 7

vi

C HAP T E R 8

C HAP T E R 9

File Handling and Applications . . . . . . . 274

Understanding Computer Files . . . . . . . . . . . . . . . .275 Understanding the Data Hierarchy . . . . . . . . . . . . . . .277 Performing File Operations . . . . . . . . . . . . . . . . . .279 Understanding Control Break Logic . . . . . . . . . . . . . .286 Merging Sequential Files . . . . . . . . . . . . . . . . . . .292 Master and Transaction File Processing . . . . . . . . . . . .301 Random Access Files . . . . . . . . . . . . . . . . . . . .310 Chapter Summary . . . . . . . . . . . . . . . . . . . . . .311 Key Terms . . . . . . . . . . . . . . . . . . . . . . . . .312 Exercises . . . . . . . . . . . . . . . . . . . . . . . . .314

Advanced Data Handling Concepts . . . . . 321

Understanding the Need for Sorting Data . . . . . . . . . . . .322 Using the Bubble Sort Algorithm . . . . . . . . . . . . . . . .323 Sorting Multifield Records . . . . . . . . . . . . . . . . . .342 Using the Insertion Sort Algorithm . . . . . . . . . . . . . . .345 Using Multidimensional Arrays . . . . . . . . . . . . . . . . .349 Using Indexed Files and Linked Lists . . . . . . . . . . . . . .356 Chapter Summary . . . . . . . . . . . . . . . . . . . . . .361 Key Terms . . . . . . . . . . . . . . . . . . . . . . . . .362 Exercises . . . . . . . . . . . . . . . . . . . . . . . . .363

Advanced Modulariza tion Techniques . . . . 371

The Parts of a Method . . . . . . . . . . . . . . . . . . . .372 Using Methods with no Parameters . . . . . . . . . . . . . .373 Creating Methods that Require Parameters . . . . . . . . . . .376 Creating Methods that Return a Value . . . . . . . . . . . . .384 Passing an Array to a Method . . . . . . . . . . . . . . . . .391 Overloading Methods . . . . . . . . . . . . . . . . . . . .398 Using Predefined Methods . . . . . . . . . . . . . . . . . .405 Method Design Issues: Implementation Hiding,

Cohesion, and Coupling . . . . . . . . . . . . . . . . . .407 Understanding Recursion . . . . . . . . . . . . . . . . . . .410 Chapter Summary . . . . . . . . . . . . . . . . . . . . . .415 Key Terms . . . . . . . . . . . . . . . . . . . . . . . . .416 Exercises . . . . . . . . . . . . . . . . . . . . . . . . .418

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

vii

C HAP T E R 1 0

C HAP T E R 1 1

C HAP T E R 1 2

Object-Oriented Programming . . . . . . . 427

Principles of Object-Oriented Programming . . . . . . . . . . .428 Defining Classes and Creating Class Diagrams . . . . . . . . .435 Understanding Public and Private Access . . . . . . . . . . . .444 Organizing Classes . . . . . . . . . . . . . . . . . . . . .448 Understanding Instance Methods . . . . . . . . . . . . . . .449 Understanding Static Methods . . . . . . . . . . . . . . . .454 Using Objects . . . . . . . . . . . . . . . . . . . . . . . .456 Chapter Summary . . . . . . . . . . . . . . . . . . . . . .462 Key Terms . . . . . . . . . . . . . . . . . . . . . . . . .463 Exercises . . . . . . . . . . . . . . . . . . . . . . . . .465

More Object-Oriented Programming Concepts . . . . . . . . . . . . . . . . . 471

Understanding Constructors . . . . . . . . . . . . . . . . .472 Understanding Destructors . . . . . . . . . . . . . . . . . .479 Understanding Composition . . . . . . . . . . . . . . . . . .481 Understanding Inheritance . . . . . . . . . . . . . . . . . .482 An Example of Using Predefined Classes:

Creating GUI Objects . . . . . . . . . . . . . . . . . . .494 Understanding Exception Handling . . . . . . . . . . . . . . .495 Reviewing the Advantages of Object-Oriented

Programming . . . . . . . . . . . . . . . . . . . . . . .501 Chapter Summary . . . . . . . . . . . . . . . . . . . . . .502 Key Terms . . . . . . . . . . . . . . . . . . . . . . . . .503 Exercises . . . . . . . . . . . . . . . . . . . . . . . . .504

Event-Driven GUI Progra mming, Multithreading, and Animation . . . . . . . 514

Understanding Event-Driven Programming . . . . . . . . . . . .515 User-Initiated Actions and GUI Components . . . . . . . . . . .518 Designing Graphical User Interfaces . . . . . . . . . . . . . .521 Developing an Event-Driven Application . . . . . . . . . . . . .524 Understanding Threads and Multithreading . . . . . . . . . . .532 Creating Animation . . . . . . . . . . . . . . . . . . . . .535 Chapter Summary . . . . . . . . . . . . . . . . . . . . . .538 Key Terms . . . . . . . . . . . . . . . . . . . . . . . . .539 Exercises . . . . . . . . . . . . . . . . . . . . . . . . .540

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

C O N T E N T S

C HAP T E R 1 3

viii

C HAP T E R 1 4

A PP E N D I X A

A PP E N D I X B

A PP E N D I X C

A PP E N D I X D

System Modeling with the UML . . . . . . . 547

Understanding System Modeling . . . . . . . . . . . . . . . .548 What is the UML? . . . . . . . . . . . . . . . . . . . . . .549 Using UML Use Case Diagrams . . . . . . . . . . . . . . . .551 Using UML Class and Object Diagrams . . . . . . . . . . . . .557 Using Other UML Diagrams . . . . . . . . . . . . . . . . . .561 Deciding When to Use the UML and Which UML

Diagrams to Use . . . . . . . . . . . . . . . . . . . . .569 Chapter Summary . . . . . . . . . . . . . . . . . . . . . .571 Key Terms . . . . . . . . . . . . . . . . . . . . . . . . .572 Exercises . . . . . . . . . . . . . . . . . . . . . . . . .573

Using Relational Databases . . . . . . . . 579

Understanding Relational Database Fundamentals . . . . . . . .580 Creating Databases and Table Descriptions . . . . . . . . . . .582 Identifying Primary Keys . . . . . . . . . . . . . . . . . . .584 Understanding Database Structure Notation . . . . . . . . . . .587 Working with Records within Tables . . . . . . . . . . . . . .588 Creating Queries . . . . . . . . . . . . . . . . . . . . . .589 Understanding Relationships Between Tables . . . . . . . . . .592 Recognizing Poor Table Design . . . . . . . . . . . . . . . .598 Understanding Anomalies, Normal Forms, and Normalization . . .600 Database Performance and Security Issues . . . . . . . . . . .609 Chapter Summary . . . . . . . . . . . . . . . . . . . . . .611 Key Terms . . . . . . . . . . . . . . . . . . . . . . . . .613 Exercises . . . . . . . . . . . . . . . . . . . . . . . . .616

Understanding Numbering Systems and Computer Codes . . . . . . . . . . . . 625

Solving Difficult Structuring Problems . . . . 633

Creating Print Charts . . . . . . . . . . . . 642

Two Variations on the Basic Structures— case and do-while . . . . . . . . . . . . 644

Glossary . . . . . . . . . . . . . . . . . . 651

Index . . . . . . . . . . . . . . . . . . . . 667

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

ix

Preface

Programming Logic and Design, Comprehensive, Eighth 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, Eighth 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.

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

P R E F A C E Organization and Coverage

x

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.

Four appendices instruct students in working with numbering systems, large unstructured programs, print charts, and post-test 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:

It is written and designed to be non-language specific. The logic used in this book can be applied to any programming language.

The examples are everyday business examples; no special knowledge of mathematics, accounting, or other disciplines is assumed.

The concept of structure is covered earlier than in many other texts. Students are exposed to structure naturally, so they will automatically create properly designed programs.

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.

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.

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

xi

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.

FLOWCHARTS, figures, and illustrations provide the reader with a visual learning experience.

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.

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

xii

F E A T U R E S

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.

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.

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

xiii

Assessment

REVIEW QUESTIONS test student comprehension of the major ideas and techniques presented. Twenty questions follow each chapter.

PROGRAMMING EXERCISES provide opportunities to practice concepts. These exercises increase in diffculty and allow students to explore logical programming concepts. Each exercise can be completed using fowcharts, pseudocode, or both. In addition, instructors can assign the exercises as programming problems to be coded and executed in a particular programming language.

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

xiv

A S S E S S M E N T

PERFORMING MAINTENANCE exercises ask students to modify working logic based on new requested specifcations. This activity mirrors real-world tasks that students are likely to encounter in their frst programming jobs. 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.

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.

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 fles are also available to instructors at sso.cengage.com.

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

xv

Instructor Resources

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.

Clear explanations. The language and explanations in this book have been refined over eight editions, providing the clearest possible explanations of difficult concepts.

Emphasis on structure. More than its competitors, this book emphasizes structure. Chapter 3 provides an early picture of the major concepts of structured programming.

Emphasis on modularity. From the second chapter, students are encouraged to write code in concise, easily manageable, and reusable modules. Instructors have found that modularization should be encouraged early to instill good habits and a clearer understanding of structure.

Objectives. Each chapter begins with a list of objectives so the student knows the topics that will be presented in the chapter. In addition to providing a quick reference to topics covered, this feature provides a useful study aid.

Chapter summaries. Following each chapter is a summary that recaps the programming concepts and techniques covered in the chapter.

Key terms. Each chapter lists key terms and their definitions; the list appears in the order the terms are encountered in the chapter. A glossary at the end of the book lists all the key terms in alphabetical order, along with 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:

Video Lessons. Designed and narrated by the author, videos in each chapter explain and enrich important concepts.

Two Truths & A Lie, Debugging Exercises, and Performing Maintenance. Complete popular exercises from the text online.

An interactive eBook. 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 for download through our Instructor Companion Site at sso.cengage.com.

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

P R E F A C E

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.

PowerPoint Presentations. This text provides PowerPoint slides to accompany each xvi chapter. Slides are included to guide classroom presentation, to make available to

students for chapter review, or to print as classroom handouts.

Solutions. Solutions to review questions and exercises are provided to assist with grading.

Test Bank®. Cengage Learning Testing Powered by Cognero is a flexible, online system that allows you to:

author, edit, and manage test bank content from multiple Cengage Learning solutions

create multiple test versions in an instant

deliver tests from your LMS, your classroom, or anywhere you want

Additional Options Visual Logic™ software. Visual Logic is a simple but powerful tool for teaching programming logic and design without traditional high-level programming language syntax. Visual Logic also interprets and executes flowcharts, providing students with immediate and accurate feedback.

PAL (Programs to Accompany) 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. 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.

Acknowledgments I would like to thank all of the people who helped to make this book a reality, especially Dan Seiter, Development Editor; Alyssa Pratt, Senior Content Developer; Jim Gish, Senior Product Manager; and Jennifer Feltri-George, Content Project Manager. I am grateful to be able to work with so many fine people who are dedicated to producing quality instructional materials.

I am indebted to the many reviewers who provided helpful and insightful comments during the development of this book, including Gail Gehrig, Florida State College at Jacksonville; Yvonne Leonard, Coastal Carolina Community College; and Meri Winchester, McHenry County College.

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

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

C H A P T E R 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 2015 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.

C H A P T E R 1 An Overview of Computers and Programming

2

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.

Hardware is the equipment, or the physical devices, associated with a computer. For example, keyboards, mice, speakers, and printers are all hardware. The devices are manufactured differently for computers of varying sizes—for example, large mainframes, laptops, and very small devices embedded into products such as telephones, cars, and thermostats. However, 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.

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:

Application software comprises all the programs you apply to a task, such as word- processing programs, spreadsheets, payroll and inventory programs, and games. When you hear people say they have “downloaded an app onto a mobile device,” they are simply using an abbreviation of application.

System software comprises the programs that you use to manage your computer, including operating systems such as Windows, Linux, or UNIX for larger computers and Google Android and Apple iOS for smartphones.

This book focuses on the logic used to write application software programs, although many of the concepts apply to both types of software.

Together, computer hardware and software accomplish three major operations in most programs:

Input—Data items enter the computer system and are placed in memory, where they can be processed. 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 or finger-swiping movements.

Processing—Processing data items may involve organizing or sorting them, checking them for accuracy, or performing calculations with them. The hardware component that performs these types of tasks is the central processing unit, or CPU. Some devices, such as

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

3

Understanding Computer Systems

tablets and smartphones, usually contain multiple processors. Writing programs that efficiently use several CPUs requires special techniques.

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 your hard drive, flash media, or a cloud-based device. (The cloud refers to devices at remote locations accessed through the Internet.) People cannot read data directly from these storage devices, but the devices hold information for later retrieval. When you send output to a storage device, sometimes it is used later as input for another program.

You write computer instructions in a computer programming language such as Visual Basic, C#, C++, or Java. Just as some people speak English and others speak Japanese, programmers write programs in different languages. Some programmers work exclusively in one language, whereas others know several and use the one that is best suited to the task at hand.

The instructions you write using a programming language are called program code; when you write instructions, you are coding the program.

Every programming language has rules governing its word usage and punctuation. These rules are called the language’s syntax. Mistakes in a language’s usage are syntax errors. If you ask, “How the geet too store do I?” in English, most people can figure out what you probably mean, even though you have not used proper English syntax—you have mixed up the word order, misspelled a word, and used an incorrect word. However, computers are not nearly as smart as most people; in this case, you might as well have asked the computer, “Xpu mxv ort dod nmcad bf B?” Unless the syntax is perfect, the computer cannot interpret the programming language instruction at all.

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—often your hard drive.

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

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

C H A P T E R 1 An Overview of Computers and Programming

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

4

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.

The false statement is #3. You write programs using a programming language such as Visual Basic or Java, and a translation program (called a compiler or interpreter) converts the statements to machine language, which is 0s and 1s.

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

5

Understanding Simple Program Logic

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

Don’t Do It Don't bake a cake like this!

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

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

C H A P T E R 1 An Overview of Computers and Programming

The number-doubling process includes three instructions:

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

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

A college classroom is similar to a named variable in that its name (perhaps 204 Adams Building) can hold different contents at different times. For example, your Logic class might meet there on Monday night, and a math class might meet there on Tuesday morning.

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.

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 smartphone display), or the output could go to a printer (which could be laser or ink-jet), or the output could be written to a disk or DVD. The logic of the output process is the same no 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.

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

7

Understanding the Program Development Cycle

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.

The false statement is #1. A program with syntax errors cannot execute; a program with no syntax errors can execute, but might produce incorrect results.

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.

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

C H A P T E R 1 An Overview of Computers and Programming

8

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 © 2015 Cengage Learning

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:

Does the director want a list of full-time employees only, or a list of full- and part-time employees together?

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?

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?

What about an employee who worked three years, took a two-year leave of absence, and has been back for three years?

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

9

Understanding the Program Development Cycle

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:

What data should be included for each listed employee? Should the list contain both first and last names? Social Security numbers? Phone numbers? Addresses?

Should the list be in alphabetical order? Employee ID number order? Length-of-service order? Some other order?

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.

Understanding the problem might be even more difficult if you are writing an app that you hope to market for mobile devices. Business developers are usually approached by a user with a need, but successful developers of mobile apps often try to identify needs that users aren’t even aware of yet. For example, no one knew they wanted to play Angry Birds or leave messages on Facebook before those applications were developed. Mobile app developers also must consider a wider variety of user skills than programmers who develop applications that are used internally in a corporation. Mobile app developers must make sure their programs work with a range of screen sizes and hardware specifications because software competition is intense and the hardware changes quickly.

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 or rules you follow to solve a problem.

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

C H A P T E R 1 An Overview of Computers and Programming

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. In the comprehensive version of this book, you can learn about storyboards and the UML, which are frequently used in interactive, object-oriented applications.

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

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

11

Understanding the Program Development Cycle

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.

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 programmer’s deepest concern, 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.

Programmers often compile their code one section at a time. It is far less overwhelming and easier to understand errors that are discovered in 20 lines of code at a time than to try to correct mistakes after 2,000 lines of code have been written. 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.

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

C H A P T E R 1

An Overview of Computers and Programming

12

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 © 2015 Cengage Learning

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

Don’t Do It The programmer typed 20 instead of 2.

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.

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

13

Understanding the Program Development Cycle

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

Don’t Do It The programmer typed "+" instead of "*".

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

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

C H A P T E R 1 An Overview of Computers and Programming

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.

14

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.

The false statement is #3. 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.

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.

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.

A flowchart is a pictorial representation of the same thing.

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

15

Using Pseudocode Statements and Flowchart Symbols

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 statement, although you might choose to do so.

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:

Instead of start and stop, some pseudocode developers would use other terms such as begin and end.

Instead of writing input myNumber, some developers would write get myNumber or read myNumber.

Instead of writing set myAnswer = myNumber * 2, some developers would write calculate myAnswer = myNumber times 2 or compute myAnswer as myNumber doubled.

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. Quick Reference 1-1 summarizes the pseudocode standards used in this book. (Note that the Quick Reference mentions modules; you will learn about modules in Chapter 2. Additional pseudocode style features will be discussed as topics are introduced throughout this book.)

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

C H A P T E R 1 An Overview of Computers and Programming

QUICK REFERENCE 1-1 Pseudocode Standards

Programs begin with start and end with stop; these two words are always aligned.

16 Whenever a module name is used, it is followed by a set of parentheses.

Modules begin with the module name and end with return. The module name and return are always aligned.

Each program statement performs one action—for example, input, processing, or output.

Program statements are indented a few spaces more than start or the module name.

Each program statement appears on a single line if possible. When this is not possible, continuation lines are indented.

Program statements begin with lowercase letters.

No punctuation is used to end statements.

As you learn to create pseudocode and flowchart statements, you will develop a sense for how much detail to include. The statements represent the main steps that must be accomplished without including minute points. The concept is similar to writing an essay outline in which each statement of the outline represents a paragraph.

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 that helps them to 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.

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

17

Using Pseudocode Statements and Flowchart Symbols

output myAnswer

When you create a flowchart, you draw geometric shapes that contain the individual statements and input myNumber that are connected with arrows. You use a parallelogram to represent an input symbol, which indicates an input operation. You write an input Figure 1-3 Input symbol statement in English inside the parallelogram, © 2015 Cengage Learning 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.

set myAnswer = myNumber * 2

Figure 1-4 Processing symbol © 2015 Cengage Learning 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.

Figure 1-5 Output symbol © 2015 Cengage Learning

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. You can see from the figure that the flowchart and pseudocode statements are the same— only the presentation format differs.

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

C H A P T E R 1

An Overview of Computers and Programming

18

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 © 2015 Cengage Learning

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. Quick Reference 1-2 summarizes the flowchart symbols used in this book.

QUICK REFERENCE 1-2 Flowchart Symbols

Terminal

Input/Output

Process

Flowline

Decision

Internal module call

External module call

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

19

Using Pseudocode Statements and Flowchart Symbols

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.

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.

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 © 2015 Cengage Learning

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.

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

C H A P T E R 1

An Overview of Computers and Programming

20

start

input myNumber

output myAnswer

set myAnswer = myNumber * 2

Don’t Do It This logic saves steps, but it has a fatal faw – it never ends.

Figure 1-8 Flowchart of infinite number-doubling program © 2015 Cengage Learning

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.

The false statement is #2. When you draw a flowchart, you use a rectangle to represent a processing operation.

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

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

21

Using a Sentinel Value to End a Program

computer. But again, that’s neither the best solution nor an elegant way for the program to end.

A better way to end the program is to set a predetermined value for myNumber that means “Stop the program!” For example, the programmer and the user could agree that the user will never need to know the double of 0 (zero), so the user could enter a 0 to stop. The program could then test any incoming value contained in myNumber and, if it is a 0, stop the program. Testing a value is also called making a decision.

You represent a decision in a flowchart by drawing a decision symbol, which is shaped like a diamond. The diamond usually contains a question, the answer to which is one of two mutually exclusive options—often yes or no. All good computer questions have only two mutually exclusive answers, such as yes and no or true and false. For example, “What day of the year is your birthday?” is not a good computer question because there are 366 possible answers. However, “Is your birthday June 24?” is a good computer question because the answer is always either yes or no.

The question to stop the doubling program should be “Is the value of myNumber just entered equal to 0?” or “myNumber = 0?” for short. The complete flowchart will now look like the one shown in Figure 1-9.

stop myNumber

= 0?

Yes

No

start

input myNumber

output myAnswer

set myAnswer = myNumber * 2

Don’t Do It This logic is not structured; you will learn about structure in Chapter 3.

Figure 1-9 Flowchart of number-doubling program with sentinel value of 0 © 2015 Cengage Learning

One drawback to using 0 to stop a program, of course, is that it won’t work if the user does need to find the double of 0. In that case, some other data-entry value that the user never will

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

C H A P T E R 1

An Overview of Computers and Programming

need, such as 999 or –1, could be selected to signal that the program should end. A preselected value that stops the execution of a program is often called a dummy value because it does not represent real data, but just a signal to stop. Sometimes, such a value is called a sentinel value because it represents an entry or exit point, like a sentinel who guards a fortress.

22 Not all programs rely on user data entry from a keyboard; many read data from an input device, such as a disk. When organizations store data on a disk or other storage device, they do not commonly use a dummy value to signal the end of the file. For one thing, an input record might have hundreds of fields, and if you store a dummy record in every file, you are wasting a large quantity of storage on “nondata.” Additionally, it is often difficult to choose sentinel values for fields in a company’s data files. Any balanceDue, even a zero or a negative number, can be a legitimate value, and any customerName, even “ZZ”, could be someone’s name. Fortunately, programming languages can recognize the end of data in a file automatically, through a code that is stored at the end of the data. Many programming languages use the term eof (for end of file) to refer to this marker that automatically acts as a sentinel. This book, therefore, uses eof to indicate the end of data whenever using a dummy value is impractical or inconvenient. In the flowchart shown in Figure 1-10, the eof question is shaded.

stop eof? Yes

No

start

input myNumber

output myAnswer

set myAnswer = myNumber * 2

Don’t Do It This logic is not structured; you will learn about structure in Chapter 3.

Figure 1-10 Flowchart using eof © 2015 Cengage Learning

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

23

Understanding Programming and User Environments

TWO TRUTHS & A LIE Using a Sentinel Value to End a Program

1. A program that contains an infinite loop is one that never ends.

2. A preselected value that stops the execution of a program is often called a dummy value or a sentinel value.

3. Many programming languages use the term fe (for file end) to refer to a marker that automatically acts as a sentinel.

The false statement is #3. The term eof(for end of flie) is the common term for a file sentinel.

Understanding Programming and User Environments Many approaches can be used to write and execute a computer program. When you plan a program’s logic, you can use a flowchart, pseudocode, or a combination of the two. When you code the program, you can type statements into a variety of text editors. When your program executes, it might accept input from a keyboard, mouse, microphone, or any other input device, and when you provide a program’s output, you might use text, images, or sound. This section describes the most common environments you will encounter as a new programmer.

Understanding Programming Environments When you plan the logic for a computer program, you can use paper and pencil to create a flowchart, or you might use software that allows you to manipulate flowchart shapes. If you choose to write pseudocode, you can do so by hand or by using a word-processing program. To enter the program into a computer so you can translate and execute it, you usually use a keyboard to type program statements into an editor. You can type a program into one of the following:

A plain text editor

A text editor that is part of an integrated development environment

A text editor is a program that you use to create simple text files. It is similar to a word processor, but without as many features. You can use a text editor such as Notepad that is included with Microsoft Windows. Figure 1-11 shows a C# program in Notepad that accepts a number and doubles it. An advantage to using a simple text editor to type and save a program is that the completed program does not require much disk space for storage. For example, the file shown in Figure 1-11 occupies only 314 bytes of storage.

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

C H A P T E R 1 An Overview of Computers and Programming

This line contains a prompt that tells the user what to enter. You will learn more about prompts in Chapter 2.

24

Figure 1-11 A C# number-doubling program in Notepad

You can use the editor of an integrated development environment (IDE) to enter your program. An IDE is a software package that provides an editor, compiler, and other programming tools. For example, Figure 1-12 shows a C# program in the Microsoft Visual Studio IDE, an environment that contains tools useful for creating programs in Visual Basic, C++, and C#.

Figure 1-12 A C# number-doubling program in Visual Studio

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

25

Understanding Programming and User Environments

Using an IDE is helpful to programmers because usually it provides features similar to those you find in many word processors. In particular, an IDE’s editor commonly includes such features as the following:

It uses different colors to display various language components, making elements like data types easier to identify.

It highlights syntax errors visually for you.

It employs automatic statement completion; when you start to type a statement, the IDE suggests a likely completion, which you can accept with a keystroke.

It provides tools that allow you to step through a program’s execution one statement at a time so you can more easily follow the program’s logic and determine the source of any errors.

When you use the IDE to create and save a program, you occupy much more disk space than when using a plain text editor. For example, the program in Figure 1-12 occupies more than 49,000 bytes of disk space.

Although various programming environments might look different and offer different features, the process of using them is very similar. When you plan the logic for a program using pseudocode or a flowchart, it does not matter which programming environment you will use to write your code, and when you write the code in a programming language, it does not matter which environment you use to write it.

Understanding User Environments A user might execute a program you have written in any number of environments. For example, a user might execute the number-doubling program from a command line like the one shown in Figure 1-13. A command line is a location on your computer screen at which you type text entries to communicate with the computer’s operating system. In the program in Figure 1-13, the user is asked for a number, and the results are displayed.

Figure 1-13 Executing a number-doubling program in a command-line environment

Many programs are not run at the command line in a text environment, but are run using a graphical user interface, or GUI (pronounced gooey), which allows users to interact with a program in a graphical environment. When running a GUI program, the user might type input into a text box or use a mouse or other pointing device to select options on the screen. Figure 1-14 shows a number-doubling program that performs exactly the same task as the one in Figure 1-13, but this program uses a GUI.

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

C H A P T E R 1 An Overview of Computers and Programming

26

Figure 1-14 Executing a number-doubling program in a GUI environment

A command-line program and a GUI program might be written in the same programming language. (For example, the programs shown in Figures 1-13 and 1-14 were both written using C#.) However, no matter which environment is used to write or execute a program, the logical process is the same. The two programs in Figures 1-13 and 1-14 both accept input, perform multiplication, and perform output. In this book, you will not concentrate on which environment is used to type a program’s statements, nor will you care about the type of environment the user will see. Instead, you will be concerned with the logic that applies to all programming situations.

TWO TRUTHS & A LIE Understanding Programming and User Environments

1. You can type a program into an editor that is part of an integrated development environment, but using a plain text editor provides you with more programming help.

2. When a program runs from the command line, a user types text to provide input.

3. Although GUI and command-line environments look different, the logic of input, processing, and output apply to both program types.

The false statement is #1. An integrated development environment provides more programming help than a plain text editor.

Understanding the Evolution of Programming Models People have been writing modern computer programs since the 1940s. The oldest programming languages required programmers to work with memory addresses and to memorize awkward codes associated with machine languages. Newer programming languages look much more like natural language and are easier to use, partly because they allow programmers to name variables instead of using unwieldy memory addresses. Also, newer programming languages allow programmers to create self-contained modules or program segments that can be pieced together in a variety of ways. The oldest computer programs were written in one piece, from start to finish, but modern programs are rarely written that way—they are created by teams of programmers, each developing reusable and connectable program procedures. Writing several small modules is easier than writing one

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

27

Understanding the Evolution of Programming Models

large program, and most large tasks are easier when you break the work into units and get other workers to help with some of the units.

Ada Byron Lovelace predicted the development of software in 1843; she is often regarded as the first programmer. The basis for most modern software was proposed by Alan Turing in 1935.

Currently, two major models or paradigms are used by programmers to develop programs and their procedures:

Procedural programming focuses on the procedures that programmers create. That is, procedural programmers focus on the actions that are carried out—for example, getting input data for an employee and writing the calculations needed to produce a paycheck from the data. Procedural programmers would approach the job of producing a paycheck by breaking down the process into manageable subtasks.

Object-oriented programming focuses on objects, or “things,” and describes their features (also called attributes) and behaviors. For example, object-oriented programmers might design a payroll application by thinking about employees and paychecks, and by describing their attributes. Employees have names and Social Security numbers, and paychecks have names and check amounts. Then the programmers would think about the behaviors of employees and paychecks, such as employees getting raises and adding dependents and paychecks being calculated and output. Object-oriented programmers would then build applications from these entities.

With either approach, procedural or object oriented, you can produce a correct paycheck, and both models employ reusable program modules. The major difference lies in the focus the programmer takes during the earliest planning stages of a project. For now, this book focuses on procedural programming techniques. The skills you gain in programming procedurally—declaring variables, accepting input, making decisions, producing output, and so on—will serve you well whether you eventually write programs using a procedural approach, an object-oriented approach, or both. The programming language in which you write your source code might determine your approach. You can write a procedural program in any language that supports object orientation, but the opposite is not always true.

TWO TRUTHS & A LIE Understanding the Evolution of Programming Models

1. The oldest computer programs were written in many separate modules.

2. Procedural programmers focus on actions that are carried out by a program.

3. Object-oriented programmers focus on a program’s objects and their attributes and behaviors.

The false statement is #1. The oldest programs were written in a single piece; newer programs are divided into modules.

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

C H A P T E R 1 An Overview of Computers and Programming

Chapter Summary Together, computer hardware (physical devices) and software (instructions) accomplish three major operations: input, processing, and output. You write computer instructions in a28 computer programming language that requires specific syntax; the instructions are translated into machine language by a compiler or interpreter. When both the syntax and logic of a program are correct, you can run, or execute, the program to produce the desired results.

For a program to work properly, you must develop correct logic. Logical errors are much more difficult to locate than syntax errors.

A programmer’s job involves understanding the problem, planning the logic, coding the program, translating the program into machine language, testing the program, putting the program into production, and maintaining it.

When programmers plan the logic for a solution to a programming problem, they often use flowcharts or pseudocode. When you draw a flowchart, you use parallelograms to represent input and output operations, and rectangles to represent processing. Programmers also use decisions to control repetition of instruction sets.

To avoid creating an infinite loop when you repeat instructions, you can test for a sentinel value. You represent a decision in a flowchart by drawing a diamond-shaped symbol that contains a question, the answer to which is either yes or no.

You can type a program into a plain text editor or one that is part of an integrated development environment. When a program’s data values are entered from a keyboard, they can be entered at the command line in a text environment or in a GUI. Either way, the logic is similar.

Procedural and object-oriented programmers approach problems differently. Procedural programmers concentrate on the actions performed with data. Object-oriented programmers focus on objects and their behaviors and attributes.

Key Terms A computer system is a combination of all the components required to process and store data using a computer.

Hardware is the collection of physical devices that comprise a computer system.

Software consists of the programs that tell the computer what to do.

Programs are sets of instructions for a computer.

Programming is the act of developing and writing programs.

Application software comprises all the programs you apply to a task.

An app is a piece of application software; the term is frequently used for applications on mobile devices.

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

29

Key Terms

System software comprises the programs that you use to manage your computer.

Input describes the entry of data items into computer memory using hardware devices such as keyboards and mice.

Data items include all the text, numbers, and other information processed by a computer.

Processing data items may involve organizing them, checking them for accuracy, or performing mathematical operations on them.

The central processing unit, or CPU, is the computer hardware component that processes data.

Output describes the operation of retrieving information from memory and sending it to a device, such as a monitor or printer, so people can view, interpret, and work with the results.

Information is processed data.

Storage devices are types of hardware equipment, such as disks, that hold information for later retrieval.

The cloud refers to remote computers accessed through the Internet.

Programming languages, such as Visual Basic, C#, C++, or Java, are used to write programs.

Program code is the set of instructions a programmer writes in a programming language.

Coding the program is the act of writing programming language instructions.

The syntax of a language is its grammar rules.

A syntax error is an error in language or grammar.

Computer memory is the temporary, internal storage within a computer.

Random access memory (RAM) is temporary, internal computer storage.

Volatile describes storage whose contents are lost when power is lost.

Nonvolatile describes storage whose contents are retained when power is lost.

Machine language is a computer’s on/off circuitry language.

Source code is the statements a programmer writes in a programming language.

Object code is translated machine language.

A compiler or interpreter translates a high-level language into machine language and indicates if you have used a programming language incorrectly.

Binary language is represented using a series of 0s and 1s.

To run or execute a program is to carry out its instructions.

Scripting languages (also called scripting programming languages or script languages) such as Python, Lua, Perl, and PHP are used to write programs that are typed directly from a keyboard. Scripting languages are stored as text rather than as binary executable files.

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

C H A P T E R 1 An Overview of Computers and Programming

A logical error occurs when incorrect instructions are performed, or when instructions are performed in the wrong order.

The logic of a computer program is the complete sequence of instructions that lead to a problem’s solution.

30 A variable is a named memory location whose value can vary.

The program development cycle consists of the steps that occur during a program’s lifetime.

Users (or end users) are people who employ and benefit from computer programs.

Documentation consists of all the supporting paperwork for a program.

An algorithm is the sequence of steps necessary to solve any problem.

An IPO chart is a program development tool that delineates input, processing, and output tasks.

A TOE chart is a program development tool that lists tasks, objects, and events.

Desk-checking is the process of walking through a program solution on paper.

A high-level programming language supports English-like syntax.

A low-level machine language is made up of 1s and 0s and does not use easily interpreted variable names.

Debugging is the process of finding and correcting program errors.

Conversion is the entire set of actions an organization must take to switch over to using a new program or set of programs.

Maintenance consists of all the improvements and corrections made to a program after it is in production.

Pseudocode is an English-like representation of the logical steps it takes to solve a problem.

A flowchart is a pictorial representation of the logical steps it takes to solve a problem.

An input symbol indicates an input operation and is represented by a parallelogram in flowcharts.

A processing symbol indicates a processing operation and is represented by a rectangle in flowcharts.

An output symbol indicates an output operation and is represented by a parallelogram in flowcharts.

An input/output symbol or I/O symbol is represented by a parallelogram in flowcharts.

Flowlines, or arrows, connect the steps in a flowchart.

A terminal symbol indicates the beginning or end of a flowchart segment and is represented by a lozenge.

A loop is a repetition of a series of steps.

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

31

Exercises

An infinite loop occurs when repeating logic cannot end.

Making a decision is the act of testing a value.

A decision symbol is shaped like a diamond and used to represent decisions in flowcharts.

A dummy value is a preselected value that stops the execution of a program.

A sentinel value is a preselected value that stops the execution of a program.

The term eof means end of file.

A text editor is a program that you use to create simple text files; it is similar to a word processor, but without as many features.

An integrated development environment (IDE) is a software package that provides an editor, compiler, and other programming tools.

Microsoft Visual Studio IDE is a software package that contains useful tools for creating programs in Visual Basic, C++, and C#.

A command line is a location on your computer screen at which you type text entries to communicate with the computer’s operating system.

A graphical user interface, or GUI (pronounced gooey), allows users to interact with a program in a graphical environment.

Procedural programming is a programming model that focuses on the procedures that programmers create.

Object-oriented programming is a programming model that focuses on objects, or “things,” and describes their features (also called attributes) and behaviors.

Exercises

Review Questions

1. Computer programs also are known as .

a. hardware c. data b. software d. information

2. The major computer operations include .

a. hardware and software b. input, processing, and output c. sequence and looping d. spreadsheets, word processing, and data communications

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

C H A P T E R 1 An Overview of Computers and Programming

3. Visual Basic, C++, and Java are all examples of computer .

a. operating systems c. machine languages b. hardware d. programming languages

4. A programming language’s rules are its . 32

a. syntax c. format b. logic d. options

5. The most important task of a compiler or interpreter is to .

a. create the rules for a programming language b. translate English statements into a language such as Java c. translate programming language statements into machine language d. execute machine language programs to perform useful tasks

6. Which of the following is temporary, internal storage?

a. CPU c. keyboard b. hard disk d. memory

7. Which of the following pairs of steps in the programming process is in the correct order?

a. code the program, plan the logic b. test the program, translate it into machine language c. put the program into production, understand the problem d. code the program, translate it into machine language

8. A programmer’s most important task before planning the logic of a program is to .

a. decide which programming language to use b. code the problem c. train the users of the program d. understand the problem

9. The two most commonly used tools for planning a program’s logic are .

a. flowcharts and pseudocode b. ASCII and EBCDIC c. Java and Visual Basic d. word processors and spreadsheets

10. Writing a program in a language such as C++ or Java is known as the program.

a. translating c. interpreting b. coding d. compiling

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

33

Exercises

11. An English-like programming language such as Java or Visual Basic is a programming language.

a. machine-level c. high-level b. low-level d. binary-level

12. Which of the following is an example of a syntax error?

a. producing output before accepting input b. subtracting when you meant to add c. misspelling a programming language word d. all of the above

13. Which of the following is an example of a logical error?

a. performing arithmetic with a value before inputting it b. accepting two input values when a program requires only one c. dividing by 3 when you meant to divide by 30 d. all of the above

14. The parallelogram is the flowchart symbol representing .

a. input c. either a or b b. output d. none of the above

15. In a flowchart, a rectangle represents .

a. input c. a question b. a sentinel d. processing

16. In flowcharts, the decision symbol is a .

a. parallelogram c. lozenge b. rectangle d. diamond

17. The term eof represents .

a. a standard input device b. a generic sentinel value c. a condition in which no more memory is available for storage d. the logical flow in a program

18. When you use an IDE instead of a simple text editor to develop a program, .

a. the logic is more complicated c. the syntax is different b. the logic is simpler d. some help is provided

19. When you write a program that will run in a GUI environment as opposed to a command-line environment, .

a. the logic is very different c. you do not need to plan the logic b. some syntax is different d. users are more confused

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

C H A P T E R 1 An Overview of Computers and Programming

20. As compared to procedural programming, with object-oriented programming, .

a. the programmer’s focus differs b. you cannot use some languages, such as Java c. you do not accept input 34 d. you do not code calculations; they are created automatically

Programming Exercises

1. Match the definition with the appropriate term.

1. Computer system devices a. compiler

2. Another word for programs b. syntax

3. Language rules c. logic

4. Order of instructions d. hardware

5. Language translator e. software

2. In your own words, describe the steps to writing a computer program.

3. Match the term with the appropriate shape (see Figure 1-15).

A.1. Input

C.3. Output

D.4. Decision

5. Terminal

B.2. Processing

Figure 1-15 Identifying shapes © 2015 Cengage Learning

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

35

Exercises

4. Draw a flowchart or write pseudocode to represent the logic of a program that allows the user to enter a value. The program divides the value by 2 and outputs the result.

5. Draw a flowchart or write pseudocode to represent the logic of a program that allows the user to enter a value for one edge of a cube. The program calculates the surface area of one side of the cube, the surface area of the cube, and its volume. The program outputs all the results.

6. Draw a flowchart or write pseudocode to represent the logic of a program that allows the user to enter two values. The program outputs the product of the two values.

7. a. Draw a flowchart or write pseudocode to represent the logic of a program that allows the user to enter values for the width and length of a room’s floor in feet. The program outputs the area of the floor in square feet.

b. Modify the program that computes floor area to compute and output the number of 6-inch square tiles needed to tile the floor.

8. a. Draw a flowchart or write pseudocode to represent the logic of a program that allows the user to enter values for the width and length of a wall in feet. The program outputs the area of the wall in square feet.

b. Modify the program that computes wall area to allow the user to enter the price of a gallon of paint. Assume that a gallon of paint covers 350 square feet of a wall. The program outputs the number of gallons needed and the cost of the job. (For this exercise, assume that you do not need to account for windows or doors, and that you can purchase partial gallons of paint.)

c. Modify the program that computes paint cost to allow the user to enter the number of doorways that do not have to be painted. Assume that each doorway is 14 square feet. Output the number of gallons needed and the cost of the job.

9. Research current rates of monetary exchange. Draw a flowchart or write pseudo- code to represent the logic of a program that allows the user to enter a number of dollars and convert it to Euros and Japanese yen.

10. Draw a flowchart or write pseudocode to represent the logic of a program that allows the user to enter values for a salesperson’s base salary, total sales, and commission rate. The program computes and outputs the salesperson’s pay by adding the base salary to the product of the total sales and commission rate.

11. A consignment shop accepts a product for sale and sets an initial price. Each month that the item doesn’t sell, the price is reduced by 20 percent. When the item sells, the item’s owner receives 60 percent of the sale price, and the shop gets 40 percent. Draw a flowchart or write pseudocode to represent the logic of a program that allows the user to enter an original product price. The output is the sale price, the owner’s cut, and the shop’s cut each month for the first three months the item is on sale.

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

C H A P T E R 1 An Overview of Computers and Programming

12. A mobile phone app allows a user to press a button that starts a timer that counts seconds. When the user presses the button again, the timer stops. Draw a flowchart or write pseudocode that accepts the elapsed time in seconds and displays the value in minutes and seconds. For example, if the elapsed time was 130 seconds, the output would be 2 minutes and 10 seconds.

36

Performing Maintenance

1. In this chapter you learned that some of the tasks assigned to new programmers frequently involve maintenance—making changes to existing programs because of new requirements. A file named MAINTENANCE01-01.txt is included with your downloadable student files. Assume that this program is a working program in your organization and that it needs modifications as described in the comments (lines that begin with two slashes) at the beginning of the file. Your job is to alter the program to meet the new specifications.

Find the Bugs

Since the early days of computer programming, program errors have been called bugs. The term is often said to have originated from an actual moth that was discovered trapped in the circuitry of a computer at Harvard University in 1945. Actually, the term bug was in use prior to 1945 to mean trouble with any electrical apparatus; even during Thomas Edison’s life, it meant an industrial defect. However, the term debugging is more closely associated with correcting program syntax and logic errors than with any other type of trouble.

1. Your downloadable files for Chapter 1 include DEBUG01-01.txt, DEBUG01-02.txt, and DEBUG01-03.txt. Each file starts with some comments (lines that begin with two slashes) that describe the program. Examine the pseudocode that follows the introductory comments, then find and correct all the bugs.

2. Your downloadable files for Chapter 1 include a file named DEBUG01-04.jpg that contains a flowchart with syntax and/or logical errors. Examine the flowchart and then find and correct all the bugs.

Game Zone

1. In 1952, A. S. Douglas wrote his University of Cambridge Ph.D. dissertation on human-computer interaction, and created the first graphical computer game—a version of Tic-Tac-Toe. The game was programmed on an EDSAC vacuum-tube mainframe computer. The first computer game is generally assumed to be Spacewar!,

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

37

Exercises

developed in 1962 at MIT; the first commercially available video game was Pong, introduced by Atari in 1972. In 1980, Atari’s Asteroids and Lunar Lander became the first video games to be registered with the U. S. Copyright Office. Throughout the 1980s, players spent hours with games that now seem very simple and unglamorous; do you recall playing Adventure, Oregon Trail, Where in the World Is Carmen Sandiego?, or Myst?

Today, commercial computer games are much more complex; they require many programmers, graphic artists, and testers to develop them, and large management and marketing staffs are needed to promote them. A game might cost many millions of dollars to develop and market, but a successful game might earn hundreds of millions of dollars. Obviously, with the brief introduction to programming you have had in this chapter, you cannot create a very sophisticated game. However, you can get started.

Mad Libs is a children’s game in which players provide a few words that are then incorporated into a silly story. The game helps children understand different parts of speech because they are asked to provide specific types of words. For example, you might ask a child for a noun, another noun, an adjective, and a past-tense verb. The child might reply with such answers as table, book, silly, and studied. The newly created Mad Lib might be:

Mary had a little table

Its book was silly as snow

And everywhere that Mary studied

The table was sure to go.

Create the logic for a Mad Lib program that accepts five words from input, then creates and displays a short story or nursery rhyme that uses them.

Up for Discussion

1. Which is the better tool for learning programming—flowcharts or pseudocode? Cite any educational research you can find.

2. What is the image of the computer programmer in popular culture? Is the image different in books than in TV shows and movies? Would you like that image for yourself?

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

C H A P T E R 2 Elements of High-Quality Programs

In this chapter, you will learn about:

Declaring and using variables and constants

Performing arithmetic operations

The advantages of modularization

Modularizing a program

Hierarchy charts

Features of good program design

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

39

Declaring and Using Variables and Constants

Declaring and Using Variables and Constants As you learned in Chapter 1, data items include all the text, numbers, and other information that are processed by a computer. When you input data items into a computer, they are stored in variables in memory where they can be processed and converted to information that is output.

When you write programs, you work with data in three different forms: literals (or unnamed constants), variables, and named constants.

Understanding Unnamed, Literal Constants and their Data Types All programming languages support two broad data types; numeric describes data that consists of numbers and string describes data that is nonnumeric. Most programming languages support several additional data types, including multiple types for numeric values that are very large or very small and for those that do and do not have fractional decimal digits. Languages such as C++, C#, Visual Basic, and Java distinguish between integer (whole number) numeric variables and floating-point (fractional) numeric variables that contain a decimal point. (Floating-point numbers are also called real numbers.) Thus, in some languages, the values 4 and 4.3 would be stored in different types of numeric variables. Additionally, many languages allow you to distinguish between smaller and larger values that occupy different numbers of bytes in memory. You will learn a little more about these specialized data types later in this chapter, and even more when you study a programming language, but this book uses the two broadest types: numeric and string.

When you use a specific numeric value, such as 43, within a program, you write it using the digits and no quotation marks. A specific numeric value is often called a numeric constant (or literal numeric constant) because it does not change—a 43 always has the value 43. When you store a numeric value in computer memory, additional characters such as dollar signs and commas are not input or stored. Those characters can be added to output for readability, but they are not part of the number.

A specific text value, or string of characters, such as “Amanda”, is a string constant (or literal string constant). String constants, unlike numeric constants, appear within quotation marks in computer programs. String values are also called alphanumeric values because they can contain alphabetic characters as well as numbers and other characters. For example, “$3,215.99 U.S.”, including the dollar sign, comma, periods, letters, and numbers, is a string. Although strings can contain numbers, numeric values cannot contain alphabetic characters. The numeric constant 43 and the string constant “Amanda” are examples of unnamed constants—they do not have identifiers like variables do.

Watch the video Declaring Variables and Constants.

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

C H A P T E R 2 Elements of High-Quality Programs

Working with Variables Variables are named memory locations whose contents can vary or differ over time. For example, in the number-doubling program in Figure 2-1, myNumber and myAnswer are variables. At any moment in time, a variable holds just one value. Sometimes, myNumber holds 2 and myAnswer holds 4; at other times, myNumber holds 6 and myAnswer holds 12. The ability 40 of variables to change in value is what makes computers and programming worthwhile. Because one memory location can be used repeatedly with different values, you can write program instructions once and then use them for thousands of separate calculations. One set of payroll instructions at your company produces each employee paycheck, and one set of instructions at your electric company produces each household’s bill.

start

stop

input myNumber

output myAnswer

set myAnswer =

myNumber * 2

start

input myNumber

set myAnswer = myNumber * 2

output myAnswer

stop

Figure 2-1 Flowchart and pseudocode for the number-doubling program © 2015 Cengage Learning

In most programming languages, before you can use any variable, you must include a declaration for it. A declaration is a statement that provides a data type and an identifier for a variable. An identifier is a program component’s name. A data item’s data type is a classification that describes the following:

What values can be held by the item

How the item is stored in computer memory

What operations can be performed on the item

As mentioned earlier, most programming languages support several data types, but in this book, only two data types will be used: num and string.

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

41

Declaring and Using Variables and Constants

When you declare a variable, you provide both a data type and an identifier. Optionally, you can declare a starting value for any variable. Declaring a starting value is known as initializing the variable. For example, each of the following statements is a valid declaration. Two of the statements include initializations, and two do not:

num mySalary num yourSalary = 14.55 string myName string yourName = "Juanita"

Figure 2-2 shows the number-doubling program from Figure 2-1 with the added declarations shaded. Variables must be declared before they are used for the first time in a program. Some languages require all variables to be declared at the beginning of the program, others allow variables to be declared at the beginning of each module, and others allow variables to be declared anywhere at all as long as they are declared before their first use. This book will follow the convention of declaring all variables together.

stop

input myNumber

output myAnswer

set myAnswer = myNumber * 2

Declarations num myNumber num myAnswer

start

start

Declarations

num myNumber

num myAnswer

input myNumber

set myAnswer = myNumber * 2

output myAnswer

stop

Figure 2-2 Flowchart and pseudocode of number-doubling program with variable declarations © 2015 Cengage Learning

In many programming languages, if you declare a variable and do not initialize it, the variable contains an unknown value until it is assigned a value. A variable’s unknown value commonly is called garbage. Although some languages use a default value for some variables (such as assigning 0 to any unassigned numeric variable), this book will assume that an unassigned variable holds garbage. In many languages it is illegal to use a garbage-holding variable in an arithmetic statement or to display it as output. Even if you work with a language that allows you to display garbage, it serves no purpose to do so and constitutes a logical error.

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

C H A P T E R 2 Elements of High-Quality Programs

When you create a variable without assigning it an initial value (as with myNumber and myAnswer in Figure 2-2), your intention is to assign a value later—for example, by receiving one as input or placing the result of a calculation there.

Naming Variables 42 The number-doubling example in Figure 2-2 requires two variables: myNumber and myAnswer. Alternatively, these variables could be named userEntry and programSolution, or inputValue and twiceTheValue. As a programmer, you choose reasonable and descriptive names for your variables. The language translator (interpreter or compiler) then associates the names you choose with specific memory addresses.

Every computer programming language has its own set of rules for creating identifiers. Most languages allow letters and digits within identifiers. Some languages allow hyphens in variable names, such as hourly-wage, and some allow underscores, as in hourly_wage. Some languages allow dollar signs or other special characters in variable names (for example, hourly$); others allow foreign-alphabet characters, such as ˛ or �. Each programming language has a few (perhaps 100 to 200) reserved keywords that are not allowed as variable names because they are part of the language’s syntax. For example, the data type names in a language, such as num and string, would not be allowed as variable names. When you learn a programming language, you will learn its list of keywords.

Different languages put different limits on the length of variable names, although in general, the length of identifiers in newer languages is virtually unlimited. In the oldest computer languages, all variable names were written using all uppercase letters because the keypunch machines used at that time created only uppercase letters. In most modern languages, identifiers are case sensitive, so HoUrLyWaGe, hourlywage, and hourlyWage are three separate variable names. Programmers use multiple conventions for naming variables, often depending on the programming language or standards adopted by their employers. Quick Reference 2-1 describes commonly used variable naming conventions.

QUICK REFERENCE 2-1 Variable Naming Conventions

Languages where Convention for naming variables Examples commonly used

Camel casing is the convention in which hourlyWage Java, C# the variable starts with a lowercase letter lastName and any subsequent word begins with an uppercase letter. It is sometimes called lower camel casing to emphasize the difference from Pascal casing.

(continues)

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

43

Declaring and Using Variables and Constants

(continues)

Languages where Convention for naming variables Examples commonly used

Pascal casing is a convention in which HourlyWage Visual Basic the first letter of a variable name is LastName uppercase. It is sometimes called upper camel casing to distinguish it from lower camel casing.

Hungarian notation is a form of camel numHourlyWage C for Windows API casing in which a variable’s data type is stringLastName programming part of the identifier.

Snake casing is a convention in which hourly_wage C, C++, Python, Ruby parts of a variable name are separated last_name by underscores.

Mixed case with underscores is a Hourly_Wage Ada variable naming convention similar to Last_Name snake casing, but new words start with an uppercase letter.

Kebob case is sometimes used as the hourly-wage Lisp (with lowercase name for the style that uses dashes to last-name letters), COBOL (with separate parts of a variable name. The uppercase letters) name derives from the fact that the words look like pieces of food on a skewer.

Adopting a naming convention for variables and using it consistently will help make your programs easier to read and understand.

Even though every language has its own rules for naming variables, you should not concern yourself with the specific syntax of any particular computer language when designing the logic of a program. The logic, after all, works with any language. The variable names used throughout this book follow only three rules:

1. Variable names must be one word. The name can contain letters, digits, hyphens, or underscores. No language allows embedded spaces in variable names, and most do not allow punctuation such as periods, commas, or colons. This book uses only alphabetic letters, digits, and underscores in variable names. Therefore, r is a legal variable name, as are rate and interestRate. The variable name interest rate is not allowed because of the space.

2. Variable names must start with a letter. Some programming languages allow variable names to start with a nonalphabetic character such as an underscore. Almost all programming languages prohibit variable names that start with a digit. This book follows the most common convention of starting variable names with a letter.

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

C H A P T E R 2 Elements of High-Quality Programs

3.

When you write a program using an editor that is packaged with a compiler in an IDE, the compiler may display variable names in a different color from other program components. This visual aid helps your variable names stand out from words that are part of the programming language.

Variable names should have some appropriate meaning. This is not a formal rule 44

of any programming language. When computing an interest rate in a program, the computer does not care if you call the variable g, u84, or fred. As long as the correct numeric result is placed in the variable, its actual name doesn’t matter. However, it’s much easier to follow the logic of a statement like set interestEarned = initialInvestment * interestRate than a statement like set f = i * r or set someBanana = j89 * myFriendLinda. When a program requires changes, which could be months or years after you write the original version, you and your fellow programmers will appreciate clear, descriptive variable names in place of cryptic identifiers. Later in this chapter, you will learn more about selecting good identifiers.

Notice that the flowchart in Figure 2-2 follows the preceding rules for variables: Both variable names, myNumber and myAnswer, are single words without embedded spaces, and they have appropriate meanings. Some programmers name variables after friends or create puns with them, but computer professionals consider such behavior unprofessional and amateurish.

Assigning Values to Variables When you create a flowchart or pseudocode for a program that doubles numbers, you can include a statement such as the following:

set myAnswer = myNumber * 2

Such a statement is an assignment statement. This statement incorporates two actions. First, the computer calculates the arithmetic value of myNumber * 2. Second, the computed value is stored in the myAnswer memory location.

The equal sign is the assignment operator. The assignment operator is an example of a binary operator, meaning it requires two operands—one on each side. (An operand is simply a value used by an operator.) The assignment operator always operates from right to left, which means that it has right-associativity or right-to-left associativity. This means that the value of the expression to the right of the assignment operator is evaluated first, and then the result is assigned to the operand on the left. The operand to the right of an assignment operator must be a value—for example, a named or unnamed constant or an arithmetic expression. The operand to the left of an assignment operator must be a name that represents a memory address—the name of the location where the result will be stored.

For example, if you have declared two numeric variables named someNumber and someOtherNumber, then each of the following is a valid assignment statement:

set someNumber = 2 set someNumber = 3 + 7 set someOtherNumber = someNumber set someOtherNumber = someNumber * 5

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

45

Declaring and Using Variables and Constants

In each case, the expression to the right of the assignment operator is evaluated and stored at the location referenced on the left side. The result to the left of an assignment operator is called an lvalue. The l is for left. Lvalues are always memory address identifiers.

The following statements, however, are not valid:

set 2 + 4 = someNumber set someOtherNumber * 10 = someNumber set someNumber + someOtherNumber = 10

Don’t Do It The operand to the left of an assignment operator must represent a memory address.

In each of these cases, the value to the left of the assignment operator is not a memory address, so the statements are invalid.

When you write pseudocode or draw a flowchart, it might help you to use the word set in assignment statements, as shown in these examples, to emphasize that the left-side value is being set. However, in most programming languages, the word set is not used, and assignment statements take the following simpler form:

someNumber = 2 someOtherNumber = someNumber

Because the abbreviated form is how assignments appear in most languages, this convention is used for the rest of this book.

Understanding the Data Types of Variables Computers handle string data differently from the way they handle numeric data. You may have experienced these differences if you have used application software such as spreadsheets or database programs. For example, in a spreadsheet, you cannot sum a column of words. Similarly, every programming language requires that you specify the correct type for each variable, and that you use each type appropriately.

A numeric variable is one that can hold digits and have mathematical operations performed on it. In this book, all numeric variables can hold a decimal point and a sign indicating positive or negative; some programming languages provide specialized numeric types for these options. In the statement myAnswer = myNumber * 2, both myAnswer and myNumber are numeric variables; that is, their intended contents are numeric values, such as 6 and 3, 14.8 and 7.4, or –18 and –9.

A string variable can hold text, such as letters of the alphabet, and other special characters, such as punctuation marks. If a working program contains the statement lastName = "Lincoln", then lastName is a string variable. A string variable also can hold digits either with or without other characters. For example, “235 Main Street” and “86” are both strings. A string like “86” is stored differently than the numeric value 86, and you cannot perform arithmetic with the string. Programmers frequently use strings to hold digits when they will never be used in arithmetic statements–for example, an account number or a zip code.

Type-safety is the feature of some programming languages that prevents assigning values of an incorrect data type. You can assign data to a variable only if it is the correct type. (Such

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

C H A P T E R 2

Elements of High-Quality Programs

languages are called strongly typed.) If you declare taxRate as a numeric variable and inventoryItem as a string, then the following statements are valid:

taxRate = 2.5 inventoryItem = "monitor"

The following are invalid because the type of data being assigned does not match the variable 46 type:

taxRate = "2.5" inventoryItem = 2.5 taxRate = inventoryItem inventoryItem = taxRate

Don’t Do It If taxRate is numeric and inventoryItem is a string, then these assignments are invalid.

Watch the video Understanding Data Types.

Declaring Named Constants Besides variables, most programming languages allow you to create named constants. A named constant is similar to a variable, except it can be assigned a value only once. You use a named constant when you want to assign a useful name for a value that will never be changed during a program’s execution. Using named constants makes your programs easier to understand by eliminating magic numbers. A magic number is an unnamed constant, like 0.06, whose purpose is not immediately apparent.

For example, if a program uses a sales tax rate of 6 percent, you might want to declare a named constant as follows:

num SALES_TAX_RATE = 0.06

After SALES_TAX_RATE is declared, the following statements have identical meaning:

taxAmount = price * 0.06 taxAmount = price * SALES_TAX_RATE

The way in which named constants are declared differs among programming languages. This book follows the convention of using all uppercase letters in constant identifiers, and using underscores to separate words for readability. Using these conventions makes named constants easier to recognize. In many languages a constant must be assigned its value when it is declared, but in some languages a constant can be assigned its value later. In both cases, however, a constant’s value cannot be changed after the first assignment. This book follows the convention of initializing all constants when they are declared.

When you declare a named constant, program maintenance becomes easier. For example, if the value of the sales tax rate changes from 0.06 to 0.07 in the future, and you have declared a named constant SALES_TAX_RATE, you only need to change the value assigned to the named constant at the beginning of the program, then retranslate the program into machine language, and all references to SALES_TAX_RATE are automatically updated. If you used the unnamed literal 0.06 instead, you would have to search for every instance of the value and

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

47

Performing Arithmetic Operations

replace it with the new one. Additionally, if the literal 0.06 was used in other calculations within the program (for example, as a discount rate or price), you would have to carefully select which instances of the value to alter, and you would be likely to make a mistake.

Sometimes, using unnamed literal constants is appropriate in a program, especially if their meaning is clear to most readers. For example, in a program that calculates half of a value by dividing by two, you might choose to use the unnamed literal 2 instead of incurring the extra time and memory costs of creating a named constant HALF and assigning 2 to it. Extra costs that result from adding variables or instructions to a program are known as overhead.

TWO TRUTHS & A LIE Declaring and Using Variables and Constants

1. A variable’s data type describes the kind of values the variable can hold and the types of operations that can be performed with it.

2. If name is a string variable, then the statement set name = "Ed" is valid.

3. The operand to the right of an assignment operator must be a name that represents a memory address.

The false statement is #3. The operand to the left of an assignment operator must be a name that represents a memory address—the name of the location where the result will be stored. The value to the right of an assignment operator might be a constant, arithmetic expression, or other value.

Performing Arithmetic Operations Most programming languages use the following standard arithmetic operators:

+ (plus sign)—addition

– (minus sign)—subtraction

* (asterisk)—multiplication

/ (slash)—division

Many languages also support additional operators that calculate the remainder after division, raise a number to a power, manipulate individual bits stored within a value, and perform other operations.

Each of the standard arithmetic operators is a binary operator; that is, each requires an expression on both sides. For example, the following statement adds two test scores and assigns the sum to a variable named totalScore:

totalScore = test1 + test2

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

C H A P T E R 2 Elements of High-Quality Programs

The following adds 10 to totalScore and stores the result in totalScore:

totalScore = totalScore + 10

In other words, this example increases the value of totalScore. This last example looks odd in algebra because it might appear that the value of totalScore and totalScore plus 10 are equivalent. You must remember that the equal sign is the assignment operator, and that the statement is actually taking the original value of totalScore, adding 10 to it, and assigning the result to the memory address on the left of the operator, which is totalScore.

In programming languages, you can combine arithmetic statements. When you do, every operator follows rules of precedence (also called the order of operations) that dictate the order in which operations in the same statement are carried out. The rules of precedence for the basic arithmetic statements are as follows:

Expressions within parentheses are evaluated first. If there are multiple sets of parentheses, the expression within the innermost parentheses is evaluated first.

Multiplication and division are evaluated next, from left to right.

Addition and subtraction are evaluated next, from left to right.

The assignment operator has a very low precedence. Therefore, in a statement such as d = e * f + g, the operations on the right of the assignment operator are always performed before the final assignment to the variable on the left.

48

When you learn a specific programming language, you will learn about all the operators that are used in that language. Many programming language books contain a table that specifies the relative precedence of every operator used in the language.

For example, consider the following two arithmetic statements:

firstAnswer = 2 + 3 * 4 secondAnswer = (2 + 3) * 4

After these statements execute, the value of firstAnswer is 14. According to the rules of precedence, multiplication is carried out before addition, so 3 is multiplied by 4, giving 12, and then 2 and 12 are added, and 14 is assigned to firstAnswer. The value of secondAnswer, however, is 20, because the parentheses force the contained addition operation to be performed first. The 2 and 3 are added, producing 5, and then 5 is multiplied by 4, producing 20.

Forgetting about the rules of arithmetic precedence, or forgetting to add parentheses when you need them, can cause logical errors that are difficult to find in programs. For example, the following statement might appear to average two test scores:

average = score1 + score2 / 2

However, it does not. Because division has a higher precedence than addition, the preceding statement takes half of score2, adds it to score1, and stores the result in average. The correct statement is: average = (score1 + score2) / 2

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

49

Performing Arithmetic Operations

You are free to add parentheses even when you don’t need them to force a different order of operations; sometimes you use them just to make your intentions clearer. For example, the following statements operate identically: totalPriceWithTax = price + price * TAX_RATE totalPriceWithTax = price + (price * TAX_RATE)

In both cases, price is multiplied by TAX_RATE first, then it is added to price, and finally the result is stored in totalPriceWithTax. Because multiplication occurs before addition on the right side of the assignment operator, both statements are the same. However, if you feel that the statement with the parentheses makes your intentions clearer to someone reading your program, then you should use them.

All the arithmetic operators have left-to-right associativity. This means that operations with the same precedence take place from left to right. Consider the following statement: answer = a + b + c * d / e – f

Multiplication and division have higher precedence than addition or subtraction, so the multiplication and division are carried out from left to right as follows:

c is multiplied by d, and the result is divided by e, giving a new result.

Therefore, the statement becomes: answer = a + b + (temporary result just calculated) – f

Then, addition and subtraction are carried out from left to right as follows:

a and b are added, the temporary result is added, and then f is subtracted. The final result is then assigned to answer.

Another way to say this is that the following two statements are equivalent: answer = a + b + c * d / e – f answer = a + b + ((c * d) / e) – f

Quick Reference 2-2 summarizes the precedence and associativity of the five most frequently used operators.

QUICK REFERENCE 2-2 Precedence and Associativity of Five Common Operators

Operator Precedence (compared to other symbol Operator name operators in this table) Associativity = Assignment Lowest Right-to-left

+ Addition Medium Left-to-right

- Subtraction Medium Left-to-right

* Multiplication Highest Left-to-right

/ Division Highest Left-to-right

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

C H A P T E R 2 Elements of High-Quality Programs

Watch the video Arithmetic Operator Precedence.

The Integer Data Type 50

As mentioned earlier in this chapter, many modern programming languages allow programmers to make fine distinctions between numeric data types. In particular, many languages treat integer numeric values (whole numbers) and floating-point numeric values (numbers with decimal places) differently. In these languages, you can always assign an integer, such as 3, to a floating-point variable or named constant, and it will be converted to 3.0. However, you cannot assign a floating-point value (such as 3.0) directly to an integer variable, because the decimal position values will be lost, even when they are 0.

When you work with a language that makes distinctions between integer and floating-point values, you can combine the different types in arithmetic expressions. When you do, addition, subtraction, and multiplication work as expected. For example, the result of 2.3 + 5 is 7.3, and the result of 4.2 * 2 is 8.4. When you mix types, division works as expected as well. For example, the result of 9.3 / 3 is 3.1.

However, in many languages, dividing an integer by another integer is a special case. In languages such as Java, C++, and C#, dividing two integers results in an integer, and any fractional part of the result is lost. For example, in these languages, the result of 7 / 2 is 3, not 3.5 as you might expect. Programmers say that the decimal portion of the result is cut off, or truncated.

When programming in a language that truncates the results of integer division, you must be particularly careful with numbers lower than 1. For example, if you write a program that halves a recipe, you might use an expression such as 1 / 2 * cupsSugar. No matter what the value of cupsSugar is, the result will always be 0 because 2 goes into 1 zero whole times.

Many programming languages also support a remainder operator, which is sometimes called the modulo operator or the modulus operator. When used with two integer operands, the remainder operator is the value that remains after division. For example, 24 Mod 10 is 4 because when 24 is divided by 10, 4 is the remainder. In Visual Basic, the remainder operator is the keyword Mod. In Java, C++, and C#, the operator is the percent sign (%).

The remainder operator can be useful in a variety of situations. For example, you can determine whether a number is even or odd by finding the remainder when the number is divided by 2. Any number that has a remainder of 0 is even, and any number with a remainder of 1 is odd.

Because the remainder operator differs among programming languages, and because the operation itself is handled differently when used with negative operands, the remainder operator will not be used in the rest of this language-independent book. Similarly, this book uses one data type, num, for all numeric values, and it is assumed that both integer and floating-point values can be stored in num variables and named constants.

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

51

Understanding the Advantages of Modularization

TWO TRUTHS & A LIE Performing Arithmetic Operations

1. Parentheses have higher precedence than any of the common arithmetic operators.

2. Operations in arithmetic statements occur from left to right in the order in which they appear.

3. The following adds 5 to a variable named points:

points = points + 5

The false statement is #2. Operations of equal precedence in an arithmetic statement are carried out from left to right, but operations within parentheses are carried out first, multiplication and division are carried out next, and addition and subtraction take place last.

Understanding the Advantages of Modularization Programmers seldom write programs as one long series of steps. Instead, they break down their programming problems into smaller units and tackle one cohesive task at a time. These smaller units are modules. Programmers also refer to them as subroutines, procedures, functions, or methods; the name usually reflects the programming language being used. For example, Visual Basic programmers use procedure (or subprocedure). C and C++ programmers call their modules functions, whereas C#, Java, and other object- oriented language programmers are more likely to use method. Programmers in COBOL, RPG, and BASIC (all older languages) are most likely to use subroutine.

You can learn about modules that receive and return data in Chapter 9 of the comprehensive version of this book.

A main program executes a module by calling it. To call a module is to use its name to invoke the module, causing it to execute. When the module’s tasks are complete, control returns to the spot from which the module was called in the main program. When you access a module, the action is similar to putting a DVD player on pause. You abandon your primary action (watching a video), take care of some other task (for example, making a sandwich), and then return to the main task exactly where you left off.

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

C H A P T E R 2 Elements of High-Quality Programs

The process of breaking down a large program into modules is modularization; computer scientists also call it functional decomposition. You are never required to modularize a large program to make it run on a computer, but there are at least three reasons for doing so:

Modularization provides abstraction. 52

Modularization helps multiple programmers to work on a problem.

Modularization allows you to reuse work more easily.

Modularization Provides Abstraction One reason that modularized programs are easier to understand is that they enable a programmer to see the “big picture.” Abstraction is the process of paying attention to important properties while ignoring nonessential details. Abstraction is selective ignorance. Life would be tedious without abstraction. For example, you can create a list of things to accomplish today:

Do laundry Call Aunt Nan Start term paper

Without abstraction, the list of chores would begin:

Pick up laundry basket Put laundry basket in car Drive to Laundromat Get out of car with basket Walk into Laundromat Set basket down Find quarters for washing machine … and so on.

You might list a dozen more steps before you finish the laundry and move on to the second chore on your original list. If you had to consider every small, low-level detail of every task in your day, you would probably never make it out of bed in the morning. Using a higher-level, more abstract list makes your day manageable. Abstraction makes complex tasks look simple.

Abstract artists create paintings in which they see only the big picture—color and form—and ignore the details. Abstraction has a similar meaning among programmers.

Likewise, some level of abstraction occurs in every computer program. Fifty years ago, a programmer had to understand the low-level circuitry instructions the computer used. But now, newer high-level programming languages allow you to use English-like vocabulary in which one broad statement corresponds to dozens of machine instructions. No matter which high-level programming language you use, if you display a message on the monitor, you are never required to understand how a monitor works to create each pixel on the screen. You

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

53

Understanding the Advantages of Modularization

write an instruction like output message and the details of the hardware operations are handled for you by the operating system.

Modules provide another way to achieve abstraction. For example, a payroll program can call a module named computeFederalWithholdingTax(). When you call this module from your program, you use one statement; the module itself might contain dozens of statements. You can write the mathematical details of the module later, someone else can write them, or you can purchase them from an outside source. When you plan your main payroll program, your only concern is that a federal withholding tax will have to be calculated; you save the details for later.

Modularization Helps Multiple Programmers to Work on a Problem When you divide any large task into modules, you gain the ability to more easily divide the task among various people. Rarely does a single programmer write a commercial program that you buy. Consider any word-processing, spreadsheet, or database program you have used. Each program has so many options, and responds to user selections in so many possible ways, that it would take years for a single programmer to write all the instructions. Professional software developers can write new programs in weeks or months, instead of years, by dividing large programs into modules and assigning each module to an individual programmer or team.

Modularization Allows You to Reuse Work If a module is useful and well written, you may want to use it more than once within a program or in other programs. For example, a routine that verifies the validity of dates is useful in many programs written for a business. (For example, a month value is valid if it is not lower than 1 or higher than 12, a day value is valid if it is not lower than 1 or higher than 31 if the month is 1, and so on.) If a computerized personnel file contains each employee’s birth date, hire date, last promotion date, and termination date, the date-validation module can be used four times with each employee record. Other programs in an organization can also use the module; these programs might ship customer orders, plan employees’ birthday parties, or calculate when loan payments should be made. If you write the date-checking instructions so they are entangled with other statements in a program, they are difficult to isolate and reuse. On the other hand, if you place the instructions in a separate module, the unit is easy to use and portable to other applications. The feature of modular programs that allows individual modules to be used in a variety of applications is reusability.

You can find many real-world examples of reusability. When you build a house, you don’t invent plumbing and heating systems; you incorporate systems with proven designs. This certainly reduces the time and effort it takes to build a house. The systems you choose are in service in other houses, so they have been tested under a variety of circumstances, increasing their reliability. Reliability is the feature of programs that assures you a module has been proven to function correctly. Reliable software saves time and money. If you create the

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

C H A P T E R 2 Elements of High-Quality Programs

functional components of your programs as stand-alone modules and test them in your current programs, much of the work will already be done when you use the modules in future applications.

54 TWO TRUTHS & A LIE Understanding the Advantages of Modularization

1. Modularization eliminates abstraction, a feature that makes programs more confusing.

2. Modularization makes it easier for multiple programmers to work on a problem.

3. Modularization allows you to reuse work more easily.

The false statement is #1. Modularization enables abstraction, which allows you to see the big picture.

Modularizing a Program Most programs consist of a main program, which contains the basic steps, or the mainline logic, of the program. The main program then accesses modules that provide more refined details.

When you create a module, you include the following:

A header—The module header includes the module identifier and possibly other necessary identifying information.

A body—The module body contains all the statements in the module.

A return statement—The module return statement marks the end of the module and identifies the point at which control returns to the program or module that called the module. In most programming languages, if you do not include a return statement at the end of a module, the logic will still return. However, this book follows the convention of explicitly including a return statement with every module.

Naming a module is similar to naming a variable. The rules and conventions for naming modules are slightly different in every programming language, but in this text, module names follow the same general rules used for variable identifiers:

Module names must start with a letter and cannot contain spaces.

Module names should have some meaning.

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

55

Modularizing a Program

Although it is not a requirement of any programming language, it frequently makes sense to use a verb as all or part of a module’s name, because modules perform some action. Typical module names begin with action words such as get, calculate, and display. When you program in visual languages that use screen components such as buttons and text boxes, the module names frequently contain verbs representing user actions, such as click or drag.

Additionally, in this text, module names are followed by a set of parentheses. This will help you distinguish module names from variable names. This style corresponds to the way modules are named in many programming languages, such as Java, C++, and C#.

As you learn more about modules in specific programming languages, you will find that you sometimes place variable names within the parentheses that follow module names. Any variables enclosed in the parentheses contain information you want to send to the module. For now, the parentheses at the end of module names will be empty in this book.

When a main program wants to use a module, it calls the module. A module can call another module, and the called module can call another. The number of chained calls is limited only by the amount of memory available on your computer. In this book, the flowchart symbol used to call a module is a rectangle with a bar across the top. You place the name of the module you are calling inside the rectangle.

Some programmers use a rectangle with stripes down each side to represent a module in a flowchart, and this book uses that convention if a module is external to a program. For example, prewritten, built-in modules that generate random numbers, compute standard trigonometric functions, and sort values often are external to your programs. However, if the module is being created as part of the program, the book uses a rectangle with a single stripe across the top.

In a flowchart, you draw each module separately with its own sentinel symbols. The beginning sentinel contains the name of the module. This name must be identical to the name used in the calling program or module. The ending sentinel contains return, which indicates that when the module ends, the logical progression of statements will exit the module and return to the calling program or module. Similarly, in pseudocode, you start each module with its name and end with a return statement; the module name and return statements are vertically aligned and all the module statements are indented between them.

For example, consider the program in Figure 2-3, which does not contain any modules. It accepts a customer’s name and balance due as input and produces a bill. At the top of the bill, the company’s name and address are displayed on three lines, which are followed by the customer’s name and balance due. To display the company name and address, you can simply include three output statements in the mainline logic of a program, as shown in Figure 2-3, or you can modularize the program by creating both the mainline logic and a displayAddressInfo() module, as shown in Figure 2-4.

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

C H A P T E R 2 Elements of High-Quality Programs

start

input name, balance

Declarations string name num balance

output "ABC Manufacturing"

56

output "Total: ", balance

output "Omro, WI 54963"

output "Customer: ", name

output "47 Park Lane"

stop

In an interactive program, you would add prompts such as Please enter name and Please enter balance. These have been omitted here to keep the example short. You will learn more about prompts later in this chapter.

start

Declarations

string name

num balance

input name, balance

output "ABC Manufacturing"

output "47 Park Lane"

output "Omro, WI 54963"

output "Customer: ", name

output "Total: ", balance

stop

Figure 2-3 Program that produces a bill using only main program © 2015 Cengage Learning

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

Modularizing a Program

output "Total: ", balance

output "Omro, WI 54963"

output "Customer: ", name

stop return

input name, balance

output "47 Park Lane"

Declarations string name num balance

start

displayAddressInfo()

output "ABC Manufacturing"

displayAddressInfo()

57

start

Declarations

string name

num balance

input name, balance

displayAddressInfo()

output "Customer: ", name

output "Total: ", balance

stop

displayAddressInfo() output "ABC Manufacturing"

output "47 Park Lane"

output "Omro, WI 54963" return

Figure 2-4 Program that produces a bill using main program that calls displayAddressInfo() module © 2015 Cengage Learning

When the displayAddressInfo() module is called in Figure 2-4, logic transfers from the main program to the displayAddressInfo() module, as shown by the large red arrow in both the flowchart and the pseudocode. There, each module statement executes in turn before logical control is transferred back to the main program, where it continues with the

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

C H A P T E R 2 Elements of High-Quality Programs

statement that follows the module call, as shown by the large blue arrow. Programmers say the statements that are contained in a module have been encapsulated.

Neither of the programs in Figures 2-3 and 2-4 is superior to the other in terms of functionality; both perform exactly the same tasks in the same order. However, you may prefer the modularized version of the program for at least two reasons:

58 First, the main program remains short and easy to follow because it contains just one statement to call the module, rather than three separate output statements to perform the work of the module.

Second, a module is easy to reuse. After you create the address information module, you can use it in any application that needs the company’s name and address. In other words, you do the work once, and then you can use the module many times.

A potential drawback to creating modules and moving between them is the overhead incurred. The computer keeps track of the correct memory address to which it should return after executing a module by recording the memory address in a location known as the stack. This process requires a small amount of computer time and resources. In most cases, the advantage to creating modules far outweighs the small amount of overhead required.

Determining when to modularize a program does not depend on a fixed set of rules; it requires experience and insight. Programmers do follow some guidelines when deciding how far to break down modules or how much to put in each of them. Some companies may have arbitrary rules, such as “a module’s instructions should never take more than a page,” or “a module should never have more than 30 statements,” or “never have a module with only one statement.” Rather than use such arbitrary rules, a better policy is to place together statements that contribute to one specific task. The more the statements contribute to the same job, the greater the functional cohesion of the module. A module that checks the validity of a date variable’s value, or one that asks a user for a value and accepts it as input, is considered cohesive. A module that checks date validity, deducts insurance premiums, and computes federal withholding tax for an employee would be less cohesive.

Chapter 9 of the comprehensive version of this book provides more information on designing modules for high cohesion. It also explores the topic of coupling, which is a measure of how much modules depend on each other.

Watch the video Modularizing a Program.

Declaring Variables and Constants within Modules You can place any statements within modules, including input, processing, and output statements. You also can include variable and constant declarations within modules. For example, you might decide to modify the billing program in Figure 2-4 so it looks like the one

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

59

Modularizing a Program

in Figure 2-5. In this version of the program, three named constants that hold the three lines of company data are declared within the displayAddressInfo() module. (See shading.)

output "Total: ", balance

output "Customer: ", name

stop

input name, balance

output LINE1

output LINE2

Declarations string name num balance

Declarations

string LINE1 = "ABC Manufacturing"

string LINE2 = "47 Park Lane"

string LINE3 = "Omro, WI 54963"

displayAddressInfo()

start displayAddressInfo()

start Declarations

string name num balance

input name, balance displayAddressInfo()

output "Customer: ", name

output "Total: ", balance stop

displayAddressInfo() Declarations

string LINE1 = "ABC Manufacturing"

string LINE2 = "47 Park Lane"

string LINE3 = "Omro, WI 54963" output LINE1 output LINE2 output LINE3 return

return

output LINE3

Figure 2-5 The billing program with constants declared within the module © 2015 Cengage Learning

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

C H A P T E R 2 Elements of High-Quality Programs

Variables and constants are usable only in the module in which they are declared. Programmers say the data items are visible or in scope only within the module in which they are declared. That means the program only recognizes them there. Programmers also say that variables and constants are local to the module in which they are declared. In other words, when the strings LINE1, LINE2, and LINE3 are declared in the displayAddressInfo()

60 module in Figure 2-5, they are not recognized and cannot be used by the main module.

One of the motivations for creating modules is that separate modules are easily reusable in multiple programs. If the displayAddressInfo() module will be used by several programs within the organization, it makes sense that the definitions for its variables and constants must come with it. This makes the modules more portable; that is, they are self-contained units that are easily transported.

Besides local variables and constants, you can create global variables and constants. Global variables and constants are known to the entire program; they are said to be declared at the program level. That means they are visible to and usable in all the modules called by the program. The opposite is not true—variables and constants declared within a module are not usable elsewhere; they are visible only to that module.

In many modern programming languages, the main program itself is a module, so variables and constants declared there cannot be used elsewhere. To make the examples in this book easier to follow, variables and constants declared at the start of a main program will be considered global and usable in all modules. Until Chapter 9 in the comprehensive version, this book will use only global variables and constants so that you can concentrate on the main logic and not yet be concerned with the techniques necessary to make one module’s data available to another. For example, in Figure 2-5, the main program variables name and balance are global variables and could be used by any module.

Many programmers do not approve of using global variables and constants. They are used here so you can more easily understand modularization before you learn the techniques of sending local variables from one module to another. Chapter 9 of the comprehensive version of this book will describe how you can make every variable local.

Understanding the Most Common Configuration for Mainline Logic In Chapter 1, you learned that a procedural program contains procedures that follow one another in sequence. The mainline logic of almost every procedural computer program can follow a general structure that consists of three distinct parts:

1. Housekeeping tasks include any steps you must perform at the beginning of a program to get ready for the rest of the program. They can include tasks such as variable and constant declarations, displaying instructions to users, displaying report headings, opening any files the program requires, and inputting the first piece of data.

Inputting the first data item is always part of the housekeeping module. You will learn the theory behind this practice in Chapter 3. Chapter 7 covers file handling, including what it means to open and close a file.

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

61

Modularizing a Program

2. Detail loop tasks do the core work of the program. When a program processes many records, detail loop tasks execute repeatedly for each set of input data until there are no more. For example, in a payroll program, the same set of calculations is executed repeatedly until a check has been produced for each employee.

3. End-of-job tasks are the steps you take at the end of the program to finish the application. You can call these finish-up or clean-up tasks. They might include displaying totals or other final messages and closing any open files.

Figure 2-6 shows the relationship of these three typical program parts. Notice how the housekeeping() and endOfJob() tasks are executed just once, but the detailLoop() tasks repeat as long as the eof condition has not been met. The flowchart uses a flowline to show how the detailLoop() module repeats; the pseudocode uses the words while and endwhile to contain statements that execute in a loop. You will learn more about the while and endwhile terms in subsequent chapters; for now, understand that they are a way of expressing repeated actions.

stop

Yes

No

not eof?

start

Declarations

housekeeping()

endOfJob()

detailLoop()

start

Declarations

housekeeping()

while not eof

detailLoop()

endwhile

endOfJob()

stop

Figure 2-6 Flowchart and pseudocode of mainline logic for a typical procedural program © 2015 Cengage Learning

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

C H A P T E R 2 Elements of High-Quality Programs

Many everyday tasks follow the three-module format just described. For example, a candy factory opens in the morning, and the machines are started and filled with ingredients. These housekeeping tasks occur just once at the start of the day. Then, repeatedly during the day, candy is manufactured. This process might take many steps, each of which occurs many times. These are the steps in the detail loop. Then, at the end of the day, the machines are

62 cleaned and shut down. These are the end-of-job tasks.

Not all programs take the format of the logic shown in Figure 2-6, but many do. Keep this general configuration in mind as you think about how you might organize many programs. For example, Figure 2-7 shows a sample payroll report for a small company. A user enters employee names until there are no more to enter, at which point the user enters XXX. As long as the entered name is not XXX, the user enters the employee’s weekly gross pay. Deductions are computed as a flat 25 percent of the gross pay, and the statistics for each employee are output. The user enters another name, and as long as it is not XXX, the process continues. Examine the logic in Figure 2-8 to identify the components in the housekeeping, detail loop, and end-of-job tasks. You will learn more about the payroll report program in the next few chapters. For now, concentrate on the big picture of how a typical application works.

Payroll Report

Name Gross Deductions Net

Andrews

Brown 350.00 1050.00

Carter 1275.00 318.75 956.25

Young

***End of report

1000.00 250.00 750.00

1400.00

1100.00 275.00 825.00

Figure 2-7 Sample payroll report © 2015 Cengage Learning

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

63

Modularizing a Program

start

Declarations string name num gross num deduct num net num RATE = 0.25 string QUIT = "XXX" string REPORT_HEADING = "Payroll Report" string COLUMN_HEADING = "Name Gross

Deductions Net" string END_LINE = "***End of report"

Figure 2-8 Logic for payroll report © 2015 Cengage Learning

housekeeping()

stop

return

Yes name not equal

to QUIT?

No

housekeeping()

endOfJob()

detailLoop()

detailLoop()

deduct = gross * RATE

input gross

output name, gross, deduct, net

input name

return

endOfJob()

return

output END_LINEnet = gross – deduct

Some programmers would not bother to create a module that contains only one or two statements. Instead, they would keep these statements in the mainline logic. The module is shown here so you can better see the big picture of how the mainline logic works using beginning, repeated, and ending tasks.

output REPORT_HEADING

output COLUMN_HEADING

input name

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

C H A P T E R 2 Elements of High-Quality Programs

TWO TRUTHS & A LIE Modularizing a Program

64 1. A calling program calls a module’s name when it wants to use the module.

2. Whenever a main program calls a module, the logic transfers to the module; when the module ends, the program ends.

3. Housekeeping tasks include any steps you must perform just once at the beginning of a program to get ready for the rest of the program.

Creating Hierarchy Charts You may have seen hierarchy charts for organizations, such as the one in Figure 2-9. The chart shows who reports to whom, not when or how often they report.

CEO

VP OF MARKETING VP OF INFORMATION The false statement is #2. When a module ends, the logical flow transfers back to the main calling module and resumes where it left off.

EASTERN SALES MANAGER

WESTERN SALES MANAGER

OPERATIONS MANAGER

PROGRAMMING MANAGER

SALES REP SALES REP SALES REP SALES REP SALES REP EVENING

OPERATOR PROGRAMMER PROGRAMMER

Figure 2-9 An organizational hierarchy chart © 2015 Cengage Learning

When a program has several modules calling other modules, programmers often use a program hierarchy chart (sometimes called a structure chart) that operates in a similar manner to show the overall picture of how modules are related to one another. A hierarchy chart does not tell you what tasks are to be performed within a module, when the modules are called, how a module executes, or why they are called—that information is in the flowchart or pseudocode. A hierarchy chart tells you only which modules exist within a program and which modules call

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

65

Figure 2-11 shows an example of a hierarchy chart for the billing program of a mail-order company. The hierarchy chart is for a more complicated program, but like the payroll report chart in Figure 2-10, it supplies module names and a general overview of the tasks to be performed, without specifying any details.

detailLoop() endOfJob()

processOrder()

checkInventory() checkCredit()

displaySummaries()

computeBill()

computeTax()

getOrder()

housekeeping()

main program

getOrder()

Creating Hierarchy Charts

others. The hierarchy chart for the program in Figure 2-8 looks like Figure 2-10. It shows that the main module calls three others—housekeeping(), detailLoop(), and endOfJob().

main program

housekeeping() detailLoop() endOfJob()

Figure 2-10 Hierarchy chart of payroll report program in Figure 2-8 © 2015 Cengage Learning

Figure 2-11 Billing program hierarchy chart © 2015 Cengage Learning

Because program modules are reusable, a specific module may be called from several locations within a program. For example, in the billing program hierarchy chart in Figure 2-11, you can see that the getOrder() module is used twice. By convention, you blacken a corner of each box that represents a module used more than once. This action alerts readers that any change to this module could have consequences in multiple locations.

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

C H A P T E R 2 Elements of High-Quality Programs

A hierarchy chart can be both a planning tool for developing the overall relationship of program modules before you write them and a documentation tool to help others see how modules are related after a program is written. For example, if a tax law changes, a programmer might be asked to rewrite the computeTax() module in the billing program diagrammed in Figure 2-11. As the programmer changes the computeTax() module, the

66 hierarchy chart shows other dependent modules that might be affected. A hierarchy chart is useful for getting the big picture in a complex program.

Hierarchy charts are used in procedural programming, but other types of diagrams frequently are used in object-oriented environments. Chapter 13 of the comprehensive edition of this book describes the Unified Modeling Language, which uses a set of diagrams to describe a system.

TWO TRUTHS & A LIE Creating Hierarchy Charts

1. You can use a hierarchy chart to illustrate modules’ relationships.

2. A hierarchy chart tells you what tasks are to be performed within a module.

3. A hierarchy chart tells you only which modules call other modules.

The false statement is #2. A hierarchy chart tells you nothing about tasks performed within a module; it only depicts how modules are related to each other.

Features of Good Program Design As your programs become larger and more complicated, the need for good planning and design increases. Think of an application you use, such as a word processor or a spreadsheet. The number and variety of user options are staggering. Not only would it be impossible for a single programmer to write such an application, but without thorough planning and design, the components would never work together properly. Ideally, each program module you design needs to work well as a stand-alone component and as an element of larger systems. Just as a house with poor plumbing or a car with bad brakes is fatally flawed, a computer- based application can be highly functional only if each component is designed well. Walking through your program’s logic on paper (called desk-checking, as you learned in Chapter 1) is an important step to achieving superior programs. Additionally, you can implement several design features while creating programs that are easier to write and maintain. To create good programs, you should do the following:

Provide program comments where appropriate.

Choose identifiers thoughtfully.

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

67

Features of Good Program Design

Strive to design clear statements within your programs and modules.

Write clear prompts and echo input.

Continue to maintain good programming habits as you develop your programming skills.

Using Program Comments When you write programs, you often might want to insert program comments. Program comments are written explanations that are not part of the program logic but that serve as documentation for readers of the program. In other words, they are nonexecuting statements that help readers understand programming statements. Readers might include users who help you test the program and other programmers who might have to modify your programs in the future. Even you, as the program’s author, will appreciate comments when you make future modifications and forget why you constructed a statement in a certain way.

The syntax used to create program comments differs among programming languages. This book starts comments in pseudocode with two forward slashes. For example, Figure 2-12 contains comments that explain the origins and purposes of variables in a real estate program.

Program comments are a type of internal documentation. This term distinguishes them from supporting documents outside the program, which are called external documentation. Appendix C discusses other types of documentation.

Declarations num sqFeet

// sqFeet is an estimate provided by the seller of the property num pricePerFoot

// pricePerFoot is determined by current market conditions num lotPremium

// lotPremium depends on amenities such as whether lot is waterfront

Figure 2-12 Pseudocode that declares variables and includes comments © 2015 Cengage Learning

In a flowchart, you can use an annotation symbol to hold information that expands on what is stored within another flowchart symbol. An annotation symbol is most often represented by a three-sided box that is connected to the step it references by a dashed line. Annotation symbols are used to hold comments or sometimes statements that are too long to fit neatly into a flowchart symbol. For example, Figure 2-13 shows how a programmer might use some annotation symbols in a flowchart for a payroll program.

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

C H A P T E R 2 Elements of High-Quality Programs

output PROMPT

input hours

pay = hours * RATE

Declarations string PROMPT = "Enter hours worked: " num hours num RATE = 13.00 num pay

stop

output pay

start

Program assumes all employees make the same standard hourly rate.

Note: RATE is expected to increase on January 1.

68

Figure 2-13 Flowchart that includes annotation symbols © 2015 Cengage Learning

You probably will use comments in your coded programs more frequently than you use them in pseudocode or flowcharts. For one thing, flowcharts and pseudocode are more English-like than the code in some languages, so your statements might be less cryptic. Also, your comments will remain in the program as part of the program documentation, but your planning tools are likely to be discarded once the program goes into production.

Including program comments is not necessary to create a working program, but comments can help you to remember the purpose of variables or to explain complicated calculations, especially when you come back to a program months or years after writing it. Some students do not like to include comments in their programs because it takes time to type them and they aren’t part of the “real” program, but the programs you write in the future probably will require some comments. When you acquire your first programming job and modify a program written by another programmer, you will appreciate well-placed comments that explain complicated sections of the code.

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

69

Features of Good Program Design

An additional responsibility regarding comments is that they must be kept current as a program is modified. Outdated comments can provide misleading information about a program’s status.

Choosing Identifiers The selection of good identifiers is an often-overlooked element in program design. When you write programs, you choose identifiers for variables, constants, and modules. You learned the rules for naming variables and modules earlier in this chapter: Each must be a single word with no embedded spaces and must start with a letter. Those simple rules provide a lot of leeway in naming program elements, but not all identifiers are equally good. Choosing good identifiers simplifies your programming job and makes it easier for others to understand your work.

Some general guidelines include the following:

Although not required in any programming language, it usually makes sense to give a variable or constant a name that is a noun (or a combination of an adjective and noun) because it represents a thing. Similarly, it makes sense to give a module an identifier that is a verb, or a combined verb and noun, because a module takes action.

Use meaningful names. Creating a data item named someData or a module named firstModule() makes a program cryptic. Not only will others find it hard to read your programs, but you will forget the purpose of these identifiers even within your own programs. All programmers occasionally use short, nondescriptive names such as x or temp in a quick program; however, in most cases, data and module names should be meaningful. Programmers refer to programs that contain meaningful names as self-documenting. This means that even without further documentation, the program code explains itself to readers.

Use pronounceable names. A variable name like pzf is neither pronounceable nor meaningful. A name that looks meaningful when you write it might not be as meaningful when someone else reads it; for instance, preparead() might mean “Prepare ad” to you, but “Prep a read” to others. Look at your names critically to make sure they can be pronounced. Very standard abbreviations do not have to be pronounceable. For example, most businesspeople would interpret ssn as a Social Security number.

Don’t forget that not all programmers share your culture. An abbreviation whose meaning seems obvious to you might be cryptic to someone in a different part of the world, or even a different part of your country. For example, you might name a variable roi to hold a value for return on investment, but a French-speaking person might interpret the meaning as king.

Be judicious in your use of abbreviations. You can save a few keystrokes when creating a module called getStat(), but is the module’s purpose to find the state in which a city is located, input some statistics, or determine the status of some variables? Similarly, is a variable named fn meant to hold a first name, file number, or something else? Abbreviations can also confuse people in different lines of work: AKA might suggest a sorority (Alpha Kappa Alpha) to a college administrator, a registry (American Kennel Association) to a dog breeder, or an alias (also known as) to a police detective.

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

C H A P T E R 2 Elements of High-Quality Programs

To save typing time when you develop a program, you can use a short name like efn. After the program operates correctly, you can use a text editor’s Search and Replace feature to replace your coded name with a more meaningful name such as employeeFirstName. When working in an integrated development environment, you can use the technique known as refactoring to rename every instance of an identifier.

70 Many IDEs support an automatic statement-completion feature that saves typing time. After the first time you use a name like employeeFirstName, you need to type only the first few letters before the compiler editor offers a list of available names from which to choose. The list is constructed from all the names you have used that begin with the same characters.

Usually, avoid digits in a name. A zero can be confused with the letter O, and the lowercase letter l is misread as the numeral 1. Of course, use your judgment: budgetFor2014 probably will not be misinterpreted.

Use the rules your language allows to separate words in long, multiword variable names. For example, if the programming language you use allows hyphens or underscores, then use a module name like initialize-data() or initialize_data(), which is easier to read than initializedata(). Another option is to use camel casing to create an identifier such as initializeData(). If you use a language that is case sensitive, it is legal but confusing to use variable names that differ only in case. For example, if a single program contains empName, EmpName, and Empname, confusion is sure to follow.

Consider including a form of the verb to be, such as is or are, in names for variables that are intended to hold a status. For example, use isFinished as a string variable that holds a Y or N to indicate whether a file is exhausted. The shorter name finished is more likely to be confused with a module that executes when a program is done. (Many languages support a Boolean data type, which you assign to variables meant to hold only true or false. Using a form of to be in identifiers for Boolean variables is appropriate.)

Many programmers follow the convention of naming constants using all uppercase letters, inserting underscores between words for readability. In this chapter you saw examples such as SALES_TAX_RATE.

Organizations sometimes enforce different rules for programmers to follow when naming program components. It is your responsibility to find out the conventions used in your organization and to adhere to them.

Programmers sometimes create a data dictionary, which is a list of every variable name used in a program, along with its type, size, and description. When a data dictionary is created, it becomes part of the program documentation.

When you begin to write programs, the process of determining what variables, constants, and modules you need and what to name them all might seem overwhelming. The design process is crucial, however. When you acquire your first professional programming assignment, the design process might very well be completed already. Most likely, your first assignment will be to write or modify one small member module of a much larger application. The more the original programmers adhered to naming guidelines, the better the original design was, and the easier your job of modification will be.

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

71

Features of Good Program Design

Designing Clear Statements In addition to using program comments and selecting good identifiers, you can use the following tactics to contribute to the clarity of the statements within your programs:

Avoid confusing line breaks.

Use temporary variables to clarify long statements.

Avoiding Confusing Line Breaks Some older programming languages require that program statements be placed in specific columns. Most modern programming languages are free-form; you can arrange your lines of code any way you see fit. As in real life, with freedom comes responsibility; when you have flexibility in arranging your lines of code, you must take care to make sure your meaning is clear. With free-form code, programmers are allowed to place two or three statements on a line, or, conversely, to spread a single statement across multiple lines. Both make programs harder to read. All the pseudocode examples in this book use appropriate, clear spacing and line breaks.

Using Temporary Variables to Clarify Long Statements When you need several mathematical operations to determine a result, consider using a series of temporary variables to hold intermediate results. A temporary variable (or work variable) is not used for input or output, but instead is just a working variable that you use during a program’s execution. For example, Figure 2-14 shows two ways to calculate a value for a real estate salespersonCommission variable. Each example achieves the same result—the salesperson’s commission is based on the square feet multiplied by the price per square foot, plus any premium for a lot with special features, such as a wooded or waterfront lot. However, the second example uses two temporary variables: basePropertyPrice and totalSalePrice. When the computation is broken down into less complicated, individual steps, it is easier to see how the total price is calculated. In calculations with even more computation steps, performing the arithmetic in stages would become increasingly helpful.

// Using a single statement to compute commission salespersonCommission = (sqFeet * pricePerFoot + lotPremium) * commissionRate

// Using multiple statements to compute commission basePropertyPrice = sqFeet * pricePerFoot totalSalePrice = basePropertyPrice + lotPremium salespersonCommission = totalSalePrice * commissionRate

Figure 2-14 Two ways of achieving the same salespersonCommission result © 2015 Cengage Learning

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

C H A P T E R 2 Elements of High-Quality Programs

Programmers might say using temporary variables, like the second example in Figure 2-14, is cheap. When executing a lengthy arithmetic statement, even if you don’t explicitly name temporary variables, the programming language compiler creates them behind the scenes (although without descriptive names), so declaring them yourself does not cost much in terms of program execution time.

72

Writing Clear Prompts and Echoing Input When program input should be retrieved from a user, you almost always want to provide a prompt for the user. A prompt is a message that is displayed on a monitor to ask the user for a response and perhaps explain how that response should be formatted. Prompts are used both in command-line and GUI interactive programs.

For example, suppose a program asks a user to enter a catalog number for an item the user is ordering. The following prompt is not very helpful:

Please enter a number.

The following prompt is more helpful:

Please enter a five-digit catalog order number.

The following prompt is even more helpful:

The five-digit catalog order number appears to the right of the item's picture in the catalog. Please enter it now.

When program input comes from a stored file instead of a user, prompts are not needed. However, when a program expects a user response, prompts are valuable. For example, Figure 2-15 shows the flowchart and pseudocode for the beginning of the bill-producing program shown earlier in this chapter. If the input was coming from a data file, no prompt would be required, and the logic might look like the logic in Figure 2-15.

input name, balance

Declarations string name num balance

start start

Declarations

string name

num balance

input name, balance

Figure 2-15 Beginning of a program that accepts a name and balance as input © 2015 Cengage Learning

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

73

Features of Good Program Design

However, if the input was coming from a user, including prompts would be helpful. You could supply a single prompt such as Please enter a customer’s name and balance due, but inserting more requests into a prompt generally makes it less likely that the user can remember to enter all the parts or enter them in the correct order. It is almost always best to include a separate prompt for each item to be entered. Figure 2-16 shows an example.

output "Please enter customer’s name "

Declarations string name num balance

start

output "Please enter balance due "

input name

input balance

start

Declarations

string name

num balance

output "Please enter customer’s name "

input name

output "Please enter balance due "

input balance

Figure 2-16 Beginning of a program that accepts a name and balance as input and uses a separate prompt for each item © 2015 Cengage Learning

Users also find it helpful when you echo their input. Echoing input is the act of repeating input back to a user either in a subsequent prompt or in output. For example, Figure 2-17 shows how the second prompt in Figure 2-16 can be improved by echoing the user’s first piece of input data in the second prompt. When a user runs the program that is started in Figure 2-17 and enters Green for the customer name, the second prompt will not be Please enter balance due. Instead, it will be Please enter balance due for Green. For example, if a clerk was about to enter the balance for the wrong customer, the mention of Green might be enough to alert the clerk to the potential error.

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

C H A P T E R 2 Elements of High-Quality Programs

74

output "Please enter customer’s name "

Declarations string name num balance

start

input name

input balance

start

Declarations

string name

num balance

output "Please enter customer’s name "

input name

output "Please enter balance due for ", name

input balance

output "Please enter balance due for ", name

Notice the space before the quotation mark in the prompt that asks the user for a balance due. The space will appear between "for" and the last name.

Figure 2-17 Beginning of a program that accepts a customer’s name and uses it in the second prompt © 2015 Cengage Learning

Maintaining Good Programming Habits When you learn a programming language and begin to write lines of program code, it is easy to forget the principles you have learned in this text. Having some programming knowledge and a keyboard at your fingertips can lure you into typing lines of code before you think things through. But every program you write will be better if you plan before you code. Maintaining the habits of first drawing flowcharts or writing pseudocode, as you have learned here, will make your future programming projects go more smoothly. If you desk-check your program logic on paper before coding statements in a programming language, your programs will run correctly sooner. If you think carefully about the variable and module names you choose, and design program statements to be easy to read and use, your programs will be easier to develop and maintain.

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

75

Chapter Summary

TWO TRUTHS & A LIE Features of Good Program Design

1. A program comment is a message that is displayed on a monitor to ask the user for a response and perhaps explain how that response should be formatted.

2. It usually makes sense to give each variable a name that contains a noun and to give each module a name that contains a verb.

3. Echoing input can help a user to confirm that a data item was entered correctly.

The false statement is #1. A program comment is a written explanation that is not part of the program logic but that serves as documentation for those reading the program. A prompt is a message that is displayed on a monitor to ask the user for a response and perhaps explain how that response should be formatted.

Chapter Summary Programs contain data in three different forms: literals (or unnamed constants), variables, and named constants. Each of these types of data can be numeric or string. Variables are named memory locations, the contents of which can vary. A variable declaration includes a data type and an identifier; optionally, it can include an initialization. Every computer programming language has its own set of rules for naming variables; however, all variable names must be written as one word without embedded spaces and should have appropriate meaning. A named constant is similar to a variable, except it can be assigned a value only once.

Most programming languages use +, –, *, and / as the four standard arithmetic operators. Every operator follows rules of precedence that dictate the order in which operations in the same statement are carried out; multiplication and division always take precedence over addition and subtraction. The rules of precedence can be overridden using parentheses.

Programmers break down programming problems into smaller, cohesive units called modules, subroutines, procedures, functions, or methods. To execute a module, you call it from another program or module. Any program can contain an unlimited number of modules, and each module can be called an unlimited number of times. Modularization provides abstraction, allows multiple programmers to work on a problem, and makes it easier for you to reuse work.

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

C H A P T E R 2 Elements of High-Quality Programs

When you create a module, you include a header, a body, and a return statement. A program or module calls a module’s name to execute it. You can place any statements within modules, including declarations, which are local to the module. Global variables and constants are those that are known to the entire program. The mainline logic of almost every procedural computer program can follow a general structure that consists of three distinct parts: housekeeping tasks, detail loop tasks, and end-of-job tasks. 76 A hierarchy chart illustrates modules and their relationships; it indicates which modules exist within a program and which modules call others.

As programs become larger and more complicated, the need for good planning and design increases. You should use program comments where appropriate. Choose identifiers wisely, strive to design clear statements within your programs and modules, write clear prompts and echo input, and continue to maintain good programming habits as you develop your programming skills.

Key Terms Numeric describes data that consists of numbers.

String describes data that is nonnumeric.

An integer is a whole number.

A floating-point number is a number with decimal places.

Real numbers are floating-point numbers.

A numeric constant (or literal numeric constant) is a specific numeric value.

A string constant (or literal string constant) is a specific group of characters enclosed within quotation marks.

Alphanumeric values can contain alphabetic characters, numbers, and punctuation.

An unnamed constant is a literal numeric or string value.

A declaration is a statement that provides a data type, an identifier, and, optionally, an initial value.

An identifier is a program component’s name.

A data item’s data type is a classification that describes what values can be assigned, how the item is stored, and what types of operations can be performed with the item.

Initializing a variable is the act of assigning its first value, often at the same time the variable is declared.

Garbage describes the unknown value stored in an unassigned variable.

Keywords comprise the limited word set that is reserved in a language.

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

77

Key Terms

Camel casing is a naming convention in which the initial letter is lowercase, multiple-word names are run together, and each new word within the name begins with an uppercase letter.

Lower camel casing is another name for the camel casing naming convention.

Pascal casing is a naming convention in which the initial letter is uppercase, multiple-word names are run together, and each new word within the name begins with an uppercase letter.

Upper camel casing is another name for the Pascal casing naming convention.

Hungarian notation is a naming convention in which a data type or other information is stored as part of a name.

Snake casing is a convention in which parts of a name are separated by underscores.

Mixed case with underscores is a naming convention similar to snake casing, but new words start with an uppercase letter.

Kebob case is sometimes used as the name for the style that uses dashes to separate parts of a name.

An assignment statement assigns a value from the right of an assignment operator to the variable or constant on the left of the assignment operator.

The assignment operator is the equal sign; it is used to assign a value to the variable or constant on its left.

A binary operator is an operator that requires two operands—one on each side.

An operand is a value used by an operator.

Right-associativity and right-to-left associativity describe operators that evaluate the expression to the right first.

An lvalue is the memory address identifier to the left of an assignment operator.

A numeric variable is one that can hold digits, have mathematical operations performed on it, and usually can hold a decimal point and a sign indicating positive or negative.

A string variable can hold text that includes letters, digits, and special characters such as punctuation marks.

Type-safety is the feature of some programming languages that prevents assigning values of an incorrect data type.

A named constant is similar to a variable, except that its value cannot change after the first assignment.

A magic number is an unnamed constant whose purpose is not immediately apparent.

Overhead describes the extra resources a task requires.

Rules of precedence dictate the order in which operations in the same statement are carried out.

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

C H A P T E R 2 Elements of High-Quality Programs

The order of operations describes the rules of precedence.

Left-to-right associativity describes operators that evaluate the expression to the left first.

The remainder operator is an arithmetic operator used in some programming languages; when used with two integer operands, it results in the remainder after division.

78 Modules are small program units that you can use together to make a program. Programmers also refer to modules as subroutines, procedures, functions, or methods.

To call a module is to use the module’s name to invoke it, causing it to execute.

Modularization is the process of breaking down a program into modules.

Functional decomposition is the act of reducing a large program into more manageable modules.

Abstraction is the process of paying attention to important properties while ignoring nonessential details.

Reusability is the feature of modular programs that allows individual modules to be used in a variety of applications.

Reliability is the feature of modular programs that assures you a module has been tested and proven to function correctly.

A main program runs from start to stop and calls other modules.

The mainline logic is the logic that appears in a program’s main module; it calls other modules.

The module header includes the module identifier and possibly other necessary identifying information.

The module body contains all the statements in the module.

The module return statement marks the end of the module and identifies the point at which control returns to the program or module that called the module.

Encapsulation is the act of containing a task’s instructions in a module.

A stack is a memory location in which the computer keeps track of the correct memory address to which it should return after executing a module.

The functional cohesion of a module is a measure of the degree to which all the module statements contribute to the same task.

Visible describes data items when a module can recognize them.

In scope describes data that is visible.

Local describes variables that are declared within the module that uses them.

A portable module is one that can more easily be reused in multiple programs.

Global describes variables that are known to an entire program.

Housekeeping tasks include steps you must perform at the beginning of a program to get ready for the rest of the program.

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

79

Exercises

Detail loop tasks of a program include the steps that are repeated for each set of input data.

End-of-job tasks hold the steps you take at the end of the program to finish the application.

A hierarchy chart is a diagram that illustrates modules’ relationships to each other.

Program comments are written explanations that are not part of the program logic but that serve as documentation for those reading the program.

Internal documentation is documentation within a coded program.

External documentation is documentation that is outside a coded program.

An annotation symbol contains information that expands on what appears in another flowchart symbol; it is most often represented by a three-sided box that is connected to the step it references by a dashed line.

Self-documenting programs are those that contain meaningful identifiers that describe their purpose.

A data dictionary is a list of every variable name used in a program, along with its type, size, and description.

A temporary variable (or work variable) is a variable that you use to hold intermediate results during a program’s execution.

A prompt is a message that is displayed on a monitor to ask the user for a response and perhaps explain how that response should be formatted.

Echoing input is the act of repeating input back to a user either in a subsequent prompt or in output.

Exercises

Review Questions

1. What does a declaration provide for a variable?

a. a name c. both of the above b. a data type d. none of the above

2. A variable’s data type describes all of the following except .

a. what values the variable can hold b. how the variable is stored in memory c. what operations can be performed with the variable d. the scope of the variable

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

C H A P T E R 2 Elements of High-Quality Programs

3. The value stored in an uninitialized variable is .

a. garbage c. compost b. null d. its identifier

4. The value 3 is a . 80

a. numeric variable c. string variable b. numeric constant d. string constant

5. The assignment operator .

a. is a binary operator c. is most often represented by a colon b. has left-to-right associativity d. two of the above

6. Which of the following is true about arithmetic precedence?

a. Multiplication has a higher precedence than division. b. Operators with the lowest precedence always have left-to-right

associativity. c. Division has higher precedence than subtraction. d. all of the above

7. Which of the following is a term used as a synonym for module in some programming languages?

a. method c. both of these b. procedure d. none of these

8. Which of the following is a reason to use modularization?

a. Modularization avoids abstraction. b. Modularization reduces overhead. c. Modularization allows you to more easily reuse your work. d. Modularization eliminates the need for syntax.

9. What is the name for the process of paying attention to important properties while ignoring nonessential details?

a. abstraction c. extinction b. extraction d. modularization

10. Every module has all of the following except .

a. a header c. a body b. local variables d. a return statement

11. Programmers say that one module can another, meaning that the first module causes the second module to execute.

a. declare c. enact b. define d. call

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

81

Exercises

12. The more that a module’s statements contribute to the same job, the greater the of the module.

a. structure c. functional cohesion b. modularity d. size

13. In most modern programming languages, a variable or constant that is declared in a module is in that module.

a. global c. in scope b. invisible d. undefined

14. Which of the following is not a typical housekeeping task?

a. displaying instructions c. opening files b. printing summaries d. displaying report headings

15. Which module in a typical program will execute the most times?

a. the housekeeping module c. the end-of-job module b. the detail loop d. It is different in every program.

16. A hierarchy chart tells you .

a. what tasks are to be performed within each program module b. when a module executes c. which routines call which other routines d. all of the above

17. What are nonexecuting statements that programmers place within code to explain program statements in English?

a. comments c. trivia b. pseudocode d. user documentation

18. Program comments are .

a. required to create a runnable program b. a form of external documentation c. both of the above d. none of the above

19. Which of the following is valid advice for naming variables?

a. To save typing, make most variable names one or two letters. b. To avoid conflict with names that others are using, use unusual or

unpronounceable names. c. To make names easier to read, separate long names by using underscores

or capitalization for each new word. d. To maintain your independence, shun the conventions of your

organization.

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

C H A P T E R 2 Elements of High-Quality Programs

20. A message that asks a user for input is a(n) .

a. comment c. echo b. prompt d. declaration

82

Programming Exercises

1. Explain why each of the following names does or does not seem like a good variable name to you.

a. d

b. dsctamt

c. discountAmount

d. discount Amount

e. discount

f. discountAmountForEachNewCustomer

g. discountYear2015

h. 2015Discountyear

2. If productCost and productPrice are numeric variables, and productName is a string variable, which of the following statements are valid assignments? If a statement is not valid, explain why not.

a. productCost = 100

b. productPrice = productCost

c. productPrice = productName

d. productPrice = "24.95"

e. 15.67 = productCost

f. productCost = $1,345.52

g. productCost = productPrice - 10

h. productName = "mouse pad"

i. productCost + 20 = productPrice

j. productName = 3-inch nails

k. productName = 43

l. productName = "44"

m. "99" = productName

n. productName = brush

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

83

Exercises

o. battery = productName

p. productPrice = productPrice

q. productName = productCost

3. Assume that income = 8 and expense = 6. What is the value of each of the following expressions?

a. income + expense * 2

b. income + 4 – expense / 2

c. (income + expense) * 2

d. income – 3 * 2 + expense

e. 4 * ((income – expense) + 2) + 10

4. Draw a typical hierarchy chart for a program that produces a monthly bill for a cell phone customer. Try to think of at least 10 separate modules that might be included. For example, one module might calculate the charge for daytime phone minutes used.

5. a. Draw the hierarchy chart and then plan the logic for a program needed by the sales manager of The Henry Used Car Dealership. The program will determine the profit on any car sold. Input includes the sale price and actual purchase price for a car. The output is the profit, which is the sale price minus the purchase price. Use three modules. The main program declares global variables and calls housekeeping, detail, and end-of-job modules. The housekeeping module prompts for and accepts a sale price. The detail module prompts for and accepts the purchase price, computes the profit, and displays the result. The end-of-job module displays the message Thanks for using this program.

b. Revise the profit-determining program so that it runs continuously for any number of cars. The detail loop executes continuously while the sale price is not 0; in addition to calculating the profit, it prompts the user for and gets the next sale price. The end-of-job module executes after 0 is entered for the sale price.

6. a. Draw the hierarchy chart and then plan the logic for a program that calculates a person’s body mass index (BMI). BMI is a statistical measure that compares a person’s weight and height. The program uses three modules. The first prompts a user for and accepts the user’s height in inches. The second module accepts the user’s weight in pounds and converts the user’s height to meters and weight to kilograms. Then, it calculates BMI as weight in kilograms divided by height in meters squared, and displays the results. There are 2.54 centimeters in an inch, 100 centimeters in a meter, 453.59 grams in a pound, and 1,000 grams in a

kilogram. Use named constants whenever you think they are appropriate. The last module displays the message End of job.

b. Revise the BMI-determining program to execute continuously until the user enters 0 for the height in inches.

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

C H A P T E R 2 Elements of High-Quality Programs

84

7. Draw the hierarchy chart and design the logic for a program that calculates service charges for Hazel’s Housecleaning service. The program contains housekeeping, detail loop, and end-of-job modules. The main program declares any needed global variables and constants and calls the other modules. The housekeeping module displays a prompt for and accepts a customer’s last name. While the user does not enter ZZZZ for the name, the detail loop accepts the number of bathrooms and the number of other rooms to be cleaned. The service charge is computed as $40 plus $15 for each bathroom and $10 for each of the other rooms. The detail loop also displays the service charge and then prompts the user for the next customer’s name. The end-of-job module, which executes after the user enters the sentinel value for the name, displays a message that indicates the program is complete.

8. Draw the hierarchy chart and design the logic for a program that calculates the projected cost of an automobile trip. Assume that the user’s car travels 20 miles per gallon of gas. Design a program that prompts the user for a number of miles driven and a current cost per gallon. The program computes and displays the cost of the trip as well as the cost if gas prices rise by 10 percent. The program accepts data continuously until 0 is entered for the number of miles. Use appropriate modules, including one that displays End of program when the program is finished.

9. a. Draw the hierarchy chart and design the logic for a program needed by the manager of the Stengel County softball team, who wants to compute slugging percentages for his players. A slugging percentage is the total bases earned with base hits divided by the player’s number of at-bats. Design a program that prompts the user for a player jersey number, the number of bases earned, and the number of at-bats, and then displays all the data, including the calculated slugging average. The program accepts players continuously until 0 is entered for the jersey number. Use appropriate modules, including one that displays End of job after the sentinel is entered for the jersey number.

b. Modify the slugging percentage program to also calculate a player’s on-base percentage. An on-base percentage is calculated by adding a player’s hits and walks, and then dividing by the sum of at-bats, walks, and sacrifice flies. Prompt the user for all the additional data needed, and display all the data for each player.

c. Modify the softball program so that it also computes a gross production average (GPA) for each player. A GPA is calculated by multiplying a player’s on-base percentage by 1.8, then adding the player’s slugging percentage, and then dividing by four.

10. Draw the hierarchy chart and design the logic for a program for the River Falls Homes Construction Company. Design a program that prompts the user for a lot number in the River Falls subdivision and data about the home to be built there, including number of bedrooms, number of bathrooms, and the number of cars the garage holds. Output is the price of the home, which is a $50,000 base price plus $17,000 for each bedroom, $12,500 for each bathroom, and $6,000 for

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

85

Exercises

each car the garage holds. The program accepts lot numbers continuously until 0 is entered. Use named constants where appropriate. Also, use appropriate modules, including one that displays End of job after the sentinel is entered for the lot number.

11. Draw the hierarchy chart and design the logic for a program for Arnie’s Appli- ances. Design a program that prompts the user for a refrigerator model name and the interior height, width, and depth in inches. Calculate the refrigerator capacity in cubic feet by first multiplying the height, width, and depth to get cubic inches, and then dividing by 1728 (the number of cubic inches in a cubic foot). The program accepts model names continuously until “XXX” is entered. Use named constants where appropriate. Also use modules, including one that displays End of job after the sentinel is entered for the model name.

Performing Maintenance

1. A file named MAINTENANCE02-01.txt is included with your downloadable student files. Assume that this program is a working program in your organiza- tion and that it needs modifications as described in the comments (lines that begin with two slashes) at the beginning of the file. Your job is to alter the program to meet the new specifications.

Find the Bugs

1. Your downloadable files for Chapter 2 include DEBUG02-01.txt, DEBUG02-02. txt, and DEBUG02-03.txt. Each file starts with some comments that describe the problem. Comments are lines that begin with two slashes (//). Following the comments, each file contains pseudocode that has one or more bugs you must find and correct.

2. Your downloadable files for Chapter 2 include a file named DEBUG02-04.jpg that contains a flowchart with syntax and/or logical errors. Examine the flowchart and then find and correct all the bugs.

Game Zone

1. For games to hold your interest, they almost always include some random, unpredictable behavior. For example, a game in which you shoot asteroids loses some of its fun if the asteroids follow the same, predictable path each time you play. Therefore, generating random values is a key component in creating most inter- esting computer games. Many programming languages come with a built-in

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

C H A P T E R 2 Elements of High-Quality Programs

module you can use to generate random numbers. The syntax varies in each language, but it is usually something like the following: myRandomNumber = random(10)

In this statement, myRandomNumber is a numeric variable you have declared and the expression random(10) means “call a method that generates and returns a random number between 1 and 10.” By convention, in a flowchart, you would place a statement like this in a processing symbol with two vertical stripes at the edges, as shown below.

86

myRandomNumber = random(10)

Create a flowchart or pseudocode that shows the logic for a program that generates a random number, then asks the user to think of a number between 1 and 10. Then display the randomly generated number so the user can see whether his or her guess was accurate. (In future chapters, you will improve this game so that the user can enter a guess and the program can determine whether the user was correct.)

Up for Discussion

1. Many programming style guides are published on the Web. These guides suggest good identifiers, explain standard indentation rules, and identify style issues in specific programming languages. Find style guides for at least two languages (for example, C++, Java, Visual Basic, or C#) and list any differences you notice.

2. What advantages are there to requiring variables to have a data type? 3. As this chapter mentions, some programming languages require that named constants

are assigned a value when they are declared; other languages allow a constant’s value to be assigned later in a program. Which requirement do you think is better? Why?

4. Many products use Pascal casing or camel casing in their names–for example, MasterCard. Name as many more as you can.

5. Distance measurement is one situation in which using integer division and the remainder operator might be useful. For example, if the programming language supports it, you can divide a measurement of 123 inches by 12 to get 10 feet, and then use the remainder operator to discover that the measurement is 3 inches over 10 feet. Think of several other situations in which you might find a remainder operator useful.

6. Would you prefer to write a large program by yourself, or to work on a team in which each programmer produces one or more modules? Why?

7. Extreme programming is a system for rapidly developing software. One of its tenets is that all production code is written by two programmers sitting at one machine. Is this a good idea? Does working this way as a programmer appeal to you? Why or why not?

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

C H A P T E R 3 Understanding Structure

In this chapter, you will learn about:

The disadvantages of unstructured spaghetti code

The three basic structures—sequence, selection, and loop

Using a priming input to structure a program

The need for structure

Recognizing structure

Structuring and modularizing unstructured logic

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

C H A P T E R 3 Understanding Structure

The Disadvantages of Unstructured Spaghetti Code Professional business applications usually get far more complicated than the examples you have seen so far in Chapters 1 and 2. Imagine the number of instructions in the computer programs that guide an airplane’s flight or audit an income tax return. Even the program that produces your paycheck at work contains many, many instructions. 88 Designing the logic for such a program can be a time-consuming task. When you add hundreds or thousands of instructions to a program, it is easy to create a complicated mess. The descriptive name for logically snarled program statements is spaghetti code, because the logic is as hard to follow as one noodle through a plate of spaghetti. Not only is spaghetti code confusing, the programs that contain it are prone to error, difficult to reuse, and hard to use as building blocks for larger applications. Programs that use spaghetti code logic are unstructured programs; that is, they do not follow the rules of structured logic that you will learn in this chapter. Structured programs do follow those rules, and eliminate the problems caused by spaghetti code.

For example, suppose that you start a job as a dog washer and that you receive the instructions shown in Figure 3-1. This flowchart is an example of unstructured spaghetti code. A computer program that is organized similarly might “work”—that is, it might produce correct results—but it would be difficult to read and maintain, and its logic would be hard to follow.

You might be able to follow the logic of the dog-washing process in Figure 3-1 for two reasons:

You might already know how to wash a dog.

The flowchart contains a limited number of steps.

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

89

The Disadvantages of Unstructured Spaghetti Code

stop

Yes

Yes

Yes

No

No

No

Catch dog

Turn on water

Turn off water

Yes

Get dog wet and apply shampoo

Catch dog

No

Rinse dog

Does dog run away?

Does dog run away?

Does dog have shampoo on?

Does dog run away?

start

Don’t Do It This example does not use good programming style. By the end of the chapter, you will know how to make this example structured, which will make it less confusing.

Figure 3-1 Spaghetti code logic for washing a dog © 2015 Cengage Learning

However, imagine that you were not familiar with dog washing, or that the process was far more complicated. (For example, imagine you must wash 100 dogs concurrently while applying flea and tick medication, giving them haircuts, and researching their genealogy.)

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

C H A P T E R 3 Understanding Structure

Depicting more complicated logic in an unstructured way would be cumbersome. By the end of this chapter, you will understand how to make the unstructured process in Figure 3-1 clearer and less error-prone.

Software developers say that a program that contains spaghetti code has a shorter life than one with structured code. This means that programs developed using spaghetti code exist as production programs in an organization for less time. Such programs are so difficult to alter that when improvements are required, developers often find it easier to abandon the existing program and start from scratch. This takes extra time and costs more money.

90

TWO TRUTHS & A LIE The Disadvantages of Unstructured Spaghetti Code

1. Spaghetti code is the descriptive name for logically snarled programs.

2. Programs written using spaghetti code cannot produce correct results.

3. Programs written using spaghetti code are more difficult to maintain than other programs.

The false statement is #2. Programs written using spaghetti code can produce correct results, but they are more difficult to understand and maintain than programs that use structured techniques.

Understanding the Three Basic Structures In the mid-1960s, mathematicians proved that any program, no matter how complicated, can be constructed using one or more of only three structures. A structure is a basic unit of programming logic; each structure is one of the following:

sequence

selection

loop

With these three structures alone, you can diagram any task, from doubling a number to performing brain surgery. You can diagram each structure with a specific configuration of flowchart symbols.

The Sequence Structure The sequence structure is shown in Figure 3-2. It performs actions or tasks in order, one after the other. A sequence can contain any number of tasks, but there is no option to branch off and skip any of the tasks. Once you start a series of actions in a sequence, you must continue step by step until the sequence ends.

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

91

Understanding the Three Basic Structures

As an example, driving directions often are listed as a sequence. To tell a friend how to get to your house from school, you might provide the following sequence, in which one step follows the other and no steps can be skipped: go north on First Avenue for 3 miles turn left on Washington Boulevard go west on Washington for 2 miles stop at 634 Washington

The Selection Structure Figure 3-2 Sequence structure

The selection structure, or decision structure, © 2015 Cengage Learning is shown in Figure 3-3. With this structure, one of two courses of action is taken based on the answer to a question. A flowchart that describes a selection structure begins with a decision symbol, and the branches of the decision must join at the bottom of the structure. Pseudocode that describes a selection structure starts with if. Pseudocode uses the end-structure statement endif to clearly show where the structure ends.

Some people call the selection structure an if-then-else because it fits the following statement:

if someCondition is true then do oneProcess

else do theOtherProcess

endif Figure 3-3 Selection structure

For example, you might provide part of the © 2015 Cengage Learning directions to your house as follows: if traffic is backed up on Washington Boulevard then

continue for 1 block on First Avenue and turn left on Adams Lane else

turn left on Washington Boulevard endif

Similarly, a payroll program might include a statement such as: if hoursWorked is more than 40 then

calculate regularPay and overtimePay else

calculate regularPay endif

These if-else examples can also be called dual-alternative ifs (or dual-alternative selections) because they contain two alternatives—the action taken when the tested condition is true

Yes No

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

C H A P T E R 3 Understanding Structure

and the action taken when it is false. Note that it is perfectly correct for one branch of the selection to be a “do nothing” branch. In each of the following examples, an action is taken only when the tested condition is true: if it is raining then

take an umbrella 92 endif

if employee participates in the dental plan then deduct $40 from employee gross pay

endif

The previous examples without else clauses are single- alternative ifs (or single-alternative selections); a diagram of their structure is shown in Figure 3-4. In these cases, you do not take any special action if it is not raining or if the employee does not belong to the dental plan. The branch in which no action is taken is called the null case or null branch.

Yes No

Figure 3-4 Single-alternative selection structure © 2015 Cengage Learning

The Loop Structure The loop structure is shown in Figure 3-5. A loop continues to repeat actions while a condition remains true. The action or actions that occur within the loop are the loop body. In the most common type of loop, a condition is evaluated; if the answer is true, you execute the loop body and evaluate the condition again. If the condition is still true, you execute the loop body again and then reevaluate the condition. This continues until the condition becomes false, and then you exit the loop structure. Programmers call this structure a while loop; pseudocode that describes this type of loop starts with while and ends with the end-structure statement endwhile. A flowchart that describes the while loop structure always begins with a decision symbol that has a branch that returns to a spot prior to the decision. You may hear programmers refer to looping as repetition or iteration.

No

Yes

Figure 3-5 Loop structure © 2015 Cengage Learning

The while loop tests a condition before executing the loop body even once. Another type of structured loop tests a condition after the first loop body execution. You will learn more about this alternate type of loop in Chapter 4 and in Appendix D. For the rest of this chapter, assume that all loops are while loops that ask the controlling question before the loop body ever executes. All logical problems can be solved using only the three structures—sequence, selection, and while loop.

Some programmers call a while loop a while…do loop, because it fits the following statement:

while testCondition continues to be true do someProcess

endwhile

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

93

Understanding the Three Basic Structures

When you provide directions to your house, part of the directions might be: while the address of the house you are passing remains below 634

travel forward to the next house look at the address on the house

endwhile

You encounter examples of looping every day, as in each of the following: while you continue to be hungry

take another bite of food determine whether you still feel hungry

endwhile

while unread pages remain in the reading assignment read another unread page determine whether there are more pages to read

endwhile

Combining Structures All logic problems can be solved using only these three structures—sequence, selection, and loop. The structures can be combined in an infinite number of ways. For example, you can have a sequence of tasks followed by a selection, or a loop followed by a sequence. Attaching structures end to end is called stacking structures. For example, Figure 3-6 shows a structured flowchart achieved by stacking structures, and shows pseudocode that follows the flowchart logic.

sequence

Yes

No

stepB

stepA

Yes No

stepE stepD

conditionF?

conditionC?

stepA stepB if conditionC is true then

stepD else

stepE endif while conditionF is true

stepG endwhile

selection

loop stepG

Figure 3-6 Structured flowchart and pseudocode with three stacked structures © 2015 Cengage Learning

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

C H A P T E R 3

Understanding Structure

Whether you are drawing a flowchart or writing pseudocode, you can use any opposite, mutually exclusive words to represent decision outcomes—for example, Yes and No or true and false. This book follows the convention of using Yes and No in flowchart diagrams and true and false in pseudocode.

The pseudocode in Figure 3-6 shows a sequence, followed by a selection, followed by a loop. 94 First stepA and stepB execute in sequence. Then a selection structure starts with the test of

conditionC. The instruction that follows the if clause (stepD) executes when its tested condition (conditionC) is true, the instruction that follows else (stepE) executes when the tested condition is false, and any instructions that follow endif execute in either case. In other words, statements beyond the endif statement are “outside” the selection structure. Similarly, the endwhile statement shows where the loop structure ends. In Figure 3-6, while conditionF continues to be true, stepG continues to execute. If any statements followed the endwhile statement, they would be outside of, and not a part of, the loop.

Besides stacking structures, you can replace any individual steps in a structured flowchart diagram or pseudocode with additional structures. This means that any sequence, selection, or loop can contain other sequence, selection, or loop structures. For example, you can have a sequence of three tasks on one branch of a selection, as shown in Figure 3-7. Placing a structure within another structure is called nesting structures.

if conditionH is true then stepJ stepK stepL

endif

No Yes

stepJ

stepK

stepL

conditionH?

Figure 3-7 Flowchart and pseudocode showing nested structures—a sequence nested within a selection © 2015 Cengage Learning

In the pseudocode for the logic shown in Figure 3-7, the indentation shows that all three statements (stepJ, stepK, and stepL) must execute if conditionH is true. These three statements constitute a block, or a group of statements that executes as a single unit.

In place of one of the steps in the sequence in Figure 3-7, you can insert another structure. In Figure 3-8, the process named stepK has been replaced with a loop structure that begins with a test of the condition named conditionM.

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

95

Understanding the Three Basic Structures

conditionH? No Yes

stepJ

stepL

stepN conditionM?

No

Yes

if conditionH is true then stepJ while conditionM is true

stepN endwhile stepL

endif

Figure 3-8 Flowchart and pseudocode showing nested structures—a loop nested within a sequence, nested within a selection © 2015 Cengage Learning

In the pseudocode shown in Figure 3-8, notice that if and endif are vertically aligned. This shows that they are “on the same level.” Similarly, stepJ, while, endwhile, and stepL are aligned, and they are evenly indented. In the flowchart in Figure 3-8, you could draw a vertical line through the symbols containing stepJ, the entry and exit points of the while loop, and stepL. The flowchart and the pseudocode represent exactly the same logic.

When you nest structures, the statements that start and end a structure are always on the same level and are always in pairs. Structures cannot overlap. For example, if you have an if structure that contains a while structure, then the endwhile statement will come before the endif. On the other hand, if you have a while that contains an if, then the endif statement will come before the endwhile.

There is no limit to the number of levels you can create when you nest and stack structures. For example, Figure 3-9 shows logic that has been made more complicated by replacing stepN with a selection. The structure that performs stepP or stepQ based on the outcome of conditionO is nested within the loop that is controlled by conditionM. In the pseudocode in Figure 3-9, notice how the if, else, and endif that describe the condition selection are aligned with each other and within the while structure that is controlled by conditionM. As before, the indentation used in the pseudocode reflects the logic laid out graphically in the flowchart.

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

C H A P T E R 3

Understanding Structure

96

conditionH? No Yes

stepJ

stepL

stepQ stepP

No

Yes

conditionO?

conditionM?

No Yes

if conditionH is true then stepJ while conditionM is true

if conditionO is true then stepP

else stepQ

endif endwhile stepL

endif

Figure 3-9 Flowchart and pseudocode for a selection within a loop within a sequence within a selection © 2015 Cengage Learning

Many of the preceding examples are generic so that you can focus on the relationships of the symbols without worrying what they do. Keep in mind that generic instructions like stepA and generic conditions like conditionC can stand for anything. For example, Figure 3-10 shows the process of buying and planting flowers outdoors in the spring after the danger of frost is over. The flowchart and pseudocode structures are identical to those in Figure 3-9. In the exercises at the end of this chapter, you will be asked to develop more scenarios that fit the same pattern.

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

97

Understanding the Three Basic Structures

No Yes

No

Yes

No Yes

are we planting flowers this year?

plant flowers in ground

if we are planting flowers this year then buy flowers in pots while frost is still possible

if it is over 50F today then bring potted flowers outdoors for the day

else keep potted flowers inside for the day

endif endwhile plant flowers in ground

endif

is frost still possible?

is it over 50F today?

keep potted flowers inside for the day

buy flowers in pots

bring potted flowers outdoors for the day

Figure 3-10 The process of buying and planting flowers in the spring © 2015 Cengage Learning

The possible combinations of logical structures are endless, but each segment of a structured program is a sequence, a selection, or a loop. The three structures are shown together in Quick Reference 3-1. Notice that each structure has one entry point and one exit point. One structure can attach to another only at one of these points.

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

C H A P T E R 3 Understanding Structure

QUICK REFERENCE 3-1 The Three Structures

entry

Sequence

entry

No

No

Yes Yes

Selection

exit

entry

Loop

exit

98

exit

Try to imagine physically picking up any of the three structures using the entry and exit “handles.” These are the spots at which you could connect one structure to another. Similarly, any complete structure, from its entry point to its exit point, can be inserted within the process symbol of any other structure, forming nested structures.

In summary, a structured program has the following characteristics:

A structured program includes only combinations of the three basic structures— sequence, selection, and loop. Any structured program might contain one, two, or all three types of structures.

Each of the structures has a single entry point and a single exit point.

Structures can be stacked or connected to one another only at their entry or exit points.

Any structure can be nested within another structure.

A structured program is never required to contain examples of all three structures. For example, many simple programs contain only a sequence of several tasks that execute from start to finish without any needed selections or loops. As another example, a program might display a series of numbers, looping to do so, but never making any decisions about the numbers.

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

99

Using a Priming Input to Structure a Program

Watch the video Understanding Structure.

TWO TRUTHS & A LIE Understanding the Three Basic Structures

1. Each structure in structured programming is a sequence, selection, or loop.

2. All logic problems can be solved using only three structures—sequence, selection, and loop.

3. The three structures cannot be combined in a single program.

Using a Priming Input to Structure a Program Recall the number-doubling program discussed in Chapter 2; Figure 3-11 shows a similar program. The program accepts a number as input and checks for the end-of-data condition. If the condition is not met, then the number is doubled, the answer is displayed, and the next number is input.

The false statement is #3. The three structures can be stacked or nested in an infinite number of ways.

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

C H A P T E R 3

Understanding Structure

100

input originalNumber

Declarations num originalNumber num calculatedAnswer

start

stop not eof? No

Yes

output calculatedAnswer

calculatedAnswer = originalNumber * 2

Don’t Do It This logic is not structured.

Figure 3-11 Unstructured flowchart of a number-doubling program © 2015 Cengage Learning

Recall from Chapter 1 that this book uses eof to represent a generic end-of-data condition when the exact tested parameters are not important to the discussion. In this example, the test is for not eof because processing will continue while the end of the data has not been reached.

Is the program represented by Figure 3-11 structured? At first, it might be hard to tell. The three allowed structures were illustrated in Quick Reference 3-1, and the flowchart in Figure 3-11 does not look exactly like any of those three shapes. However, because you may stack and nest structures while retaining overall structure, it might be difficult to determine whether a flowchart as a whole is structured. It is easiest to analyze the flowchart in Figure 3-11 one step at a time. The beginning of the flowchart looks like Figure 3-12. Is this portion of the flowchart structured? Yes, it is a sequence of two tasks—making declarations and inputting a value.

start

input originalNumber

Declarations num originalNumber num calculatedAnswer

Figure 3-12 Beginning of a number-doubling flowchart © 2015 Cengage Learning

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

101

Using a Priming Input to Structure a Program

Adding the next piece of the flowchart looks like Figure 3-13. After a value is input for originalNumber, the not eof? condition is tested. The sequence is finished; either a selection or a loop is starting. You might not know which one, but you do know that with a sequence, each task or step must follow without any opportunity to branch off. So, which type of structure starts with the question in Figure 3-13? Is it a selection or a loop?

Selection and loop structures both start with a question, but they differ as follows:

In a selection structure, the logic branches in one of two directions after the question, and then the flow comes back together; the question is not asked a second time within the selection structure.

In a loop, each time the answer to the question results in the execution of the loop body, the flow of logic returns to the question that started the loop. When the body of a loop executes, the question that Figure

input originalNumber

Yes

not eof? No

Declarations num originalNumber num calculatedAnswer

start

3-13 Number-doubling controls the loop is always asked again.

flowchart continued © 2015 Cengage Learning If the end-of-data condition is not met in the number-

doubling problem in the original Figure 3-11, then the result is calculated and output, a new number is obtained, and the logic returns to the question that tests for the end of the file. In other words, while the answer to the not eof? question continues to be Yes, a body of two statements continues to execute. Therefore, the not eof? question starts a structure that is more likely to be a loop than a selection.

The number-doubling problem does contain a loop, but it is not a structured loop. In a structured while loop, the rules are:

1. You ask a question.

2. If the answer indicates you should execute the loop body, then you do so.

3. After you execute the loop body, then you must go right back to ask the question again—you can’t go anywhere else!

The flowchart in Figure 3-11 asks a question. If the answer is Yes (that is, while not eof? is true), then the program performs two tasks in the loop body: It does the arithmetic and it displays the results. Doing two things is acceptable because two tasks with no possible branching constitute a sequence, and it is fine to nest one structure within another structure. However, when the sequence ends, the logic does not flow right back to the loop- controlling question. Instead, it goes above the question to get another number. For the loop in Figure 3-11 to be a structured loop, the logic must return to the not eof? question when the embedded sequence ends.

The flowchart in Figure 3-14 shows the program with the flow of logic returning to the not eof? question immediately after the nested two-step sequence. Figure 3-14 shows

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

C H A P T E R 3

Understanding Structure

102

input originalNumber

Declarations num originalNumber num calculatedAnswer

start

stop

not eof? Yes

No

output calculatedAnswer

calculatedAnswer = originalNumber * 2

Don’t Do It

This logic is structured, but the program never accepts subsequent input values.

Figure 3-14 Structured, but nonfunctional, flowchart of number-doubling problem © 2015 Cengage Learning

a structured flowchart, but it has one major flaw—the flowchart does not do the job of continuously doubling different numbers.

Follow the flowchart through a typical program run, assuming the eof condition is an input value of 0. Suppose that when the program starts, the user enters 9 for the value of originalNumber. That is not eof, so the number is multiplied by 2, and 18 is displayed as the value of calculatedAnswer. Then the question not eof? is asked again. The not eof? condition must still be true because a new value representing the sentinel (ending) value has not been entered and cannot be entered. The logic never returns to the input originalNumber task, so the value of originalNumber never changes. Therefore, 9 doubles again and the answer 18 is displayed again. The not eof? result is still true, so the same steps are repeated. This goes on forever, with the answer 18 being calculated and output repeatedly. The program logic shown in Figure 3-14 is structured, but it does not work as intended. Conversely, the program in Figure 3-15 works, but it is not structured because after the tasks execute within a structured loop, the flow of logic must return directly to the loop-controlling question. In Figure 3-15, the logic does not return to this question; instead, it goes “too high” outside the loop to repeat the input originalNumber task.

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

103

Using a Priming Input to Structure a Program

input originalNumber

Declarations num originalNumber num calculatedAnswer

start

stop

not eof? Yes

No

output calculatedAnswer

calculatedAnswer = originalNumber * 2

Don’t Do It This logic is not structured.

Figure 3-15 Functional but unstructured flowchart © 2015 Cengage Learning

How can the number-doubling problem be both structured and work as intended? Often, for a program to be structured, you must add something extra. In this case, it is a priming input step. A priming input or priming read is an added statement that gets the first input value in a program. For example, if a program will receive 100 data values as input, you input the first value in a statement that is separate from the other 99. You must do this to keep the program structured.

Consider the solution in Figure 3-16; it is structured and it does what it is supposed to do. It contains a shaded, additional input originalNumber statement. The program logic contains a sequence and a loop. The loop contains another sequence.

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

C H A P T E R 3

Understanding Structure

104

This step gets all subsequent inputs.

This is the priming input.

input originalNumber

Declarations num originalNumber num calculatedAnswer

start

stop

not eof? Yes

No

output calculatedAnswer

input originalNumber

calculatedAnswer = originalNumber * 2

Figure 3-16 Functional, structured flowchart for the number-doubling problem © 2015 Cengage Learning

The additional input originalNumber step shown in Figure 3-16 is typical in structured programs. The first of the two input steps is the priming input. The term priming comes from the fact that the input is first, or primary (it gets the process going, as in “priming the pump”). The purpose of the priming input step is to control the upcoming loop that begins with the not eof? question. The last element within the structured loop gets the next, and all subsequent, input values. This is also typical in structured loops—the last step executed within the loop body alters the condition tested in the question that begins the loop, which in this case is the not eof? question.

In Chapter 2, you learned that the group of preliminary tasks that sets the stage for the main work of a program is called the housekeeping section. The priming input is an example of a housekeeping task.

Figure 3-17 shows another way you might attempt to draw the logic for the number- doubling program. At first glance, the figure might seem to show an acceptable solution to the problem—it is structured, it contains a sequence followed by a single loop with a sequence of three steps nested within it, and it appears to eliminate the need for the priming input statement. When the program starts, the declarations are made and the

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

105

Using a Priming Input to Structure a Program

not eof? question is asked. If it is not the end of input data, then the program gets a number, doubles it, and displays it. Then, if the not eof? condition remains true, the program gets another number, doubles it, and displays it. The program might continue while many numbers are input. At some point, the input number will represent the eof condition; for example, the program might have been written to recognize the value 0 as the program-terminating value. After the eof value is entered, its condition is not immediately tested. Instead, a result is calculated and displayed one last time before the loop-controlling question is asked again. If the program was written to recognize eof when originalNumber is 0, then an extraneous answer of 0 will be displayed before the program ends. Depending on the language you are using and on the type of input being used, the results might be worse: The program might terminate by displaying an error message or the value output might be indecipherable garbage. In any case, this last output is superfluous—no value should be doubled and output after the eof condition is encountered.

As a general rule, a program-ending test should always come immediately after an input statement because that’s the earliest point at which it can be evaluated. Therefore, the best solution to the number-doubling problem remains the one shown in Figure 3-16—the structured solution containing the priming input statement.

input originalNumber

Declarations num originalNumber num calculatedAnswer

start

stop

not eof? Yes

No

output calculatedAnswer

calculatedAnswer = originalNumber * 2

Don’t Do It This logic is structured, but fawed. When the user inputs the eof value, it will incorrectly be doubled and output.

Figure 3-17 Structured but incorrect solution to the number-doubling problem © 2015 Cengage Learning

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

C H A P T E R 3 Understanding Structure

TWO TRUTHS & A LIE Using a Priming Input to Structure a Program

106 1. A priming input is the statement that repeatedly gets all the data that is input in a program.

2. A structured program might contain more instructions than an unstructured one.

3. A program can be structured yet still be incorrect.

The false statement is #1. A priming input gets the first input.

Understanding the Reasons for Structure At this point, you may very well be saying, “I liked the original number-doubling program back in Figure 3-11 just fine. I could follow it. Also, the first program had one less step in it, so it was less work. Who cares if a program is structured?”

Until you have some programming experience, it is difficult to appreciate the reasons for using only the three structures—sequence, selection, and loop. However, staying with these three structures is better for the following reasons:

Clarity—The number-doubling program is small. As programs get bigger, they get more confusing if they are not structured.

Professionalism—All other programmers (and programming teachers you might encounter) expect your programs to be structured. It is the way things are done professionally.

Efficiency—Most newer computer languages support structure and use syntax that lets you deal efficiently with sequence, selection, and looping. Older languages, such as assembly languages, COBOL, and RPG, were developed before the principles of structured programming were discovered. However, even programs that use those older languages can be written in a structured form. Newer languages such as C#, C++, and Java enforce structure by their syntax.

In older languages, you could leave a selection or loop before it was complete by using a “go to” statement. The statement allowed the logic to “go to” any other part of the program whether it was within the same structure or not. Structured programming is sometimes called goto-less programming.

Maintenance—You and other programmers will find it easier to modify and maintain structured programs as changes are required in the future.

Modularity—Structured programs can be easily broken down into modules that can be assigned to any number of programmers. The routines are then pieced back together like modular furniture at each routine’s single entry or exit point. Additionally, a module often can be used in multiple programs, saving development time in the new project.

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

Recognizing Structure

TWO TRUTHS & A LIE Understanding the Reasons for Structure

1.

2.

3.

Structured programs are clearer than unstructured programs.

You and other programmers will find it easier to modify and maintain structured programs as changes are required in the future.

Structured programs are not easily divided into parts, making them less prone to error.

107

The false statement is #3. Structured programs can be easily broken down into modules that can be assigned to any number of programmers.

Recognizing Structure When you are beginning to learn about structured program design, it is difficult to detect whether a flowchart of a program’s logic is structured. For example, is the flowchart segment in Figure 3-18 structured?

Yes, it is. It has a sequence and a selection structure.

Is the flowchart segment in Figure 3-19 structured?

Yes, it is. It has a loop and a selection within the loop.

Is the flowchart segment in the upper-left corner of Figure 3-20 structured?

B? Yes No

A

C

Figure 3-18 Example 1 © 2015 Cengage Learning

No, it is not built from the three basic structures. One way to straighten out an unstructured flowchart segment is to use the “spaghetti bowl” method; that is, picture the flowchart as a bowl of spaghetti that you must untangle. Imagine you can grab one piece of pasta at the top of the bowl and start pulling. As you “pull” each symbol out of the tangled mess, you can untangle the separate paths until the entire segment is structured.

D?

E?

Yes

No No Yes

F

Figure 3-19 Example 2 © 2015 Cengage Learning

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

C H A P T E R 3 Understanding Structure

108 H?

I? Yes

Yes No

No

No

G

J K H?

G

H?

G

J

G 1

2

3

4

5

6

7

No Yes H?

I?

G

J

No

No

Yes H?

I?

G

J J

No

No

Yes

Yes

H?

I?

G

J J K

No

No

Yes

Yes

H?

I?

G

J J K

This program segment is Don’t Do It

not structured.

Figure 3-20 Example 3 and process to structure it © 2015 Cengage Learning

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

109

Recognizing Structure

Look at the diagram in the upper-left corner of Figure 3-20. If you could start pulling the arrow at the top, you would encounter a box labeled G. (See Figure 3-20, Step 1.) A single process like G is part of an acceptable structure—it constitutes at least the beginning of a sequence structure.

Imagine that you continue pulling symbols from the tangled segment. The next item in the flowchart is a question that tests a condition labeled H, as you can see in Figure 3-20, Step 2. At this point, you know the sequence that started with G has ended. Sequences never have questions in them, so the sequence is finished; either a selection or a loop is beginning with question H. A loop must return to the loop-controlling question at some later point. You can see from the original logic that whether the answer to H is Yes or No, the logic never returns to H. Therefore, H begins a selection structure, not a loop structure.

To continue detangling the logic, you would pull up on the flowline that emerges from the left side (the No side) of Question H. You encounter J, as shown in Step 3 of Figure 3-20. When you continue beyond J, you reach the end of the flowchart.

Now you can turn your attention to the Yes side (the right side) of the condition tested in H. When you pull up on the right side, you encounter Question I. (See Step 4 of Figure 3-20.)

In the original version of the flowchart in Figure 3-20, follow the line on the left side of Question I. The line emerging from the left side of selection I is attached to J, which is outside the selection structure. You might say the I-controlled selection is becoming entangled with the H-controlled selection, so you must untangle the structures by repeating the step that is causing the tangle. (In this example, you repeat Step J to untangle it from the other usage of J.) Continue pulling on the flowline that emerges from J until you reach the end of the program segment, as shown in Step 5 of Figure 3-20.

Now pull on the right side of Question I. Process K pops up, as shown in Step 6 of Figure 3-20; then you reach the end.

At this point, the untangled flowchart has three loose ends. The loose ends of Question I can be brought together to form a selection structure; then the loose ends of Question H can be brought together to form another selection structure. The result is the flowchart shown in Step 7 of Figure 3-20. The entire flowchart segment is structured—it has a sequence followed by a selection inside a selection.

If you want to try structuring a more difficult example of an unstructured program, see Appendix B.

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

C H A P T E R 3 Understanding Structure

TWO TRUTHS & A LIE Recognizing Structure

110 1. Some processes cannot be expressed in a structured format.

2. An unstructured flowchart can achieve correct outcomes.

3. Any unstructured flowchart can be “detangled” to become structured.

The false statement is #1. Any set of instructions can be expressed in a structured format.

Structuring and Modularizing Unstructured Logic Recall the dog-washing process illustrated in Figure 3-1 at the beginning of this chapter. When you look at it now, you should recognize it as an unstructured process. Can this process be reconfigured to perform precisely the same tasks in a structured way? Of course!

Figure 3-21 demonstrates how you might approach structuring the dog-washing logic. Part 1 of the figure shows the beginning of the process. The first step, Catch dog, is a simple sequence. This step is followed by a question. When a question is encountered, the sequence is over, and either a loop or a selection starts. In this case, after the dog runs away, you must catch the dog and determine whether he runs away again, so a loop begins. To create a structured loop like the ones you have seen earlier in this chapter, you can repeat the Catch dog process and return immediately to the Does dog run away? question.

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

111

Structuring and Modularizing Unstructured Logic

Catch dog

Catch dog

Does dog run away?

start

Catch dog

Catch dog

Yes

Yes

Yes

Yes

Yes

No

No

No

No

No Turn off water

Does dog run away?

Turn on water

Catch dog

Does dog run away?

start

Catch dog

Yes

No

Does dog run away?

Turn on water

Catch dog

Catch dog

Turn off water

Does dog run away?

Turn on water

Does dog run away?

start

Catch dog

Don’t Do It This loop is not structured because its logic does not return to the question after its body executes.

1

3

2

Figure 3-21 Steps to structure the dog-washing process © 2015 Cengage Learning

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

C H A P T E R 3 Understanding Structure

In the original flowchart in Figure 3-1, you turn on the water when the dog does not run away. This step is a simple sequence, so it can correctly be added after the loop. When the water is turned on, the original logic checks whether the dog runs away after this new development. This starts a loop. In the original flowchart, the lines cross, creating a tangle, so you repeat as many steps as necessary to detangle the lines. After you turn off the water and

112 catch the dog, you encounter the question Does dog have shampoo on? Because the logic has not yet reached the shampooing step, there is no need to ask this question; the answer at this point always will be No. When one of the logical paths emerging from a question can never be traveled, you can eliminate the question. Part 2 of Figure 3-21 shows that if the dog runs away after you turn on the water, but before you’ve gotten the dog wet and shampooed him, you must turn the water off, catch the dog, and return to the question that asks whether the dog runs away.

The logic in Part 2 of Figure 3-21 is not structured because the second loop that begins with the question Does dog run away? does not immediately return to the loop- controlling question after its body executes. So, to make the loop structured, you can repeat the actions that occur before returning to the loop-controlling question. The flowchart segment in Part 3 of Figure 3-21 is structured; it contains a sequence, a loop, a sequence, and a final, larger loop. This last loop contains its own sequence, loop, and sequence.

After the dog is caught and the water is on, you wet and shampoo the dog. Then, according to the original flowchart in Figure 3-1, you once again check to see whether the dog has run away. If he has, you turn off the water and catch the dog. From this location in the logic, the answer to the Does dog have shampoo on? question will always be Yes; as before, there is no need to ask a question when there is only one possible answer. So, if the dog runs away, the last loop executes. You turn off the water, continue to catch the dog as he repeatedly escapes, and turn the water on. When the dog is caught at last, you rinse the dog and end the program. Figure 3-22 shows both the complete flowchart and pseudocode.

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

113

Structuring and Modularizing Unstructured Logic

start

stop

Catch dog

Catch dog

Turn off water

Turn on water

Catch dog

Catch dog

Turn on water

Get dog wet and apply shampoo

No

No

No

No

Yes

Yes

Yes

Does dog run away?

Does dog run away?

Does dog run away?

Does dog run away?

Turn off water

Turn on water

Catch dog

Rinse dog

Catch dog

No

Yes

Yes Does dog run away?

start Catch dog while dog runs away

Catch dog endwhile Turn on water while dog runs away

Turn off water Catch dog while dog runs away

Catch dog endwhile Turn on water

endwhile Get dog wet and apply shampoo while dog runs away

Turn off water Catch dog while dog runs away

Catch dog endwhile Turn on water

endwhile Rinse dog

stop

Figure 3-22 Structured dog-washing flowchart and pseudocode © 2015 Cengage Learning

The flowchart in Figure 3-22 is complete and is structured. It contains alternating sequence and loop structures.

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

C H A P T E R 3

Understanding Structure

114

Figure 3-22 includes three places where the sequence-loop-sequence of catching the dog and turning on the water are repeated. If you wanted to, you could modularize the duplicate sections so that their instruction sets are written once and contained in a separate module. Figure 3-23 shows a modularized version of the program; the three module calls are shaded.

Rinse dog

Does dog run away?

Does dog run away?

Does dog run away?

Yes

Yes

Yes

No

No

No

start

catchDogStartWater()

catchDogStartWater()

catchDogStartWater()

catchDogStartWater()

Get dog wet and apply shampoo

Turn off water

Catch dog

Catch dog

Turn off water

Turn on water

stop

return

start catchDogStartWater() while dog runs away

Turn off water catchDogStartWater()

endwhile Get dog wet and apply shampoo while dog runs away

Turn off water catchDogStartWater()

endwhile Rinse dog

stop

catchDogStartWater() Catch dog while dog runs away

Catch dog endwhile Turn on water

return

Figure 3-23 Modularized version of the dog-washing program © 2015 Cengage Learning

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

115

Structuring and Modularizing Unstructured Logic

One advantage to modularizing the steps needed to catch the dog and start the water is that the main program becomes shorter and easier to understand. Another advantage is that if this process needs to be modified, the changes can be made in just one location. For example, if you decided it was necessary to test the water temperature each time you turned on the water, you would add those instructions only once in the modularized version. In the original version in Figure 3-22, you would have to add those instructions in three places, causing more work and increasing the chance for errors.

No matter how complicated, any set of steps can always be reduced to combinations of the three basic sequence, selection, and loop structures. These structures can be nested and stacked in an infinite number of ways to describe the logic of any process and to create the logic for every computer program written in the past, present, or future.

For convenience, many programming languages allow two variations of the three basic structures. The case structure is a variation of the selection structure and the do loop is a variation of the while loop. You can learn about these two structures in Appendix D. Even though these extra structures can be used in most programming languages, all logical problems can be solved without them.

Watch the video Structuring Unstructured Logic.

TWO TRUTHS & A LIE Structuring and Modularizing Unstructured Logic

1. When you encounter a question in a logical diagram, a sequence should be ending.

2. In a structured loop, the logic returns to the loop-controlling question after the loop body executes.

3. If a flowchart or pseudocode contains a question to which the answer never varies, you can eliminate the question.

The false statement is #1. When you encounter a question in a logical diagram, either a selection or a loop should start. However, any type of structure might end before the question is encountered.

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

C H A P T E R 3 Understanding Structure

Chapter Summary Spaghetti code is the descriptive name for unstructured program statements that do not follow the rules of structured logic. 116 Clearer programs can be constructed using only three basic structures: sequence, selection, and loop. These three structures can be combined in an infinite number of ways by stacking and nesting them. Each structure has a single entry point and a single exit point; one structure can attach to another only at one of these points.

A priming input is the statement that gets the first input value prior to starting a structured loop. Usually, the last step within the loop body gets the next and all subsequent input values.

Programmers use structured techniques to promote clarity, professionalism, efficiency, and modularity.

One way to order an unstructured flowchart segment is to imagine it as a bowl of spaghetti that you must untangle.

Any set of logical steps can be rewritten to conform to the three structures: sequence, selection, and loop.

Key Terms Spaghetti code is snarled, unstructured program logic.

Unstructured programs are programs that do not follow the rules of structured logic.

Structured programs are programs that do follow the rules of structured logic.

A structure is a basic unit of programming logic; each structure is a sequence, selection, or loop.

A sequence structure contains series of steps executed in order. A sequence can contain any number of tasks, but there is no option to branch off, skipping any of the tasks.

A selection structure or decision structure contains a question, and, depending on the answer, takes one of two courses of action before continuing with the next task.

An end-structure statement designates the end of a pseudocode structure.

An if-then-else is another name for a dual-alternative selection structure.

Dual-alternative ifs (or dual-alternative selections) define one action to be taken when the tested condition is true and another action to be taken when it is false.

Single-alternative ifs (or single-alternative selections) take action on just one branch of the decision.

The null case or null branch is the branch of a decision in which no action is taken.

A loop structure continues to repeat actions while a test condition remains true.

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

117

Exercises

A loop body is the set of actions that occur within a loop.

A while loop is a structure that continues to repeat a process while some condition remains true.

Repetition and iteration are alternate names for a loop structure.

A while…do loop is an alternate name for a while loop.

Stacking structures is the act of attaching structures end to end.

Nesting structures is the act of placing a structure within another structure.

A block is a group of statements that executes as a single unit.

A priming input or priming read is the statement that reads the first input prior to starting a structured loop that uses the data.

Goto-less programming is a name to describe structured programming, because structured programmers do not use a “go to” statement.

Exercises

Review Questions

1. Snarled program logic is called code.

a. snake c. spaghetti b. string d. gnarly

2. The three structures of structured programming are .

a. sequence, selection, and loop c. sequence, order, and process b. selection, loop, and iteration d. if, else, and then

3. A sequence structure can contain .

a. only one task c. no more than three tasks b. exactly three tasks d. any number of tasks

4. Which of the following is not another term for a selection structure?

a. decision structure c. dual-alternative if structure b. loop structure d. if-then-else structure

5. The structure that tests a condition, takes action if the result is true, and then tests the condition again can be called all of the following except a(n) .

a. iteration c. repetition b. loop d. if-then-else

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

C H A P T E R 3 Understanding Structure

6. Placing a structure within another structure is called the structures.

a. stacking c. building b. untangling d. nesting

7. Attaching structures end to end is called . 118

a. stacking c. building b. untangling d. nesting

8. When an action is required if a condition is true, but no action is needed if it is false, you use a .

a. sequence c. dual-alternative selection b. loop d. single-alternative selection

9. To take action as long as a condition remains true, you use a .

a. sequence c. dual-alternative selection b. loop d. single-alternative selection

10. When you must perform one action when a condition is true and a different one when it is false, you use a .

a. sequence c. dual-alternative selection b. loop d. single-alternative selection

11. Which of the following attributes do all three basic structures share?

a. Their flowcharts all contain exactly three processing symbols. b. They all have one entry and one exit point. c. They all contain a decision. d. They all begin with a process.

12. Which is true of stacking structures?

a. Two incidences of the same structure cannot be stacked adjacently. b. When you stack structures, you cannot nest them in the same program. c. Each structure has only one point where it can be stacked on top of another. d. When you stack structures, the top structure must be a sequence.

13. When you input data in a loop within a program, the input statement that precedes the loop .

a. is the only part of the program allowed to be unstructured b. cannot result in eof c. is called a priming input d. executes hundreds or even thousands of times in most business programs

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

119

Exercises

14. A group of statements that executes as a unit is a .

a. block c. chunk b. family d. cohort

15. Which of the following is acceptable in a structured program?

a. placing a sequence within the true branch of a dual-alternative decision b. placing a decision within a loop c. placing a loop within one of the steps in a sequence d. All of these are acceptable.

16. In a selection structure, the structure-controlling question is .

a. asked once at the beginning of the structure b. asked once at the end of the structure c. asked repeatedly until it is false d. asked repeatedly until it is true

17. When a loop executes, the structure-controlling question is .

a. asked exactly once b. never asked more than once c. asked either before or after the loop body executes d. asked only if it is true, and not asked if it is false

18. Which of the following is not a reason for enforcing structure rules in computer programs?

a. Structured programs are clearer to understand than unstructured ones. b. Other professional programmers will expect programs to be structured. c. Structured programs usually are shorter than unstructured ones. d. Structured programs can be broken down into modules easily.

19. Which of the following is not a benefit of modularizing programs?

a. Modular programs are easier to read and understand than nonmodular ones. b. If you use modules, you can ignore the rules of structure. c. Modular components are reusable in other programs. d. Multiple programmers can work on different modules at the same time.

20. Which of the following is true of structured logic?

a. You can use structured logic with newer programming languages, such as Java and C#, but not with older ones.

b. Any task can be described using some combination of the three structures: sequence, selection, and loop.

c. Structured programs require that you break the code into easy-to-handle modules that each contain no more than five actions.

d. All of these are true. Copyright 2015 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.

C H A P T E R 3 Understanding Structure

Programming Exercises

1. In Figure 3-10, the process of buying and planting flowers in the spring was shown using the same structures as the generic example in Figure 3-9. Use the same logical structure as in Figure 3-9 to create a flowchart or pseudocode that describes some other process you know.

120

2. Each of the flowchart segments in Figure 3-24 is unstructured. Redraw each segment so that it does the same thing but is structured.

a.

B? Yes

No

A

C

b.

E? Yes No

D

H

I

F

G? Yes

No

c.

L? Yes

Yes

No

K

P

R

M

N

O? Yes

No

Q?

No

Figure 3-24 Flowcharts for Exercise 2 (continues) © 2015 Cengage Learning

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

121

Exercises

(continued)

d.

T? Yes

Yes

No

S

Y

A

U

V

X

Yes

No

Z?

W?

No

e.

B? Yes

Yes

No

G

I

I

C

D

F

Yes

No

H?

E?

No

Figure 3-24 Flowcharts for Exercise 2 © 2015 Cengage Learning

3. Write pseudocode for each example (a through e) in Exercise 2, making sure your pseudocode is structured and accomplishes the same tasks as the flowchart segment.

4. Assume that you have created a mechanical arm that can hold a pen. The arm can perform the following tasks:

Lower the pen to a piece of paper.

Raise the pen from the paper.

Move the pen 1 inch along a straight line. (If the pen is lowered, this action draws a 1-inch line from left to right; if the pen is raised, this action just repositions the pen 1 inch to the right.)

Turn 90 degrees to the right.

Draw a circle that is 1 inch in diameter.

Draw a structured flowchart or write structured pseudocode describing the logic that would cause the arm to draw or write the following. Have a fellow student act

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

C H A P T E R 3 Understanding Structure

as the mechanical arm and carry out your instructions. Don’t reveal the desired outcome to your partner until the exercise is complete.

a. a 1-inch square

b. a 2-inch by 1-inch rectangle 122 c. a string of three beads

d. a short word (for example, cat)

e. a four-digit number

5. Assume that you have created a mechanical robot that can perform the following tasks:

Stand up.

Sit down.

Turn left 90 degrees.

Turn right 90 degrees.

Take a step.

Additionally, the robot can determine the answer to one test condition:

Am I touching something?

a. Place two chairs 20 feet apart, directly facing each other. Draw a structured flowchart or write pseudocode describing the logic that would allow the robot to start from a sitting position in one chair, cross the room, and end up sitting in the other chair. Have a fellow student act as the robot and carry out your instructions.

b. Draw a structured flowchart or write pseudocode describing the logic that would allow the robot to start from a sitting position in one chair, stand up and circle the chair, cross the room, circle the other chair, return to the first chair, and sit. Have a fellow student act as the robot and carry out your instructions.

6. Draw a structured flowchart or write pseudocode that describes the process of guessing a number between 1 and 100. After each guess, the player is told that the guess is too high or too low. The process continues until the player guesses the correct number. Pick a number and have a fellow student try to guess it by following your instructions.

7. Looking up a word in a dictionary can be a complicated process. For example, assume that you want to look up logic. You might open the dictionary to a random page and see juice. You know this word comes alphabetically before logic, so you flip forward and see lamb. That is still not far enough, so you flip forward and see monkey. You have gone too far, so you flip back, and so on. Draw a structured flowchart or write pseudocode that describes the process of looking up a word in a dictionary. Pick a word at random and have a fellow student attempt to carry out your instructions.

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

123

Exercises

8. Draw a structured flowchart or write structured pseudocode describing how to do a load of laundry. Include at least two decisions and two loops.

9. Draw a structured flowchart or write structured pseudocode describing how to study for an exam. Include at least two decisions and two loops.

10. Draw a structured flowchart or write structured pseudocode describing how to wrap a present. Include at least two decisions and two loops.

11. Draw a structured flowchart or write structured pseudocode describing the steps to prepare your favorite dish. Include at least two decisions and two loops.

Performing Maintenance

1. A file named MAINTENANCE03-01.txt is included with your downloadable stu- dent files. Assume that this program is a working program in your organization and that it needs modifications as described in the comments (lines that begin with two slashes) at the beginning of the file. Your job is to alter the program to meet the new specifications.

Find the Bugs

1. Your downloadable files for Chapter 3 include DEBUG03-01.txt, DEBUG03-02.txt, and DEBUG03-03.txt. Each file starts with some comments that describe the problem. Comments are lines that begin with two slashes (//). Following the comments, each file contains pseudocode that has one or more bugs you must find and correct.

2. Your downloadable files for Chapter 3 include a file named DEBUG03-04.jpg that contains a flowchart with syntax and/or logical errors. Examine the flowchart and then find and correct all the bugs.

Game Zone

1. Choose a simple children’s game and describe its logic, using a structured flowchart or pseudocode. For example, you might try to explain Rock, Paper, Scissors; Musical Chairs; Duck, Duck, Goose; the card game War; or the elimination game Eenie, Meenie, Minie, Moe.

2. Choose a television game show such as Wheel of Fortune or Jeopardy! and describe its rules using a structured flowchart or pseudocode.

3. Choose a sport such as baseball or football and describe the actions in one limited play period (such as an at-bat in baseball or a possession in football) using a structured flowchart or pseudocode.

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

C H A P T E R 3 Understanding Structure

Up for Discussion

1. Find more information about one of the following people and explain why he or she is important to structured programming: Edsger Dijkstra, Corrado Bohm, Giuseppe

124 Jacopini, and Grace Hopper.

2. Computer programs can contain structures within structures and stacked structures, creating very large programs. Computers also can perform millions of arithmetic calculations in an hour. How can we possibly know the results are correct?

3. Develop a checklist of rules you can use to help you determine whether a flowchart or pseudocode segment is structured.

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

  • Structure Bookmarks
    • Artifact
    • Buy. Rent. Access. Access student data files and other study tools on cengagebrain.com. For detailed instructions visit http://solutions.cengage.com/ctdownloads/ Store your Data Files on a USB drive for maximum effi ciency in organizing and working with the files. Macintosh users should use a program to expand WinZip or PKZip archives. Ask your instructor or lab coordinator for assistance.
    • E I G H T H E D I T I O N
    • Artifact
    • Artifact
    • Artifact
    • Artifact
    • Artifact
    • Artifact
    • Artifact
    • Artifact
    • Artifact
    • Artifact
    • Artifact
    • C O N T E N T S
    • Artifact
    • C O N T E N T S
    • P R E F A C E
    • Artifact
    • Artifact
    • Artifact
    • Artifact
    • Artifact
    • Artifact
    • Artifact
    • Artifact
    • Artifact
    • Artifact