Open navigation menu
Close suggestions
Search
Search
en
Change Language
Upload
Sign in
Sign in
Download free for days
0 ratings
0% found this document useful (0 votes)
43 views
Programming Practice - Technique
Uploaded by
Md Mamunur Rashid songram
AI-enhanced title
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content,
claim it here
.
Available Formats
Download as PDF or read online on Scribd
Download now
Download
Save Programming Practice _ Technique For Later
Download
Save
Save Programming Practice _ Technique For Later
0%
0% found this document useful, undefined
0%
, undefined
Embed
Share
Print
Report
0 ratings
0% found this document useful (0 votes)
43 views
Programming Practice - Technique
Uploaded by
Md Mamunur Rashid songram
AI-enhanced title
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content,
claim it here
.
Available Formats
Download as PDF or read online on Scribd
Download now
Download
Save Programming Practice _ Technique For Later
Carousel Previous
Carousel Next
Save
Save Programming Practice _ Technique For Later
0%
0% found this document useful, undefined
0%
, undefined
Embed
Share
Print
Report
Download now
Download
You are on page 1
/ 232
Search
Fullscreen
Progrananallng) Practices TechmicMes Sixth Edition_ PREFACE PURPOSE AND EVOLUTION OF THIS BOOK CONCEPTS AND TECHNIQUES This book is intended for use in an introctuction to business programming course. This course may be the first data processing course a student takes; it may be taken along with an introductory data processing course; or it may have an introductory course as a prerequisite. No prior know! edge of computers is assumed, so | have included brief discussions of material that students who have taken an intcoductory course may already have encountered. The extent of overlap with such an introductory course is, however, minimal, ILis the purpose of this text to present certain fundamental program ting concepts that are commonly encountered in business uses of a com- puter, When these topics are taught as part of a language course—as they frequently are, too much time is spent on the concepts, at the expense of an in-depth treatment of the language itself. Moreover, the concepts must Usually be taught in more than one course to ensure that the students are able to complete the programming assignments. By covering these con- cepts in a separate course that will be a prerequisite or corequisite for the language courses, more time is available for the instructors of these latter courses to explore special features of the languages. When | first started teaching a "programming concepts” course in the carly 70s, this type of course was not common and textbooks were few in number. One week before the beginning of the spring semester in 1978, 1 covered that the book | had been using was out of print. was forced to develop a series of handouts to replace the text. This gave me an opportu- nity to correct deficiencies I had perceived in the text, and after five years of use, these handouts became the basis for a book. The approach taken, however, was unstructured, and therefore not really appropriate for to- day's programming courses which emphasize the structured approach, When | decided to switch to a structured approach, ! found none of the available structured texts really met my needs, | therefore decided to write the book | wanted. This is the result This text covers concepts that are generally required in business program- ming, including the programming process, structured program develop- mnW OVERVIEW OF THE TEXT fy pceace ment, Controlling program flow, control breaks, tables, ani multiile processing ‘A variety of methods for planning and docunienting computer programs are presented and illustrated. Included are structure charts, program flowcharts, pseudocode, Nassi-Shneiderman flowcharts, and HIPO chats, In addition, truth tables and decision tables are examined as techniques for dealing with limited aspects of a problem (rather than with the problem a a whole as the other techniques do}, Structure charts, program flowcharts, and pseuclocode— the more com ton techniques used in the development of structured programis—are fundamental to this text. HIPO charts incorporate structure charts and pseudocode, and add information about input and output. Because 50 many ways have been devised for representing the input and output por- tions of HIPO charts, do not caver this technique in great detail. Nasi Shneiderman flowcharting is relatively new, gaining in populacity, and is, therefore, covered in more depth. Why present so many techniques? Why not settle on the one or two that are best? For one thing, there is no consensus as to which are best. Each has its advocates, based on the user's prior training and experience. This is true for both data processing instructors and data processing managers. ‘And tastes in techniques do change. My experience is probably not atypical. | started preparing program flowcharts in 1960, and for a long time { could see no need for any other technique. (Today ! am willing to admit that program flowcharts do have some limitations, not the least of which is the difficulty non-data processing people have in understanding them and the effort required to revise them.) Pseudocode at first seemed like a lot of unnecessary work, particularly since my pseudocode ended up being almost like the program itself. | recognize now that my pseudocoding stan- dards were not very well thought out. | feel today that pseudocode may become even more popular because itis easily understood and can be re vised readily when a word processor is used in its preparation. U was very skeptical when I first encountered Nassi-Shneiderman flowcharting, but today it is my preferred way to plan a structured pro- gram, | like the way Nassi-Shneiderman flowcharts reveal the structure of program modules; they are relatively compact, easy to read, can be par- tially prepared with @ word processor (though not as easily as pseudocode can), and thus are relatively easy to revise. We can expect planning and documentation tools to change in the fue ture. New techniques will be developed. Older techniques will become less widely used. Some people will resist the changes. How then to best prepare the students? [tis my hope that by exposing the students to a vari- ety of techniques they will be better able to leatn and apply any new ones their future employers decide to adopt. ‘The first chapter introduces the programming process. The traditional ap- proach to program development is taken, including the development of al- gorithms and the preparation of program flowcharts. The importance of desk checking is stressed. The approach in this chapter Is nonstructured since students seem to find it easier initially to understand this way of han= ling a problem,Pacrnce y Chapter 2 introduces the fundamental concepts of structured pro: gramming, The three basic programming structures (sequence, loop, and selection) are presented, along with some variations. Structure charts, structured program flowcharts, and pseuddocorte are usec! to plan and docu: menit the structured programs. In Chapter 3 we examine the use of conditions in loop and selection structures to conivol the order of processing. Boolean algebra is intro: duced as a way of dealing with combinations of conditions, and (ruth tables ase used to evalusle compound conditions. The imporiance of the order in which comparisons are made is examined. input editing, and vari ous methods for detecting the end of a data file are discussed Chapter 4 expands the discussion of Chapter 3 by considering complex combinations of conditions that may control processing. Decision tables are introduced as a technique for dealing with the difficulties presented by these combinations, Chapter 5 begins the discussion of control breaks, a factor in the pro- duction of most business reports. Nassi-Shneiderman flowcharting, an in creasingly popular technique for the planning of structured programs, is introduced. The topic of control breaks is examined further in Chapter 6, where rnuttilevel control breaks are dealt with. Group printing and group indica tion are illustrated. the HIPO chart, another techniquie for planning, and documenting structured programs, is presented, Chapter 7 deals with tables, the use of which can make the progran ming task much simpler in many situations. A variety of tables are pre- sented. The advantages and disadvantages of ascending, descending, and unordered argument tables are examined. Ways of placing table data in the computer's memory are considered, as are ways of accessing this data (searching and direct table addressing). Multidimensional tables are exam- ined brietly Chapters 8 and 9 consider techniques for processing multiple input files. in the former we deal with the processing associated with sequential master files. This includes creating, updating, and maintaining sequential magnetic tape and magnetic disk files. in Chapter 9 we examine magnetic disk files that have been organized to permit accessing a desired record di rectly, Indexed files (ISAM, VSAM, and fully indexed) and random files are considered. Again, techniques for creating, updating, and maintaining these files are examined. The chapter ends with a discussion of some of the considerations involved in selecting an organization for a file ‘An Appendix has been included that examines numeric considerations that can be troublesome to a programmer. While not strictly relevant to the topic of structured programming, they are very much worth covering if time permits. The student will also find a glossary and an index at the end of the text. Fach chapter starts with a list of objectives the student should be able to ‘meet upon completing the chapter and ends with a chapter summary, a list of key terms for the slucent to master, and exercises for testing the stu dents’ comprehension of the materia, The exercises emphasize the appli cation of the techniques presented in the chapter. | believe that the true measure of the comprehension of a new technique is the extent to which it can be applied to a new problem.FOR THE INSTRUCTOR ACKNOWLEDGMENTS: VE Paseace We have an extensive set of transparency masters to go with the text, At instructor’s manual is provided that contains solutions to the exercises and some suggestions that may help the instructor present the material more effectively ‘The amount of time available for a course such as this will vary, so some instructors may have to skim over certain topics and techniques, ot even skip some completely, Decision tables and HIPO ae likely candidates. The Giscussion of multidimensional fables in Chapter 7 can also be omitted in a pinch, as can the discussion of Boolean algebra and truth tables. And if time gets really tight, | suppose even Nassi-Shneiderman flowcharts could be omnitied. | thank the following reviewers whose comments and suggestions were so helpful in the final preparation of this book: Professor Neil F. Dunn, Massachusetts Bay Community College; Professor Richard Fleming, North Lake College; Professor Seth Hock, Columbus Institute of Technology; Professor Michael Jeffries, University of Tampa; Professor Norman Liebling, San Jacinto College; Professor Leonard Presby, William Paterson College; Professor Bob Saldarini, Bergen Community College; Professor Tim Sylvester, College of Du Page; and Dr. R. Kenneth Walter, Weber State College.PREFACE ‘The Programming Process ouecrives INTRODUCTION EXAMPLE: POSITIVE, NEGATIVE, AND ZERO NUMBERS Dating the Problem / Preparing an Algorithen # Preparing @ Program Flowchart / Coding the Prograin / Debugging and Testing / Documenting EXAWPLE: GROSS PAY Problem Definition / Algorithm / Test Input and ulput Data / Program Flowchart SUMMARY kev TERNS: EXERCISES Introduction to Structured Programming opsectves INTRODUCTION MODULAR PROGRAVING Implementing the Modular Approach # Problems with the Modular Approach | Examples of Program Modules TOP-DOWN PROGRAMMING Siructure Charts / identlying Modulos / Feeviowing the Stwcture Chart / Stucture Charts and Flowcharts / Goaing the Modules PROGRAMMING STRUCTURES. Sequence Structure / Loop Stucture / Selection Structure 1 Structure Charis and Program Structures STRUCTURED CODING Pseudocode / A Structured Progrem in Psoudocode ADDITIONAL STRUCTURES FOR Loop / PERFORM UNTIL Instruction / REPEAT UNTIL instruction 1 CASE Instruction _CONTENTS w 2 2 2 25 2% 2 40 “4 vatwm scunawany KEY TEAMS Extacises Conditions that Control Processing oniecrives. wTRODUCTION -OMPANISONS OF TWIO VALUES SORTING THREE NUMBERS COMBINATIONS OF CONDITIONS Boolean Algebra f Truth Tables 1 Special Boolean Equaliles 1 Bealoan Algebra in Prograruming ORDER OF COMPARISONS INPUT EDITING. Sequence Checking / Restricted-Value ‘Tests / Miscellaneous Other Tests | Ertor Routines DETECTING END OF DATA Sentinel Value ? Countor SUMMARY KEY TEAMS EXERCISES, Complex Combinations of Conditions ossecrives! INTRODUCTION FILE INQUIRY EXAMPLE Problem Detintion J Truth Table / Structure Chart 7 Pseudocode J Program Flowchart # “est Input Data / Test Output Data # Postscript DECISION TABLES Components of a Decision Table / Redundancy and Contradiction 1 Examples of Decision ‘Tables / Extended-Eniry and Mixed-Enty ‘Tables SUMMARY KEY TERMS. EXEROISES Controt Breaks onuecrives INTRODUCTION ‘GROSS PAY REVISED Handling the Conte! Break / Special Problems / Structure Chart / Program Flowchart / Pseudocode NASSI-SHNEIDERMAN FLOWCHABTS, Representing the Three Logical Siructwes / Revised Gross Pay Problem PURCHASE SUMMARY Problem Definition 7 Structure Chait / NassiShneiderman Flowchart / Psoudocode “0 4a 6 62 ot 6s 58 oo 67 or 67 67 0 a oa a7 87 7 87‘SUMMARY KEY TERMS. EXERCISES Mulilevel Control Breaks owectives INTRODUCTION FIELO SALES SUBIMARY Problem Detintion / Structure Charl f Progam Flowchart 7 Ovcision Table for Module 200 5 Paeudocode / Nassi-Shnelderman Flowchart (of Modulo 200 / Altoraato Handling of ‘Quiput J Accumulating an Printing Totals # Group-Printed Field Sales Summary Report HPO CHARTS Preparing @ HIPO Chart / Advantages and Disadvantages of HPO SUMMARY KEY TERMS. EXERCISES Tables onuecrives INTRODUCTION TERMINOLOGY Single and Paired Tablas Argument and Function Tables / Discrete and Segmanted Argument Tables (ORDER OF TABLE ARGUMENTS ‘Ascending Order ! Desconding Order / Noithor Ascending nor Descending / Postscript ‘TABLES IN MEMORY Roforencing Table Entties / Geting the Tables Inlo Memory / Organizing the Table File ( Reading the Table Fila SEARCHING A DISCRETE TABLE Sequential Search 1 Binary Soarch [SEGMENTED TABLE EXAWPLE Getting the Table into Memory / Soarching the Table USING A TABLE TO ACCUMULATE RESULTS OF PROCESSING ‘TABLES OF VARIABLE SIZE Discrete / Segmented DIRECT TABLE ADDRESSING Determining the index of the Function / Adcitional Examples of Direct Addressing MULTIDIMENSIONAL TABLES Two-Dimensional Tables / Two-Dimensional ‘Tables in One Dimension SUMMARY KEY TERNS EXERCISES: ‘Muttifle Processing: Sequentiat Access oBlecTives 10s 1a, fos wr ‘07 07 or ws 1 26 126 128 28 128 8 131 136 42 14 us “7 189 189 159 155 185 1xmuTROpUE HON TemMiNOLOGY Master and Transaction Flos / Sequential and Serial Access / Wiaintaning, Updating, and Reterencing FILE MEDIA FOR SEQUENTIAL FILES MAGNETIC TAPE Creating a Master File / Updating a Master File # Adging Records to a Fila / Deleting records trom a File ¢ A Combined Ad and Delete Run 1 Combining Updating and ‘Maintenance / Backup for Tape Files MAGNENC DISK. Creating a Master File / Updating a Master File / Adding Records # Deleting Rocordis ¢ Combining Updating and Maintenance / Backup for Disk Files ACTIVITY ANO VOLATILITY Postscaiet SUMMARY Key TERMS Exencises Muttfite Procossing: Direct Access oavecrives, ineTRODUCTION ‘STORING DATA ON DISK INDEXED FES ISAM Files / VSAM Filos / Fully indexed Files AANDOM FILES Determining the Location of Records / Random File Processing SELECTING A FILE ORGANIZATION Sutmnany KEY TEAMS EXERCISES ‘APPENDIX— NUMERIC CONSIDERATIONS Objectives Introduction Rounding Determining tho Size of & Resut Aditon / Subtraction / Malipication 7 Division Output Eating ‘Accuracy ard Precision Key Terms Exercises GLossany IoEX Ib 174 182 183 109 13 183 185 15 185 195 ‘7 202 203 203 204 204 208 204 205 209 209 210 210 ay 218‘OBJECTIVES INTRODUCTION HAPTER THE PROGRAMMING PROCESS Upon completing this chapter the student should be able to: 1 List the steps in the programming process. 2 Explain the processing depicted by a program flowchart. 3 Describe good flowcharting practices. 4 Prepare an algorithm, a program flowchart, test input data, and test output data for a simple problem: 5 Define and use the key terms at the end of the chapter. ‘A computer program consists of a group of instructions for a computer that cause it to perform a desired task. The computer program is a means to an end. The end will normally be defined as information that is needed to solve a problem. The programming process is, therefore, a problem. solving process, and it consists of the following activities: 1 Defining the problem 2 Preparing an algorithm 3 Preparing a program flowchart 4 Coding the program 5 Debugging and testing 6 Documenting These activities can be visualized as shown in Figure 1-1, Activities 1 through 5 each include checking procedures that the programmer must FIGURE 1-1 The progiamming process, ar ii nie ra Po2 SrinistaRLD PrectaananK conc Gury out thoroughly before proceeding, the next activity. AL any tine it may hecome necessary to retusn to an earlier activity to etoal with unantick pated problems. Activity 6, documenting (keeping, a written record of wha is done}, occurs simultancously with the other five activities In the remainder of this chapter we will discuss each of these activitios with particule emphasis on preparing algoritiins ural Howeharts. hwo ex amples will be used! to illustrate the programming process. EXAMPLE: POSITIVE, NEGATIVE, AND ZERO NUMBERS Defining the Problem Consider a very simple problem in which awe are to determine how many positive, negative, and zero numbers there are in a list of numbers, The definition of the problem begins with a statement of the desired out put (results to be produced by the program). Unless this statement is cor- rect and clear, all succeeding activities will be of doubtful value. The statement should be in writing so that misunderstandings can be mini- mized. Our statement could be as follows: Given a list of numbers, find out how many are positive, how many are negative, and how many are zero, A description of what the output is to look like is another element of the problem definition. Output to be printed can be described using a print chart (Figure 1-2). If output is to be displayed on a CRY (cathode ray tube) terminal, also referred to as a VOT (visual display terminal), it can be docu- mented on a display system layout sheet (Figure 1-3). Output to be placed in a file is described on a record format form (Figure 1-4). Before proceeding, let us consider how data is organized to facilitate processing. At the highest level we have files, which are collections of re- lated records. We can have a file that contains information about students, a file of customer information, or a file with information about products, A record is a collection of data that pertains to a particulae entity in a file, for example, a student, a customer, or a product. Records are composed of fields—also called items, such as name, acklress, age, price, course code, Fields, in turn, are a collection of characters: letters, numbers, or special symbols, such as a comma, dotlar sign, or decimal point. The record for- mat form shows the arrangement of fields in a record, the size of each field, and the type of characters that can appeat in each field The input (data to be processed) must also be documented as part of the problem definition, If punched cards are to be processed, a multiple card layout form (Figure 1-5) will be used. Data coming from a file may be described on a record format form. Input coming from a CRT tesmminal can be shown on the display system layout sheet, The solutions to some problems involve complex calculations, These must also be described in detail as part of the problem definition The definition of the problem will usually be provided to the pro- grammer (the person who writes the program) by a systems analyst (someone who plans the collection of equipment, programs, people, and procedures that make p a system). For simpler problems, the pro- grammer may prepare the definition. in some smaller computer installa: ions, the functions of analyst and programmer may be combined in a single position.uepaue — CLUDE scabs ima Sn ed nO SOY 0 AGH ‘2u patop e999 PIES —— ‘eu penoB Ie PER PIO eg ro NvHD 3a “OMLNaD zO¥RHN TSS a FULLLevHD [spun lat ahciescrandos momueutg sen cerns JSITVINEWIDOO UO BSWWYEDOUL Tn On ‘DUR PAROP IEEEG POS ayy3270 Information Display System Leyout SheetIBM ERRESREES "scan wens aas covouser cotaons wae H MULTIPLE-CARD LAYOUT FORE eee Sguagsagogasasgsunssoouusussssagggassscoueasassasasseuessay PERE gganeagaazegeggszasgazaga4 age sgsgeegussssssususugsassasusssgs15 998 susgogaagss ggggsgessssgaggssasssgaassogg Qursgaogasaassessggngssszggauggaarssaguaszgcasgagaza9aa¢93911 5393 FIGURE 1-5 Multpie-card layou form, Preparing an Algorithm Once the problem has been defined, we can prepare an algorithm (a de- scription of the sequence of steps required to solve a problem). In defin: ing an algorithm that will work on a computer, we must consider the computer’ limited capabilities: + A computer can perform arithmetic operations (usually limited to addi- tion, subtraction, multiplication, and division). * it can compare two things and, on the basis of the result of the com- parison, choose among alternative courses of action. * {tan move data about in its memory (a part of the computer in which data and instructions can be stored). + The computer can also input (read in) data and output (write out} results. Despite these limitations, we can use the computer to solve very complex problems. The trick is to figure out the exact sequence of steps to be fol- 6CamPIER 1 te pHOGAMENG PROCESS. 7 lowed such that the computer will provide us with the information we de. sire. This sequence of steps is the algorithm, es litle An Initial Algorithm: Mach of shat we human bein conscious thought because we use our past experiences. This makes it dif- ficult at frst for us to define a sequence of very simple steps that will make this machine we call the computer do what we want. 1 is not that the steps themselves are difficult or complex, but rather that we must provide the machine with much more detailed instructions than we would have to give to a human being in order to get the job done. It we wanted a student in this course to tell us how many of our list of numbers were positive, how ‘many negative, and how many zero, the original statement of the problem would probably be sufficient instruction. If we want a computer t0 do the job, we will have to prepare an algorithm such as the following: s do equi 4, ifthe number is positive, add one to the positive counter, 2. lf the number is negative, add one to the negative counter. 3. the number is zero, add one to the zero counter. (A counter is a device for keeping tack of the number of times something occurs.) These steps will be executed (performed) one at a time in the order given, Refining the Algorithm This takes care of one number, but we are sup- posed to process a list of numbers. Let us assume that the computer will get its list of numbers one at a time. Once we have determined whether a umber is positive, negative, or zero, and have incremented (added one to) the appropriate counter, we must go back and get another number, process this number, and so on, until we run out of numbers. We also must make some provision for getting the answer out of the computer. We will therefore refine our algorithm to incorporate two additional steps: 1. Read a number; if there are no more numbers, go to step 5. 2. If the number is positive, add one to the positive counter and go to step 1. 3. If the number is negative, add one to the negative counter and go to step 1 4, tf the number is zero, add one to the zero counter and go to step 1. 5. Print counters. Steps 1, 2, 3, and 4 illustrate how we can alter the normal sequential execu tion of our algorithm; the go-to instruction causes a branch (also called a transfer of control) to a step that is not next in sequence. This version of the algorithm is better, but there are still a few improve- ‘ments that can be made, For one thing, if we reach step 4, we will know that the number in question is zero. if itis not zero, that is, if i is either positive or negative, we will increment a counter at step 2 oF 3 and go back to step 1; therefore, step 4 can simply be: 4, Add one to the zero counter and go to step 1 ‘There also is a problem with the incrementing of the counters. ach time we find a positive number, we add one to the positive counter, but we do not know what the counter was equal to initially. Our algorithm assumes that the counters are all set fo zero when we start out, but we ‘cannot safely make that assumption. We may in fact be attempting to add ‘one to some number other than zero (in which case our results will bePreparing @ Program Flowchart FIGURE 16 8 stiuciunce procnanwines conccers wong, OF to something that iy not even a valid number fin which ease Uae computer will stop with what is known as an execution-time error, an error that occurs while a program is being executed), Murphy's law seems to have boen written with computers in mind Anything that can go wrong will When we write programs, we must try to anticipate all the problems that may asise and find ways to avoid them; therefore, we will include a step that will initialize the counters (set their initial values) to zero. A final re- finement for our algorithay is the inclusion ofa step to indicate that the job is done. This results in the algorithm shown in Figure 1-6. ‘The process we have gone through here in developing our algorithm is fairly typical, We started out with an algorithm that contained the main processing steps required, but we fad to go through a series of refine. ments to make the process more efficient and to include some steps that We had failed to consider in our initial solution. Unless a problem is very simple, even an experienced programmer will have difficulty defining an initial solution that is completely correct. Desk-Checking the Algorithm How do we know that this algorithm pro- duces correct results? Before proceeding to the next activity, the prepara. tion of a program flawchart, we can check our algorithm by making up a list of numbers and seeing what happens when we attempt to process this list with our algorithm. This is referred to as desk-checking the algorithm. ‘Table 1-1 shows the steps in the order they will be executed, and what wil happen to our counters, if we process the following list of numbers: 16,3,-7,0,4,-6,-2,8 The final results in Table 1-1 indicate that our data consists of four positive humbers, three negative numbers, and one zero. This checks with the test data, so we have verified that our algorithm does produce the correct 1 sults. The algorithm that we have created and tested becomes an important part of our documentation, When we are completely satisfied that our algorithm is correct, we are ready to prepare a program Howchart, a symbolic representation of our al- gorithm. The preparation of the program flowchart consists of translating the algorithm into a form in which the steps are shown by a set of outlines which has been adopted as a standard by the American National Standards Institute {ANSI}. The program flowchariing outlines we will need are Numbers algo, 4. Sel positve, ngatve, and 2er0 eaunters 10 0. 2, Pead a card; foro aro no more nurabore, goto step 6 5, llthe cumber s positive, acd ene fo the poslve counter and goto step 2 4 the number is negative, add ono to the negative counter and go to sop 2 5. Add one tothe 2ero courier an go to step 2 6 Print counters,rae tt COMPLE Is HE PROGHMLHIG PROCESS DESK-CHECKING NUMBERS ALGORIT A Counters step Number Posltive gave ero 1 None 0 ° 0 2 16 ° ° ° 2 16 1 0 0 2 3 ' o 0 a a 2 0 0 2 7 2 0 4 a 7 2 0 4 4 a) 2 ' “ 2 0 2 1 4 3 6 2 1 4 4 o 2 ‘ a 5 a 2 ' 1 2 4 2 ' 1 3 4 3 1 2 6 8 ' a “6 5 ' 1 4 “6 3 2 1 2 2 a 2 1 3 “2 3 2 1 4 22 a a 7 2 8 3 3 1 a 8 4 a 1 2 Nona ‘ 3 1 é None 4 3 1 7 None 4 3 4 shown in Figure 1-7. The processing to be done at each step is written inside the appropriate outline. There are flowcharting templates avail- able that contain these outlines; one should always be used to produce a legible flowchart. The algorithm was stated in everyday English—more or less—but now ‘we will be planning a solution that takes into account the capabilities of the computer. For example, how will a computer know if a number is posi- tive? As humans, we look for the presence of a plus (+) sign—or the ab- sence of a minus () sign—in front of a nonzero number. But to get the computer to determine if a number is positive, we are forced to use its limited capabilities. Its ability to compare two things helps us here, for what, after all, is a positive number! It is a number that is greater than zero. Similarly, a negative number is one that is less than zero. So if we compare a number to zero, we can find out if itis positive, negative, or zero. A Flowchart for Our Problem Figure 1-6 is a program flowchart derived from the algorithm of Figure 1-6. (The numbers at the upper leit of the out- Tines are not used in standard flowcharts, but are included here to identify parts of the flowchart in the discussion that follows.) This flowchart, like all program flowcharts, starts with the terminal out- fine (1). The word inside this outline need not be START, but it should be appropriate (for example, BEGIN), ‘A flowline takes us from the terminal outline to the process outline (2) which the three counters, here called POSCTR, NEGCTR, and ZEROCTR, are initialized to a value of zero. POSCTR, NEGCTR, and ZEROCTR are10 sirucrunco pnocnasans CoNce : | setae rcson: Repeats te cmprion < Counotacioncante ior tho, tan, Sent to tioscond Farivat: ——Aepromas te paint at C_) mht Oo = | ‘Seatac FIGURE 1-7 Program lowcharing outines. symbolic ways of referring to the locations in the computer's memory in which we will accumulate our counts. The use of POSCTR, NEGCTR, and ZEROCTR to represent the counters is the programmer's choice, although each programming language imposes some limits on the names that may be used. The names used in the flowchart should be the same as the names that will be used in the program. They should also be chosen to help the reader recall what is being represented; that is, they should be mnemonics, Note the arrow (<4 in "POSCTR <0.” The arrow indicates that we are replacing the value currently in the memory locations used for POSCTR byFIGURE 1-8 CunPTER 1 WHE pRocrewannKs PROGESS UL (= {=| BEHOSTA 6 Numbers program flowchart. zenocra the value zero, The annotation outline (3) explains what is being done in the process outline (2). ‘A flowline now takes us to the input outline (5). Although this outline is used for both input and output, we know that here it is being used for in- put because of the word “Read” inside the outline, This represents the reading of a record that contains a number to be analyzed. You may have ‘observed that we have skipped over the connector outline (4). We will be coming back to it shortly. After the input operation—assuming that there was a record to read—a flowline takes us to the decision outline (6). Here the number read {rom the record (identified by the name NUMBER) is compared to zero, just as in steps 3, 4, and 5 of the algorithm. This comparison took three steps in ‘our algorithm, but we can show itin a single outline, We are able with one comparison to determine if NUMBER is greater than (>), less than (<), oF equal 10 (=) zero. Each exit from the decision outline is labeled with the appropriate symbol: >, <, or =. NUMBER = zero, the flow will be to the process outline (7), where ZEROCTR will be incremented by adding one to it, This is indicated on the flowchart as: ZEROCTR — ZEROCTR +1 “That is, take the contents of ZEROCTR, add one to it, and place the result back at ZEROCIR, Similarly, if NUMBER < zero, the flow is to (@), where NEGCTR is incremented; if NUMBER > zero, the flow is to (9), where POSCTR is incremented,12 srmuctunce pHosnamanc concer Alter the appropriate counter has been incremented, the flow in, each case is to a connector (called an out-connector because the tlowline comes “out” of another outline to the connecior). Inside the out-connectors (10) the number 1 appears. This tells us that the flow is to move to an in- Connector thal contains a1, The in-connector (4)is a connector with a flow- line that takes the flow into another part of the flowchart, in Usis ease the input operation that reads the next number, More than one out-connector can take the flow to a particular in-connector, but there can be only one in-connector corresponding to an out-connector You will note that to the right of the input outline (5) the characters FOF appear above a flowline. This indicates that when there are no more dala records in the file (end-offile), the flow will move to the right (11) instead of down (6). The inpuvoutput outline (11) is used for output purposes in this case; we know this because of the word "Print” inside the outline. This is how we get the contents of our counters out of the computer and into a form that we can use. Finally, the flowchart ends with a terminal outline (12), this flowchart has only one ending terminal outline, so our program will always end here. Instead of STOP, the programmer can use any appropriate word, such as END or HALT, but the same word should be used consistently for all end. ing terminal outlines within a flowchart. ‘We now have what appears to be a completed flowchart. However, be. fore proceeding to the next activity —coding the program—we must check the flowchart to see if it produces the correct results. In going from the algorithm to the flowchart we altered the way in which we were doing things (for example, there is only one comparison: of NUMBER to zero), 50 it is possible that the flowchart we have created from our algorithm may not yield the correct results, itis possible that we may have made a logic enor (an ertor in our reasoning, as reflected in the flowchart). Just as we tested the algorithm, we should now test the flowchart of Figure 1-8 with the same set of data, This exercise will be left to the student. The completed flowchart now becomes an important part of our documentation. Some Howcharting Guidelines The following are some guidelines that will prove helpful in preparing a program flowchart; this is not an exhau: tive list of all the do’s and don'ts of flowcharting, but it does cover the most important considerations: 1A flowchart should be read the way a printed page is read: from top to bottom and from left to right. Any bottom-to-top ot right-to-left flow should be clearly identified by an arrow on the flowline unless the flowline is an exit from a decision outline. 2 Every program flowchart starts with a single terminal outline (usually in the upper left corner) and ends with one or more terminal outlines, 3 The descriptive names that identify data items being used and the operations being performed should be used consistently 4 The words used inside the outlines should be chosen so that they will have meaning for anyone reading the flowchart 5 The contents of a decision outline should consist of the two items being compared (either two descriptive names or a name and a constant), separated by a colon, as shown in Figure 1-6, 6 Each exit from a decision outline should be labeled with the appro- priate condition: <, >, =, = (less than or equal), = (greater than or equal), or # (not equal).Coding the Program CMpren aN enOGIANMING PROCESS 13 7 ry to leave white space in the flowehart by using connectors instead of flowlines that wander all over the flowchart 8 Be consistent in the level of detail shown; for example, if deserip- live names are used in calculations, they should also be used when mov. ing data 9 There should be onfy one flowline into an outline, Any merging flows should be brought together on a flowline. 16 With only two exceptions, there should be only one flowline out of an oulline. The obvious exception is the decision outline. The other onc is the input outline, where the EOF condition may be represented by a labeled flowline that exits from the right of the outline 11 Use the process outline for operations performed on data (for ex- ample, initializing a total field to zeros} and use the preparation outline for operations performed on the program itsell. These latter operations will be encountered in subsequent chapters 12 Entering and exiting flowlines should be positioned in the center of an outline. 13 Use annotations to explain anything that may not be obvious. Remember, the purpose of the flowchart is to document the processing, steps; therefore, the processing represented by the flowchart should be easily understood by anyone likely to read it. The above guidelines apply to standard program flowcharts, In the next chapter, we will encounter modifications to guidelines 5, 6, and 10, to ac- commodate structured programming techniques. When we are satisfied that the logic of the flowchatt is correct, we can go ‘on to the next activity: coding the program. The use of the word “coding” deserves some comment. The coding that is done i spy stories consists of taking important information and rewriting it in a form that can be under- stood only by somebody who knows the secret of the rewriting process and can thus decode the message. “Coding” has entirely different implica- tions for us. We are going to write instructions for the computer in a form that is relatively easy for somebody else to understand. A special transla~ tion program will be used by the computer to convert the source program that we write into an object program. The object program will be in a bi- nary form (composed of 1s and 03), which the computer can use but which we humans have difficulty understanding. Coding, then, refers to the writ. ing of instructions for the computer. There are a variety of languages that have been designed to make it relatively easy to give instructions to the computer. The exact form that these instructions take will be determined by the computer language that is used. For each language, there are cod- ing forms on which the programmer can write the instructions. Programming Languages High-level languages are the most widely used type because they are relatively casy to learn, the resulting programs are generally casy to understand and modify, and programs written for one Computer can usually be used on another computer with only minor mod fications. In this text we will refer to the following high-level languages: \ BASIC (Beginner's All-purpose Symbolic Instruction Code): an easy-to- earn and easy-to-use language that-was originally developed for students to use in solving algebraic problems but has been modified to handle busi ness data processing also, BASIC is widely used on personal computers.FIGURE 1-9 Msi TUNED PROGHLAENG CONCH IS COBOL (COmman Business Oriented Language): designed for business data-processing requirements, COBOL was driginally wed on large com. puters but is now available even on some personal computers FORTRAN (FORimula TRANslator): designed for mathematical problem jolying, FORTRAN has been modified aver the years, most recently to include structured programming capabilities, It ip available on most computers Pascal: a general-purpose programming language designed with the heeds of steuctured programming in mind. Pascal is available on most computers. RPG It {Report Program Generator): a powerful, relatively easy-to-learn language for business applications. RPG 11 is widely used on smaller busi- ness computers but is also available on large computers and some per sonal computers. ANSI standards exist for BASIC, COBOL, FORTRAN, and Pascal, These are all procedure-oriented languages; 2 programmer using one of these lan- guages must define the step-by-step procedure to be followed, A compiler is used to translate each source program instruction into one or more ob- ject program instructions. (There are also BASIC interpreters, which will be discussed below.) RPG Il is an example of a problem-orichted language, urbors program favichast wi two-way branches. Comer) posotn -a NegerR "8 Ininee zenocr® courners “ a ~ ‘eROCTA zenocrn oOc1wPTER 1 THE PROBING PROCESS 15 one in which the programmer describes the problem but dovs not define all the steps that must be followed; a generator program uses the problem descriptions in the source program to generate an object program ‘An assembler language is a low-level language. Assembler langua, source programs ave translated into object programs by an assembler prom {slam which produces one object program instruction for each source pro {ram instruction. There are many assembler languages; each type of computer has its own unique version, Assembler languages ace celatively difficult to learn and understand, and programs written far one type of computer usually cannot be used on another computer without extensive revisions. Itis not surprising, then, that assembler language programming is not widely used for business data processing. Coding from the Flowchart A programmer writes a computer program by expressing in a programming language the processing steps shown in a program flowchart. The flowchart in Figure 1-8 can be used with any of the languages described above. However, because of the way the testing of NUMBER is shown in the flowchart, itis better suited to languages such as RPG I, assembler, or FORTRAN, which allow for three-way branches (three exits from a decision outline, labeled "<," "=," and “>"). If we intended to use COBOL, BASIC, or Pascal, we would probably draw the flowchart as shown in Figure 1-9, using two-way branches {two exits from a decision outline, labeled "=<" and “=,” or ">" and "=," or "and "#"), Because our concern in this text is with structured program- ming techniques which use two-way branches and because two-way branches can be used in any programming language, we will restrict ourselves to the use of this type of branching in future flowcharts. Ex- amples of two-way branches are shown in Figure 1-10. Desk-Checking the Flowchart Before proceeding to the next step in the programming process, the programmer must desk-check the code for syntax errors (violations of the rules of the particular programming lan- FIGURE 1-10 Two-way branch examplesDobtigging and Testing 16 siHUcIURe Donel CONCEPTS Ruage being used) and compare: the program te the tlowehad to he suse that the program contaias no logic errors When a program has been coded, cacofully examined for syntax eccors, and checked against the flowchart for logic errors, the progeammer can convert the code to a machine-readable form (a form that can be read by the computer), With today’s computers, that usually means entering the program through the keyboard of a CRY terminal, a task thal the pro. grammer is likely to perform. An experienced programmer may actually be able to code a portion of the program at the terminal rather than first wat ing it on a coding form. When the program is in a machine-readable form, it ts submitted as input, along with data specially prepared to check the logic of the program, to a translation program (for example, a compiter, generator, assembler, or interpreter) Using a Compiler, Generator, or Assembler If a compiler, generator, or assembler is used, the entire program is processed as a unit. The transla. tion program checks for syntax errors the programmer may have missed and produces both a fisting (printed copy) of the program and diagnostic messages that tell the programmer what syntax errors were detected and where they are in the program. If syntax errors are detected, assembler programs and some compilers and generators will go no further. However, some compilers and generators are capable of making assumptions about what code is appropriate when certain kinds of syntax errors are detected, Translation programs with this capability may thus be able to produce an object progeam which can be executed. Since the compiler or generator will probably make some incorrect assumptions, the resulting program output is unlikely to be what the programmer had in mind, but even a litle ‘output may prove useful in starting the process of removing logic errors If the translation program is incapable of producing an object program, the programmer has only the listing and diagnostic messages to work with in correcting the syntax errors. I there is any program output to work with, the programmer must review it to identify the logic errors that have resulted in incorrect output. When the syntax and logic errors have been corrected (to the best of the programmer’s abilities), the program is resub- mitted to the translation program and the process of cor‘ecting the syntax and logic errors is repeated. When all syntax errors have been eliminated, the program can be run (executed) to produce output, Beginning programmers have a tendency to think that when a program produces output, the job is completed. The program output must be care- fully examined to ensure that iis correct. If itis not, the sources of the problems (the logic errors) must be identified and corrected. The process of detecting and correcting errors (bugs) in a program continues until the desired output is obtained, This process is referred to as debugging and testing a program. Using an interpreter If an interpreter is used, the syntax of each instruc tion is checked as itis entered. Instructions that contain syntax errors are corrected and reentered; instructions without errors are executed immedi- ately. The resulting output must be examined to identify logic errors in the program. The logic errors must then be corrected and the program rerunDocumenting EXAMPLE: GROSS PAY Problem Definition ‘opin 4 16 Peioanameas Pre tr (interpreted and executed again). This process continues until all bugs have been removed (rom the program. No object program is produced, Fach time the program is cun, it must be interpreted again, Although the preparation of documentation has been left until fast in our discussion of the programming process, documentation actually begins with the definition of the problem, We must keep a weitten record of everything we do in creating, 2 program. In the process described above, ‘we have prepared the following documents: + A definition of the problem, consisting of a written problem state- ment; descriptions of output and input, including some or all of the fol lowing: print chart, multiple-card layout form, record layout form, and display system layout sheet; and descriptions of any complex processing, + An algorithm * A program flowchart + A source program, as recorded in the program listing produced by the translation program * A record of the test input data and the resulting output All of these serve as documentation for our progeam. The importance of these documents can not be overemphasized. Any program that is going to be used regularly is almost certain to be changed at some time. The requirements may change, oF an error in the program that was not detected with the test data may be discovered. In any event, when the time comes to change a program, even the programmer who wrote it is likely to have difficulty remembering the details of the program tunless it has been well documented. And if the original prograinmer is no Jonger available, it may be virtually impossible to modify the program un- less very careful and detailed documentation exists. Without adequate documentation, it may be necessary to rewrite completely a program that must be changed. Itis time to review the programming process, and there is no better way to do this than by working through another problem. Given a file of employee records, we are to produce a report of the em- playees’ gross earnings (earnings before taxes and other deductions are subtracted). Each input record contains the employee number, the hours worked, and the hourly pay rate. To simplify the problem, we assume that employees are being paid just straight time—no overtime or holiday pays therefore, an employee's gross pay will merely be the product of the hours worked and the pay rate. ‘There will be a line in the report, called a detail line, for each employee. Each detail fine contains information about a single entity, in this case, an employee. This detail fine will contain the employee's number and gross pay. There also will be a line printed at the end, when all employee records, have been processed, that will contain the sum ofall employees’ gross pay.Algortthn io MED PHGGHAMKING CONCEPIS this is coferred to as a fatal fine because it contains 9 summary total derived from the records of more than one employee. Since we are not planning to code a program in a specific language, we need not be concerned wilh the exact form of the input and oviput; there fore, our task is limited to preparing the following: © Analgorithna + Test input and output data + A program flowchart On the basis of our prior experience with the Numbers problem, we can make a first pass at our algorithm. As we wite it, we will probably have ta leave a few steps incomplete, Developing the Algorithm Referring to Figure 1-6, we see that the first step in that algorithm was an initialization step. Most algorithms will sequire such a step at the very beginning. Next will come an unknown ‘umber of steps for processing each employee record, and, finaly, the processing required when there is no more data, We can therefore break the algorithm down into three identifiable components at this time * Initialization * Processing of data * End-of-file processing It is more than fikely that we will not know when we begin to write the algorithm precisely what will require initialization, but this step can be completed as we develop the remaining steps. The most difficult of the three components to visualize is usually the second one, the processing of data, In this case, the processing for each employee record will include reading a record, computing the gross pay, adding the gross pay to the final total, and printing a detail line for the employee. When there are no more employee records to process, all we have to do is to print out the total that we have accumulated of all employees’ earnings and termi- nate processing. We can therefore devise a preliminary version of an algorithm that looks {ike the one in Figure 1-11. Step 1 will be completed when we discover what needs to be initialized. We know that we have to read a record and that eventually we will run out of data and have to branch to some step down the line; however, at the beginning, we are not sure just what step that will be, so step 2 is also left incomplete. We compute an employee's gross pay in step 3. To finish our processing of an emplayee, we must add each employee's gross pay to the final total FIGURE 1-11 Gross Pay alga, fst pass, Read a cad; at EOF go ta step? ustily hours by tae to get gross pay, ‘Add gross pay 0 a, Print ompleyee dota ine, Goto sep 2, Print oa no. Hal 1 2 3 4 & iest Input and Output Data GWPIER 1: PHOGHAMIARIG PACES! 19 and print out a fine in our report for the employee, as in steps 4 and 5. In the Numbers problem, we had to accumulate counts of each type of aum- ber. Here we are accumulating a total of an amount that we are calculating, but the process és quite similar. Any field that is being used! to accumulate total, whether itis a counter or 4 sum of some other amounts, must be initialized; therefore, we will have to initialize the final total field to in step 1 The detail tine that we are to print is to contain the employee oumber and the gross pay. We can assume that step 3 will place the gross pay in the output record, but how does the employee number get there? Once again, it depends on the programming language being used. BASIC, FOR: TRAN, Pascal, and RPG Hallow the programmer to specily in the output in struction the name by which a field was identified in the input. Assembler and COBOL, however, require thal the programmer write instructions to move the contents of an input data field (o an output record. To make sure that our solution is complete, let us assume that we need another step to move the employee number into an output record. Once we have per- formed this step, we can print the detail line and go back to step 2 to get the next record, When we have completed processing all the employee records, we ‘will print out the total of all employees’ earnings and then halt, Step 2, therefore, must specify that at EOF we will go to the step that prints the total line. Alternative Algorithms We can now complete our algorithm, as shown in Figure 1-12. It should be noted that there is some fiexibility in ordering some of these steps, Steps and 2 must be in the order given, We want to initialize the final total only once, so it must be outside of the loop (a group of processing steps that is used repeatedly) starting at step 2 that is used to process the employee records. Reading the employee record must bee the first step in the loop because we can do nothing else until we have data to work with. However, we can move the employee number from the input area to the output area at any time between the reading of the record and the printing of the detail line. Calculation of the final total must follow the calculation of the employee's gross pay, but it need not follow it directly. It could occur after step 5 or 6 of Figure 1-12. Figure 1-13 contains an acceptable alternative to the algorithm of Figure 1-12, We should not assume that either of these algorithms is correct. Rather, we should desk-check them with some data. We must prepare input lest data FIGURE 1-12 FIGURE 1-13 Grass Pay algoritim completed. ‘Gross Pay algorithm, ternative version, 1, Iaiz tnt tts, 1. nae tal ota 2, Read a car al EOF goto stop 8 2, Rad a cai at EOF go to stop 8. 3. Mutily hours by rte to get a1oss pay. 53, Move erpoyee number to out record. 44 Add gross pay to total 4 Mulply hours by rate to get gross pay 5. Move employee number to ouput record. 5, Print employee deta ne 6. Pant employee deta ine. 5, Add goss pay to fal 7. Goto stop 2 7. Goto stop? 8, Prin toa ne 8 Print ttl. 9, Hat 9. Va20 StRUCIUNED PHoceaMnniG CONCEPTS for our algorithm, as in Table 1-2. 1 our algorithm is correct, we should got the output shown in the table, (The first column contains the employee number; the second, the employee's gross pay and the total for all em ployees.) Will we? Table 1-3 steps through the algorithm of Figure 1-12 TABLE 1-2 GROSS PAY INPUT AND OUTPUT OATA, Input daca Employee ruiner ote Output records Employee Step number Hours Rate : 2 2 1234 40 6.00 3 1234 40 6.00 4 1234 40 09 5 1234 40 6.00 6 1234 0 6.00 r 1204 40 6.00 2 3748 35 8.00 3 3748 35 8.00 4 3745 35 800 5 3748 35 800 6 amas 36 8.00 7 37a 35 8.00 2 6240 40 750 3 240 40 7.80 4 5240 40 750 5 5240 40 750 6 6240 40 750 [sao 1820.00 7 240 40 2.50 30000 20.00 2 None 00.00 20.00 one sea since [ao] None 00CCuAPEH Te PHONG Output is produced by steps 6 and 6, as indicated by the boxes in the lable, This is the same output shown in Table 1-2, so the algorithm io Fig ure 1-12 is correct. Similarly, Table 1-4 shows that the alternative algorithm, Figure 1-8, also produces the correct output Program Flowchart Since there are several algorithms that will work for our Gross Pay exam ple, there also are several acceplable flowcharts. The one shown in Fig- ure 4-14 is for the initial algorithm of Figure 1-12. [Note the use of an asterisk (4) to represent multiplication. This is the symbol normally used in both flowcharts and programs. Division is represented by a siash ().] How ‘would this flowchart have to be modified to represent the logic of the al- xorithm in Figure 1432 Before proceeding to coding the program, we must desk-check our Fig- ure 1-14 flowchart. We should process our test input data through the flowchart to see if we get the correct output. When we are satisfied that we have a flowchart that will yield the desired results, we can include it in our documentation, TABLE 1-4 TESTING ALGORITHM OF FIGURE 113 Input records | Output records Detalt Employee Employer Gross. Total step uber Hours ate umber pay 1 2 2 2 2 1234 40 500 > > 3 1234, 40 800 1208 2 4 1238 0 5.00 1238 240.00 5 1204 40 600 12a 240.00 0 6 1234 “0 500 1238 240.00 240.00 7 1234 0 800 1284 240.00 240.00 2 3748 35 8.00 1234 240.00 240.00 3 3743 35 800 3748 240.00 24000 4 3748 35 800 3740 200.00 40.00 5 sma 35 800 ora, 26000 240.00 6 3748 38 8.00 ‘748 2000 520.00 7 3748 35 800 ama 260.00, 520.00) 2 be40 0 799 ane 260,09, 520.00, 3 5240 40 750 Beto 2000 520.00 4 5240 0 750 240 300.09 520.00, 5 5240 40 750 sao —=SS=«8000 520.00 6 e240 40 750 ato 30000) 820.00 7 5040 0 750 B40 30000 20.00, 2 None Bato 300.00 220.00 8 None 240, 300.00 [000 | 8 None 6240 300.00‘SUMMARY FIGURE 1-14 22. sructunece pro a [= [8 /-o=) role mba orn Gross Pay flowchart, In this chapter we examined the traditional programming process: I Clearly defining the problem 2 Preparing an algorithm, desk-checking it, and going back to correct it necessary 3 Preparing a program flowchart in accordance with the standard and desk-checking the flowchart 4 Coding the program from the flowchart and desk-checking the coding 5 Debugging and testing the program 6 Documenting the program, a process that should be going on at all stages in the development of a program In the next chapter we will see how the second and third steps are changed by the structured programming approach.key TEAMS EXERCISES CORMIER 1s HE PROGIAMIBG MHOCESS 23 algorithm initialize binary input branch item bug fisting, claracter logic error coding loop computer program memory counte; object program debugging output desk checking prograin flowehatt detail line programming process documenting record £OF run execute source program execution-time error syntax error field testing file total line high-level language translation program increment 1 A payroll register is to be procluced. The input consists of employee umber, em- ployee'’s gross pay, income tax, union dues, and other deductions. ‘The printed payroll register is to contain a detail line for each employee and a final total line as follows: Detail Line: Employee number, gross pay, Income tax, union dues, other deduc- ions, and net pay (gross pay ~ income lax ~ union dues ~ other deductions) Total Line: Total net pay for all employees Documentation for this prablem is to consist of the followin, ‘gram flowchart, test input data, and test output data gorithm, pro 2. An inventory report is to be produced. The input consists of item number, open- ing inventory amount, amount purchased, and amount sold. “The printed inventory report is to contain a cetail line for each item anda final total line as follows: Detail Line: Item number, opening inventory amount, amount purchased, amount sold, and ending inventory amount [opening Inventory * purchases sales) Total Line: Total opening inventory, total amount purchased, total amount sold, and total ending inventory The total opening iaventoty is the total of the opening inventory amount for all items. The other totals are computed in @ similar fashion, Documentation for this problem is to consist of the following: algorithm, pro- ‘gear flowchart, test input data, and test outpat data 5. savings account balance report is 10 be produced. The input consists of ace count number, balance forward, deposits (sum ofall deposits), withdrawals (sum of all withdrawals), and interest earned The printed account balance report is to contain a detall line for each account and a final total line as follows:24 stALCIUNED pnocnannne cone) Desai Lines Acco earned, and ending interest) At nuenbey, balance forward, eleposits, wills, interest balance (balance forward + deposits ~ withdrawals + Total tine: Total balances forward, total deposits, tola withdrawals, total i terest eared, and! total ending balances, The total balances forward is the tolat of the balance forwarcl amount for all accounts, The other totals are cornputed in a similar fashion, Documentation for this problem is to consist of the following: algorithm, pio- ‘gram flowchart, test input data, and test output data,OBJECTIVES INTRODUCTION CHAPTER, INTRODUCTION TO STRUCTURED PROGRAMMING Upon completing this chapter the stucent should be able to: 1 Prepare a structure chart. 2 Discuss the essential features of a structured program and why they are considered essential. 3 Prepare a siructured program flowchart 4 Write a structured program in pseudacode, 5 Define and use the key terms at the end of the chapter. In the early days of programming —the 1950s and 1960s, when computers were slower, of limited capability, and more expensive-—there was a pre. ium placed on writing programs that required as little storage as possible and could be executed in the minimum amount of time, One result of this ‘emphasis was that programmers often spent a great deal of time devis- ing clever techniques and algorithms to save computer time and memory, Some of these early programmers were truly ingenious, and their pro. grams could properly be considered works of art. Sometimes, however, because of amazing ingenuity, inadequate documentation, ot both, the programming logic used by these programmers was extremely difficult to understand. Today, as hardware costs continue to fall and programmer salaries con tinue to rise, the writing of programs consumes an increasing portion of data-processing costs. In addition, as much as 80 percent of programming effort Is spent on maintenance programming, that is, modifying existing, programs to correct errors oF to meet changing needs. When the logic of a program is not easily understood, maintaining the program is at best very difficult. In some cases, itis virtually impossible. If the original prow grammer is no longer available, somebody else must become familiarized with the program logic before any changes can be made. If the program logic is obscure, it may be cheaper to completely rewrite the program than {0 try to modify it. I the program logic is convoluted enough, and enough time has passed, even the original programmer may not remember why something was done in 2 particular way. ‘A program that is difficult to maintain can greatly increase dataeprocess- ing costs, so it is not surprising that data-processing managers are les terested in clever code and more interested in an organized, systematic approach to programming, Today we see a major emphasis on writing pro- 2828 STHUCTURED POGrAMMNG CONCERTS grams with staightlorward, casily understood logie, programs thal can be Written and mairitained with a minimum expenditure of time and effort The term structured programming refers to a collection of techniques that have evolved frorn the pioneering work of Edsger Dijkstra, These tech niques are meant to increase programmer productivity by reducing the lime required to write, test, debug, and maintain programs. Structured programming emphasizes the truly creative part of the programming pro: cess the carefull and systematic planning of programs. Coding (that is, translating the plan into instructions for the computer) is largely a cleri- cal task once the syntax rules of a language have been mastered. In this, chapter we will discuss how structured programming has evolved from modular programming, We will examine the fundamental structures used in structured programming, and we will begin to use structured flowcharts, structure charts, and pseudocode as tools for planning programs MODULAR PROGRAMMING One of the early attempts at improving programmer productivity through better planning was the use of modular programming. In modular pro- gramming, the program is broken down into modules (pieces), each of which performs a single, limited function andi written and debugged sep- arately from other modules. Because the purpose and size of each module are limited, the likelihood of errors is reduced. Each prograrn contains a main program module, which ultimately con- trols everything that happens; it transfers control to submodules so that they may perform their functions, but each submodule returns control to the main module when it has completed its task, Ifthe task assigned to a submodule is too complex, it must itself be broken down into other mod- ules, which it controls. This process of successively subdividing modules continues until each module has only a limited task to perform. This task can be input, output, manipulating data, controlling other modules, or some combination of these. A module may temporarily transfer control (branch) to another module, but each module must eventually return con- trol to the module from which it originally received control Modules are independent in the sense that no module can have direct access to any other module except its calling module and its own sub- modules. However, the results produced by one module can be used by any other module when itis given control. Because the modules are independent, different programmers can work simultaneously on different parts of the same program. This reduces the time that elapses between beginning and completing a program. In addi- tion, a module can be radically changed without affecting other modules as long as its original function remains unchanged. Implementing the Modular Approach ‘Modular programming is implemented by using subroutines, a group of instructions that performs a limited processing task, such as printing @ portion of a report, reading an input record, or calculating a square root Subroutines can be discussed from a variety of perspectives, but we will restrict ourselves here to considering external and internal subroutines. Since internal subroutines are more frequently used in business data processing, we will discuss them first. We will then briefly look at exter nal subroutines,mnie 27 En EOOUCTION To STRUCTURED PO {ternal Subroutines An intemal subroutine is part of the program that Uses it. The task performed by the subroutine may be one that is required a more than one place in the program, but the code appears in the pro: gram only once. ‘The progeam transfers Control to the subroutine when the task needs to be performed. When the task is completed, control is Feturned to the instruction following the one that trantsferied contial to the subroutine The instructions that transfer control to the subroutine and back again are commonly identified as call and return instructions, respectively. A subroutine retuins control to the instruction following the cal instruction when it has completed its task. This is possible because at the time a sub- routine is called, the location of the instruction to which contol is to be retusned is stored in a register, a special-purpose memory device in the computer. This location is the position in memory of the instruction following the call instruction. When itis time to retuen to the calling program, the location to which to return is retrieved from the register. Figure 2-1 illustrates how a subroutine can be called from more than one place in a program. ‘The calling of an internal subroutine is represented in a program flow: chart by a horizontally striped process outline, as in Figure 2-2. The name Of the internal subroutine is weitten in the striped area. The flowchart of the internal subroutine will be part of the flowchart of the program that calls it. Like a program flowchart, the subroutine flow- chart begins and ends with a terminal outline. inside the beginning ter- ‘minal outline appears the name of the subroutine, and inside the ending terminal outline is placed the word RETURN. Figure 2-3 illustrates the flow: Charting of an internal subroutine that performs a series of calculations. One disadvantage of subroutines is that using them results in generally slower execution speed for the program as.a whole, but the high speed of today’s computers has reduced the significance of this disadvantage Another drawback is that some languages impose strict constraints on how data is passed to and from a subroutine and problems may arise if these FIGURE 2-1 Trarsfer to and torn @ subroutine, aL sun Keyimeme pat tat CALL ote patol cond CALL FIGURE 2-2 Calin infernal subroutines28 stAUCIUREO PROGRAMING GOMES co) constraints are not closely observed. On balance, however, the disadvan- lages of using modular programming arc far outweighed by the benefits reductions in the time required to write, test, debug, and maintain pro- rams, resulting in substantial cost savings. External Subroutines External subroutines are used for tasks that more than one program is likely to want performed: for example, calculating a square root. The term “external” is used because the instructions for doing the processing will not be part of the program using the routine. The external subroutine is treated almost like a separate program, Its instruc- tions are translated like any other program, and the resulting object code is stored in a library where it is available to any program requesting it. As a result, the work of designing, writing, and debugging needs to be done only once. To use an external subroutine, the programmer needs to know where to find it, what its name is, how to send daia to it, and how the answer will come back. Once these technicalities are dealt with, however, the pro- grammer can make use of the code to perform a task, with confidence that the subroutine will provide correct results. ‘The use of an external subroutine is represented in a program flowchart by the predefined process outline of Figure 2-4. The processing repre~ sented by the outline is not explained in the flowchart in which it appears. Usually a flowchart or a description of the processing is available in some other document. External subroutines are frequently used for complex processing that is heeded by many users, such as mathematical or statistical routines or the sorting of files. Any progranmer can access and use external subroutines without having to understand the techniques involved. FIGURE 2-4 Calling extemal subroutinesOHAFER 2 aUTHODUCHION IO SHRICTUREO PHOCHALRANG 29 Probloms with the Modutar Approach Examples of Program Modules The modular programming approach initially met with some resistance from programmers because it restricted their activities. When portions of a program are allocated to different programmers, no one programmer can be said to “owa” the programm; instead, it belongs to a team. Team pro grammers, for example, no longer have free rein fo make up names {0 refer to data, for all programmers must use the same names for certain items of data, For each file, standard field names are established thal must be used in programs that process the file. Even when the programmer is free to eceate a name, there are frequently naming conventions that must be followed, A more significant difficulty with the modular approach lay in determin: ing exactly what constitutes a module. Early modular programming efforts often produced programs that consisted of one very large module and sev- eral small ones, Definitions of the functions to be performed by modules simply were not as limited as they should have been. To counteract this problem, arbitrary limits were sei on the number of instructions that a module could consist of. (For example, an ofter-used rule of thumb was that a module should consist of no more than 50 statements, about the number that fit on one page of a program listing.) These arbitrary rules helped programmers to identify a module with a function that was too broadly defined, but at the same time use of the rules in some cases d layed the development of good programming practices. instead of design- ing modules to do a particular job, programmers defined them in terms of an arbitrary number of instructions. A further early difficulty with the modular approach lay in the emphasis placed on the planning phase of programming, an emphasis that is some. limes unsettling to both programmers and managers, Clearly, planning essential if the functions of the modules are to be properly defined, Pro- grammers and managers frequently work under severe time pressures, however, and there is a natural tendency to want to get on with the cod. ing. The time spent in planning the program produces no actual code, so it may appear that progress is not being made. In the long run, however, the time invested in careful planning pays off in lower programming costs. {f the modules are assigned to different programmers, someone has to coordinate the project to ensure that each module performs its assigned funetion and that proper fleld names are used. With some languages (nota- bly COBOL), if programmers must make up a name for the results of the processing done by'a particular module, they have to make sure that the same name has not been used by another programmer for a different pur- pose. Modular programming thus requires a substantial amount of coord nation and standardization. We humans tend to resist change, so the early resistance to modular programming was not surprising, Today, however, the obvious advantages of the modular approach have made it an integral patt of all structured pro: gramming efforts The Numbers and Gross Pay examples in Chapter 1 have three major functions: 1 Reading the data 2 Processing it 3 Printing the resultsTOP-DOWN PROGRAMMING Structure Charts FIGURE 25 —Leveld and level modules, [ae 30 JOFUNKED PREIANIAING CONE The third function for the Gross Pay problem can be subdivided into 3a Printing detail output 3b Printing final ovtpuat We will return to these two examples as we examine some of the tools used in planning structured progtams In addition to the modules noted above, each program also needs a main program module, Execution begins and ends in this module. In be- tween, the main module transfers control to the other modules at the ap propriate times. The top-down approach has evolved as a useful technique in planning a modular program. In top-down programming we first define the main pro- gram module, which initiates program execution, calls other modules to perform specific functions, and then terminates execution. Hf the function to be performed by a module called by the main program module is suffi ciently complex, this submodule must in turn be broken down into subor- dinate modules that will handle pieces of the larger function, The structure chart is a commonly used planning tool in top-down pro: gramming, [This tool is sometimes referred to as a hierarchy, or hierarchi- cal, chart or a visual table of contents (VIOC}.] There is no standard for structure charts, and the technique discussed below, wiich seems to be a workable, logical way to use the tool, is a blending of ideas from a variety of sources. Rectangles are used to represent modules, as shown in Figure 2. Fach module is assigned a number, with zero reserved for the main program module. This module represents the entire program, and is referred to as a level0 module. Below it are shown level-i modules that are called by—and are therefore directly under the control of—the main program module. There may be up to three level-1 modules. The first module defined at level-t is the one that will be executed repeatedly, for example, a module that processes input data records. A second module handles the process- ing that is required before the data itself can be processed (for example, loading a table, as discussed in Chapter 7). Processing that is done after the last data record has been processed (for example, printing a final total) is placed in a third level-1 module. The modules are ordered from left to right in the order in which they normally are executed, as shown in Fig po ‘a0 200 ‘0 ble wamectiase ‘iaIdentitying Modules FIGURE 2.6 wsrri¢2: mrROBUC HON TO SAUCTURED PROGRAMING 3 ure 2:5. Level? modutes are added for any level-1 modutes that volved task to perform. Some of these level-? modules may in turn have to be broken down into submodules, and some of these: may algo have to be subdivided. The subdivision of modules ends when each module has a clearly defined, single function to perforin. tn general, a morlule should be sinall enough to be casily coded and tested. A properly subdivided module will have at least two modules at the next lower level. fa module has only one subordinate medulo, it should there fore be reexamined. (An exception to this cule is discussed in the next see tion.) Excessive subdivision of a module, on the other hand, is more difficult to identify, This condition may not make itself apparent until the calling module is flowcharted and the complexity of its logic revealed, In that situation, the way in which the module is subdivided should be recon- sidered, Figure 2-6 shows a completed structure chart for a program that updates an iaventory file. A module name is a short description of what the module does. The identi- fication of a module also includes a number. There is a great diversity of opinion about how to number modules. The system described here has the advantages of being both simple and tlexible. The numbers for modules that show the processing that lakes place before the data records are processed have the number 1 in the first post tion. In Figure 2-6, module “100 load product table” has two subordinate ‘modules, one to read the table records, and another to store the table ‘Structure chart ora program to update an nventoy fie ie | [RRR Seer 10 feosReviewing the Structure Chart 82 StHUCTUMID prOGHAMHAED CoNcrPTS data. The numbers of these modules also contain the number in the first position. Module “200 process transaction" has five subordinate functions: Reading transaction record » Reading, rsaster record + Updating inventory level * Writing master record + Printing error message Gransaction records contain data about a business activity, stich as a sale or a receipt of merchandise; files of transaction records are retained for a relatively short period of time. A master file is retained indefinitely; its records contain information that must be used regularly, such as the amount of an item that is in inventory.) The numbers of all modules subor- dinate to module 200 contain the number 2 in the first position. Mod- ules 210 through 250 are level-? modules, as are modules 110 and 120, but because of space limitations, they are drawn at what appears to be a lower level. An alternative way of dealing with the space-limitation problem is to Use more than one page for the structure chart. We can put on one page the level and level-T modules and thea have a separate page for each level-t module and its subordinate modules. ‘The modules for the processing that takes place when there are no more data records have the number 3 in the fist position, unless modules that were previously defined are also used here. in that case, the earlier ‘module number is used. For example, module "300 print final totals” has a single subordinate module (*260 write tine”), which is the same module called by "250 print error message.” This is an example of the exception referred to in the previous section. A madule may have a single subor- dinate module if that single module is subordinate to at least one other module. Note that the rectangle for such a module is shaded in the upper right comer. : “Module numbers normally appear as part of the module names usec! in the program. This helps in relating the source program to the structure chart on which itis based, The modules will usually appear in the program in module number order. This facilitates locating modules in the source progam. Note that the numbers 110 and 120, rather than 101 and 102, are used for the modules subordinate to “100 load product table.” Leaving gaps be- tween the numbers allows us to readily insert a module between two oth- crs in the program if we later discover a need to do so. ‘Thrce-digit module numbers can be used as long, as no fevel-t module has more than 9 subordinate modules. If module 200 has 9 subordinate modules, we can use numbers 210, 220, ...,290 for the subordinate mod- Ules, If module 200 has 10 or more Subordinate modules, we use four-digit module numbers: 2010, 2020, ..,2100, ‘After a structure chart has been prepared, it must be reviewed to be sure it is complete and properiy structured. This review starts at the top and pro- ceeds down through the various levels. To determine if everything is in- cluded that is necessary, the user (the person or group for whom the program is being developed) should be consulted. The user is most fami‘Structure Charts ond Floweharts Coding the Modules Coammren 2: vionvenon ve sinuGrunen prOcteamans 9 iar with the problem and can offer valuable comments about the comple ness of the sinucture charts Whether the chart is properly structured! is for the most part a question of whether each module is assigned a single, limited function. any mod ule has not been subslivided property, the structure chart must be revised The process of developing the structure chart begins with defining the main program module. Ifa module contains any obvious subordinate func- tions, they are broken out and placed at the next lower level, under the module to which they are subordinate. A module usually has either zero, or two or more subordinate modules; it will have a single subordinate module only if the subordinate module performs a function that is re- quired elsewhere in the program. This top-down design of the program focuses attention first on the ov all structure of the program and leaves the cletals of the particular individ- ual functions until after the structure chart has been prepared. This contrasts with program flowcharting, in which we immediately plan the de- tailed processing steps, developing a sequence of these steps as a solution to the problem. Typically, @ program flowchart must be revised frequently, for example, when one of more required processing steps have been omit: ted, or the steps have been listed in the wrong order. Because in develop- ing a structure chart the processing details are left until the end, structure charts requite far less revision. The structure chart is a tool for planning the structure of a program. It shows the functions to be performed and the relationship between mod- ules, but it usually provides too little information to serve as a basis for coding a program. It does not show the exact processing steps, nor does it show under what conditions and in which order the modules will be used. For these reasons, the use of structure charts does not preclude the use of program flowcharts. In fact, after a structure chart has been prepared, flowcharts of the individual modules may be prepared as an aid in writing, the code. The logic of some modules will be so simple that it will be poss ble to write the code without the use of flowcharts. For others modules, flowcharts may be required as part of the documentation of the program Structure charts are easier than flowcharts for the user to understand, For this reason, they are an effective tool for communicating the design of a program to the user and for obtaining suggestions for corrections and improvements. Later in this chapter we will examine an altemative to pro- Bram flowcharts that both shows the processing details and is easily under- stood by a user. Figure 2-7 contains a structure chart for the Numbers problem of Chap- ter 1. This contrasts with the program flovichart of Figure 1-8, Since there ‘was no processing required before the first data record was cead, there are only two level-1 modules. In top-down programming, the level module is coded first It is tested us- ing dummy modules for the level modules. These dummy modules can be called by the level-0 module; they give the appearance of performing, the desired function without actually doing so. They do, however, permitFIGURE 2-7 PROGRAMMING STRUCTURES 34 stnUGFUNED PROGRAMMING CONCEPTS [2 Seer Es [=| ‘Structure chat for Nunbers problem, the testing of the level0 module. When the level-0 module checks out with the dummy level-1 modules, attention can be turned to coding the ac- tual level-t modules ‘Wher an actual level-1 module is coded, it will use dummy modules for its subordinate functions while its logic is being tested. When the level-1 module (slong with its dummy modules) yields correct results, it replaces the corresponding dummy level! module in a test of the level0 module. If the level-0 module (which had previously performed properly) now fails, the problem can be traced to the new level-t module. This incorporation of new modules into the program one at a time greatly facilitates identify- ing and correcting the source of problems. Once a level-t module checks out (both by itself and with the level-0 module), attention can be directed to developing and testing modules to replace its dummy modules. In this way, the program is literally coded from the top of the structure chart down to the lowest-level modules. When the last dummy module is finally replaced and produces satisfactory results as part of the entire program, a usable program exists, Since a structure chart gives no indication of the size ofits modules, its possible that during the coding of a module we may discover that itis too large. Then the structure chart will have to be revised to make the function ‘of each module more manageable. This will require the recoding of those modules whose functions have changed. One of the early objectives in designing structured programs was to elimi- nate the confusion resulting from the use of branch, or go-t, instructions. Itis sometimes difficult to follow the flow of a program through a series of branches. tn addition, because branch instructions enable the programmer to transfer control to any instruction in a program, when a problem does ‘occur, it may be hard to determine what processing led,up to the problem. For example, a problem occurring in a partion of a program that can be reached by any of three different branch instructions may be the result of an error in the code preceding any of the three branches. Knowing which of the three branch instructions was executed immediately prior to the occurrence of the problem would be a big help in identifying the problem.Sequence Structure omeren 2. wsinooUC TON TO StHUOTUREH HERA I I the postion of the program where the problem appeaes is in an internal subroutine aecessed by means of a call instruction, the register containing the return address can be checked to determine what processing immed ately preceded the call of the subroutine: There is ao universal agreement that a program must be completely free of branch instructions. There are some who feel that a limited use of branch instractions under special circumstances (for example, within a module) is acceptable. However, there ave a significant number of advo- cates of structured programming whe take the position that branch in structions should not be used at all. The solutions that we will develop will use no go-to instructions; that is, they will be part of what is sometimes called GOTO!ess programming. ‘Three logic patterns, or structures, have been identified which are suffi cient for any structured program: the sequence structure, the loop struc- ture, and the selection structure. None of the three requires the use of branch instructions. In the sequence structure, instructions are executed in the order in which they are encountered. Figure 2-8a shows a generalized sequence structure, and Figure 2-8b shows a specific sequence structure from the program flowchast of Figure 1-14. Note that the only way to enter a sequence steuc- ture is at the top, and the only way to exit from itis at the bottom, ‘The rectangle in the generalized sequence structure can represent any unconditional operation: + An 1/O (input or output) operation * An arithmetic operation * An operation involving moving data about in the computer's memory ‘One outline not allowed in a sequence structure is the decision outline, FHOUNE 28 Sequsncesuctie 1 Il (2) Generalized; (0) tom Gross ay problom. noss + Pay probi Instrction- HOURS teseucton-2 “TOTAL #enoss ‘OuTENPLY mnenieny woLoop Structure 36 SMHUCrUnED PHOGRaMIWAG CoREEPES The processing steps in a sequence stiuciure can be combined and represented by one rectangle with a single cotry point and a single exit point. I the processing steps constitute the task of a module, when we combine them into a single rectangle we acc in effect using that rectangle to represent the entire module. This is the reverse of the process that we go through in top-down programming, where we take a rectangle repre- senting a module and break it down into discrete processing steps. Fach module can thus be viewed as a structare with a single entrance and a single exit ‘The loop (or iteration) structure provides for the repetition of one or more instructions for as fong as a given situation, referred to as a condition, ex- ists. When a condition exists, itis true (1); when it does not exist, itis false (F). The loop is executed as long as the condition is true. Figure 2-9 illustrates the loop structure. As with the sequence structure, there is a single entrance and a single exit from the loop structure. Neither of the examples in Chapter 1 contains an abvious example of the loop structure, although both of them contain loops that read and process records. if we modify the flowchart of Figure 1-14 slightly, however, we get the example of the loop structure shown in Figure 2-10. The condition that controls the loop is "not EOF.” As long as end-oF{ile is not encountered, the loop— including the reading of a record—will be executed. the test for EOF cannot be part of the input operation; it must be at the beginning, Of the loop. We no longer show an FOF exit from the input outline. The use of connectors to return the flow to the beginning of the loop is not a branch. The connectors are used to avoid having a flowing that clutters up the flowchart. There is a problem with the flowchart in Figure 2-10 when we do reach EOF because there is no exit from the loop until just prior to reading an: other record. Unless we change the flowchart, we will attempt to process a nonexistent record after EOF has been detected. We really should test for EOF immediately after attempting to read a record. This can be done by us- ing what is known as a priming read, which is an initial read that is used only for the first record in the file, just before the condition is checked the first time, We then place at the end of the loop the input operation for the rest of the records. Now the EOF condition will be detected as soon as it ‘occurs, and the loop will be terminated, No attempt will be made to pro- cess a record that does not exist. The revised flowchart is shown in Fig- Ure 2-11. This logic also handles the unlikely situation of an input file that contains no data records, Some people object to using an extra input operation just for a single record. One reason for this objection is that input instructions require a large amount of memory, but this is no problem if a single copy of the in- FIGURE 2.9. Genoralzod loop suet.FIGURE 2.10 CMPrEN 2: WIHODUEHON Fo SinUCIUREO ProGHAWIEKG 87 Cm) HE >} Modi’ Gross Pay lowchar. put instructions is placed in a modute that can be called. This requires a modification of the structure chart to include the priming read as part of what is done before the first data record is processed. This is illustrated by Figure 2-12, a structure chart for the Gross Pay problem of Chapter 1. The umber assigned to the module that reads a data record starts with the number 2 rather than 1 because all but the first read will be controlled by module 200. Module “240 write line” is used for the printing of both the detail line and the total line, a technique that is characteristic of structured COBOL programming, In other languages, the output would probably be handled differently. ‘An instruction in the loop will be executed only if the not-£OF condition is true. Since no branch instructions are allowed, there is no way to get into the loop without first satisfying this conditionSelection Structure FIGURE 241 38 StRUCTURKO PnooHAMMNG Con Coin [=H G Tove Gross Pay flowchart wth priming cea. The activities that make up a loop structure can be represented by a sin- gle rectangle. This rectangle can then be combined with other rectangles in a sequence structure into a single rectangle representing a modute, ‘he third structure, called the selection structure, is illustrated in Figure 2a. Note that flowcharting guideli es Numbers 5 and 6 must be modified to accommodate the selection structure. Exits from the decision outline areaurren 2, wmopUGHON TO SIRLEIUNED pRoGHAMEG — 39 r = 1 woo | 210 20 240, \ fond colts ete scart esr FIGURE 212 Gross Pay stustur char. labeled “1” and “F* instead of with the relationships “<," “>," "=," etc. The relationship becomes part of the condition inside the outline rather than a label for an exit. A condition is tested, and one of two alternative courses of action is selected depending on whether the condition is true or false, Note that like the sequence and loop structures, there is a single entry point and a single exit point from the selection structure, Because of the single exit point, whatever structure follows the selection structure will be executed, regariless of the stalus of the condition. A selection structure derived from the Numbers flowchart of Figure 1-9 is shown in Figure 2-136. In some situations, there may be no action taken if the condition is false. This situation is flowcharted as shown in Figure 2-13c. Like the activities represented by a loop structure, selection-structure activities can be combined and represented by a single rectangle, as part of a sequence structure. Structure Charts and Program Structures We can use sequence, loop, and selection structures to flowchart the pro- gram represented by a structure chart. The processing to be performed by any module can be represented as a sequence of these three structures. Since both loop and selection structures can be represented by a single rectangle, an entire program module can be represented by a sequence structure, And since a sequence structure can also be represented by a single rectangle, we can represent any module by a single rectangle. Thus, we have what appears on the structure chart: a rectangle representing an entire module If we start at the lowest level in a structure chart and work our way up {0 the next higher level, we can combine all modules subordinate to a calling module into a single rectangle which represents the function performed by the calling module and its subordinate modules. This process can continueSTRUCTURED CODING. 40 sthuctUnco srogrAMANG conceeTS a “zeROETH zendorn o FIGURE 2-18 Selecon structure, (a) General (0) from Numbors probom; {6) mth no false action, ta until the level-i modules are combined into the level-0 module that repre- sents the entire program, Remember: A significant feature of the three structures is that each has a single entry point and a single exit point. One can neither enter (branch into) the middle of a structure nor exit (branch out from) the middle of a structure, How the sequence, loop, and selection structures arc coded depends on the programming language used. Of course, not all programming languages provide these structures, but COBOL, FORTRAN 77, Pascal, and some versions of BASIC permit the writing of any program using these structures (or vatiations thereof) without recourse to branch instructions. In the other versions of BASIC and in assembler and RPG, the programmer ‘must improvise these structures, and branch instructions must be used. {RPG II, available on the IBM System/38, does include these structures.)Pseudocode FIGURE 2-14 Clipren 2. muinoouCTION Yo smnuCIURED PeoGRaMANNG 44 Nevertheless, programmers using assembler, RPG Il, and those versions of BASIC not providing these structures can still benetit from the application of the principles of modular and top-down programming, To illustrate structured coding, we will use a pseudocode (literally, a fake code), a recognized aiternative to lowcharting, for planning structured pro- grams. Pseudocode is an extension of, and a replacement for, the al gorithm developed in Chapter 1. Normally either pseudocode or flowcharts are used to show the details of the processing taking place in program modules; however, we will use both techniques There are no generally accepted standards for pseudocode, We will work with a form that has a minimum number of rules ancl is essentially Tanguage-independent (not oriented to any pasticular progeamming lan- ‘guage). Since pseudocode instructions are written in English, they can be easily understood and reviewed by users. The only syntax rules to be con- ‘cerned with involve the loop and selection structures. In our pseudocode instructions, the only capitalized words are those associated with these same structures: DO WHILE, END DO, If, THEN, ELSE, and END IF. Sequence Structure The pseudocode for the sequence structure in Figure 28 is shown in Figure 2-14. We simply express in English what itis we want (0 do, in the order in which we want to do it. Loop Structure The loop structure is illustrated by the DO WHILE instruction: DO WHILE (condition-A) Instruction-1 instruction END DO [The ellipses (...) indicate where ather instructions may appear.j As long as condition-A is true, all instructions between DO WHILE and END 00 will be executed. Obviously, at some point one of the instructions in the loop must do something to make condition-A false, or we will have an endless loop. It is important to note the indention of all instructions within the loop. Indenting these instructions three or four spaces makes the structure of the program more obvious, Also observe that END is aligned left with 00 WHILE it might be argued that there is, in effect, a branch back to the begin ning of the loop, but a programmer can implement the DO WHILE instruc- tion without writing a single branch instruction ‘Sequence structure pseudocode. multiply hours by ale to got gross pay ‘add gr0s8 pay 10 fala gross pay ‘ove input amplayee umber 10 output empiyoe number pint deat ine42. grnucruneD Pnexs ates Concerns Selection Structure The selection streture is ilusteated by the 1F-THEN. ELSE instruction: IF condition-B THEN instruction-t ELSE instruction-F END IF This structure allows for a choice between two alternative courses of ac tion. If condition-B is true, instruction-T is executed; if condition-B is false, instruction-F is executed. (Instruction-T and instruction-F may each actually represent a number of instructions.) Again, indention is used to make clear the structure, of the progeam. The ELSE and END instructions are both placed directly below the IP, Note that this structure provides for choosing, between two alternatives without using any branch instructions As noted earlier, itis possible that no action may be taken if the condi: tion is false. Then the IF-THEN-ELSE is written as follows: IF condition: THEN instruction-t ELSE nut) END IF In this case we have a null ELSE: that is, if condition-B is false, nothing is done. This fact is explicitly indicated by writing “(null)” indented under ELSE; this arrangement means that there can be no question about a miss: ing alternative. A Structured Program in Pseudocode The use of pseudocode is illustrated in Figure 215, which is based on the structure chart of Figure 2-7, with a priming read added. Modules are ot- dered by number. Indention within the DO WHILE and IF-THEN-ELSE struc- tures is consistent, Note that the instruction executed when NUMBER is not positive (the ELSE instruction) is another IF-THEN-ELSE instruction. An 1F-THEN-ELSE within another IF-THEN-ELSE is referred to as a nested IF instruction. The nested IF may also be part of a THEN (true) alternative, The enlire nested IF is indented, and each IF has its ELSE and END IF. We can also have nested DO WHILE insteuctions; that is, a DO WHILE may be one of the instruc- tions encountered within a loop. Similarly, a DO WHILE can be one of the instructions in an If-THEN-ELSE, and an IF-THEN-ELSE can be used in a DO. WHILE loop. ‘The initialization of the counters takes place in the main program mod- ule. A case can be made for making this part of the 100 module, since it is, done before processing any transactions, However, the pseudocode is, supposed to be language-independent. Putting the initialization in the 00 module presumes that instructions must be executed to set the coun- ters to zero. This is the case with Pascal and BASIC, but not with COBOL, FORTRAN, RPG I, and assembler. Therefore, we will put the initialization at the start of the 000 module, where it can easity be handled cither way,
You might also like
PASCAL Plus Data Structures, Algorithms, and Advanced Programming PDF
PDF
50% (2)
PASCAL Plus Data Structures, Algorithms, and Advanced Programming PDF
657 pages
CSC 414 - Session - 02
PDF
No ratings yet
CSC 414 - Session - 02
11 pages
Algorithm and Flowcharting
PDF
No ratings yet
Algorithm and Flowcharting
43 pages
Program Analysis Fycs
PDF
No ratings yet
Program Analysis Fycs
10 pages
FDT 801 Updated Note
PDF
No ratings yet
FDT 801 Updated Note
47 pages
Unit-1 DS
PDF
No ratings yet
Unit-1 DS
50 pages
Institute - Uie Department-Academic Unit-2
PDF
No ratings yet
Institute - Uie Department-Academic Unit-2
27 pages
Lec.1 Algorithm & Flow Chart
PDF
No ratings yet
Lec.1 Algorithm & Flow Chart
17 pages
Introduction to Programming
PDF
No ratings yet
Introduction to Programming
28 pages
Lesson 5 - Lecture in Algorithm and Flowcharting: Introduction To Programming Languages
PDF
0% (1)
Lesson 5 - Lecture in Algorithm and Flowcharting: Introduction To Programming Languages
46 pages
3a - Introduction to Software Development
PDF
No ratings yet
3a - Introduction to Software Development
38 pages
Yoder Schrag Nassi - Schart
PDF
No ratings yet
Yoder Schrag Nassi - Schart
8 pages
Design and Analysis of Algorithm
PDF
No ratings yet
Design and Analysis of Algorithm
48 pages
Mastering Data Structures & Algorithms
PDF
No ratings yet
Mastering Data Structures & Algorithms
26 pages
This Course Is Designed To Enable Students To Acquire Basic Knowledge of Programming
PDF
No ratings yet
This Course Is Designed To Enable Students To Acquire Basic Knowledge of Programming
8 pages
Unit I - Basic Concepts of Programming
PDF
No ratings yet
Unit I - Basic Concepts of Programming
52 pages
Script 1 1
PDF
No ratings yet
Script 1 1
12 pages
Chapter 2 Introduction DSA
PDF
No ratings yet
Chapter 2 Introduction DSA
49 pages
Fransiskus Yogi Candra - 21412747 - Bi - Chapter 12
PDF
No ratings yet
Fransiskus Yogi Candra - 21412747 - Bi - Chapter 12
12 pages
FOC-unit 2
PDF
No ratings yet
FOC-unit 2
13 pages
2 Flowchart
PDF
No ratings yet
2 Flowchart
28 pages
An Introduction To Computers and Problem Solving
PDF
No ratings yet
An Introduction To Computers and Problem Solving
45 pages
Problem Solving Technique using Computer
PDF
No ratings yet
Problem Solving Technique using Computer
29 pages
Lesson 1
PDF
No ratings yet
Lesson 1
5 pages
Structured Programming With C Language
PDF
No ratings yet
Structured Programming With C Language
47 pages
UNIT 2
PDF
No ratings yet
UNIT 2
34 pages
Problem Solving
PDF
No ratings yet
Problem Solving
5 pages
CC102 Lesson Proper For Week 1 To 5
PDF
No ratings yet
CC102 Lesson Proper For Week 1 To 5
28 pages
SOFTWARE DEVELOPMENT 500 STUDY GUIDE
PDF
No ratings yet
SOFTWARE DEVELOPMENT 500 STUDY GUIDE
397 pages
Lesson Proper
PDF
No ratings yet
Lesson Proper
9 pages
Problem Solving With Computers
PDF
No ratings yet
Problem Solving With Computers
11 pages
c++ (1)
PDF
No ratings yet
c++ (1)
69 pages
Module I - C
PDF
No ratings yet
Module I - C
16 pages
1 Flowchart
PDF
No ratings yet
1 Flowchart
28 pages
01-Chap 01-BASIC CONCEPTS
PDF
No ratings yet
01-Chap 01-BASIC CONCEPTS
48 pages
ICT Progaramming For Users
PDF
No ratings yet
ICT Progaramming For Users
3 pages
Algorithms, Flowcharts & Program Design: Compro
PDF
No ratings yet
Algorithms, Flowcharts & Program Design: Compro
39 pages
Programming Logic and Design Comprehensive 6th Edition Joyce Farrell instant download
PDF
100% (2)
Programming Logic and Design Comprehensive 6th Edition Joyce Farrell instant download
52 pages
University Assignment2
PDF
No ratings yet
University Assignment2
5 pages
Assigment 22
PDF
No ratings yet
Assigment 22
7 pages
Unit 1
PDF
No ratings yet
Unit 1
15 pages
Download ebooks file Programming Logic and Design Comprehensive 6th Edition Joyce Farrell all chapters
PDF
100% (2)
Download ebooks file Programming Logic and Design Comprehensive 6th Edition Joyce Farrell all chapters
80 pages
unit-2
PDF
No ratings yet
unit-2
13 pages
Employee Management System: School of Mathematics and Systems Engineering
PDF
No ratings yet
Employee Management System: School of Mathematics and Systems Engineering
65 pages
Basic Computer Programming Using VB6
PDF
No ratings yet
Basic Computer Programming Using VB6
54 pages
Problem Analysi
PDF
No ratings yet
Problem Analysi
31 pages
Inbound 6438813414504259877
PDF
No ratings yet
Inbound 6438813414504259877
9 pages
Fundamentals of Computer Programming
PDF
No ratings yet
Fundamentals of Computer Programming
20 pages
Basic programming civic nd1
PDF
No ratings yet
Basic programming civic nd1
13 pages
Module 1
PDF
No ratings yet
Module 1
79 pages
Algorithms
PDF
No ratings yet
Algorithms
93 pages
Algorithms
PDF
No ratings yet
Algorithms
93 pages
Conclusion: Page 1 of 17
PDF
No ratings yet
Conclusion: Page 1 of 17
17 pages
(Ebook) Programming Logic and Design: Comprehensive by Joyce Farrell ISBN 9781111823931, 1111823936 download
PDF
100% (1)
(Ebook) Programming Logic and Design: Comprehensive by Joyce Farrell ISBN 9781111823931, 1111823936 download
40 pages
Characteristics of A Good Programming Language
PDF
No ratings yet
Characteristics of A Good Programming Language
17 pages
DAY_1
PDF
No ratings yet
DAY_1
22 pages