You are on page 1of 15
PRGBLEM SOLVING, ABBRTRACTION, AND STE PWISE REFINEMENT INMRODUCTION I-LTHE PROGRAMMER’S ALGORITHM Defning he Probl Panning he Solution Coding the Progam Testing and Debugiog the Progam 1-2 PROBLEM SOLVING USING ALGORITHMS [3 PROBLEM ABSTRACTION AND STEPWISE REFINEMENT PROBLEM SOLVING IN ACTION: PYTHAGOREAN THEOREM. PROBLEM SOLVING IN ACTION: SALES TAX. PROBLEM SOLVING IN ACTION. CREDIT CARD INTEREST (CHAPTER SUMMARY (QUESTIONS AND PROBLEMS. Questions Problems Problem Soitig Chap. 1 INTRODUCTION Programming reduces to the art and science of problem solving. To be a good [rogramuner, yeu must be a good! problem solver. To be a good problem suver, {you must atack problem in a methodical way, from inital problem inspection ‘and efnition to final solution, testing, and documentation. Inte beginning, when confronted with @ programming problem, you will be tempted to get to the ‘computer and start coding as soon as you get an idea of how to solve it. However, you must resist this temptation. Such an approach might work for simple problems, but will not work when you are confronted with the complex problems found in today's real world. A good carpenter might attempt to build a dog house without a plan, bot sald never 00d set of blueprint. Inthis chapter, you will earn about a systematic method that will make you 4 good problem solver, and therefore a good programmer—1 call it the ‘programmer's algorithm. In particular, you will study the steps required to solve {just about any programming problem using a top-down structured approach. You willbe introduced tothe concept of abstraction, which allows problems to be viewed in general tems without agonizing over the implementation deals required by computer language. From an intial abstract solution, you wil refine the solution step-by-step until it reaches a level that can be coded iret ito a computer program, Make sure you understand this material and work the related problems at the end of the chapter. As you become more experienced in programing, you wil find thatthe “secre” to successful programming is good planning through abstract analysis and stepwise refinement, which results in op- own structured software designs, Such designs are supported by languages like (CH, In the capers that follow, you will build on this knowledge to create workable C+ programs, nous” with 1-1 THE PROGRAMMER'S ALGORITHM Before we look atthe programme's algorithm, it might be helpful to define what js meant by an algorithm. In technical tems, is as follows: An algrithm is a series of step-by-step instructions that produces a solution toa problem. se 1 nPop At 7 Algoritns ae not woque o Any se of instvtions, suchas thse you migh( Ging in recipe or at assembly)guide, can be considered analgoritn. The programe etpe fot you, the programmer, 10 follow wien developing programs. The algrithm is as follows: ‘THE PROGRAMMBR’S ALGORITHM + Deine the problem, ‘Plan te problem solution. + Code the program. + Test and debug the program. + Document the program. Defining the Problem ‘You might suggest that defining the problem isan obvious step in solving any problem. However, it often isthe mast overlooked step, especially in computet programming. The lack of good problem definition often results in“spiniing your heels” especially in more complex computer programming applications. ‘Think ofa typical computer programming problem, such as controling the inventory ofa large department store. What must be considered as part of the problem definition? The frst consideration probably is what you want to get out ‘ofthe system. Will the output information consist of printed inventory reports or, in aditon, wil the sytem automatically generate product orders based on sales? Most any information generated by a customer transaction be saved permanently on disk, of can it be discarded? What type of data i the output information to consist of Is it umerical data, character data, or both? How must the output data be formated? All of these questions must be answered in order wo define the ‘ouput requirements Careful consideration of the output requirements usually leads 0 deciding ‘what must be pu into the system inorder o obtain the desired system output. For instance, in our department store inventory example, a desired output would be most likely a summary of customer transactions. How are these transaction to be entered ino the system? Is the data to be obtained from a Keyboard or is product information to be entered automatically via an optical character recogition (OCR) system that reads the bar code on the product price tags? Does the input Problem Solving Chap, 1 consist ofall numerical data, character data, or a combination of both? What is the format ofthe data? ‘The next consideration is processing, Wi vast ot une customer processing ‘be done at the cash register terminal, or wil it be handled by a central store ‘computer? What aboot credit card verification and inventory records? Will this processing be done by ¢ local microcomputer @minicomputer located within the sore, ora central mainframe computer located in a diferent part ofthe county? ‘What kind of programs will be written to do the processing, and who will write them? What sort of calculations and decisions must be made on the data within individual programs to achieve the desired outpu? All of these questions must be answered when defining any computer programming problem. In summary, you could say that problem definition must, consider the application requirements of output, input, and processing, The ‘department store inventory problem clearly requires precise definition. However, even with small application programs, you must stil consider the type of ouipa, input, and processing that te problem requires, ‘When defining a roblem, look for the nouns and verbs within « problem statement, The nouns often suggest input and output information, and the verbs suggest processing steas. The application will always dictate the problem Aefinition. 1 will discuss problem definition fuer a: w begin 10 develop ‘computer programs to solve teal probiems, ee ee PROBLEM-SOLVING TIP Look forthe nouns and verbs within a problem statement; they often provide cles to the required outpt, isput and processing. The nouns suggest output and input, and the verbs suggest processing steps. ee Planning the Solution ‘The planning stage associated with any problem is probably the most important Patt of the solution, and computer programming is no exception. Imagine trying 10 build a house without a good set of blueprins. The results could be catastrophic! ‘The same is true of trying to develop computer software without a good plan. ‘When developing computer softwar, the planing stage is implemented using a collection of algorithms. As you already know, an alporitym ic» series of step-by- step instructions zat produce results 3s piv wiv. et panning compare Programs, algorithms are used to outline the solution steps using Englsh-like: Sec. 1-1 The Programmers Algorithm 5 Statements, called pseudocode, that require ess. precision than a formal Programming language. A good pseudocode algorithm should be independent of, but casly translated into, any formal programming language. Pseudocode is an informal set of English-lke statements that are generally accepted within the computer industry 10 denote common computer programming operations. Pseudocoe statement ee used to desribe the steps ina computer algorithm, Coding the Program Cing the program shoud be one ofthe simplest ass inthe whole programming process, provided you have done a good job of defining the problem and planing its soluion. Coding involves the actual writing of the program in a formal Programming language. The computer language you use willbe determined by the ‘ature of he problem, the programming languages available to yoo, and the limits of the computer system. Once a language is chosen, the program is writen, or ‘coded, by translating your algorithm steps into the formal language code | should caution you, however, that coding is really a mechanical process and should be considered secondary to algorithm development. In the future computers. will generate their own program code from well-constructed ‘lgorithms. Research inthe fed of artifical iteligence has resulted in “code seneraton” sofware. The thing to keepin mind is that computers might someday fsenerate ther own programming code from algorithms, bu it takes the creativity {and common sense of a human being 10 plan the solution and develop the algorithm. Testing and Debugging the Program ri ‘You will con find out tha its a are and joyous occasion when a coded program actually “runs” the fist time without any errors. OF coutse, good problem ‘definition and planning will avoid many program mistakes, or “bugs,” However, there always are a few bugs that manage to go undetected, regardless of how ‘uch planing you do, Geting rid of the program bugs (debugging) often isthe ‘most time-consuming jo inthe whole programming proces, Indus statistics show that often over 50 percent of «programmer's time is often spent on program debugging. Problem Solving Chap. 1 ‘There is no absolue correct procedure for debugging a program, but & systematic approach can help make the process easier. The basic steps of ebugaing areas follows + Realizing that you have an enor. + Locating and determining the cause ofthe error. «+ Fixing the error. First ofall, you have to realize that you have an error. Sometimes, ths is ‘obviovs when your compute freezes up or crashes. At other times, the program Imight work fine until certain unexpected informatin is ecred hy someone using the program. The most subtle errors occur when the program is running fine and the results look correct, tut when you examine the results closely, they are not quite right. ‘The next step inthe debugging process is locating and determining the cause ofthe ervors—sometimes the most difficult part of debugging, This is where a 00d programming tool, called a debugger, comes into play. Fixing the error iste final step in debugging. Your knowledge ofthe C++ language this book, C+ on-line help, a C++ debugger, and your C+ reference ‘manuals are all valuable lols in fixing the error and removing the “bug” fom your program. ‘When programming in C+, there ae four things that you can do to test and Aebug your program: desk-check the program, compileink the program, rum the program, and debug the program. Desk-Checking the Program Desk-checkng a program is similar to profteadng a lester or manuscript. The ‘denis to trace through the program menaly x... he progam ge is workable. You must consider various input possibiles, and write down any results generated during program execution. In patcula, ry to determine what the program will do with unusual data by considering input posses that “should' happen. Always keep Murphys law in mind when desk checking a rogram: Ifa given condition cantor shouk't happen it wll! For example, suppose a program requires the usr to enter a value whose Square root must be found. Ofcourse, the user “should ener a negative vale, because the square root of a negative number i imaginary. However, what wil the program do if he or she does? Another input possiblity that should aways be ‘Seo. 1-1 The Programmers Algorithm 7 considered is an input of zero, especially when used as part of an arithmetic operation, such as division, ‘When you fist begin programming, you willbe tempted to skip the desk- checking phase, because you can’t wait to run the program once its writen However, as you guin experience, you soon will ealize the time-saving value of desk-checking ‘Compiling and Linking the Program At this point, you are ready o enter the program into the computer system, Once fatered, the program must be compiled, or translated, into machine code Fortunately, the compiler is designed to check for certain program errors. These ‘sually ar syntax errors that you have made when coding the program, A syntax error i any violation ofthe rules ofthe programming language, such as using a Period instead of a semicolon. There might also be type errors. A type error ‘curs when you attempt to mix different types of data, such as numeric and character data, Iis lke trying toad apples to oranges. ‘Asynta error is any violation of the rules ofthe programming languageyand pe error occurs when you attempt to mix different types of daa, During the compiling process, many C++ compilers will generate error and warning messages aswell as poston the display monitor cursor othe pot in the Program where the error was detected. The program will not compile beyond the Point ofthe ertor uni itis corected. Once an errr is corrected, you must attempt. {0 compile the program again. I other errors are detected, you must correct tein, compile the program, and so on, until the entire program is successfully compiled. Aer the program is successfully compiled, it must be linked to other ‘routines tha might be required for its execution. Linking errors will occur when Such routines are not available or cannot be located in the designated sytem directory, A link eror will occut when any roquired routines cannot be located by the compile. Problem Solving Chap. 1 Running the Program (Once the program has been compiled and linked, you must execute, oF run, i However, just because the program has been compiled and linked successfully doesn't mean that it will run suocessfolly under all possible conditions. Common bugs that occur at this stage include logic errors and runstime errors. These are the most difficult kinds of errors to detect. logic eror will occur when a oop tells the computer 10 repeat an operation, but does not tell it when to stop repeating. Ths is called an infinite loop. Such a bug will not cause an eror message to be generated, because the computer is simply doing what it was told to o. The program execution most be slopped and debugged before it can run succesfully ‘A logic error occurs when the compiler does what you tl it to do, but isnot doing what you meant it to do. A run-time eor occurs when the program attempts to perform an legal operation as defined by the laws of mathematics, or the panicular compiler n use. A runtime enor occurs when the program atempts to perform an ilegal operation, as defined by the aws of mathematics or the paiular compiler in use ‘Two common mathematical run-time errors ae division by zero and attempting to take the square root of a negative number. A. common error imposed by the compiles isan integer valve out of range. Most C++ compilers lini integers @ range of -32,768 to +32,767. Unpredictable results can occur if an integer value exceed this range. Sometimes, the progrem is automatically aborted and an error message i displayed when a runtime error occurs. Otber times, the program seems 0 exeeule properly, but generates incorect results, commonly called garbage. ‘Agun, you should consult your compiler reference manual to determine the exact nature ofthe problem. The ertor mast be located and corrected before anther attempt i made to ran the program. Using a Debugger One ofthe most important programming tools hn + debugeer. A aq ue srONpHOD F JO aoUNSIEA au -L Ze fs ‘sweygorg pu suojsend) ouessay pu wats jo ranpoud 3401 fens 28eyon reg sees me nyo 2602 Kg payne sanjen twoy afeyos seine or surodie Jo sw dopvap oF ne 5,40 Koy “9 ‘uisso0ud poe Jo sua, uf womuyaP mayoxd max sous oETy“39U8II01 JO 4 TTBVLATOOWNN,, Pe 20U8]0 uN 51 ved 3H TEVLATIOV.. ‘oid ey suse Jo 1s v dojiag “soyDU S¢C = STO + OO st ued ain jo u¥ua| gerdsooe wre 249 pue SDM! SZ = SO OF st nd 9g Jo gum aqgerdaaoe urusrur ayy yoy SURBU SI “SDN 2-05 (00 st ued 24 jo wFu>} 2m ve soreaxpur SuUaesp wed x uo wosuauP Ys nezodo waqyst ont ay jo 200d ur woesodo asa 2805 oyu o1 wojgoxd pres ypais aun uy parezua8 wos ay SEAT “p -a-puv sum, Bus fod peo S08 a4) sig Area ydu ue ut peas 0} smog 051 ou ar-az “qo © wos Wa oF | woo Pau on wONMES aa -T sas xp Kg pana rao Ko wagon uw ‘oepud ‘sup “wos 2 aida osuxibte jo Be ® dogog mou 19007 swa|qord {iparpep 39 woneado ayy puooes 2491, Ayn “og js “Ogg uegy sea 29 snus soUEeg 2a “06s 01 feaka 40 wey ssf OU st ausfeg 2g) AOU Aa OA 3,008 lupjgad waza pus upais a ut vonessdo uayngy aus w Ay ues “2 ue au afenduy Ture Bod pormonns vo saumnus yoru slew 25 94, “LL {ssssod wun ssinduoo poof enw Sonsueraeneys 200 1A “0 ‘wewaunoop poo’ sy pasmbat suey uuu gp Sy “sumsfoud sno gap pu 1s31 1 op we nok ven Sup 2909 21S 4 doug Bumjog weyqare ‘robvem Sowing Chap. 1 Due tothe simplicity ofthe problem, only one level of refinement is needed, 3s follows: First Level of Refinement GaDaia() BEGIN ‘Write a program description message tothe use. ‘Write a user prompt to enter the account balance (Balance). Read (Balance), END. Calculatelnerest() BEGIN If Balance <= $00'Then Assign (0.18 x Balance) to Interest. If Balance > 500 Then Assign (0.18 x 500) + [0.15 x Balance ~ $00} to Interest END. DisplayResuls() BEGIN Write(interest END. ‘As you can se, the two decision-making operations sated inthe problem definition have been incorporated inlo our Caleulaelteres) algorithm. Notice the use of indentation to show which calculation goes with which ifthen operation, The use of indentation is an important pat of pseudocode, because it shows the algorithm structure ata glance. How might you replace the two ifthen operations in this algorithm with a singe tls operation? Think about i, as it willbe let as a problem atthe end of thechaper! CHAPTER SUMMARY ‘The five major steps that must be performed when developing software are (1) define the problem, (2) plan the problem solution, (3) code the program, (4) Questions and Problems 25 test and debug the program, and (5) document the program. When defining the problem, you must consider the ouput, input, and processing requirements of the ‘application. Planning the problem solution requires that you specify the problem solution steps via an algorithm. An algorithm is a series of step-by-step instrtions tat provides a solution othe problem in finite amount of time, Abstraction and stepwise refinement are powerful tools for problem solving Abstraction allows you to view the problem in general terms, without agonizing ‘over the implementation details of a computer language. Stepwise refinement is applied to an inital abstract problem solution to develop gradually a set of elated algorithms that can be diretly coded using a structured computer language, such as CH, Once a codeable algorithm is developed, it must be coded into some formal Janguage that the computer system can understand. The language used in this text is C+. Once coded, the program must be tested and debugged through desk- checking, compiling. and execution, Finaly, the entire programming process, from problem definition 1 esting and debugging, must be documented so that it can be easily understood by you or anyone else working with it ‘Your C++ debugger is one ofthe best tools that you ean use to deal with ‘bugs that creep into your programs. It allows you to do sowce-hevel debugging and helps with the two hardest parts of debugging: finding the error and finding ‘the cause of the error. I does this by allowing you to trace into your programs and their functions one step ata time, Ths slows down the program execotion so that you can examine the contents of the individual data elements and program output ‘at any given point in the program, QUESTIONS AND PROBLEMS Questions 1 Define an algoith, 2. List he five steps of he programmer's algorithm, 4. What three things must be considered during the problem-defnition phase of programming? 4. What tools are employed for planning the ssltions 19 2 programming problem? 5. Enplan how problem abstaction aid in solving problems. 6. Explain the process of stepwise refinement 7. The writing ofa program is called ‘robvem Sowing Chap. 1 Due tothe simplicity ofthe problem, only one level of refinement is needed, 3s follows: First Level of Refinement GaDaia() BEGIN ‘Write a program description message tothe use. ‘Write a user prompt to enter the account balance (Balance). Read (Balance), END. Calculatelnerest() BEGIN If Balance <= $00'Then Assign (0.18 x Balance) to Interest. If Balance > 500 Then Assign (0.18 x 500) + [0.15 x Balance ~ $00} to Interest END. DisplayResuls() BEGIN Write(interest END. ‘As you can se, the two decision-making operations sated inthe problem definition have been incorporated inlo our Caleulaelteres) algorithm. Notice the use of indentation to show which calculation goes with which ifthen operation, The use of indentation is an important pat of pseudocode, because it shows the algorithm structure ata glance. How might you replace the two ifthen operations in this algorithm with a singe tls operation? Think about i, as it willbe let as a problem atthe end of thechaper! CHAPTER SUMMARY ‘The five major steps that must be performed when developing software are (1) define the problem, (2) plan the problem solution, (3) code the program, (4) Questions and Problems 25 test and debug the program, and (5) document the program. When defining the problem, you must consider the ouput, input, and processing requirements of the ‘application. Planning the problem solution requires that you specify the problem solution steps via an algorithm. An algorithm is a series of step-by-step instrtions tat provides a solution othe problem in finite amount of time, Abstraction and stepwise refinement are powerful tools for problem solving Abstraction allows you to view the problem in general terms, without agonizing ‘over the implementation details of a computer language. Stepwise refinement is applied to an inital abstract problem solution to develop gradually a set of elated algorithms that can be diretly coded using a structured computer language, such as CH, Once a codeable algorithm is developed, it must be coded into some formal Janguage that the computer system can understand. The language used in this text is C+. Once coded, the program must be tested and debugged through desk- checking, compiling. and execution, Finaly, the entire programming process, from problem definition 1 esting and debugging, must be documented so that it can be easily understood by you or anyone else working with it ‘Your C++ debugger is one ofthe best tools that you ean use to deal with ‘bugs that creep into your programs. It allows you to do sowce-hevel debugging and helps with the two hardest parts of debugging: finding the error and finding ‘the cause of the error. I does this by allowing you to trace into your programs and their functions one step ata time, Ths slows down the program execotion so that you can examine the contents of the individual data elements and program output ‘at any given point in the program, QUESTIONS AND PROBLEMS Questions 1 Define an algoith, 2. List he five steps of he programmer's algorithm, 4. What three things must be considered during the problem-defnition phase of programming? 4. What tools are employed for planning the ssltions 19 2 programming problem? 5. Enplan how problem abstaction aid in solving problems. 6. Explain the process of stepwise refinement 7. The writing ofa program is called

You might also like