) SECOND EDITION < JUST ENOUGH PROGRAMMING LOGIC AND DESIGN JOYCE FARRELL ; · COURSE TECHNOLOGY I CENGAGE Learning Aun ra li a • 8r111I • Japan • K«u • Mexico · Singapore • S~ in • United Klngdom • Un1ttd Stales C°"l'.t .... :IDU~.._ .ua.--M<t• ....... -. • • -··-------------.. - .. --~· · ...Wiit',,_._ ....... _, 4$ ,_. .... WWl)lftlc'tftir....Ut.:....,n, ~ ................ ~-"90"'~ ............... .,c.W .... ZCIQllB'L ) This is an electronic version of the print teXtbook. Due to electronic rights restrictions, some third pany content may be suppressed Ed.ilorial review bas 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 iL For valuable information on pricing. previous editions, changes to current editions. and alternate formats. please visit www ccngage.comlhigbcred to search by JSBC'\# , author. title, or keyword for materials m your areas of interest C°"l'.t .... :IDU~.._ .ua.--M<t• ....... -. • • -··-------------.. - .. --~·· ~ ............... _, 4$ ,_. .... WWl)lftlc'tftir....Ut.:....,n, ~ ................ ~-"90"'~ ............... .,c.W .... ZCIQllB'L < , .. COURSE TECHNOLOGY I CENGAGE Learning· Just Enough Programm i ng L og ic and Desig n, Sec ond Editi on Joy ce Fa rr ell Executive Editor: Marie lee Acquisitions Ed itor: Brandi Shailer Senior Produa Manager: Alyssa Pratt Developmental Editor: Dan Seiter Associate Produa Manage r: Stephanie Lorenz Associate Marketing Manager: Shanna Shelton Senior Content Project Manage r: tatherine DiMa»a Associate Art Director: Faith Brosnan Senior Print Buyer: Julio Esperas Copyeditor: Michael Beckett Proofreader: Harold Johnson Indexer: Sharon Hilgenberg Compositor: lntegra Printed in the United States or America I 2 3 4 5 6 7 16 15 14 13 12 C 2013 Course Technology, Cengage Leaming ALL RIGHTS RESERVED No part of this work covered by the copyri ght here in may be reproduced, transmi tted , stored or used in any form or by any means-- graphic, electronic:. or mechanic.at, In cluding but not limited to photocopying, recording. scanning. digitizing, tap ing, Web distribution, information networks, or information storage and retr ie v;1I systems, except as permitted under Section 107 or 108 of the 1976 united States Copyri ght Act- without the prior written permission of the publisher. -, For product Information and technology assistance, contact us at Cen ga ge Learning Cu st om er & Sales S up po rt. www .ce ngage.com/support. For permission to use material from this text or product. su'bmit all requesu onllne at cengage.com/pe rm lsslons. Further permi ss i ons questions can be e-mailed to pe rmlsslonreques10cen ga g e.com. ISBN ·13: 97B· l · l11-82595 ·9 ISBN · lO: 1· 11 l· B2595·5 Course Technology 20 Channel Center Street Boston, MA 02210 USA Cengage learni ng is a l ead ing prov ider of customized learning soluti ons with office loc.ation:s around the globe, induding Singapore, the United Kingdom, Australia, Meic ico, Braz il, and J apan locate your local office at : in te rnational.c:enga ge .com/region Ce ngage Learning products are represented in canada by Nelson Education, ltd. For your lifelong learning solutions, visit course.ce ngage.com. Vis it our corporate Web site at cengage.com. Some of the product names and company names used In this book have been used for identificati on purposes only and may be trademarks or registered trademarks of their respective manufacturers and sellers. Course Technology, a part of Cengage learn ing, reserves the right to revise this publication an.d make changes from time to time in iu content without notice. ~ lOll~ i.c.m1 All Rip> R-M~"" ll0"""""4.-0< ~ iO •bokor iol*'- Doc.,......,.,..,. rl&OO.,....llllml .....,._ ft'"J'b< _«ol_ dlc ·--"°""'""" 6dilorul ~"" twcklalocd'tbMI. ..y ; : •e:S<OCtcat: ~ • ~ · .rrccttllcCl"«hD lrsllm&q~ocr.. Ca.ptc ~~ho rlJ}d. totl'llllO'lceddi:t•md<Oat:rccatq.Llmr' ~f·'· • ;• c ~b ~ ~:ai« tt.. ) < Brief Contents Preface ix CHAPTER 1 CHAPTER 2 CHAPTER 3 CHAPTER 4 CHAPTER 5 CHAPTER 6 CHAPTER 7 APPEND IX A APPENDIX B An Overview of Co mputers and Logi c Understandi ng Structure Making Dec isions Looping • • • • Arrays Us i ng Method s Object- Or iented Programming Understandi ng Numbering Systems a nd Computer Codes Two Special Structu res-case and do - wh ile ......... Index . 1 31 65 109 143 173 205 • • 225 231 237 m <'Ol')'rifl< 311:1.c..r.&.e-.. o\ll Rli!lb' ltco<rwd • ...,. ... l><copod.-·~ .. ·- ..... _ oo.. .. --. ~--I"") __ ,"' ................ 111c.-d~1 <Cb;liort• ~ lil1kll:o1il :"<\"""9 -~:hlf.a;t' J u:c:d ~dOa auc ~, d!«I dlocrt-cr&ll ~' 'J.'l"""'«r Cai.,...: ~ffbl2'n&d$k~tl9nC>-Mo-n"<'<:llblttl! _,.ttmtil 111.1~._..u,:tblUll1ttilliaWμ1«.d. > < iv Contents CHAPTER 1 CHAPTER 2 Pr ef ac e ix An Ov erv iew of Com pu t er s and Lo gic . 1 Understanding Computer Components and Operations . 2 Understanding the Pr ogramming Process . 5 Understanding the Pr oblem . 6 Planning the Logic . . . . . . . . . 7 Coding the Program . . . . . . . 8 Using Software to Tr anslate the Program into Machine Langu a ge . 8 Tes ting the Program . . . . . 9 P utting the Pr og r am into P roduction . . . . . 10 M aintaining the Pr ogram . . . . . . . . 10 Using Pseudocode Statements and Flowchart Symbols 11 The A dvantages of Re p etition . . 13 Using and Naming Variables and Constants 15 Assigning Values to Va!l'iables . . 17 Performing Arithm e tic Operations . . 18 Understanding Data T ypes and De claring Va r iables 19 Ending a Pr ogram by Using Sentinel Values . . 21 Understanding the Evolution of Prog r amming T echniques 23 Review Questions 24 Find the Bugs 26 Exercises . . . 27 Understa ndi ng S tr uc ture . . . Understanding Unstructured Spaghetti Code . . Understanding the Three Basic Structures: Sequenc e, Se l ection , and Loop The Sequence Structu re The Selection Structu re The Loop Structu re Combining Structu r es Using the Pr iming Input Unde r standing the R e asons for Structu re . 31 32 34 34 35 36 36 43 49 <'Ol')'rifl< 311:1.c..r.&.e-.. All Rli!lb' ltco<rwd • ...,. ... l><copod.-·~ .. ·- ..... _ oo.. .. --. ~--I"") __ ,"' ................ 111c.-d~1 <Cb;liort• ~ lil1kll:o1il :"<\"""9 -~:hlf.a;t' J u:c:d ~dOa auc ~, d!«I dlocrt-cr&ll ~' 'J.'l"""'«r Cai.,...: ~ffbl2'n&d$k~tl9nC>-Mo-n"<'<:llblttl! _,.ttmtil 111.1~._..u,:tblUll1ttilliaWμ1«.d. > Recognizing Structure and Structuring Unstructured Log ic 50 Structuring the Dog-Washing Process 54 Review Questions 58 Fi nd the Bugs 60 Exercises . . . 60 v CHAPTER 3 Making Decisions 65 Evaluati ng Boolean Expressions to Make Comparisons 66 Using the Relational Comparison Operators 70 Understanding AND Logic . . . . . . . . . 73 Nesting AND Decisio ns for Efficiency . . . . 75 Combining Decisions Using the AND Operator 78 Avo idin g Common Errors in an AND Selection 80 Understanding OR Logic . . . . . . . . 82 Writing OR Decisions for Efficiency . . . . . 84 Combining Decisions in an OR Selection . . 85 Avo i ding Common Errors in an OR Selection 87 Making Selections Within Ranges . . . . . . 91 Avo i ding Common Errors Whe n Using Range Checks 93 Understanding Precedence When Combining AND and OR Operators 97 Using the NOT Operator 99 Review Questions .100 Fi nd the Bugs 103 Exercises . . . . .103 CHAPTER 4 Looping 109 Understanding the Adva nt ages of Looping . . . . .110 Controlling Loops with Counters and Sentinel Values .110 Using a Definite whi 1e Loop with a Counter . . 111 Using an Indefinite wh i 1e Loop with a Sentinel Value 113 Nested Loops . . . . . . . . . . . . . . .117 Mix in g Constant and Variable Sentinel Values . . . . 119 Avoiding Common Loop Mistakes . . . . . . . . . . .123 M ista ke: Neglecting to Init iali ze the Loop Control Variable 123 Mistake: Neglecting to Alter the Loop Control Variable 125 M ist ake : Using the Wro ng Comparison with the Loop Control Variable . . . . . . . . . . . . . . . . . . . . . .127 Mistake: Including Statements Inside the Loop that Belong Outside the Loop 127 Using a for Loop . . . . . . . . . . . . . . . . . . . .129 ~ lOll~ i.c.m1 All Rip> R - M ~"" ll0""""4,-0< ~ iO • bokor iol*'- Doc.,.....,.,..,. rl&OO.,....llllml .....,._ ft'"J'b< _<ool_ dlc ·--"°""'""" 6dilorul ~"" twcklalocd'tbMI. ..y ; : •e:S<OCtcat: ~ • ~ · .rrccttllcCl"«hD lrsllm&q~ocr.. Ca.ptc ~~ho rlJ}d. totl'llllO'lceddi:t•md<Oat:rccatq.Llmr' ~f·'· • ;• c ~b ~ ~:ai« tt.. < vi - , CONTENT: S CHAPTER 5 CHAPTER 6 Common Loop App lications . . . . . Using a Loop to Accumulate Totals Using a Loop to Validate Data Review Questions find the Bugs Exercises Arrays Understanding Arrays . . . . . . . . . . How Arrays Occupy Computer Memory . . . . . Man i pulating an Array to Replace Nested Decis i ons Us in g Constants with Arrays . . . . Searching an Array Using a whi 1 e Loop Using Parallel Arrays . . . . . Improving Search Efficiency . . . . Remaining Within Array Bounds . . . Using a for Loop to Process Arrays Review Questions Ftnd the B ugs Exercises . . . Using Methods • • . . . . . 131 131 133 136 139 139 1 ~ .144 .1 44 146 154 155 .158 162 .164 .165 166 168 169 Understanding Modularity . . . . . . . . . . 17 4 Modu l arization Provides Abstraction . . . . 17 4 Modularization Reduces or E limin ates Repetition 175 Modularization Al l ows Multiple Programmers to Work on a Problem . . . . . . . . . . . . . . 176 M odularization Makes It Easier to Re use Work 176 Modu larization Provides Implementation Hi ding .177 Creating a Method . . . . . . . . . . . . . . 177 Modular izing Program Logic . . . . . . . . 178 Modular i zing a Program for Functiona l Cohesion and Portability 183 Understanding Scope . . . . . . . . . . . . .186 Creating Methods That Require a Single Parameter .189 Creating Methods That Requ i re Mu ltip le Parameters 192 Creating Methods That Return Values .193 Using Prewritten Built-In Methods .198 Rev i ew Questions 199 f and the B ugs 202 Exercises . . . 202 C°"l'.t .... :IDU~.._ .ua.--M<t• ....... -. • • -··-------------.. - .. --~· · ...Wiit',,_._ ....... _, 4$ ,_. .... WWl)lftlc'tftir....Ut.:....,n, ~ ................ ~-"90"'~ ............ ... .,c.W .... ZCIQllB'L ) < CHAPTER 7 APPENDIX A APPENDIX B Object-Oriented Programming 205 An Overview of Some Princ i ples of Object-Oriented Programming 206 Defining a Class . . . . . . . . 208 Instantiating an Object . . . . . . 209 Understanding Public and Private Access .211 vii Understanding Inheritance .21 4 Understanding Polymorphism . . . . 215 Understanding Encapsulation . . . . .217 Advantages of Obiect-Oriented Programm i ng 219 Rev i ew Questions .220 Find the Bugs . . . . . . . . . . 222 Exercises . . . . . . . . . . . 222 Understanding Numbering Systems and Com p uter Codes 225 Two Special St ru ct ure s- case and do - wh i 1 e Index . . . . . . • • . . . . 231 237 ~.M)CO.,...i..-.r,r ~-.-M.,- ... k..,W.-• · ;• l ............ ,...,0.. .. .-.....,._ __ ,...~_m.tw 111 ,,.._,.. _ _ ~ ,, Ea~ft"t'10i'-., ~ .. .. , :;: ; <'Clelllc* doa.o:ic mccr~ 6:1.tbeCl"a:.0 loaSqupai : ~ Lcwq 1.-no fllc n;tit •.-..c t'r· -" «WDI a'-181f'C-tl dlD ........ ~ &. > < ) C°"l'.t .... :IDU~.._ .ua.--M<t• ....... -. • • -··-------------.. - .. --~· · ...Wiit',,_._ ....... _, 4$ ,_. .... WWl)lftlc'tftir....Ut.:....,n, ~ ................ ~-"90"'~ ............... .,c.W .... ZCIQllB'L < Preface Just Enough Programming Logic and Design, Second Edition, is a guide to developing structured program logic for the beginning ptrogrammer. This book contains only seven chapters and two appendices- just enough to make the student comfortable with programming logic before tackling the syntax of a programming language. This book is intended to provide a complete, sound, yet compact start in logic- just enough for a short logic course, just enough as an accompaniment to a programming language book. or just enough as a supplement to a computer literacy course. 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 a mathematical background beyond high school business math. All the examples illustrate one or two major points; they do not contain so many features that students become lost following irrelevant and extraneous details. This book does not cover advanced logical concepts such as file handling, multidimensio, naJ arrays, or overloading methods. This book provides just enough material for a solid background in logic. no matter what programming languages students eventually use to write programs. Organization and Coverage Just Enough Programming Logic and Design, 2e introduces students to programming concepts and enforces good style and logical thinking. General programming concepts are introduced in Chapt er 1. Chapter 2 discusses the key concepts of structure, including what stru. cture is, how to recognize it, and most importantly, the advantages to writing structured programs. Chapters 3, 4, 5, and 6 cover selections, loops, arrays, and methods. Chapter 7 is a straightforward introduction to the concepts of obj ect -oriented programming. Two appendices allow students to gain extra experience with using the binary numbering system and understanding case and do-whi 1e structures. Just Enough Programming Logi c and Design, 2e combines text explanations with flowcharts and pseudocode examples to provide students with alternative means of expressing structured logic. Multiple-choice review questions, debugging exercises, and numerous detailed, full ~ program exercises at the end of each chapter reinforce understanding and retention of the material presented. ix COl')'rif!< 311:1.c..r.&.e-.. All Rli!lb' ltco<rwd • ...,..,. l><copod.-«~ la •11otc or·.o- oo.. .. --. ~--I"") -•1 II< Wl>'"""-dlc<80nlt d~1 <Cb;liort•~ lil1kll:o1il :"<\"""9 -~:hlf.a;t' J u:c:d ~dOa auc ~,. d!«I dlocrt-cr&ll ~' 'J.'l"""'«r Cai.,...: ~ffbl2'n&d$k~tl9nC>-Mo-n"<'<:llblttl! _,.ttmtil 111.1~._..u,:tblUll1ttilliaWμ1«.d. > < x 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 thelr learning style. .....,. __ _ ..... U'-"f -- if ,_., ' "" •• , • tMft • f ... tJ: ,,..,_._ °"'"'' ~ o~•<OWtl• .,.,,,~. · .... If •tt ... , ,,..... 4'¥\'&Nitt • o.1\4, ..... l .,.,,,, .. ...... -·· _,, (illnl-U ...__ ..... •·--- " ............................... .,,. ........ ..., .......... CICl1. •~c.-.rf•c.uc...._ ....... ~ .. O..ln Us ing the NOT Operator M1..- Pf'.'fUJ1uno. l;.nsu~i"' ._,... .. "'1f -"'°' '°"" •w rht IOOl ·~""·"" 10 .~ • ...,.... ..r • lloolt•n ""pmt.IOn. r •• ..... pa. 11 ... r.~ ....... ,...,,."' ell"""' ' • oo i. ~""" 1h111 "' cqu.tl rn 11 ~1 '-Of ... • II '""' Mt1Pl-f c.IJI. -·· VJDEO LESSONS help explain important chapter concepts Videos are available for complimentary download at www.cengagebrain com C°"l'.t .... :IDU~.._ .ua.--M<t• ....... -. • • -··-------------.. - .. --~· · ...Wiit',,_._ ....... _, 4$ ,_. .... WWl)lftlc'tftir....Ut.:....,n, ~ ................ ~-"90"'~ ............... .,c.W .... ZCIQllB'L ) < Un de rstanding Precedence When Combining AND and OR Operators Moot P"'P•Jllmln\l lln~ .no.. iw to «tmi>IM .. maoy ""° ood Olt """''""' "' 1111 ••r<...._ .. yw """' r"' ..... """"" that ""' ""'11 ..... ._ ....... ,, "' "' k..c 7'Son nd\ uf chttt ln&1> «>pa~ .. a tQQIM" You <•n cltd;rt ~ combM MlH SCOll f"q~ in 97 7S •nd IN th< ntultl;~• <c>Mit'°"' •uth • ,...........,. loloo llW- (ull<N1n11- f f se:ord ,_ Klh SCXlll NIJ s.c:ort1' ,... KlN: SCOtC 4NO KontJ - t(UI SCOU •h*" cl~~r~ •• ,.,, • .... ''""""" - "hil" ....,., ()n '"" "'"" Jund, d 1"!' .- "' - oal)· .... al tt- ...... "' ,.... ......... lhm tt. lopc .... 1o11 .... ~ If tc:o.re.J ,.. Hitt.SCc.£ OJt tcord ,.. Ml' SCOtE OI s~l ,.. Kiii\ SCOlE ttwt. c1a.J.•Cr~ • • ,.&$, .... c1a.s.s.Cr.ade • ·r~~i· .... " Theo• b«aono """' alfnl'IJ&at.<d - !"" <mtlbW ""°and Ol _....... •llhln th< ,,..,. """"""'- Wlwn )"" combln. AVJ and 011. -•Wl1< tht - °"""'"'' ..... prec~ mf"-'""'11 l hr-.&S Buolt"An , .• ~ .r~ <"·•hutf'CS linii. # ... ~ ..... --.'*Y---· -- ... ---- lft ........ ~ hllta.h.-..oll•)•.C11.l•w.at .. NnAW.~oc:bll .... ... _ _,,_ ......... _~·"""""---Olt- CJ'C.'UIP1 "-' ~ A.tm o;:ini:Jt • • •• 4 •Jlt lr'ld .. Oil.-• • ...,. ft1" n&rnpk, a:;nl~f II Pffllnrl' t)u1 dftmn.1"°'" ...... hn" .I tn{A'M' l h\o~tr" p:l\""1 ~ I""''"-"'• dd(OUnted lodt«. "-""'""' th.t ~•Ill•- .iio....J lot <hlldrct1 {•it<' ll •nd und<'rl ud ""''°'<II....,. I-lilt 6S ond nidtt) "''"' .Klt'nd G-r>trd .........,.. Tho f~"I ccK!c loo4 <<.>><>noble IM prodll«s mcorT<CI l'«IAlb bcclUli< th• •'t"- tlu l co11t.,.,. m< "'° O!'""•IO< ('C<' sfudlf1I} ....Juolt' brfur< t!w otlf tlUI ('Cl<lt.dm 1h< Ol .,....lO< If .t00 <• u me 11qo - u ,,_,. ri~I ... '"C'I , ..... OUtP'O't. -01J.C-0Uf\t •.PJ>lfu• ""'" rw Nl''l'i•· ·--th.ti • ,,,.,..,. pat,.., ,, 10 '~""old. !"'111'0 "'1wld Ml t~T • dl-..nt (Cl< b< llk,..('IJ CtJ '''" I cht I f U>l<m<ni. t.ht pan o4 th> r.,.......,,. m AJ -"""' 1ht N4l J.'11 r • <'"V ~ -C"l.,. t'Y.>ltMl<d lint. F<>t a 11).)..,. old •nd an R· xi ~ lOll~ tc.m.:1 All Rip> R-M~"" ll0""""4,-0< ~ iO •ltokor kl*'- Doc.,.....,...,.,. rl&OO.,....tltml .....,._ ft'.fJ'b< _<ool_ dlc ·--"°""'""" 6dilorul ~"" twcklalocd'tbMI. ..y ; : •e:S<OCtcat: ~ • ~· .rrccttllcCl"«hD lrsllm&q~ocr.. Ca.ptc ~~ho rlJ}d. totl'llllO'lceddi:t•md<Oat:rccatq.Llmr' ~f·'· • ;• c ~b ~ ~:ai« tt.. > < Assessment xii _ _.••••W•llll'"*"e.~.,.... .......... --- I( ••• ·- J ,..,._ti f!I IN...,....• ... •.., .,_ _. aa.1 ti ....-w...,, & Nut. ........ ti'ifilUI ............................... - .~ ....... - ................. .. "'*" ..... ,,.. ,...,.. ........,. ,, , ... ....,._. ...,.""' ................. titt\.now-. ' "" - 14 -~~-•r• 1t.n:•,....~••1~•~e.tuw ____ ,.,.., u ... , ... • ••I H • • .. •••O'I•· •• ,,,up ..... , ' ....,.... .. _ ... ,.., ... .... "Ot". ' ...... , • • .............. offY """ ' .. " ... ..... ,... "-- .,.. Mnlllrn J D:lln • ~..., .. Fllld I~~ 8'11S ,_.. .. t 't' tll'lhi°'*fltt"l_..tllM.~t t.c.Dl~C.-.. ... L•M.•'4l0ltu. t..l• _,.......J.o _ ••-•-.'°P°"" ,..._ ............. .. ..., .... ·- ·- ' - ' ... ... 11 ...... ................ ... ,_,.,"" ... - ---- ., .. , ._ ..... '- .. .. ..., .. ~ ""' ..... ·-~" .......... - ... ·--·--·-· -1o1oo.--...i • ..... f9all ......... _, 1t.......-1 ......... ~ l ~ .. .......,...., __., ...... '-' ..... ~.~., ......... ...., ............... , EXERCISES pr ovide opportunities to practice concepts These exe r cises increase in difficulty and allow students to explore logical programming concepts Each exercise can be completed using flowcharts, pseudocode , or both In addition , instructors can assig n the exercises as programming problems to be coded and executed in a particular • g language 101 C.,..t .... :IDU~.._ .ua.-- M<t• ....... -. ••-··-------------.. - .. --~· · ...Wiit',,_._ ....... _, 4$ ,_. .... WWl)lftlc'tftir....Ut.:....,n, ~ ................ ~-"90"'~ ............... .,c.W .... ZCIQllB'L ) < Instructor Resources Supplementary Material Just Enough Programming Logic and Design. 2e can be enhanced by the following materials: • Video . The author has created and narrated 25 short videos that explain and clarify key chapter topics. These videos are available for complimentary download at www .cen gagebrain.com • £..book Companions . Just Enough Visual Basic and Just Enough Java are e--book companions to Just Enough Programming Logic and Design. Each book introduces students to the basics of the respective programming language-just enough to get started writing programs that help demonstrate the logical concepts of programming. Each book's chapters parallel those in Just Enough Programming Logic and Design. These books provide complete, sound, yet compact foundations to using modern programming languages. • Debugging Exercises. Because examining programs critically and closely is a crucial programming skill, each chapter includes a Find the Bugs section in which programming examples contain syntax errors and logical errors for students to find and correct. Debugging Exercises are available for students to download at www.cengagebrain.com. These 6Jes are also available to instructors through the Lnstructor Resources CD and login.cengage.com. • Visual Logic•, version 2.0. Visual Logic is a simple but powerful tool fo r teaching programming logic and design without traditional high-level programming language syntax. Visual Logic uses flowcharts to explain the essential programming concepts discussed in this book, including variables, input, assignment, output, conditions. loops. procedures, graphics, arrays. and files. Visual Logic also interprets and executes flowcharts, providing students with immediate and accurate feedback. Visual Logic combines the power of a high-level language with the ease and simplicity of flowcharts. Visual Logic is available for purchase along with your text. Contact your instructor or your Cengage Learning sales representative for more information. Instructor Resources The following teaching tools are available to the instructor on a single CD-ROM. Many are also available for download at our Instructor Companion Site. Simply search fo r this text at login.cengage.com An instructor login is required. • El ectronic 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 Overviews, Chapter Objectives, Teaching Tips, Quick Quizzes, Class Discussion Topics, Additional Projects, Additional Resources, and Key Terms. A sample syllabus is also available. • PowerPolnt Presentations. This text provides PowerPoint slides to accompany each chapter. Slides may be used to guide classroom presentations. to make available to students for chapter review, or to print as classroom handouts. Files are provided for every xiii C°"l'.t .... :IDU~.._ .ua.--M<t• ....... -. • • -··-------------.. - .. --~· · ...Wiit',,_._ ....... _, 4$ ,_. .... WWl)lftlc'tftir....Ut.:....,n, ~ ................ ~-"90"'~ ............... .,c.W .... ZCIQllB'L ) < Ack no wle dgme nts figure in the text instructors may use the files to customize PowerPoint slides, illustrate quizzes, or create handouts. • Solutions. Suggested solutions to r eview questions and exercises are available. • Exam View. This textbook is accompanied by Exam View, a powerful testing software xiv package that allows instructors to create and administer printed, LAN-based, and Inte rn et exams. Exam View includes hundreds of questions that correspond to the text, enabling students to generate detailed study guides that include page references for further review. The computer-based and Internet testing components allow students to take exams at their computers, and save the instructor ti.me by grading each exam automatically. These test banks are also available in Blackboard, Web CT, and Angel compatible fo rmats. Acknowledgments I would like to thank all of the people who contributed to the production of this boo k. Dan Seiter served as Development Editor, making suggestions and corrections that make this book a superior pr oduct T hanks also to Alyssa Pratt, Senior Product Manager; Brandi Shailer, Acquisitions Editor; and Green Pen QA. Technical Editors. l tha nk the reviewers who provided he lpful and insightful comments during the development of this book, including Tom Johnson, California State University Long Beach; and Charlene Seymour-La n e, Brown Mackie College. As always, thanks to my husband, Geoff, for his constant support. FinaJJy, this book is dedicated to Xander Nakos. - Joyce Fan-ell °""""')(> ' '°"""'" 1.r-iw All .... - •i.t ..... ._.. ..-..1.• . , . , ... .. - ... - °"" ·- ~ --- _....,ti. '"h .. - ... - -~· · ) < An Overview of Computers and Logic After completing this chapter, you will be able to : @) Explain computer components and operations ® Discuss the steps invotved in the programming process @) Use pseudocode statements and flowchart symbols @> Use and name variables and constants @) Explain data types and declare var i ab l es @) End a program by us i ng sentinel values @) Discuss the evolution of programming techniques C-:lllUC.S.U.W. ~kll!D-- ....,_...,...,...__ •-•la .... -•-lfl!OL----_,.., q; ,_., __ _, 4 •l ----11111., _ ....... ~- ... --.... "-~-·-·--- .. .,_. ..... .. =-lL ) < An Overview of Compute rs and Logic Understanding Computer Components and Operations Hardware and software are the two major components of any computer system. • Hardware is the equipment, or the devices, associated with a computer. 2 • Software is computer instructions; software tells the hardware what to do. Software is pro1rams, which are instruction sets written by programmers. You can buy prewritten programs (such as Microsoft Word, iTunes, or The Sims) that are stored on a disk or that you download from the Web. Alternatively, you can write your own programs. When you write software instructions, you are programmina,. Software can be classified into two broad types: • ApplJcation software comprises all the programs you apply to a task- word-processing programs, spreadsheets, payroll and inve ntory programs, and even games. • System software comprises the programs you use to manage your computer, including operating systems such as Windows, L in ux, or UNLX. This book focuses on the logic used to write application software programs, although many of the co ncepts apply to both types of software. Together, computer hardware and software accomplish three major operations: • Input- Hardware devices that perform input operations include keyboards and mice. Through these devices, data, or facts, enter the computer system. • Processin& -P rocessing data items may involve organizing them, checking them for accuracy, or performing mathematical operations on them. The hardware component that performs these types of tasks is the ~ntral processln1 unit or CPU • Output- After data items have been processed, they become Information. Information often is sent to a printer, monitor, or some other output device so people can view, interpret, and use the results. Sometimes, you store output on hardware, such as a disk or Oash media that holds information for later retr ieval as input for another program. You write software instructions in a computer programmin& lan1ua1e, such as Visual Basic, C#, C++, or Java. Just as some people speak English and others speak Japanese, programmers write programs in differenl languages. Some programmers work exclusively in one language, whereas others know severaJ and use the one that seems most appropriate for the task at hand. The instructions you write are called program code; when you write a program, you are codln& the program. Program code is also called source code. No matter which programming language a computer programmer uses, the language has rules governing its word usage and punctuation. These rules are the syntax of the language. lf 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 orde r, misspelled a word, and used a wrong word. However, computers are not C...,.,.lOI:~.._., ....... _,...._"" ..... -- ... · ·-··-0..•_.,... ____ ..... 41 __ .. _ .._ _.oq..., - ......... ~- .. ., 41 ·----~--- "-"'" ec.,...,'- __ ,,. ____ .. ei_lf .... _ ... > < Understanding Computer Components an d Operations nearly as smart as most people; with a compllter, you might as well have asked, "Xpu mxv ot dodnm cad.I B? " Unless the syntax is perfect, the computer cannot interpret the programming language instruction at all. Every computer operates on circuitry that consists of millions of on /off switches. Each programming language uses a piece of software to translate programming language statements into object code , which is the computer's on /off circuitry language, or machine l anguage Machine language is represented as a series of Os and ls, also called binary form The language translation software that converts a programmer's statements to binary form is called a compiler or interpreter, and it issues a message if you have made a syntax error- that is, if you have misspelled a programming language word or used incorre ct punctuation. Therefore, syntax errors are relatively easy to locate and cor .rect because your compiler or interpreter highlights them. and your program will not run until all such errors are corrected. Although compilers and l nterp<eters work in slightly different way s. their basic function ls the same-to translate your programming statements in to code the computer can use The use of a compiler or an in t erpreter depends on which programming language is used. However, there are some languages for wh i ch both compilers and int erpreters are available When a program's instructions are carried out, the program runs or executes A program that Is free of syntax errors can be executed, but it might not produce cor rect results. for a program to work properly, you must give the instructions to the computer in a specific sequence, you must not leave any instructions out, and you must not add extraneous instructions. By doing this, you are developing the logic of the computer program. Suppose you instruct someone to make a cake as follows: • Stir • Add two eggs • Add a gallon of gasoline -4---- • Bake at 350 degrees for 45 minutes • Add three cups of flour Don'tDo It Oorl't bake a cake lite this! The dangerous cake-baking instructions are shown with a warning icon. You will see this icon when a table or figure contains a piogramming practice thal is being used as an ex.ample of what not to do. Even though the cake-baking instructions use correct English spelling and grammar, the instructions are out of sequence, some are missing. and some instructions belong to procedures other than baking a cake. (Some programmers make a distinction between syntax errors, which stem from incorrect spelling and punctuation, and semantic errors , which occur when the grammar is correct but the statement makes no sense in the current context.} If you follow these instructions, you will not make an edible cake, and you may end up with a disaster. Such logical errors are much more difficult to locate than syntax errors. The cake recipe is an extreme example, but suppose the error was more subtle. For ex.ample, the C.,,tlrlla»:JC...,._... ADll...,..-.. ,.... ...,_...-... '••-••,_o.c._,-. __ ,_,,,_.,.l .. ;; a••-..,•--~· • 3 > < 4 M Overview of Compute rs and Logic correct recipe might require three eggs instead of two, or might require a teaspoon of vanilla. It is easy to determine whether eggs is spelled incorrectly in a recipe, but perhaps impossible for you to know if there are too few eggs until after the cake is baked and you taste it. Similarly, it is easy for a compiler or interpreter to locate syntax errors. but often impossible for it to locate logical er rors until the program executes. Just as baking directions can be provided in French, German, or Spanish, the logic of a program can be expressed in any number of programming languages. This book focuses almost exclusively on logic development. Because this book is not concerned with a specific language, the programming examples could have been written in Japanese, C++, or Java. The logic is the same in any language. For convenience, the book uses English! Once instructions have been input to the computer and translated into machine language, a program can execute. You can write a program that takes a number (an input step), doubles it (processing), and tells you the answer (output) in a programming language such as Java or C++, but if you wrote it using English-like statements, it would look like this: Input ori gi na 1 Number. Compute calculatedAnswer = originalNumber times 2. Output calculatedAnswer. The instruction to Input ori gi nal Number 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 and store it at a memory location named ori gi na l Number. Computers often have several input devices, including a keyboard, mouse, USB port, and CD drive. When you learn a specific programming language, you learn how to tell the computer which input device to access for input for the current program. Usually, without special instructions to the contrary, the default input device is the keyboard. Logically, however, it doesn't matter which hardware device is used, as long as the computer knows to look for a number. The logic of the input operation-that the computer must obtain a number for input, and must do so before multiplying the number by 2-remains the same regardless of the input hardware device. The same is true in your daily life. If your boss says, ~Get Joe Parker 's phone number for me," it does not matter how you find the number. For example, you might look it up in a phone book. on your cell phone, on the internet, or call a friend who knows the number. The step that occurs when the arithmetic is performed to double original Number is an example of a processing step. Mathematical operations are not the only kind of processing, but they are very typical. After you write a program, it can be used on computers of different brand names, sizes, and speeds. When you make a phone call, your message gets through whether you use a land line or a cell phone, and it doesn 't matter which company made your cell phone. Similarly, whether you use an IBM, Macintosh, Linux, or UNIX operating system, and whether you use a laptop computer or an expensive mainframe at your university, multiplying by 2 is the same process. The hardware is not important; the logical process is. ln the number-doubling program, the Output calculatedAnswer statement represents an output operation. Within a particular program, this statement could cause the output to appear on the monitor (which might be a flat panel screen or a cathode-ray tube), or the output could go to a printer (which could be laser or ink-jet), or the output could be written Copyrlp l012 C..pa< l.<ftll;a. All R1;lll> R.,.!\'Od. M.1) - b< cqilcd. -cr~ri bo •- Ot bo ...... Due: IO~ npy..-. ddo! Pl"f-- ""1 b< :;op;catd -II>< dlool: -'<>< ~· ~ EditoNI "''~ bd 4c!cmtd am uy !i»ppm6Cd ccrJcN doa QOC. tlllltaialty 11&\.1. ax. O\cnJl kwciq o.p:ric:ia.. Cc~ lamtq, mct\n 0c rigJIC 10 tCllO\t- .mibooll<mccat at ... 1 t1mr. if~~ ~ l'«f..IR lL >