Licensed to: CengageBrain User



Similar documents
Chapter 3: JavaScript in Action Page 1 of 10. How to practice reading and writing JavaScript on a Web page

Licensed to: Printed in Canada

ELECTRONIC FUND TRANSFERS YOUR RIGHTS AND RESPONSIBILITIES

Key Features of Life Insurance

Advanced ColdFusion 4.0 Application Development Server Clustering Using Bright Tiger

AA Fixed Rate ISA Savings

The guaranteed selection. For certainty in uncertain times

Chapter 3: e-business Integration Patterns

Pay-on-delivery investing

Early access to FAS payments for members in poor health

Setting Up Your Internet Connection

ELECTRONIC FUND TRANSFERS YOUR RIGHTS AND RESPONSIBILITIES. l l

Art of Java Web Development By Neal Ford 624 pages US$44.95 Manning Publications, 2004 ISBN:

NCH Software Express Accounts Accounting Software

INDUSTRIAL AND COMMERCIAL

NCH Software MoneyLine

ELECTRONIC FUND TRANSFERS. l l l. l l. l l l. l l l

ELECTRONIC FUND TRANSFERS YOUR RIGHTS AND RESPONSIBILITIES. l l l. l l

Human Capital & Human Resources Certificate Programs

Avaya Remote Feature Activation (RFA) User Guide

A Description of the California Partnership for Long-Term Care Prepared by the California Department of Health Care Services

ELECTRONIC FUND TRANSFERS YOUR RIGHTS AND RESPONSIBILITIES. l l. l l. l l. l l

ELECTRONIC FUND TRANSFERS YOUR RIGHTS AND RESPONSIBILITIES

Normalization of Database Tables. Functional Dependency. Examples of Functional Dependencies: So Now what is Normalization? Transitive Dependencies

Teach yourself Android application development - Part I: Creating Android products

LADDER SAFETY Table of Contents

Finance 360 Problem Set #6 Solutions

SNMP Reference Guide for Avaya Communication Manager

Order-to-Cash Processes

Chapter 2 Traditional Software Development

Australian Bureau of Statistics Management of Business Providers

NCH Software Warp Speed PC Tune-up Software

NCH Software Copper Point of Sale Software

NCH Software FlexiServer

ELECTRONIC FUND TRANSFERS YOUR RIGHTS AND RESPONSIBILITIES. l l. l l

NCH Software PlayPad Media Player

CUSTOM. Putting Your Benefits to Work. COMMUNICATIONS. Employee Communications Benefits Administration Benefits Outsourcing

Design Considerations

Older people s assets: using housing equity to pay for health and aged care

Life Contingencies Study Note for CAS Exam S. Tom Struppeck

WHITE PAPER BEsT PRAcTIcEs: PusHIng ExcEl BEyond ITs limits WITH InfoRmATIon optimization

Teamwork. Abstract. 2.1 Overview

TERM INSURANCE CALCULATION ILLUSTRATED. This is the U.S. Social Security Life Table, based on year 2007.

Example of Credit Card Agreement for Bank of America Visa Signature and World MasterCard accounts

Secure Network Coding with a Cost Criterion

PENALTY TAXES ON CORPORATE ACCUMULATIONS

On-Line Banking Application

NCH Software BroadCam Video Streaming Server

A practical guide to personal financial advice Finding the right financial adviser and advice that works for you. Getting advice

Best Practices for Push & Pull Using Oracle Inventory Stock Locators. Introduction to Master Data and Master Data Management (MDM): Part 1

ADVANCED ACCOUNTING SOFTWARE FOR GROWING BUSINESSES

2013 Course Technology, Cengage Learning

Income Protection Options

Introduction to XSL. Max Froumentin - W3C

Information Systems Technician Training Series

Welcome to Colonial Voluntary Benefits. Thank you for your interest in our Universal Life with the Accelerated Death Benefit for Long Term Care Rider.

Let s get usable! Usability studies for indexes. Susan C. Olason. Study plan

A Conversation with

Benefits That Count. Colonial Life is the proud sponsor of SHRM s Annual Employee Benefits Survey. coloniallife.com

Business schools are the academic setting where. The current crisis has highlighted the need to redefine the role of senior managers in organizations.

Protection Against Income Loss During the First 4 Months of Illness or Injury *

mi-rm mi-recruitment Manager the recruitment solution for Talent Managers everywhere

Technical Support Guide for online instrumental lessons

Preschool Services Under IDEA

A short guide to making a medical negligence claim

CONTRIBUTION OF INTERNAL AUDITING IN THE VALUE OF A NURSING UNIT WITHIN THREE YEARS

Integrating Risk into your Plant Lifecycle A next generation software architecture for risk based

NCH Software Bolt PDF Printer

I m pretty lucky as far as teen librarians

Fast Robust Hashing. ) [7] will be re-mapped (and therefore discarded), due to the load-balancing property of hashing.

RFID Radio Frequency IDentification

Health Savings Account reference guide

INTERNATIONAL PAYMENT INSTRUMENTS

History of Stars and Rain Education Institute for Autism (Stars and Rain)

Breakeven analysis and short-term decision making

DOING BUSINESS WITH THE REGION OF PEEL A GUIDE FOR NEW AND CURRENT VENDORS

MOS 2013 Study Guide. Microsoft Excel EXAM Microsoft IT Academy

The width of single glazing. The warmth of double glazing.

Delhi Business Review X Vol. 4, No. 2, July - December Mohammad Talha

1B11 Operating Systems. Input/Output and Devices

Design and Analysis of a Hidden Peer-to-peer Backup Market

DISPLAYING NASDAQ LEVEL II DATA

Health Savings Account reference guide

Transcription:

Licensed to:

Licensed to: This is an eectronic version of the print textbook. Due to eectronic rights restrictions, some third party content may be suppressed. Editoria review has deemed that any suppressed content does not materiay affect the overa earning experience. The pubisher reserves the right to remove content from this tite at any time if subsequent rights restrictions require it. For vauabe information on pricing, previous editions, changes to current editions, and aternate formats, pease visit www.cengage.com/highered to search by ISBN#, author, tite, or keyword for materias in your areas of interest.

A Beginner's Guide to Programming Logic and Design, Introductory version, Seventh Internationa Edition Joyce Farre Executive Editor: Marie Lee Acquisitions Editor: Brandi Shaier Senior Product Manager: Ayssa Pratt Deveopmenta Editor: Dan Seiter Senior Content Project Manager: Catherine DiMassa Associate Product Manager: Stephanie Lorenz Associate Marketing Manager: Shanna Sheton Art Director: Faith Brosnan Text Designer: Shawn Girsberger Cover Designer: GEX Pubishing Services Interna Designer: Lisa Kuhn/Curio Press, LLC, www.curiopress.com Image Credit: istockphoto/tommaso Coia Senior Print Buyer: Juio Esperas Copy Editor: Michae Beckett Proofreader: Kim Kosmatka Indexer: Aexandra Nickerson Compositor: Integra Some of the product names and company names used in this book have been used for identification purposes ony and may be trademarks or registered trademarks of their respective manufacturers and seers. Uness otherwise credited, a art Cengage Learning, produced by Integra. Course Technoogy, a part of Cengage Learning, reserves the right to revise this pubication and make changes from time to time in its content without notice. 2013 Course Technoogy, Cengage Learning. ALL RIGHTS RESERVED. No part of this work covered by the copyright herein may be reproduced, transmitted, stored or used in any form or by any means graphic, eectronic, or mechanica, incuding but not imited to photocopying, recording, scanning, digitizing, taping, Web distribution, information networks, or information storage and retrieva systems, except as permitted under Section 107 or 108 of the 1976 United States Copyright Act, or appicabe copyright aw of another jurisdiction, without the prior written permission of the pubisher. For permission to use materia from this text or product, submit a requests onine at cengage.com/permissions. Further permissions questions can be emaied to permissionrequest@cengage.com. Library of Congress Contro Number: 2011944303 Internationa Edition: ISBN-13: 978-1-133-52637-7 ISBN-10: 1-133-52637-3 Cengage Learning Internationa Offices Asia www.cengageasia.com te: (65) 6410 1200 Brazi www.cengage.com.br te: (55) 11 3665 9900 Latin America www.cengage.com.mx te: (52) 55 1500 6000 Represented in Canada by Neson Education, Ltd. www.neson.com te: (416) 752 9100/(800) 668 0671 Austraia/New Zeaand www.cengage.com.au te: (61) 3 9685 4111 India www.cengage.co.in te: (91) 11 4364 1111 UK/Europe/Midde East/Africa www.cengage.co.uk te: (44) 0 1264 332 424 Cengage Learning is a eading provider of customized earning soutions with office ocations around the gobe, incuding Singapore, the United Kingdom, Austraia, Mexico, Brazi, and Japan. Locate your oca office at: www.cengage.com/goba. For product information: www.cengage.com/internationa Visit your oca office: www.cengage.com/goba Visit our corporate website: www.cengage.com Printed in China 12345671615141312

An Introduction to Programming CHAPTER 1 In this chapter, you wi earn about: Computer systems Simpe program ogic The steps invoved in the program deveopment cyce Pseudocode statements and fowchart symbos Using a sentine vaue to end a program Programming and user environments The evoution of programming modes

CHAPTER 1 An Introduction to Programming 2 Understanding Computer Systems A computer system is a combination of a the components required to process and store data using a computer. Every computer system is composed of mutipe pieces of hardware and software. Hardware is the equipment, or the physica devices, associated with a computer. For exampe, keyboards, mice, speakers, and printers are a hardware. The devices are manufactured differenty for arge mainframe computers, aptops, and even smaer computers that are embedded into products such as cars and thermostats, but the types of operations performed by different-sized computers are very simiar. When you think of a computer, you often think of its physica components first, but for a computer to be usefu, it needs more than devices; a computer needs to be given instructions. Just as your stereo equipment does not do much unti you provide music, computer hardware needs instructions that contro 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 te 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 downoad from the Web. For exampe, businesses use word-processing and accounting programs, and casua computer users enjoy programs that pay music and games. Aternativey, you can write your own programs. When you write software instructions, you are programming. This book focuses on the programming process. Software can be cassified into two broad types: Appication software comprises a the programs you appy to a task, such as wordprocessing programs, spreadsheets, payro and inventory programs, and even games. System software comprises the programs that you use to manage your computer, incuding operating systems such as Windows, Linux, or UNIX. This book focuses on the ogic used to write appication software programs, athough many of the concepts appy to both types of software. Together, computer hardware and software accompish three major operations in most programs: Input Data items enter the computer system and are paced in memory, where they can be processed. Hardware devices that perform input operations incude keyboards and mice. Data items incude a the text, numbers, and other raw materia 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 personne. However, data can aso incude items such as images, sounds, and a user s mouse movements. Processing Processing data items may invove organizing or sorting them, checking them for accuracy, or performing cacuations with them. The hardware component that performs these types of tasks is the centra processing unit, or CPU.

Understanding Computer Systems Output After data items have been processed, the resuting information usuay is sent to a printer, monitor, or some other output device so peope can view, interpret, and use the resuts. Programming professionas often use the term data for input items, but use the term information for data that has been processed and output. Sometimes you pace output on storage devices, such as disks or fash media. Peope cannot read data directy from these storage devices, but the devices hod information for ater retrieva. When you send output to a storage device, sometimes it is used ater as input for another program. You write computer instructions in a computer programming anguage such as Visua Basic, C#, C++, or Java. Just as some peope speak Engish and others speak Japanese, programmers write programs in different anguages. Some programmers work excusivey in one anguage, whereas others know severa and use the one that is best suited to the task at hand. The instructions you write using a programming anguage are caed program code; when you write instructions, you are coding the program. Every programming anguage has rues governing its word usage and punctuation. These rues are caed the anguage s syntax. Mistakes in a anguage s usage are syntax errors. If you ask, How the geet too store do I? in Engish, most peope can figure out what you probaby mean, even though you have not used proper Engish syntax you have mixed up the word order, misspeed a word, and used an incorrect word. However, computers are not neary as smart as most peope; in this case, you might as we have asked the computer, Xpu mxv ort dod nmcad bf B? Uness the syntax is perfect, the computer cannot interpret the programming anguage instruction at a. When you write a program, you usuay type its instructions using a keyboard. When you type program instructions, they are stored in computer memory, which is a computer s temporary, interna storage. Random access memory, orram, is a form of interna, voatie memory. Programs that are currenty running and data items that are currenty being used are stored in RAM for quick access. Interna storage is voatie its contents are ost when the computer is turned off or oses power. Usuay, you want to be abe to retrieve and perhaps modify the stored instructions ater, so you aso store them on a permanent storage device, such as a disk. Permanent storage devices are nonvoatie that is, their contents are persistent and are retained even when power is ost. If you have had a power oss whie working on a computer, but were abe to recover your work when power was restored, it s not because the work was sti in RAM. Your system has been configured to automaticay save your work at reguar intervas on a nonvoatie storage device. After a computer program is typed using programming anguage statements and stored in memory, it must be transated to machine anguage that represents the miions of on/off circuits within the computer. Your programming anguage statements are caed source code, and the transated machine anguage statements are object code. Each programming anguage uses a piece of software, caed a compier or an interpreter, to transate your source code into machine anguage. Machine anguage is aso caed binary anguage, and is represented as a series of 0s and 1s. The compier or interpreter that transates your code tes you if any programming anguage component has been used incorrecty. Syntax errors are reativey easy to ocate and correct because your compier or interpreter highights them. If you write a computer program using a anguage such as C++ 3

CHAPTER 1 An Introduction to Programming but spe one of its words incorrecty or reverse the proper order of two words, the software ets you know that it found a mistake by dispaying an error message as soon as you try to transate the program. 4 Athough there are differences in how compiers and interpreters work, their basic function is the same to transate your programming statements into code the computer can use. When you use a compier, an entire program is transated before it can execute; when you use an interpreter, each instruction is transated just prior to execution. Usuay, you do not choose which type of transation to use it depends on the programming anguage. However, there are some anguages for which both compiers and interpreters are avaiabe. After a program s source code is successfuy transated to machine anguage, the computer can carry out the program instructions. When instructions are carried out, a program runs, or executes. In a typica program, some input wi be accepted, some processing wi occur, and resuts wi be output. Besides the popuar, comprehensive programming anguages such as Java and C++, many programmers use scripting anguages (aso caed scripting programming anguages or script anguages) such as Python, Lua, Per, and PHP. Scripts written in these anguages usuay can be typed directy from a keyboard and are stored as text rather than as binary executabe fies. Scripting anguage programs are interpreted ine by ine each time the program executes, instead of being stored in a compied (binary) form. Sti, with a programming anguages, each instruction must be transated to machine anguage before it can execute. TWO TRUTHS & ALIE Understanding Computer Systems In each Two Truths and a Lie section, two of the numbered statements are true, and one is fase. Identify the fase statement and expain why it is fase. 1. Hardware is the equipment, or the devices, associated with a computer. Software is computer instructions. 2. The grammar rues of a computer programming anguage are its syntax. 3. You write programs using machine anguage, and transation software converts the statements to a programming anguage. The fase as Visua converts statement is #3. You write programs using a programming Basic or Java, and a transation program (caed a compier the statements to machine anguage, which is 0s and 1s. anguage such or interpreter)

Understanding Simpe Program Logic Understanding Simpe Program Logic A program with syntax errors cannot be fuy transated and cannot execute. A program with no syntax errors is transatabe and can execute, but it sti might contain ogica errors and produce incorrect output as a resut. For a program to work propery, you must deveop correct ogic; that is, you must write program instructions in a specific sequence, you must not eave any instructions out, and you must not add extraneous instructions. Suppose you instruct someone to make a cake as foows: Get a bow Stir Add two eggs Add a gaon of gasoine Bake at 350 degrees for 45 minutes Add three cups of four Don t Do It Don't bake a cake ike this! 5 The dangerous cake-baking instructions are shown with a Don t Do It icon. You wi see this icon when the book contains an unrecommended programming practice that is used as an exampe of what not to do. Even though the cake-baking instructions use Engish anguage syntax correcty, the instructions are out of sequence, some are missing, and some instructions beong to procedures other than baking a cake. If you foow these instructions, you wi not make an edibe cake, and you may end up with a disaster. Many ogica errors are more difficut to ocate than syntax errors it is easier for you to determine whether eggs is speed incorrecty in a recipe than it is for you to te 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 ogic can be expressed correcty in any number of programming anguages. Because this book is not concerned with a specific anguage, the programming exampes coud have been written in Visua Basic, C++, or Java. For convenience, this book uses instructions written in Engish! After you earn French, you automaticay know, or can easiy figure out, many Spanish words. Simiary, after you earn one programming anguage, it is much easier to understand severa other anguages. Most simpe computer programs incude steps that perform input, processing, and output. Suppose you want to write a computer program to doube any number you provide. You can write the program in a programming anguage such as Visua Basic or Java, but if you were to write it using Engish-ike statements, it woud ook ike this: input mynumber set myanswer = mynumber * 2 output myanswer

CHAPTER 1 An Introduction to Programming 6 The number-doubing process incudes three instructions: The instruction to input mynumber is an exampe of an input operation. When the computer interprets this instruction, it knows to ook to an input device to obtain a number. When you work in a specific programming anguage, you write instructions that te the computer which device to access for input. For exampe, when a user enters a number as data for a program, the user might cick on the number with a mouse, type it from a keyboard, or speak it into a microphone. Logicay, however, it doesn t matter which hardware device is used, as ong as the computer knows to accept a number. When the number is retrieved from an input device, it is paced in the computer s memory in a variabe named mynumber.a variabe is a named memory ocation whose vaue can vary for exampe, the vaue 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, variabe names wi not contain embedded spaces; for exampe, the book wi use mynumber instead of my Number. From a ogica perspective, when you input, process, or output a vaue, the hardware device is irreevant. The same is true in your daiy ife. If you foow the instruction Get eggs for the cake, it does not reay 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 practica considerations to getting the eggs, just as there are for getting data from a arge database as opposed to getting data from an inexperienced user working at home on a aptop computer. For now, this book is ony concerned with the ogic of operations, not the minor detais. The instruction set myanswer = mynumber * 2 is an exampe of a processing operation. In most programming anguages, an asterisk is used to indicate mutipication, so this instruction means Change the vaue of the memory ocation myanswer to equa the vaue at the memory ocation mynumber times two. Mathematica operations are not the ony kind of processing operations, but they are very typica. As with input operations, the type of hardware used for processing is irreevant after you write a program, it can be used on computers of different brand names, sizes, and speeds. In the number-doubing program, the output myanswer instruction is an exampe of an output operation. Within a particuar program, this statement coud cause the output to appear on the monitor (which might be a fat-pane pasma screen or a cathode-ray tube), or the output coud go to a printer (which coud be aser or ink-jet), or the output coud be written to a disk or DVD. The ogic of the output process is the same no matter what hardware device you use. When this instruction executes, the vaue stored in memory at the ocation named myanswer is sent to an output device. (The output vaue aso remains in computer memory unti something ese is stored at the same memory ocation or power is ost.) Watch the video A Simpe Program.

Understanding the Program Deveopment Cyce Computer memory consists of miions of numbered ocations where data can be stored. The memory ocation of mynumber has a specific numeric address, but when you write programs, you sedom need to be concerned with the vaue of the memory address; instead, you use the easy-to-remember name you created. Computer programmers often refer to memory addresses using hexadecima notation, or base 16. Using this system, they might use a vaue ike 42FF01A to refer to a memory address. Despite the use of etters, such an address is sti a hexadecima number. Appendix A contains information on this numbering system. 7 TWO TRUTHS & ALIE Understanding Simpe Program Logic 1. A program with syntax errors can execute but might produce incorrect resuts. 2. Athough the syntax of programming anguages differs, the same program ogic can be expressed in different anguages. 3. Most simpe computer programs incude steps that perform input, processing, and output. The fase statement is #1. A program with syntax errors cannot execute; a program with no syntax errors can execute, but might produce incorrect resuts. Understanding the Program Deveopment Cyce A programmer s job invoves writing instructions (such as those in the doubing program in the preceding section), but a professiona programmer usuay does not just sit down at a computer keyboard and start typing. Figure 1-1 iustrates the program deveopment cyce, which can be broken down into at east seven steps: 1. Understand the probem. 2. Pan the ogic. 3. Code the program. 4. Use software (a compier or interpreter) to transate the program into machine anguage. 5. Test the program. 6. Put the program into production. 7. Maintain the program.

CHAPTER 1 An Introduction to Programming Understand the probem 8 Maintain the program Pan the ogic Put the program into production Write the code Test the program Transate the code Figure 1-1 The program deveopment cyce Understanding the Probem Professiona computer programmers write programs to satisfy the needs of others, caed users or end users. Exampes of end users incude a Human Resources department that needs a printed ist of a empoyees, a Biing department that wants a ist of cients who are 30 or more days overdue on their payments, and an Order department that needs a Web site to provide buyers with an onine shopping cart. Because programmers are providing a service to these users, programmers must first understand what the users want. When a program runs, you usuay think of the ogic as a cyce of input-processing-output operations, but when you pan a program, you think of the output first. After you understand what the desired resut is, you can pan the input and processing steps to achieve it. Suppose the director of Human Resources says to a programmer, Our department needs a ist of a empoyees who have been here over five years, because we want to invite them to a specia thank-you dinner. On the surface, this seems ike a simpe request. An experienced programmer, however, wi know that the request is incompete. For exampe, you might not know the answers to the foowing questions about which empoyees to incude: Does the director want a ist of fu-time empoyees ony, or a ist of fu- and part-time empoyees together? Does she want to incude peope who have worked for the company on a month-tomonth contractua basis over the past five years, or ony reguar, permanent empoyees? Do the isted empoyees 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 empoyee who worked three years, took a two-year eave of absence, and has been back for three years?

Understanding the Program Deveopment Cyce The programmer cannot make any of these decisions; the user (in this case, the Human Resources director) must address these questions. More decisions sti might be required. For exampe: What data shoud be incuded for each isted empoyee? Shoud the ist contain both first and ast names? Socia Security numbers? Phone numbers? Addresses? Shoud the ist be in aphabetica order? Empoyee ID number order? Length-of-service order? Some other order? Shoud the empoyees be grouped by any criteria, such as department number or years of service? Severa pieces of documentation are often provided to hep the programmer understand the probem. Documentation consists of a the supporting paperwork for a program; it might incude items such as origina requests for the program from users, sampe output, and descriptions of the data items avaiabe for input. Fuy understanding the probem may be one of the most difficut aspects of programming. On any job, the description of what the user needs may be vague worse yet, users may not reay know what they want, and users who think they know frequenty change their minds after seeing sampe output. A good programmer is often part counseor, part detective! 9 Watch the video The Program Deveopment Cyce, Part 1. Panning the Logic The heart of the programming process ies in panning the program s ogic. During this phase of the process, the programmer pans the steps of the program, deciding what steps to incude and how to order them. You can pan the soution to a probem in many ways. The two most common panning toos are fowcharts and pseudocode. Both toos invove writing the steps of the program in Engish, much as you woud pan a trip on paper before getting into the car or pan a party theme before shopping for food and favors. You may hear programmers refer to panning a program as deveoping an agorithm. An agorithm is the sequence of steps necessary to sove any probem. In addition to fowcharts and pseudocode, programmers use a variety of other toos to hep in program deveopment. One such too is an IPO chart, which deineates input, processing, and output tasks. Some object-oriented programmers aso use TOE charts, which ist tasks, objects, and events. The programmer shoudn t worry about the syntax of any particuar anguage during the panning stage, but shoud focus on figuring out what sequence of events wi ead from the avaiabe input to the desired output. Panning the ogic incudes thinking carefuy about a

CHAPTER 1 An Introduction to Programming the possibe data vaues a program might encounter and how you want the program to hande each scenario. The process of waking through a program s ogic on paper before you actuay write the program is caed desk-checking. You wi earn more about panning the ogic throughout this book; in fact, the book focuses on this crucia step amost excusivey. 10 Coding the Program After the ogic is deveoped, ony then can the programmer write the source code for a program. Hundreds of programming anguages are avaiabe. Programmers choose particuar anguages because some have buit-in capabiities that make them more efficient than others at handing certain types of operations. Despite their differences, programming anguages are quite aike in their basic capabiities each can hande input operations, arithmetic processing, output operations, and other standard functions. The ogic deveoped to sove a programming probem can be executed using any number of anguages. Ony after choosing a anguage must the programmer be concerned with proper punctuation and the correct speing of commands in other words, using the correct syntax. Some experienced programmers can successfuy combine ogic panning and program coding in one step. This may work for panning and writing a very simpe program, just as you can pan and write a postcard to a friend using one step. A good term paper or a Hoywood screenpay, however, needs panning before writing and so do most programs. Which step is harder: panning the ogic or coding the program? Right now, it may seem to you that writing in a programming anguage is a very difficut task, considering a the speing and syntax rues you must earn. However, the panning step is actuay more difficut. Which is more difficut: thinking up the twists and turns to the pot of a best-seing mystery nove, or writing a transation of an existing nove from Engish to Spanish? And who do you think gets paid more, the writer who creates the pot or the transator? (Try asking friends to name any famous transator!) Using Software to Transate the Program into Machine Language Even though there are many programming anguages, each computer knows ony one anguage its machine anguage, which consists of 1s and 0s. Computers understand machine anguage because they are made up of thousands of tiny eectrica switches, each of which can be set in either the on or off state, which is represented by a 1 or 0, respectivey. Languages ike Java or Visua Basic are avaiabe for programmers because someone has written a transator program (a compier or interpreter) that changes the programmer s Engish-ike high-eve programming anguage into the ow-eve machine anguage that the computer understands. When you earn the syntax of a programming anguage, the commands work on any machine on which the anguage software has been instaed. However, your commands then are transated to machine anguage, which differs in various computer makes and modes.

Understanding the Program Deveopment Cyce If you write a programming statement incorrecty (for exampe, by misspeing a word, using a word that doesn t exist in the anguage, or using iega grammar), the transator program doesn t know how to proceed and issues an error message identifying a syntax error. Athough making errors is never desirabe, syntax errors are not a major concern to programmers, because the compier or interpreter catches every syntax error and dispays a message that notifies you of the probem. The computer wi not execute a program that contains even one syntax error. Typicay, a programmer deveops ogic, writes the code, and compies the program, receiving a ist of syntax errors. The programmer then corrects the syntax errors and compies the program again. Correcting the first set of errors frequenty reveas new errors that originay were not apparent to the compier. For exampe, if you coud use an Engish compier and submit the sentence The dg chase the cat, the compier at first might point out ony one syntax error. The second word, dg, is iega because it is not part of the Engish anguage. Ony after you corrected the word to dog woud the compier 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 necessariy the wrong word. Maybe dog is wrong; perhaps the subject shoud be dogs, in which case chase is right. Compiers don t aways know exacty what you mean, nor do they know what the proper correction shoud be, but they do know when something is wrong with your syntax. 11 Watch the video The Program Deveopment Cyce, Part 2. When writing a program, a programmer might need to recompie the code severa times. An executabe program is created ony when the code is free of syntax errors. After a program has been transated into machine anguage, the machine anguage program is saved and can be run any number of times without repeating the transation step. You ony need to retransate your code if you make changes to your source code statements. Figure 1-2 shows a diagram of this entire process.

CHAPTER 1 An Introduction to Programming Data that the program uses 12 Write and correct the program code Compie the program If there are no syntax errors Executabe program If there are syntax errors List of syntax error messages Program output Figure 1-2 Creating an executabe program Testing the Program A program that is free of syntax errors is not necessariy free of ogica errors. A ogica error resuts when you use a syntacticay correct statement but use the wrong one for the current context. For exampe, the Engish sentence The dog chases the cat, athough syntacticay perfect, is not ogicay correct if the dog chases a ba 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 sampe data to see whether the resuts are ogicay correct. Reca the number-doubing program: input mynumber set myanswer = mynumber * 2 output myanswer If you execute the program, provide the vaue 2 as input to the program, and the answer 4 is dispayed, you have executed one successfu test run of the program. However, if the answer 40 is dispayed, maybe the program contains a ogica error. Maybe the second ine of code was mistyped with an extra zero, so that the program reads: input mynumber set myanswer = mynumber * 20 output myanswer Don t Do It The programmer typed 20 instead of 2. Pacing 20 instead of 2 in the mutipication statement caused a ogica error. Notice that nothing is syntacticay wrong with this second program it is just as reasonabe to mutipy a number by 20 as by 2 but if the programmer intends ony to doube mynumber, then a ogica error has occurred.

Understanding the Program Deveopment Cyce The process of finding and correcting program errors is caed debugging. You debug a program by testing it using many sets of data. For exampe, if you write the program to doube a number, then enter 2 and get an output vaue of 4, that doesn t necessariy 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 " * ". 13 An input of 2 resuts in an answer of 4, but that doesn t mean your program doubes numbers it actuay ony adds 2 to them. If you test your program with additiona data and get the wrong answer for exampe, if you enter 7 and get an answer of 9 you know there is a probem with your code. Seecting test data is somewhat of an art in itsef, and it shoud be done carefuy. If the Human Resources department wants a ist of the names of five-year empoyees, it woud be a mistake to test the program with a sma sampe fie of ony ong-term empoyees. If no newer empoyees are part of the data being used for testing, you do not reay know if the program woud have eiminated them from the five-year ist. Many companies do not know that their software has a probem unti an unusua circumstance occurs for exampe, the first time an empoyee 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 aocated IP addresses, a probem known as IPV4 exhaustion. Putting the Program into Production Once the program is thoroughy tested and debugged, it is ready for the organization to use. Putting the program into production might mean simpy running the program once, if it was written to satisfy a user s request for a specia ist. However, the process might take months if the program wi be run on a reguar basis, or if it is one of a arge system of programs being deveoped. Perhaps data-entry peope 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 entirey 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 accompish. Maintaining the Program After programs are put into production, making necessary changes is caed maintenance. Maintenance can be required for many reasons: for exampe, because new tax rates are egisated, the format of an input fie is atered, or the end user requires additiona information not incuded in the origina output specifications. Frequenty, your first programming job wi require maintaining previousy written programs. When you maintain the programs others have written, you wi appreciate the effort the origina programmer put into writing cear

CHAPTER 1 An Introduction to Programming 14 code, using reasonabe variabe names, and documenting his or her work. When you make changes to existing programs, you repeat the deveopment cyce. That is, you must understand the changes, then pan, code, transate, and test them before putting them into production. If a substantia number of program changes are required, the origina program might be retired, and the program deveopment cyce might be started for a new program. Watch the video The Program Deveopment Cyce, Part 3. TWO TRUTHS & ALIE Understanding the Program Deveopment Cyce 1. Understanding the probem that must be soved can be one of the most difficut aspects of programming. 2. The two most commony used ogic-panning toos are fowcharts and pseudocode. 3. Fowcharting a program is a very different process if you use an oder programming anguage instead of a newer one. The fase statement is #3. Despite their differences, programming anguages are quite aike in their basic capabiities each can hande input operations, arithmetic processing, output operations, and other standard functions. The ogic deveoped to sove a programming probem can be executed using any number of anguages. Using Pseudocode Statements and Fowchart Symbos When programmers pan the ogic for a soution to a programming probem, they often use one of two toos: pseudocode (pronounced sue-doe-code) or fowcharts. Pseudocode is an Engish-ike representation of the ogica steps it takes to sove a probem. Pseudo is a prefix that means fase, and to code a program means to put it in a programming anguage; therefore, pseudocode simpy means fase code, or sentences that appear to have been written in a computer programming anguage but do not necessariy foow a the syntax rues of any specific anguage. A fowchart is a pictoria representation of the same thing.

Using Pseudocode Statements and Fowchart Symbos Writing Pseudocode You have aready seen exampes of statements that represent pseudocode earier in this chapter, and there is nothing mysterious about them. The foowing five statements constitute a pseudocode representation of a number-doubing probem: start input mynumber set myanswer = mynumber * 2 output myanswer stop Using pseudocode invoves writing down a the steps you wi use in a program. Usuay, programmers preface their pseudocode with a beginning statement ike start and end it with a terminating statement ike stop. The statements between start and stop ook ike Engish and are indented sighty so that start and stop stand out. Most programmers do not bother with punctuation such as periods at the end of pseudocode statements, athough it woud not be wrong to use them if you prefer that stye. Simiary, there is no need to capitaize the first word in a sentence, athough you might choose to do so. This book foows the conventions of using owercase etters for verbs that begin pseudocode statements and omitting periods at the end of statements. Pseudocode is fairy fexibe because it is a panning too, and not the fina product. Therefore, for exampe, you might prefer any of the foowing: Instead of start and stop, some pseudocode deveopers woud use other terms such as begin and end. 15 Instead of writing input mynumber, some deveopers woud write get mynumber or read mynumber. Instead of writing set myanswer = mynumber * 2, some deveopers woud write cacuate myanswer = mynumber times 2 or compute myanswer as mynumber doubed. Instead of writing output myanswer, many pseudocode deveopers woud write dispay myanswer, print myanswer, orwrite myanswer. The point is, the pseudocode statements are instructions to retrieve an origina number from an input device and store it in memory where it can be used in a cacuation, and then to get the cacuated answer from memory and send it to an output device so a person can see it. When you eventuay convert your pseudocode to a specific programming anguage, you do not have such fexibiity because specific syntax wi be required. For exampe, if you use the C# programming anguage and write the statement to output the answer to the monitor, you wi code the foowing: Consoe.Write(myAnswer); The exact use of words, capitaization, and punctuation are important in the C# statement, but not in the pseudocode statement.

CHAPTER 1 An Introduction to Programming 16 Drawing Fowcharts Some professiona programmers prefer writing pseudocode to drawing fowcharts, because using pseudocode is more simiar to writing the fina statements in the programming anguage. Others prefer drawing fowcharts to represent the ogica fow, because fowcharts aow programmers to visuaize more easiy how the program statements wi connect. Especiay for beginning programmers, fowcharts are an exceent too to hep them visuaize how the statements in a program are interreated. You can draw a fowchart by hand or use software, such as Microsoft Word and Microsoft PowerPoint, that contains fowcharting toos. You can use severa other software programs, such as Visio and Visua Logic, specificay to create fowcharts. When you create a fowchart, you draw geometric shapes that contain the individua statements and that are connected with arrows. (Appendix B contains a summary of a the fowchart symbos you wi see in this book.) You use a paraeogram to represent an input symbo, which indicates an input operation. You write an input statement in Engish inside the paraeogram, as shown in Figure 1-3. Arithmetic operation statements are exampes of processing. In a fowchart, you use a rectange as the processing symbo that contains a processing statement, as shown in Figure 1-4. To represent an output statement, you use the same symbo as for input statements the output symbo is a paraeogram, as shown in Figure 1-5. Because the paraeogram is used for both input and output, it is often caed the input/output symbo or I/O symbo. input mynumber Figure 1-3 Input symbo set myanswer = mynumber * 2 Figure 1-4 Processing symbo output myanswer Figure 1-5 Output symbo Some software programs that use fowcharts (such as Visua Logic) use a eft-santing paraeogram to represent output. As ong as the fowchart creator and the fowchart reader are communicating, the actua shape used is irreevant. This book wi foow the most standard convention of using the right-santing paraeogram for both input and output. To show the correct sequence of these statements, you use arrows, or fowines, to connect the steps. Whenever possibe, most of a fowchart shoud read from top to bottom or from eft to right on a page. That s the way we read Engish, so when fowcharts foow this convention, they are easier for us to understand. To be compete, a fowchart shoud incude two more eements: termina symbos, or start/ stop symbos, at each end. Often, you pace a word ike start or begin in the first termina symbo and a word ike end or stop in the other. The standard termina symbo is shaped ike a racetrack; many programmers refer to this shape as a ozenge, because it resembes the shape of the medication you might use to soothe a sore throat. Figure 1-6 shows a compete fowchart for the program that doubes a number, and the pseudocode for the same probem.

Using Pseudocode Statements and Fowchart Symbos You can see from the figure that the fowchart and pseudocode statements are the same ony the presentation format differs. Fowchart start Pseudocode 17 input mynumber set myanswer = mynumber * 2 output myanswer start input mynumber set myanswer = mynumber * 2 output myanswer stop stop Figure 1-6 Fowchart and pseudocode of program that doubes a number Programmers sedom create both pseudocode and a fowchart for the same probem. You usuay use one or the other. In a arge program, you might even prefer to write pseudocode for some parts and to draw a fowchart for others. When you te a friend how to get to your house, you might write a series of instructions or you might draw a map. Pseudocode is simiar to written, step-by-step instructions; a fowchart, ike a map, is a visua representation of the same thing. Repeating Instructions After the fowchart or pseudocode has been deveoped, the programmer ony needs to: (1) buy a computer, (2) buy a anguage compier, (3) earn a programming anguage, (4) code the program, (5) attempt to compie it, (6) fix the syntax errors, (7) compie it again, (8) test it with severa sets of data, and (9) put it into production. Whoa! you are probaby saying to yoursef. This is simpy not worth it! A that work to create a fowchart or pseudocode, and then a those other steps? For five doars, I can buy a pocket cacuator that wi doube any number for me instanty! You are absoutey right. If this were a rea computer program, and a it did was doube the vaue of a number, it woud not be worth the effort. Writing a computer program woud be worthwhie ony if you had many numbers (et s say 10,000) to doube in a imited amount of time et s say the next two minutes.

CHAPTER 1 An Introduction to Programming 18 Unfortunatey, the program represented in Figure 1-6 does not doube 10,000 numbers; it doubes ony one. You coud execute the program 10,000 times, of course, but that woud require you to sit at the computer and run the program over and over again. You woud be better off with a program that coud process 10,000 numbers, one after the other. One soution is to write the program shown in Figure 1-7 and execute the same steps 10,000 times. Of course, writing this program woud be very time consuming; you might as we buy the cacuator. 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 woud never want to write such a repetitious ist of instructions. Figure 1-7 Inefficient pseudocode for program that doubes 10,000 numbers A better soution 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 caed a oop. With this approach, the computer gets a number, doubes it, dispays the answer, and then starts again with the first instruction. The same spot in memory, caed 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 resut of the mutipication operation. However, the ogic iustrated in the fowchart in Figure 1-8 contains a major probem the sequence of instructions never ends. This programming situation is known as an infinite oop a repeating fow of ogic with no end. You wi earn one way to hande this probem ater in this chapter; you wi earn a superior way in Chapter 3.

Using a Sentine Vaue to End a Program start input mynumber 19 set myanswer = mynumber * 2 output myanswer Don t Do It This ogic saves steps, but it has a fata faw it never ends. Figure 1-8 Fowchart of infinite number-doubing program TWO TRUTHS & ALIE Using Pseudocode Statements and Fowchart Symbos 1. When you draw a fowchart, you use a paraeogram to represent an input operation. 2. When you draw a fowchart, you use a paraeogram to represent a processing operation. 3. When you draw a fowchart, you use a paraeogram to represent an output operation. The fase statement is #2. When you draw a fowchart, you use a rectange to represent a processing operation. Using a Sentine Vaue to End a Program The ogic in the fowchart for doubing numbers, shown in Figure 1-8, has a major faw the program contains an infinite oop. If, for exampe, the input numbers are being entered at the keyboard, the program wi keep accepting numbers and outputting their doubed vaues forever. Of course, the user coud refuse to type any more numbers. But the program cannot progress any further whie it is waiting for input; meanwhie, the program is occupying computer memory and tying up operating system resources. Refusing to enter any more numbers is not a practica soution. Another way to end the program is simpy to turn off the

CHAPTER 1 An Introduction to Programming 20 computer. But again, that s neither the best soution nor an eegant way for the program to end. A superior way to end the program is to set a predetermined vaue for mynumber that means Stop the program! For exampe, the programmer and the user coud agree that the user wi never need to know the doube of 0 (zero), so the user coud enter a 0 to stop. The program coud then test any incoming vaue contained in mynumber and, if it is a 0, stop the program. Testing a vaue is aso caed making a decision. You represent a decision in a fowchart by drawing a decision symbo, which is shaped ike a diamond. The diamond usuay contains a question, the answer to which is one of two mutuay excusive options often yes or no. A good computer questions have ony two mutuay excusive answers, such as yes and no or true and fase. For exampe, What day of the year is your birthday? is not a good computer question because there are 366 possibe answers. However, Is your birthday June 24? is a good computer question because the answer is aways either yes or no. The question to stop the doubing program shoud be Is the vaue of mynumber just entered equa to 0? or mynumber = 0? for short. The compete fowchart wi now ook ike the one shown in Figure 1-9. start input mynumber Don t Do It This ogic is not structured; you wi earn about structure in Chapter 3. mynumber = 0? Yes stop No set myanswer = mynumber times 2 output myanswer Figure 1-9 Fowchart of number-doubing program with sentine vaue of 0 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 doube of 0. In that case, some other data-entry vaue that the user never wi

Using a Sentine Vaue to End a Program need, such as 999 or 1, coud be seected to signa that the program shoud end. A preseected vaue that stops the execution of a program is often caed a dummy vaue because it does not represent rea data, but just a signa to stop. Sometimes, such a vaue is caed a sentine vaue because it represents an entry or exit point, ike a sentine who guards a fortress. Not a programs rey 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 commony use a dummy vaue to signa the end of the fie. For one thing, an input record might have hundreds of fieds, and if you store a dummy record in every fie, you are wasting a arge quantity of storage on nondata. Additionay, it is often difficut to choose sentine vaues for fieds in a company s data fies. Any baancedue, even a zero or a negative number, can be a egitimate vaue, and any customername, even ZZ, coud be someone s name. Fortunatey, programming anguages can recognize the end of data in a fie automaticay, through a code that is stored at the end of the data. Many programming anguages use the term eof (for end of fie) to refer to this marker that automaticay acts as a sentine. This book, therefore, uses eof to indicate the end of data whenever using a dummy vaue is impractica or inconvenient. In the fowchart shown in Figure 1-10, the eof question is shaded. 21 start input mynumber Don t Do It This ogic is not structured; you wi earn about structure in Chapter 3. eof? Yes stop No set myanswer = mynumber times 2 output myanswer Figure 1-10 Fowchart using eof

CHAPTER 1 An Introduction to Programming TWO TRUTHS & ALIE Using a Sentine Vaue to End a Program 22 1. A program that contains an infinite oop is one that never ends. 2. A preseected vaue that stops the execution of a program is often caed a dummy vaue or a sentine vaue. 3. Many programming anguages use the term fe (for fie end) to refer to a marker that automaticay acts as a sentine. is #3. The term eof (for end of fie) is the common term for a fie The fase statement sentine. Understanding Programming and User Environments Many approaches can be used to write and execute a computer program. When you pan a program s ogic, you can use a fowchart, 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 wi encounter as a new programmer. Understanding Programming Environments When you pan the ogic for a computer program, you can use paper and penci to create a fowchart, or you might use software that aows you to manipuate fowchart 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 transate and execute it, you usuay use a keyboard to type program statements into an editor. You can type a program into one of the foowing: A pain text editor A text editor that is part of an integrated deveopment environment A text editor is a program that you use to create simpe text fies. It is simiar to a word processor, but without as many features. You can use a text editor such as Notepad that is incuded with Microsoft Windows. Figure 1-11 shows a C# program in Notepad that accepts a number and doubes it. An advantage to using a simpe text editor to type and save a program is that the competed program does not require much disk space for storage. For exampe, the fie shown in Figure 1-11 occupies ony 314 bytes of storage.

Understanding Programming and User Environments This ine contains a prompt that tes the user what to enter. You wi earn more about prompts in Chapter 2. 23 Figure 1-11 A C# number-doubing program in Notepad You can use the editor of an integrated deveopment environment (IDE) to enter your program. An IDE is a software package that provides an editor, compier, and other programming toos. For exampe, Figure 1-12 shows a C# program in the Microsoft Visua Studio IDE, an environment that contains toos usefu for creating programs in Visua Basic, C++, and C#. Figure 1-12 A C# number-doubing program in Visua Studio

CHAPTER 1 An Introduction to Programming 24 Using an IDE is hepfu to programmers because usuay it provides features simiar to those you find in many word processors. In particuar, an IDE s editor commony incudes such features as the foowing: It uses different coors to dispay various anguage components, making eements ike data types easier to identify. It highights syntax errors visuay for you. It empoys automatic statement competion; when you start to type a statement, the IDE suggests a ikey competion, which you can accept with a keystroke. It provides toos that aow you to step through a program s execution one statement at a time so you can more easiy foow the program s ogic 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 pain text editor. For exampe, the program in Figure 1-12 occupies more than 49,000 bytes of disk space. Athough various programming environments might ook different and offer different features, the process of using them is very simiar. When you pan the ogic for a program using pseudocode or a fowchart, it does not matter which programming environment you wi use to write your code, and when you write the code in a programming anguage, 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 exampe, a user might execute the number-doubing program from a command ine ike the one shown in Figure 1-13. A command ine is a ocation 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 resuts are dispayed. Figure 1-13 Executing a number-doubing program in a command-ine environment Many programs are not run at the command ine in a text environment, but are run using a graphica user interface, or GUI (pronounced gooey), which aows users to interact with a program in a graphica environment. When running a GUI program, the user might type input into a text box or use a mouse or other pointing device to seect options on the screen. Figure 1-14 shows a number-doubing program that performs exacty the same task as the one in Figure 1-13, but this program uses a GUI.

Understanding the Evoution of Programming Modes 25 Figure 1-14 Executing a number-doubing program in a GUI environment A command-ine program and a GUI program might be written in the same programming anguage. (For exampe, 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 ogica process is the same. The two programs in Figures 1-13 and 1-14 both accept input, perform mutipication, and perform output. In this book, you wi not concentrate on which environment is used to type a program s statements, nor wi you care about the type of environment the user wi see. Instead, you wi be concerned with the ogic that appies to a programming situations. TWO TRUTHS & ALIE Understanding Programming and User Environments 1. You can type a program into an editor that is part of an integrated deveopment environment, but using a pain text editor provides you with more programming hep. 2. When a program runs from the command ine, a user types text to provide input. 3. Athough GUI and command-ine environments ook different, the ogic of input, processing, and output appy to both program types. environment provides more The fase statement programming hep is than #1. a An pain integrated deveopment text editor. Understanding the Evoution of Programming Modes Peope have been writing modern computer programs since the 1940s. The odest programming anguages required programmers to work with memory addresses and to memorize awkward codes associated with machine anguages. Newer programming anguages ook much more ike natura anguage and are easier to use, party because they aow programmers to name variabes instead of using unwiedy memory addresses. Aso,

CHAPTER 1 An Introduction to Programming 26 newer programming anguages aow programmers to create sef-contained modues or program segments that can be pieced together in a variety of ways. The odest computer programs were written in one piece, from start to finish, but modern programs are rarey written that way they are created by teams of programmers, each deveoping reusabe and connectabe program procedures. Writing severa sma modues is easier than writing one arge program, and most arge tasks are easier when you break the work into units and get other workers to hep with some of the units. Ada Byron Loveace predicted the deveopment of software in 1843; she is often regarded as the first programmer. The basis for most modern software was proposed by Aan Turing in 1935. Currenty, two major modes or paradigms are used by programmers to deveop programs and their procedures: Procedura programming focuses on the procedures that programmers create. That is, procedura programmers focus on the actions that are carried out for exampe, getting input data for an empoyee and writing the cacuations needed to produce a paycheck from the data. Procedura programmers woud approach the job of producing a paycheck by breaking down the process into manageabe subtasks. Object-oriented programming focuses on objects, or things, and describes their features (aso caed attributes) and behaviors. For exampe, object-oriented programmers might design a payro appication by thinking about empoyees and paychecks, and by describing their attributes. Empoyees have names and Socia Security numbers, and paychecks have names and check amounts. Then the programmers woud think about the behaviors of empoyees and paychecks, such as empoyees getting raises and adding dependents and paychecks being cacuated and output. Object-oriented programmers woud then buid appications from these entities. With either approach, procedura or object oriented, you can produce a correct paycheck, and both modes empoy reusabe program modues. The major difference ies in the focus the programmer takes during the eariest panning stages of a project. For now, this book focuses on procedura programming techniques. The skis you gain in programming proceduray decaring variabes, accepting input, making decisions, producing output, and so on wi serve you we whether you eventuay write programs using a procedura approach, an object-oriented approach, or both. The programming anguage in which you write your source code might determine your approach. You can write a procedura program in any anguage that supports object orientation, but the opposite is not aways true.

Chapter Summary TWO TRUTHS & ALIE Understanding the Evoution of Programming Modes 1. The odest computer programs were written in many separate modues. 27 2. Procedura 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. programs were written in a singe piece; newer The fase statement is programs are divided #1. into The odest modues. Chapter Summary Together, computer hardware (physica devices) and software (instructions) accompish three major operations: input, processing, and output. You write computer instructions in a computer programming anguage that requires specific syntax; the instructions are transated into machine anguage by a compier or interpreter. When both the syntax and ogic of a program are correct, you can run, or execute, the program to produce the desired resuts. For a program to work propery, you must deveop correct ogic. Logica errors are much more difficut to ocate than syntax errors. A programmer s job invoves understanding the probem, panning the ogic, coding the program, transating the program into machine anguage, testing the program, putting the program into production, and maintaining it. When programmers pan the ogic for a soution to a programming probem, they often use fowcharts or pseudocode. When you draw a fowchart, you use paraeograms to represent input and output operations, and rectanges to represent processing. Programmers aso use decisions to contro repetition of instruction sets. To avoid creating an infinite oop when you repeat instructions, you can test for a sentine vaue. You represent a decision in a fowchart by drawing a diamond-shaped symbo that contains a question, the answer to which is either yes or no. You can type a program into a pain text editor or one that is part of an integrated deveopment environment. When a program s data vaues are entered from a keyboard, they can be entered at the command ine in a text environment or in a GUI. Either way, the ogic is simiar.

CHAPTER 1 An Introduction to Programming Procedura and object-oriented programmers approach probems differenty. Procedura programmers concentrate on the actions performed with data. Object-oriented programmers focus on objects and their behaviors and attributes. 28 Key Terms A computer system is a combination of a the components required to process and store data using a computer. Hardware is the coection of physica devices that comprise a computer system. Software consists of the programs that te the computer what to do. Programs are sets of instructions for a computer. Programming is the act of deveoping and writing programs. Appication software comprises a the programs you appy to a task. 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 incude a the text, numbers, and other information processed by a computer. Processing data items may invove organizing them, checking them for accuracy, or performing mathematica operations on them. The centra processing unit, or CPU, is the 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 peope can view, interpret, and work with the resuts. Information is processed data. Storage devices are types of hardware equipment, such as disks, that hod information for ater retrieva. Programming anguages, such as Visua Basic, C#, C++, Java, or COBOL, are used to write programs. Program code is the set of instructions a programmer writes in a programming anguage. Coding the program is the act of writing programming anguage instructions. The syntax of a anguage is its grammar rues. A syntax error is an error in anguage or grammar. Computer memory is the temporary, interna storage within a computer. Random access memory (RAM) is temporary, interna computer storage.

Key Terms Voatie describes storage whose contents are ost when power is ost. Nonvoatie describes storage whose contents are retained when power is ost. Machine anguage is a computer s on/off circuitry anguage. Source code is the statements a programmer writes in a programming anguage. Object code is transated machine anguage. A compier or interpreter transates a high-eve anguage into machine anguage and indicates if you have used a programming anguage incorrecty. Binary anguage is represented using a series of 0s and 1s. To run or execute a program is to carry out its instructions. Scripting anguages (aso caed scripting programming anguages or script anguages) such as Python, Lua, Per, and PHP are used to write programs that are typed directy from a keyboard. Scripting anguages are stored as text rather than as binary executabe fies. A ogica error occurs when incorrect instructions are performed, or when instructions are performed in the wrong order. You deveop the ogic of the computer program when you give instructions to the computer in a specific sequence, without omitting any instructions or adding extraneous instructions. A variabe is a named memory ocation whose vaue can vary. The program deveopment cyce consists of the steps that occur during a program s ifetime. Users (or end users) are peope who empoy and benefit from computer programs. Documentation consists of a the supporting paperwork for a program. An agorithm is the sequence of steps necessary to sove any probem. An IPO chart is a program deveopment too that deineates input, processing, and output tasks. A TOE chart is a program deveopment too that ists tasks, objects, and events. Desk-checking is the process of waking through a program soution on paper. A high-eve programming anguage supports Engish-ike syntax. A ow-eve machine anguage is made up of 1s and 0s and does not use easiy interpreted variabe 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 a the improvements and corrections made to a program after it is in production. 29

CHAPTER 1 An Introduction to Programming Pseudocode is an Engish-ike representation of the ogica steps it takes to sove a probem. A fowchart is a pictoria representation of the ogica steps it takes to sove a probem. 30 An input symbo indicates an input operation and is represented by a paraeogram in fowcharts. A processing symbo indicates a processing operation and is represented by a rectange in fowcharts. An output symbo indicates an output operation and is represented by a paraeogram in fowcharts. An input/output symbo or I/O symbo is represented by a paraeogram in fowcharts. Fowines, or arrows, connect the steps in a fowchart. A termina symbo indicates the beginning or end of a fowchart segment and is represented by a ozenge A oop is a repetition of a series of steps. An infinite oop occurs when repeating ogic cannot end. Making a decision is the act of testing a vaue. A decision symbo is shaped ike a diamond and used to represent decisions in fowcharts. A dummy vaue is a preseected vaue that stops the execution of a program. A sentine vaue is a preseected vaue that stops the execution of a program. The term eof means end of fie. A text editor is a program that you use to create simpe text fies; it is simiar to a word processor, but without as many features. An integrated deveopment environment (IDE) is a software package that provides an editor, compier, and other programming toos. Microsoft Visua Studio IDE is a software package that contains usefu toos for creating programs in Visua Basic, C++, and C#. A command ine is a ocation on your computer screen at which you type text entries to communicate with the computer s operating system. A graphica user interface, or GUI (pronounced gooey), aows users to interact with a program in a graphica environment. Procedura programming is a programming mode that focuses on the procedures that programmers create. Object-oriented programming is a programming mode that focuses on objects, or things, and describes their features (aso caed attributes) and behaviors.

Review Questions Review Questions 1. Computer programs aso are known as. a. hardware b. software c. data d. information 2. The major computer operations incude. a. hardware and software b. input, processing, and output c. sequence and ooping d. spreadsheets, word processing, and data communications 31 3. Visua Basic, C++, and Java are a exampes of computer. a. operating systems b. hardware 4. A programming anguage s rues are its. a. syntax b. ogic c. machine anguages d. programming anguages c. format d. options 5. The most important task of a compier or interpreter is to. a. create the rues for a programming anguage b. transate Engish statements into a anguage such as Java c. transate programming anguage statements into machine anguage d. execute machine anguage programs to perform usefu tasks 6. Which of the foowing is temporary, interna storage? a. CPU b. hard disk c. keyboard d. memory 7. Which of the foowing pairs of steps in the programming process is in the correct order? a. code the program, pan the ogic b. test the program, transate it into machine anguage c. put the program into production, understand the probem d. code the program, transate it into machine anguage

CHAPTER 1 An Introduction to Programming 32 8. A programmer s most important task before panning the ogic of a program is to. a. decide which programming anguage to use b. code the probem c. train the users of the program d. understand the probem 9. The two most commony used toos for panning a program s ogic are. a. fowcharts and pseudocode b. ASCII and EBCDIC c. Java and Visua Basic d. word processors and spreadsheets 10. Writing a program in a anguage such as C++ or Java is known as the program. a. transating b. coding c. interpreting d. compiing 11. An Engish-ike programming anguage such as Java or Visua Basic is a programming anguage. a. machine-eve b. ow-eve c. high-eve d. binary-eve 12. Which of the foowing is an exampe of a syntax error? a. producing output before accepting input b. subtracting when you meant to add c. misspeing a programming anguage word d. a of the above 13. Which of the foowing is an exampe of a ogica error? a. performing arithmetic with a vaue before inputting it b. accepting two input vaues when a program requires ony one c. dividing by 3 when you meant to divide by 30 d. a of the above 14. The paraeogram is the fowchart symbo representing. a. input b. output c. both a and b d. none of the above

Exercises 15. In a fowchart, a rectange represents. a. input b. a sentine c. a question d. processing 16. In fowcharts, the decision symbo is a. a. paraeogram b. rectange 17. The term eof represents. c. ozenge d. diamond a. a standard input device b. a generic sentine vaue c. a condition in which no more memory is avaiabe for storage d. the ogica fow in a program 33 18. When you use an IDE instead of a simpe text editor to deveop a program,. a. the ogic is more compicated b. the ogic is simper c. the syntax is different d. some hep is provided 19. When you write a program that wi run in a GUI environment as opposed to a command-ine environment,. a. the ogic is very different b. some syntax is different c. you do not need to pan the ogic d. users are more confused 20. As compared to procedura programming, with object-oriented programming,. a. the programmer s focus differs b. you cannot use some anguages, such as Java c. you do not accept input d. you do not code cacuations; they are created automaticay Exercises 1. Drawafowchartorwritepseudocodetorepresenttheogicofaprogramthat aows the user to enter a vaue. The program divides the vaue by 2 and outputs the resut. 2. Draw a fowchart or write pseudocode to represent the ogic of a program that aows the user to enter a vaue for one edge of a cube. The program cacuates the surface area of one side of the cube, the surface area of the cube, and its voume. The program outputs a the resuts.

CHAPTER 1 An Introduction to Programming 34 3. Drawafowchartorwritepseudocodetorepresenttheogicofaprogramthat aowstheusertoentertwovaues.theprogramoutputstheproductofthe two vaues. 4. Draw a fowchart or write pseudocode to represent the ogic of a program that aows the user to enter vaues for a saesperson s base saary, tota saes, and commission rate. The program computes and outputs the saesperson s pay by adding the base saary to the product of the tota saes and commission rate. 5. Research current rates of monetary exchange. Draw a fowchart or write pseudocode to represent the ogic of a program that aows the user to enter a number of doars and convert it to Euros and Japanese yen. 6. a. Draw a fowchart or write pseudocode to represent the ogic of a program that aows the user to enter vaues for the width and ength of a wa in feet. The program outputs the area of the wa in square feet. b. Modify the program that computes wa area to aow the user to enter the price of a gaon of paint. Assume that a gaon of paint covers 350 square feet of a wa. The program outputs the number of gaons 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 partia gaons of paint.) 7. Match the definition with the appropriate term. 1. Computer system devices a. compier 2. Another word for programs b. syntax 3. Language rues c. ogic 4. Order of instructions d. hardware 5. Language transator e. software 8. In your own words, describe the steps to writing a computer program. 9. Match the term with the appropriate shape (see Figure 1-15).

Exercises 1. Input A. 2. Processing B. 35 3. Output C. 4. Decision D. 5. Termina E. Figure 1-15 Identifying shapes 10. a. Draw a fowchart or write pseudocode to represent the ogic of a program that aows the user to enter vaues for the width and ength of a room s foor in feet. The program outputs the area of the foor in square feet. b. Modify the program that computes foor area to compute and output the number of 12-inch square ties needed to tie the foor. Find the Bugs 11. Since the eary days of computer programming, program errors have been caed bugs. The term is often said to have originated from an actua moth that was discovered trapped in the circuitry of a computer at Harvard University in 1945. Actuay, the term bug was in use prior to 1945 to mean troube with any eectrica apparatus; even during Thomas Edison s ife, it meant an industria defect. However, the term debugging is more cosey associated with correcting program syntax and ogic errors than with any other type of troube. Your downoadabe fies for Chapter 1 incude DEBUG01-01.txt, DEBUG01-02.txt, and DEBUG01-03.txt. Each fie starts with some comments (ines that begin with two sashes) that describe the program. Examine the pseudocode that foows the introductory comments, then find and correct a the bugs.

CHAPTER 1 An Introduction to Programming Game Zone 36 12. In 1952, A. S. Dougas wrote his University of Cambridge Ph.D. dissertation on human-computer interaction, and created the first graphica computer game a version of Tic-Tac-Toe. The game was programmed on an EDSAC vacuum-tube mainframe computer. The first computer game is generay assumed to be Spacewar!, deveoped in 1962 at MIT; the first commerciay avaiabe 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, payers spent hours with games that now seem very simpe and ungamorous; do you reca paying Adventure, Oregon Trai, Where in the Word Is Carmen Sandiego?, ormyst? Today, commercia computer games are much more compex; they require many programmers, graphic artists, and testers to deveop them, and arge management and marketing staffs are needed to promote them. A game might cost many miions of doars to deveop and market, but a successfu game might earn hundreds of miions of doars. Obviousy, 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 chidren s game in which payers provide a few words that are then incorporated into a siy story. The game heps chidren understand different parts of speech because they are asked to provide specific types of words. For exampe, you might ask a chid for a noun, another noun, an adjective, and a past-tense verb. The chid might repy with such answers as tabe, book, siy, and studied. The newy created Mad Lib might be: Mary had a itte tabe Its book was siy as snow And everywhere that Mary studied The tabe was sure to go. Create the ogic for a Mad Lib program that accepts five words from input, then creates and dispays a short story or nursery rhyme that uses them. Up for Discussion 13. What is the image of the computer programmer in popuar cuture? Is the image different in books than in TV shows and movies? Woud you ike that image for yoursef? 14. Which is the better too for earning programming fowcharts or pseudocode? Cite any educationa research you can find.