You are on page 1of 90
Introduction Chapter 1 Chapter 2 Chapter 3 Chapter 4 Chapter 5 + ‘The Role of the Computer Programmer + How Instructions are Giv Defining the Problem 1.0 Understanding the Problem 1 The Defining Diagram 1.2 The Problem with Problem Specifications, Finding a Solution to the Problem Introduction The Concept of Variables Choosing Variable Names A More Initialization of Variables Summary ‘omplex Problem Evaluate Alternative Solutions 3.0 Introduction 3.1 Determine the most Efficient Solution Represent the Solution as an Algorithm, 4.0 What is an Algorithm? 4.1 Algorithmic Structure 4.2 — Control Squetures 43 Algorithmic Language 4.2.1 How To Write Pseudocode 4.3.2. Flowcharts 44 The Structured Pro; 4.5 Do’sand Don'ts wh amming Concept cen Writing Pscudocode Vest the Algorithm for Correctness 5.0 Tracing the Algorithm 5.1 Choosing Appropriate Test Data n to the Computer I 6 & Chapter 6 Chapter 7 Chapter 8 Chapter 9 Chapter 10 List Processing U ng Arrays 6.0 What is an Array 6.1 Accessing the Elements of an Array 6.1.1 Initializing Arrays 6.1.2 Reading Values into an Array 6.1.3 Displaying Array Values 6.1.4 Traversing Arrays 6.2 Point to Note when Manipulating Arrays The Top-Down Design Methodology What is Top-Down Design Hicrarehy Charts How to Sub-divide a Problem into Modules, Steps in Modularization Representing Modules in Pseudocode & Flowchart 5 Communication between Modules 7.6 Advantages of the Top-Down Design Method From Algorithms to Pascal Programs 8.0, Introduction 8.1 Translate Algorithm into a Specific Programming Language 8.2 Structure of'a Pascal Program 8.3 Pascal ina Nutshell 84 Translating Pseudocode into Pascal Code 8.5 Summary Program Exceution on the Computer 9.0 Steps in Executing a Program on the Computer 9.1 Types of Errors o2 Debuggi Programming Style and Quality 10.0 Prog 10.1 Pr Appendix A ~ Programming Exereises Appendix B~ Suggested Reading a2 a 4B 43 44 44 45 46 48 49 49 56 60 60 60 ol 62 64 68 oo 69 70 FOREWORD This document is designed to be used as a guide for teaching the Problem-Solving and Program Design component for the CSEC Information Technology (IT) Syllabus. However, the content is sufficiently general such that it can be used for any introductory programming course. This document provides a step-by-step approach to problem-solving by using the computer. The course is designed to equip students with problem-solving skills that will be useful in any career that they may choose, The course provides an excellent foundation for those who wish to become good programmers. Advanced programming concepts such as multi-dimensional ar file processing, records, sets, pointers, recursion and some aspects of modular programming are not dealt with at this level ANOTE TO TEACHERS This document is intended as a guide for the teachin; CSEC IT syllabus. The format is @ simple, step-by solvin of the problem-solving component of the step approach to the concept of problem- The material is deliberately presented in a simplistic manner. The aim is to de-mystify the programming concept. Many people have a phobia for programming because there is a misconception that it is a difficult subject. Computer programming is no more difficult than a foreign language. The difficulty lies in the way the subject is taught The most important phase in computer programming is the problem-solving phase. Too oft this phase is given a cursory treatment in many courses, where the majority of time is spent on teaching and debugging code on the computer. The problem here is that the student is often trying to get the program to work, without having developed a working solution in the form of an algorithm beforehand. This is like trying to give someone directions to a destination, without knowing how to get there yourself, You cannot tell the computer what to do, if' you do not know how to do it. Computers do not solve problems, programmers do, Therefore, programmers must be able to solve problems hefore they write code. This document is geared towards helping the student develop an approach to problem-solving which is simple and non-technical. The phobia for computer programming often lies in the fact that it is seen as a highly technical skill and many people are techno-phobie, The approach outlined herein is one that anyone can follow. One will notice that in the early chapters, the emphasis is more on finding a Solution, rather than writing formal algorithms. The formal way to write an algorithm is presented in Chapter 4. The idea here is not to minimize in any way the importance of formal algorithms, but rather, the intention is to get students to focus on defining the problem and figuring out how to solve it, without having 10 worry about the formal representation of their solutions at the same time. This. is not 10 st algorithm (whether in pseudocode or flowchart) is not important, I is like teaching a baby how to talk. We do not introduce them to formal sentences from day one. They first learn words, then wwe teach them how to put multiple words together to facilitate meaningful conversations. So for example, a baby will learn the words, *Mommy” and “milk” and will communicate to us in the following way: "Mommy milk”. This is perfectly understandably to a mother. The baby is asking for some milk, A pedantic linguist will say that this is not a proper sentence: it is simply two nouns, However, from the mother’s point of view, this is an important step in the communication process. As the child grows, hivher language will become more refined as he/she learns more words and how to form sentences. Litimately, the child will learn formal English and be able to communicate using perfectly phrased sentences, west that the formal When it comes to teaching programming, we should adopt a similar nurturing approach, We should not expect students to grasp everything about problem-solving in a short time. We do not \want students to become bogged down with semantics and refinements in the initial stages of the process. We want them to be able to take a problem, define it, do a manual solution and then write down the instructions in their own words, Once they have become comfortable with devising solutions, then we show them how to refine their solutions and ultimately how to choose the best solution and write it in a formal way. This is what algorithm development is all about. This is a simple, step-by-step approach, which hopefully, will become a habit after a a. we ae It is very important that teachers spend a considerable amount of time on the problem-solving section of the syllabus. It is recommended that teachers spend between 15 — 20 hours on problem-solving and algorithm development. The majority of the time should be spent on practicing a wide range of programming problems. Problems should be chosen with a view to exposing the students to various programming features, such as, condition statements, loops, the use of sentinel values, list proc modularization, and so on, {1 is only through constant application of problem-solving principles that students will learn how to design effective algorithms, Solving problems requires logical thinking, Unfortunately, « teacher cannot teach a student how to think logically. What the teacher can do is provide the student with a set of guidelines that must be Followed in order to decipher a problem and figure out how to solve it. Human beings all have the capacity to think logically. some with a greater capacity than others. The ones with the greater capacity are the ones who will be able to figure out the solutions quickly. Others may take a lot longer, but, given time, they will be able to figure it out also. This document outlines a disciplined approach to problem-solving, By ‘disciplined’, we mean that the steps outlined must be followed every time the student is faced with a problem. Through constant practice, the student will find that problem-solving/programming is not so difficult after all As with all subjects, teachers should endeavour to approach problem-solving with cathusiasm and try to stimulate interest in the subject matter by choosing simple problems that the students can relate to, Problem-solving classes should be highly interactive. They should not be “chalk and talk” affairs. Start off the subject by discussi and (ry to involve every student in the class, Some examples are the solutions to everyday problems ven in the Introd Interactive sessions have many advantages, but can also be disadvantageous sometimes, as some students tend to get carried away with the discussions and before you know it, the period ha nded and the substantive material for that session has not heen covered. It is tempting to compensate by resorting to “chalk and talk” in the next session. The problem with “chalk and talk” in a problem-solving course, is that you do not get the students’ full attention, because thes are too busy writing notes, They cannot learn to write algorithms by reading clays notes. They have to leam through practice. They also learn from making mistakes and figuring out how to recover from those mistakes. This is why it is so important that the stucents should be allowed to interact in the problem-solving sessions, with the guidance of the teacher One tried and pro tas handouts and give them out afier the class. Let the students know ahead af time that you will be giving them the handouts, so it is not necessary for them to take copious amounts of notes during the session. Use the class sessions to work examples and point out pitfalls, Follow the simple step-by-step approach and involve the students in the discussion of the various the solutions. en way to get the students full attention is to prepare the relevant class notes Finally. keep the problems simple, We want students to see how easy it is to develop solutions. We do not want them to become bogged down with complex problems. This could be a deterrent and will only serve to feed the phobia of programming. Remember, the course is introductory. We do not expect the students to become expert programmers upon completion of this course. The course will give the students a solid foundation in problem-solving, upon which they ean build. Those who have the aptitude for programming can go on to become expert programmers: others can apply the same problem-solving skills to any real-life problem that they might encounter later on in their studies or careers. INTRODUCTION The Role of the Computer Programmer Computers are designed to solve problems speedily and accurately. There is no problem that can be solved by a computer that could not be solved by humans ts well, [tis just that it would take considerably longer for humans to solve it and the degree of accuracy would not be the same. Although computers are used to solve problems. they do not have brains, They cannot think. They cannot reason, although recent advances in artificial intelligence may seem to suggest otherwise. A computer is a moron — it simply does exactly what we tell it to do. This is why the role of the computer programmer is so important There is nothing magical about the way computers solve problems. A computer simply follows (executes) a set of instructions given to it by the programmer and produces the specilied results The computer programmer ereates the instructions for the computer to follow. If the computer produces undesirable results, it is not the fault of the computer; itis the programmer's fault, As an analogy. consider the case of a food processor. The food processor has buttons that indicate the various functions that can be performed — chop, grate, puree, liquefi. and so on. Let's Suppose that you want to chop some carrots to make a stew. You place the carrots in the food processor and press the chop button, but instead of chopping the carrots, the food processor purces it, The result is t stew that looks like mush, Who would you blame for this undesired result ~ the food processor, the designer or yourself (the user)? In this case, the user did what he was supposed to do (that is, press the chop button), the food processor did what it was supposed w do. that is. it carried out the instructions associated with the chop button. The designer’manufacturer is at fault here. Clearly. the incorrect instructions were linked to the chop button In a simila Way, & computer carries out the instructions given 10 it by the programmer, The programmer must, therefore, ensure that the correet instructions are given at all times, and that the instructions are precise and unambiguous. Otherwise, the results might be undesirable and i some critical situations such as airline navigation, the result could be fatal How are Instructions given to the Computer? Instructions are gives to the computer in the form of computer programs, A computer program is a finite set of precise instructions, written in a programming language. Before we write a computer program, we first have to find a way t0 solve the problem at hand, After we have ured out how to solve the problem, we then transkate aningfull to the computer the solution into a language that is m Giving instructions to a computer can be challenging at times and require a certain amount of skill. This is because giving precise, unambiguous instructions is not inherent in human nature Humans tend to make assumptions when giving instructions and they expect other humans to reason things out in order to get to a logical conclusion. Consider the problem of giving directions to someone to get to the nearest post office starting from point A. A possible set of instructions might be: = 1. Proceed a mile or so down the road until vou reach the roundabout. 2. Turn lett at the roundabout and follow the road until you see a green house on the right hand-side. 3. The post office is ahout the 3rd or 4th building on the right after the green house. You ll see the sign in front, you can't miss it To the average person, the above instructions may appear to be clear and straightforward. However, once you start following the instructions, you may find that vital pieces of information may have been omitted and other bits of information might not be as precise as they could have been. For example, one might discover (as is often the case in such situations) that there might be « junetion or a fork in the road before one reaches the roundabout. This vital piece of information was omitted so when the person arrives at the junction he/she would have to make a decision as to which way 10 proceed. Do I tum right, left or proceed straight ahead? Making the wrong decision could lead to all sorts of consequences. Let us examine the instructions in some detail Firstly, itis imprecise and ambiguous in many respects: Consider the first instruction, proceed a mile or so down mile or so” is imprecise, How far should the person have to walk or drive before arriving at sume 2 or 2% miles, No-one would expect it to be 5 or 6 miles. So what if there is no roundabout in sight after 4 or even 5 miles? The person will be left to make a decision based on his intuition, Another ambiguity in instruction 1 is “down the road”, Which way is down’? Is it to the person’s right or to the person's lefl? Is it northwards or southwards? the roundabout? One person might assume 1% miles, another may In the second instruction, wh if there iy more than one green house on the right? The instruction should precisely state whether itis the first, second or third green house that is being referred to. This will make the statement more precise. In the third instruction, it might not be difficult for a person to figure out whether or not the post office is the 3" or 4” building. However, it would be impossible for a computer to execute an instruction written in this form, Computers must be told exactly what they must do in the correct sequence, We call the set of instructions an algorithm, Algorithms have four very important attributes, 1. ‘They must be precise 2. They must be unambiguous 3. They must he finite, that is, terminate after a finite number of steps 4, ‘The instructions must be in a logical sequence. These four attributes must be underscored and the teacher should ensure that students good grasp of what these attributes mean. This can be achieved by allowing the students to engag 1s exercises involving everyday problems that they can relate to. This is a good way to de-mystity the problem-solving process. ¢ in problem-solvil It must be emphasized that writing a program is simply a formal way of giving instructions to someone (in this ease a computer) to perform a particular task. The only difficulty in writing a program is in knowing how to solve the problem. If you do not know how to get to the post office, you would not be able to give direetions to someone. Likewise a programmer must figure out a Way 10 solve the problem before he/she proceeds to tell the computer what it should do. Figuring out how 1 solve a problem takes practice and skill, The subsequent sections will present a formal approach to problem-solving. Students should be required to adhere to the rulesapproach specified therein for all programming problems. It is only through constant practice and a disciplined approach that the phobia of computer programming, ‘an be overcame. Pr blem-solving on the Computer The design of any computer progr m involves two major phas I The Problem-Solving Phase 2, The Implementation Phase The problem-solving phase comprises the following steps, Step I:Define the problem Step 2:Find a solution to the problem Step 3:Evaluate alt Step 4:Represent the most efficient solution as an algorithm Step 5:Test the algorithm for correctness. native solutions, The implementation phaye comprises the following steps: Step 1: Translate the algorithm into a specific programming language Step 2:Execute the program on the computer Step 3:Maintain the program The details of what is done in each of the above steps will be outlined in subsequent chapters. Class Exercise Formulate problem statements for simple everyday tasks, then ask each student to write instructions/algorithms for cach task. Ask two or three students to write their solutions on the board. Then ask the class to give a critical analysis of each solution, with respect to the 4 stated auuributes of an algorithm. They must identify any ambiguous or imprecise statement, identify also any omissions and must comment on the logic of the solution, To make it more interesting, you can ask each student to follow hivher algorithm, as written, to see if the desired result is achieved. The results should be reported to the class at a later date, Some examples of everyday problems are given below I Write a recipe for making a cheese omelette. 2 Write instructions to teach your mom how to retrieve voice messages from a generic cell phone. 3. Write instructions to give directions to a visitor to get to the nearest hospital, starting from the school premises, 4 Write instructions to tell a novice how to download music from the Internet i Chapter 1 DEFINING THE PROBLEM Problem-Solving Step 1 1.0. Understanding the Problem Defining the problem is the first step towards solving a problem. It is one of the most important steps in problem-solvin dds to a clearer understanding of what is given and what is required, If the programmer does not fully understand what is required, he/she cannot produce the desired solution, Many students tend to overlook this stage of the problem-solving process and dive right into the algorithm or sometimes even the program code — much to their peril Much of the frustrations experienced by junior programmers are due to a misunderstanding of the program requirements. Sometimes improperly specified problem statements can lead to such misunderstandings. It is therefore necessary that the teacher pay careful attention to how programming problems are worded Here is an example of an improperly constructed problem statement Write « program that prints a fist of all students in the class who will be celebrating their birthdays during the monih of May The problem with this statement is that it is ambiguous and could lead to several different interpretations. For example, a student might assume that the program should determine all the students who were bom in May, another student might assume that the program should take into account those students whose birthdays full in April, but their birthday parties or celebrations are held in May, A more precise way of stating the problem would be: Write a program that prin a list of all students in the class who were born in the month of May One of the biggest challenges that beginner pr problem they are asked to solve, Defi ammers face is that of understanding the ny the problem is a way to help the programmer understand what he or she is required to do. It involves decomposing the problem into three key components 1. what is given (that is. the inputs), 2. the expected results (that is, the output). 3. the tasks that must be performed (that is, processing), The Defining Diagram \ formal approach to defining a problem is to construct a defining diagram, A defining diagram is a table with three columns, which represent the three components: input, output and processing. The input is the source data provided. The input can be easily identified by the keyword that precedes it — given, read or accep!. The output is the end result required. Keywords that help identify the output are, prin, display, produce, ouput. The processing column is a list of what actions are to be performed to achieve the required output. This is usually the most challenging part of the problem definition. If it is done properly, writing the algorithm will be fairly straightforward, If the student is unsure of exactly what goes under the processing column, the student should ask of himself the follow 12 question: What do I have to do with te inputs in order 10 produce the desired ouput?” The answer to this question is essentially what should be listed in the processing section Let us now look at a few simple examples of defining a problem. Problem 1 { program is required to read diree (3) numbers ealeulate and print their total. Defining Diagra INPUT, PROCESSING OUTPUT 3 NUMBE: Read/get 3 numbers | TOTAL Say mam], num2, mums Add numbers together Print total The first step is to identify the input (that is, the data that is given). The keyword, read, identifies the input as three numbers, that is, any three numbers, We need to find @ way to refer to each of these numbers, We can call them A, B and C or we could refer to them as num1, num? and num3, as illustrated in the defining diagram, Any name will do as long as we are consistent when referring to the numbers by name. The next step is to identity the output. The keyword, print, identifies the output as the total (or sum) of the three numbers. The final step in defining this problem is to list the processin, that must be performed in order to g numbers in order to print their total? steps. Here, we list all the actions et the desired results. What do we have to do to the three 1. We must first get the numbers, 2. We must then calculate their sum 3. We must then print the total, Itis very important to note that at this stage, we are not writing the algorithm, so we need not be concerned about the details of how each action is performed. That is, in definin, do not need to worry about how the total is calculated; we just need to know that calculating the sum is an action that must be performed. The details of iow’ the actions are performed are the subject of the algorithm development process. At this stage, the focus is on understanding the the problem, we problem, Note that. 1 In the defining diagram, the actions must be listed in a logical sequential order. 2 All the necessary actions must be explicitly stated. For example, the read action and the print action must not be assumed, The processing section is NOT the solution 10 the problem. It is simply a list of the things that must be done in order to solve the problem. Later an we will proceed to write an algorithm to tell the computer how to solve the problem. In some problems the input, output and processing parameters might not be stated as explicitly as in the one above. Let us look at an example of such a problem. Problem Given three integers representing the age of three boys respectively, write a program to find their average age and also determine the age of the oldest boy In this example, the input data is explicitly stated, but the required output is not; it is implicit in the clause, “find their average weight". The value(s) that you are asked to find, should always be reported (displayed). The problem statement could have been stated more precisely to read: Given three integers A, B, C, representing the age of three hovs respectively, write a program to find and display their average age ay well as the age of the oldest boy In this problem, there are two major tasks to be performed. Each task consists of multiple ions to he performed are not all explicitly stated in this problem. This is typical of many programming problems. The task of finding the average involves multiple actions, Likewise, the task of finding the highest age, De 12 Diagram INPUT PROCESSIN OUTPUT 3 integers Wy agel, age2, aged imeger 2. Find the average of the 3 integers 3. Find the highest age 4. Print average, highest 1. Read/avcept get 3 Average-age Highest-age Let's look at a more complex problem Problem 3 The cost of « new car is the sum of the wholesale cost, the local sales tax and the dealer's percentage mark-up. Assuming the dealer's mark-up is 10 percent of the wholesale cost and the sales tax is 6 percent, design a program to read a car ID (an integer value) and the wholesale cost of the car (a real value) and print the car ID and the cost ta the constaner Here. the input and output data are clearly stated, To arrive at the processing steps. look at what cen and what is required, then ask: “what should I do with wholesale cost in order to find the cost to the customer?” One tule of thumb to remember is that ALL the information given in a problem statement should be taken into account when formulating a problem solution, Problem statements do not usually contain redundant information, It means, therefore all the information given is necessary for solving the problem. To find the cost to the consumer we must therefore apply the wholesale cost. the 10 percent dealer's markup and the 6 percent sales tax. The defining diagram would look something like this: hat in most eases, INPUT PROCESSING OUTPUT Car-ID, Wholesale-cost_ | 1. Read/get wholesale-cost Car ID 2. Calculate the dealer's markup Consumer-cost 3. Calculate the sales tax 4, Find the sum of the wholesale- cost, the dealer's mark-up and the sales tax 5. Print results. | 1.2. The Problem with Problem Specifications If problem statements are properly specified. defining (or understanding) the problem would be fairly straightlorward. Unfortunately. many real-world programming problems are not always precise, Initial descriptions of such problems are ofien vague and sometimes ambiguous. ‘This is hecause the person posing the problem often does not know how to solve it on a computer, They are users who simply need a computerized solution. They do not care how it is done. It is the job of the programmer to seck the necessary clarifications betore embarking upon a solution, The programmer should investigate the user's need by asking the relevant questions and then fine- tuning the initial problem specifications to ensure that itis precise and clearly detined. Students should therefore be encouraged to evaluate problems statements and ask questions if there are perceived ambiguities before they proceed. They should not make assumptions about what is required. The fact that @ given problem is found in a textbook does not necessarily mean that it is properly specitied. Remember also that some information may be implicit in the problem statement and such information must be taken into account when defining the problem. A useful exercise is t0 give the class a series of problem statements. ranging from simple to complex, some precise, some 4 ambiguous, some lacking pertinent information. Ask the students to evaluate each problem statement and determine if it is properly specified. If it is. they should proceed to define the problem, If it is not, they should suggest how it could be improved, whether by adding more information or rephrasing the statement to improve clarity. Here are a few examples of imprecise problem statements: Problem 4 Write a program to print a list of all emplovees who have been in the company for over five years Problem 5 Write a pr wgram that reads « file that contains information on the height, weight and age of 100 children. The program should print the names of all the children who are overweight. Chapter 2 FINDING A SOLUTION TO THE PROBLEM Problem-Solving Step 2 Introduction Now that we have defined the problem, we know what we need to do, We now have to figure out how to do it, A problem can have many different solutions. For beginner programmers, the most important thing is to arrive at a solution that works. The initial solution might appear to be clumsy of long-winded, however, what is important at this stage is that it works. Once a solution is found, we can then review it to see how it can be optimized or made more efficient. We may have 1o go through a series of refinements in order to get the most effigient solution The first thing to do in deriving a solution is to do the problem by hand, noting each step as you proceed. Some problems might give sample input data, others might not. In cases where no. sample input data is For example, lot us revisit the problem of finding the aver ‘en, the student should create his/her own, based on the information given of set of numbers, Problem 6 Find and print the average of three numbers 1. Define the problem INPUT PROCES SING 3 NUMBERS Say mum, nwn2, nums Readiget 3 numbers average Find the average Print average Create sample input data Sample input data: 5, 3,25 3. Exeeute each processing step in the defining diagram manually Get the three numbers 5. 3, The next step says find the averaye. How do we find the average? Manually, we add the numbers together, 6 Then we divide the result by 3, that is: The next step in the processing section says, “print aver the result that we obtained above aye". This is where we display We have now completed a manual solution to the problem, The next step is to write your solution as a sequence of instructions. Sti Get the first mumber, call it num Ger the second number, cal it mum. Get the third sanber, call it num3 Add num! © mund* nas Divide result by 3 Print result Stop Intuitively, this solution works. However, when we write solutions for the computer, we must remember that computers do not have intuition, so We cannot assume anything, We have to state the obvious. For example, in our solution above, we gave an instruction to the computer to add hum, num2 and num3, but we have not told the computer where to put the result of the add operation. The result must be stored somewhere so that it can be accessed later (that is, in the next statement). This leads us to the concept of variables. 2.1. The Concept of Variables Consider the following recipe. It's grandma’s seeret recipe for making fluffy. delicious, old- fashioned pancakes. Ingredients: doe plain flour, sifted pinch of salt 200 milk sie with 7S water oe butter juice of one leon Method Sift the flour and salt into & large mixing bowl, Make 2 well in the eentre of the flour anal break the into it. Then begin whisking the eggs with a wire whisk or fork, Next gradually ad small quantities of the milk and water mixture stil luisking, Melt the butter in feying pan. Spoon 2 thyp of it imo the batier and whisk it in, shen pour the rest into a bow! and use i to lubricate the frying pan Now get the pan really hot, and then tur the heat down te medium. Spoon about 2 thyp of the batter into the hot pan, As soot as the batter hits the hot pa tip it around fiom side to side to get the base evenly ‘coated with batter. I should take only half a minute or so to cook. Flip the pancake over with a spatula =the other side will need a few sevonds only - then simply slide it out of the pan onto a plate, To serve. sprinkle each pancake with Freshly squeezed lemon juive and easter sus. Note the words highlighted in the recipe mixing howl, fiving pan, bowl, plate. These all ers for holding the batter. the butter and batter, the oil and the cooked. represent storage oF conta pancakes, respectively Just as we need containers to hold or store ingredients of this recipe, likewise. when we perform computations, we need something to store or hold the values that we manipulate, In the computer, values are stored in memory locations. There are a large number of storage locations in memory and so in order w keep track of where our values ate stored, we need to place an identifier or a label on a particular memory location so that we will know what is stored therein, The label or identifier is called a variable. Definition: A variable is a symbolic name assigned to a memory location that stores particular value In our average problem above, when we say, “ger a number, call it numl, we are actually defining a variable or an identifier for each number. so that we can refer to (or access) it | ned variables (identifiers) to the three input values, namely, nu So. in faci, we have assig Num identifies the first number, 5. Num2 identifies the second nu umber, 3 and num3 identifies the third number, 25. There are other values in the program for which we need variables, For example, we computed the sum of num, num? and num3, but we did not tell the computer where exactly to store the result, We need a variable for this purpose. So the correct instruction is as follows: and num3. respectivel storing in swat This would tell the computer that the result of the computation should be stored in a memory location called sum, If we omit this very vital piece of information, the computer would perform the computation, but would not store the result in memory, resulting in an incorrect answer Likewise, in the last two statements in the initial solution, we said, Divide result by 3 Print result There are two problems here. Firstly. we did not tell the computer to store the result of the division. Then there is ambiguity in the statement, “print result". To which result are we referring? Is it the result of the addition operation, oF is it the result of the division operation? We need to be more precise. Remember, the computer does not possess reasoning skills, Computations are performed by the urithmetic logic unit (ALU), which is part of the CPL Results of computations are temporarily stored in registers within the CPU. Any intermediate or final values that we need to access later in the program must be stored in locations in memory This means that such values must be identified by variable names. The label for the memory location is called a variable for @ good reason. The word variable is derived from the verb “% vary". This means that the value stored in a particular location can change from time to time, although the label remains the same. In the recipe above, if we wanted to make another batch of pancakes (because the first set was consumed rather quickly), we would simply pour another set of the ingredients into the same mixing bow! (that is, same storage location) and put the second batch of pancakes on the same plate. Likewise, in our avera problem, if we wanted to find the average of another set of numbers within the same problem. the input statement would be: Get num! num2, mums This time, the same variable names are used, but the variables store different numbers. For example, let"s say that the second set of numbers were 12, 9, 44. This time, nun! would identity the location in which 12 is stored, num? would identify the location which stores 9 and nun # would identify the location which stores 44. w values are placed into previously assigned memory locations, the old values are replaced by the new ones. Therefore, ifit is necessary to ain the existing value in a memory location, a different variable must be declared to hold the new data value I is always helpful to illustrate the concept of a variable by using diagrams to show the memory locations associated with each variable name, Kor example, Memory Locations 7 num! . Voriahles ae 3 9 Let us revise our initial solution to include two new variables called sum and average, Get three numbers say, nea], num2, rum Add num] * num2 ~ num3, storing in sun Divide sum by 3, storing in average Print averag 2.2, Choosing Variable Names pod practice to choose variable names that reflect the kind of data that is being stored It helps the programmer as well as the reader to understand the solution better, if the variable mes reflect what they store. Kor example, the variable name sim indicates quite clearly that a total value is stored in the memory location called stun, If instead, we used a variable name X to store the sum, this does not clearly convey the contents to the reader of the solution, and it will m maintenance more difficult make debugging and prog Most programming languages have strict rules regarding variable names, for example, they must begin with an alphabetic character and must be of a certain length, and so on, While we are not concerned with the syntax of the programming Language at this stage, it is necessury to note this. so that students will develop the habit of choosing appropriate and meaningful variable names during the problem-solving phase. It Is imperative that students grasp the concept of variables very ‘early in the problem-solving phase. They must understand that variables are associated with memory locations and as such, manipulation of variables will result in changes in the values stored in memory. 2 A More Complex Problem The average problem was a fairly simple problem, the solution of which was straightforward, however, some refinement is needed, to make the solution more efficient, This will be discussed in the next chapter. We will now look at a far more complex problem to sce how we ean apply the principles outlined above to arrive at a solution Problem 7 Jn architect's fee is calculated as a percentage of the cost of a building, The fee ix made up as follows 8% of the first $5000 is the cost of a building and ‘non the remainder, ifthe remainder is less than or equal t0 $80,000, OR 2.5% on the remainder, if the remainder is more than $80,000. 10 The architect has hired you to design a program that will accept the cost of a building and calculate and display the architect's fee In this problem there are a number of items of information that must be taken into account Remember, every bit of information in the problem statement is relevant to the solution. The first step is to define the problem to get a better understanding of what is required. Step 1: Draw a defining diagram as follows: INPUT OUTPUT Building cost Get building cost Architect's fee 1 2. Calculate architect's fee 3._Display architeet’s fee Step 2: Create Sample input Data A look at the defining diagram tells us what we have and what we need to do. However, it doesn’t tell us how to do it To figure out how to do it, we need to use all the information given in the problem and do a manual solution, Before we do a manual solution, we first need to ereate sample input data Sample input data: $100,000 Why choose $100,000 Even if we have no id nd not $100,007 4 of building costs, we can deduce from the information given that the cost is likely lo be much greater than $5,000, since it is possible that the remainder could be in excess of $80,000. So any value in excess of $5000 would be reasonable for this problem Step 3: Do a manual Solution of each processing step 1. Get building cost: 100,000 2. Calculate architeet’s fee: HOW? We must ask. “Whar do vou have to do with the input, in order to get the ouput? 3. According to the information given, the architect's fee comprises two components, The first component is the value of 8% of 5000, That is, 400. 4. We then need to subtract $000 from the input value 10 find the remainder. That is, 110,000. 5,000 — 95,000 The next component is either 3% of the remainder or 2.5% of the remainder We then check the remainder (that is. 95,000) to see whether or not it is less than or equal 0 80,000. In this ease, itis not 6. Cheek to see if the remainder is greater than 80,000, In this case, it is, (95.000 is greater than $0,000), so according to the information given, we should caleulate the next component of the architect's fee by finding 2.5% of 95,000, which is 23 7. Having found both components, we then add them together to find the total architect’s fee. That is. 400 iS Having, completed a manual solution to the problem, we are now in 4 position to formalize our solution, The next step is to write the solution as a Sequence of instructions. Remember to use variables 10 store values that we obtain or results that we compute, We need to define the following variables: Building-cost, architects-fee, remainder, firsecomponent, second-compouent Initial Solution: \ 2. Set first-component to (5/100) * 5,000 3. Sct remainder to building-cost 5.000 4. remainder <~ $0,000 then set second-component to (3/100) * remainder 3 If remainder > 80,000 then set second-component to (2.5/100) * remainder 6, Set architects-fee to first-component + second-component 7, display architeets-fee x Stop. The solutions outlined’ above seem to be very wordy, They contain many English-like statements, In Chapter 4. we will look at the correct way to represent our solution. For now. the focus is on getting a working solution in a language that we are familiar with, Let us look at one more example before we move to the refinement stage. Problem 8 Given a list of 20 integers, design « program to count the number of integers tir the fist that are larger than the first imeger in the list. Display the first value and the number of values that are greater 1. Define the problem: INPUT OUTPUT number 1. Get first-number First-number | 2 Compare each number with | Total-greater first-nuimber 3. Count numbers greater than first-number | 4. Print total-gr There are three things to note in this problem () Certain steps must be repeated until the Jast number is processed. Gi) We do not use a repetition or loop structure in the defining diagram. The defining diagram simply states what must be done and a note is made to indicate that some steps must be repeated, The defining diagram is not the solution, It is a tool to assist in understanding the problem. (iii) Repetition is implied in the diagram, that is, “compare eweh number” Create sample input data: The input list contains 20 data values, but we do not need to write down all 20 integers for our manual solution, We could choose say about 5 integers. If the solution works for 5 integers, it should work for 20, or even 1000 integers. So let us assume that our input list is as follows: 7, 6, 9,23, 3. Do a manual solutios Get first number: 7 Get next number: 6 Is 6 greater than first number (7)? No Get next number: 9 Is 9 greater than first number? Yes, then count — 1 Get next number: 23 Is 23 greater than first nun Get next number: $ Is 5 greater than first number? Vor We have reached the end of the list. Now all we have to do is display the number 7 which is our first number and the value of count which is 2 ber? Fes, then cowt 4. Outline solution ay a sequence of instructions: Jn problems such as this, which invelve repetition of a sequence of instructions, we can simplity the steps by using a structure called a Joop. If' we look at the manual solution above, we will notice that there are several steps that are repeated: Get next number Is number greater than first number We could encapsulate these statements within a loop as follows: Initial Solution. 1 Geet first-number 2 Repeat the following 19 times a get next-number b. if nex-munber » firseumber then increment count end-repeat 3 Print first-number, count Stop. 24. In jalization of Variables There is one seemingly small problem with the above solution. ‘The variable count does not have an initial value. Why does it need an initial value? In order to increment (that is, add one to) a variable, it must have had a value in the first plice, Increment means add one to something. If there is nothing in the storage area (nothing does not mean 0.0 is an aetual value}, we eannor add We cannot increment the number of cookies in a cookie jar, if itis empty. We can place a cookie in an empty jar. and then increment the number of cookies by one at a time. Likewise, we must place an initial value of @ in the memory location called coun and as we count a number, we increment the value of comit. So, we need to revise the solution above to include the following as the first statement: one to nothi ding cookies, count = 0. In computer programming terms, the variable count is referred 10 as a counter, Variables that are used as counters or used to store totals should always be assigned an initial value of 0 before they are incremented. Initialization may appear to be a trivial step, but it is very important, Many programs have tw work correctly, simply because the programmer forgot to initialize a counting variable. Rule of Thumb: A simple rule of thumb with respect to initialization is: In the solution. tf variable appears on the right-hand side of an assignment statement before a value is assigned to it, then it must he assigned an initial value before the assignment statement iy executed. 25. Summary In this seetion, we developed « systematic approach far arriving at « solution to any given problem: 1. check the processing steps in the defining diagram to see what needs to be done, then 2 create sample input data 3 carry out a manual solution 4 write a sequence of instructions, based on the manual solution, Ofien times the initial solution might not be very efficient and may appear to be clumsy, but what is importam, is that the solution works. Once, we arrive at a working solution, we ean then proceed to optimize the solution through a series of refinements, to make it more efficient. The next chapter illustrates how solutions can be refined. 4 Chapter 3 EVALUATE ALTERNATIVE SOLUTIONS Problem-Solving Step 3 There's more than one wav to skin a cat 3.0. Introduction ving arrived at an initial solution to the problem, the programmer should not rest on his I id, should explore altemative solutions, The aim is to arrive at the most efficient solution, Usually, the initial solution is the first method that comes to mind, but it is not always the best solution. This is the case with more complex problems, For most simple problems, like the problem involving average in the previous section, the solution is trivial and there may be r ternative ways must always he explored so that an informed decision can be made about which solution is the most efficient. very few alternative ways of doing it, Needless to say Here are some points to consider when developing altemative solutions: * Can you derive the result differently? Can you make the solution more general? For example, would it work if there were 100 int instead of 3? * Can you use the solution or method for another problem? For example, average temperature wwe wrade? * Can you reduce the number of steps and still maintain the logic? * Can you make it more robust? Would it work properly if incorrect data is entered’? Lot us revisit our problem involving average and see if we can find a better way of doing it Recall our initial solution 1 Get the first number, call it num 2. Get the second munber, call it num? 3. Get the third number, call it mum3 4 fed num, num2, num3, storing in sum S. Divide sum by 3, storing tn average 6. Print result 7 Stop Can you reduce the number of steps and still maintain the logic? A look at the first three statements shows that we are reading each input value directly after each other. Insicad of using three separate statements, we could use one statement to read the three values as follows: Get num), num2, num3 This is a much more efficient way because, by reducing the number of statements, we are reducing the number of CPU eyeles required, thereby resulting in faster execution af the program and betier wiilization of system resources, This should be the aim of every good programmer, We can further reduce the number of statements by combining the two arithmetic statements into one, Let’s rewrite the arithmetie statements in a more concise form: Add nuns, num? , num3, storing in sunt can be written more succinelly as: sum © num]+num2 + num3 which reads, “the variable sum is assigned the value of numt ply num2 plus num3”. Likewise, Divide sum by 3, storing in average can be written as: Average € sum +3 So instead of wo statements sum © num! + num2 + num3 Average © sum =3 We can combine them as follows: Average € (numl + num2 | num3)-+3 Here, we have not only reduced the number of statements, we have also eliminated one var This means that we are using less memory. Less memory implies ercater efficiency So let us rewrite our new and improved solu n to the average problem: Revised Solution. Get num1. num2, num3 Average © (num » num? + num3)-+3 l 3. Printaverage 4 Stop. Wow! We have reduced the number of statements from seven to four and have reduced the number af variables from five to four, without changing the logic of the solution. This. is essentially what refinement entails, Can you derive the result differently In refining our solution, we looked at an alternative way to write our input and arithmetic statements, We need also to look at alternative ways of finding the average. Is there another method that c ¢ of three numbers? Maybe not, in this particular case. but as a general rule, alternative methods should always he explored n be used to find the aver 16 Can you make the solution more general? For example, in the problem involving average, we were asked to find the average of just three integers. Suppose the requirements change and we are asked to find the average of 100 integers. Would the same algorithm work or would we have to write a different algorithm’? The algorithm above was written specifically to read three integers. so we used three variables. num nium, «J to find the average of 100 integers, Clearly. the algorithm above would not work for 100 values, If we revise the algorithm by declaring 100 variables. num!, num2, num100, and dividing the sum by 100, that would work. However. suppose next time we need to find the average of 50 integers, the algorithm would have to be revised again to declare 50 variables, and so on. . num3, respectively for each integer. Now we ni There are three problems with this approach i Using so many variables (100, $0) results in vei 2 It becomes. vet poor utilization of memory y cumbersome 10 write and manipulate so many variables in one statement, for example, get mum/, num2, num3, mand, num, numb, num?, umd, mund, um 10. num 1, nara, num 00. Besides, we'll run out of paper eventually! What if there were 1000 integers instead? I is very difficult to maintain this algorithm, because, each time the number of integer changes, we have to make major changes to the algorithm, therefore, better to design the algorithm in a general way so that it will respond correctly to any number of integers, whether positive or negative. The way we do this is to use one variable, number to store the curtent integer and an entity called V to store the number of integers (say. 3 or 100). We then employ a loop structure that repeatedly reads a value into the variable, number and then calculates the sum, When all the values have been read and summed, we exit the loop and compute the average, This is illustrated below Set N to 100 Set sum t0 0 Repeat N times Get number Auld number to sum, storing in sunt End-repeat iverage = sum +N Display average Siop Notice that in this version of the algorithm, we use an entity called N to store the number of integers that we want {0 manipulate, In this case the algorithm computes the average of 100 integers. If we wish 10 compute the average of 3 integers, all we have to do is make one simple change to the algorithm: that is. change 100 to 3 Constants: We refer to the entity N as a constant. Recall that @ variable is an area of storage whose value can change during processing. A constant is an area of stor: is, romains the same) during processing. Constants are very useful in making a program maintainable, (that is, easily modified). In the average problem, by simple changing the value we assign to the constant N, we can make our program calculate the aver whose value never changes (that ven integer Can you make the program more robust? A program is sid to be zobust if it survives various unexpected events, such ay incorrect or invalid input data, One way to make a program robust is to validate the input data, This means that the program should always check to sev if the correct data has been entered and should have a strategy 1 deal with unexpected data, One should not assume that the correct data will be centered at all times, Data entry operators, programmers and users in general are all human, We are all prone 10 making mistakes. For example, the following program is designed to read students test scores a id compute the letter grade for cach student. It is understood that the maximum test score is 100 and the minimum would be 0. Start Read ID, test-score If (est-score >= 80) then Lettergrade =A Else If (test-seore < 80 and test-score > — 70) then Lewtergrade = °B Else If ftest-score < 70 and test-seore >= 60) then Lenergrade = °C Else Lettergrade = "D Display ID, lettergrade Stop. What would happen if the user accidentally enters a test score of 150, instead of 50? What ‘would happen is this: The program would print 2005346. 8 It would not recognize the input error and would treat the 150 as a legitimate value for the test- score. The student with the above ID would get a very pleasunt and perhaps unexpected surprise when the results are published. There are two ways in’ which we could modify the above pr ‘am to make if more robust We could insert a statement afier the input than 100 or less than 0. That is: atement to check iftest-seore is gr Read ID, test-score Af (test-score > 100 or test-score <0) then Display “Error Message: Invalid Test-score” else If (test-seore >= 80) then Lettergrade =A 2. Alternatively. we could insert a test for the upper limit of 100 in the first if stat follows: If (test-score »= SO and test-score <= 100) then Lettergrade =D, grade ~ 2 Also at the end, instead of “else leriergrade = 'D', we could insert a test for the lower limit of @ as follows: It (test-score < 60 and test-score >= 0) then Either of the above adjustments would make the program more robust Errors resulting from invalid or incorrect input data can have very serious consequences. Consider what would happen if the data entry personnel at the Water Authority enters 600 cubic metres instead of 60 for your water usage last month and you get a bill amounting to 10 times the usual amount: or what Would happen if the interest on your credit card balance was computed at 215 percent instead of 21.5 percent? These are the sorts of real-world problems that can result when a program is not written to guard against invalid or incorrect data, An her Refinement Examp! Let us look at another example to see how we ean refine the original solution, The following is the initial solution for calculating the architect's fee 1 Get building-cost 2 Firs-component = (5/100) * 5,000 3. Remainder = building-cost — 5,000 4 Ifremainder <~ 80,000 then $. Second-component ~ (3/100) * remainder 6. Ifremainder » 80,000 then 7 Second-component = (2.35/10) * remainder 8 Architects-fee ~ first-component + second-component 9 Displav architects-fee 10. Stop 19 In this example, we cannot combine multiple arithmetic statements as we did in the previous example without affecting the logic of the solution, However, there are other areas that ean be refined. This example involves the use of selection structures (that is, the “/f” statements). If we trace through the logic of the solution, we can see that both /f statements will be executed regardless of the outcome of the first, Let’s assume that the input data for this problem is 50,000. A trace of the solution would yield the following values Remainder ~ buildi ‘ost — 5000 = 45,000 Step 4 would then be executed, (remainder is less than 80,000) giving, Second-component € 15.000 Although we have computed a value for second-component, the solution requires us to execute Step 5. nevertheless. So we would still check to see if remainder is greater than $0,000, even though the previous check had rendered this check unnecessary. While this step docs. not compromise the logic of the solution, it creates additional, unnecessary work for the processor. Decision statements are taxing on the CPU and therefore must be used wisely, We could eliminate the second Jf statement and still maintain the correct logic. The following is a more efficient method: If remainder <= 80,000 then Second-component = (3/100) * remainder Else Second-component ~ (2.5/100) * remainder Here, we have repliced two consceutive //stitements with a single if-then-else statement. Finally, let’s evaluate the solution for the looping example in problem & 1 Get firsenuanber 2 Repeat the following 19 times Get next-mumber If next-number > firstnumber then Increment count End-repeat Print firstontunber, count 5. Stop. Is there another way we could do this problem and arrive at the same result? This is tefl as an exercise for the reader 3.1. Determine the most Efficient Solution ‘The next step in the problem-solving phase is to determine the most efficient solution, Having evaluated and refined our solutions, choosing the most efficient solution is fairly straightforward. 20 When we use the term “efficient” in this context, we mean, not just which solution results in better utilization of memory, or which solution is shorter. The most efficient solution should have the following attributes 1 should be maintainable: 2. should use memory efficiently: 3. should be robust. Use the above criteria to determine the most efficient solutions for the problems we evaluated in this chapter. Chapter 4 REPRESENT THE SOLUTION AS AN ALGORITHM Problem-Solving Step 4 4.0 What an Algorithm? So fur, we have been developing and evaluating solutions to various problems. We have not been referring to such solutions as algorithms, even though many of them are algorithms, Not eve solution though, is an algorithm, As mentioned in the introduction, algorithms have certain properties. so. altributes, orithm; a solution should exhibit n order to qualify as an al n specific Definition: An algorithm is a sequence of precise instructions for solving a problem in a finite amount of time, Properties. An algorithm must be precise: be unambiguous: give the correct solution in all cases: eventually end. Precision versus Ambiguity A description is ambiguous if it is vague or has two or more meanings. A description is precise iF it is strictly defined or definite, Consider the following descriptions: (a) a tall person (b) a tall building (c) a tall Mower. Fach is intelligible, though not very precise. In these instances, the word tall is vague or ambiguous, although understandable, However, if the goal is precision, we have to make the descriptions clear and definite, For example, we could replace (a) ‘with a 6-foot, 8-inch person and (b) with a 4-storey building, Abernathy & Allen, “Esploring the Science of Computing” 4.1. Algorithmic Structure Every algorithm should have the following sections, in the stated order Header Algorithm’ s name or tithe Declaration A brief description of algorithm and variables used, That is, a statement of the purpose, as well as initialization of variables Body Sequence of steps ‘Terminator An end statement Itis very important that students get in the habit of writing properly structured algorithm at an carly stage. If the structure outlined above is strictly adhered to, then it will be very easy to iranslate an algorithm into a programming language, ax most programming languages have similar structure 4.2. Control Structures s @ basic unit of programming lo A structu ic. A structure can be a sequence, a select Joop (that is, repetition). The body of the algorithm is comprised of various structures. jon ora Sequential structures are: 1, Input statements, for example, a Gernum!, num? b. Read price, tax-rate e Accept guess 2. Output statements, for example, a, Print total-cost b. Display averag 3. Statements involving arithmetic operations, such as: a Sum =numt + num? b. Average = sum +2 4. Statements that assign values to variables, such as a Count=0 b. Maximum = 20 Selection structures are: IF or IF-then-clse statements, They allow decisions to be made, based on some condition that evaluates to ue. In the case of if-then-else, alternatives are executed if the condition is false. a If(A > B) then Display A b Iflage > 50) Print “Ole” Else Print “Young” Repetition or Loop structures allow statements to be repeated a fixed number of times or until some condition evaluates to false. If the number of repetitions is known beforehand, the loop structure is called a counted Joop, For example, Repeat 10 times: Print “1 End-repeat 1m good-lookii If the exact number of repetitions is unknown beforehand and is based upon some condition, then the loop is called a conditional loop. For example, d While (price #0) do Read price Total = total ~ prive End-while Here, the idea is to read a set of prices and calculate the total price. The read and assignment statements are executed until a price of 0 is encountered Problem 9 Write an algorithm that prompts the user to enter hisvher name, accepts the name and then display welcoming message on the screen, such as “Hello Pat! Have a nice day!” This is « simple algorithm that uses only sequential statements, The solution would look like this: Algorithm Weleome {Header} This algorithm displays a welcome message to the user on the screen, (Declaration; Display “Enter first name: Accept first-name Display “Hello”, first name Display “Have a nice day!” — Stop. (Terminators Body In this simple example, there iy only one variable, that is. first-name. We do not need to initialize this variable because, the accep statement takes care of that. It allows a value to be read from the keyboard and stored in the variable firs-nume, 43. ‘The Algorithmic Language During developme: of an algorithm, the notation that resembles that of a programming language. An intermediate notation called pseudo cade is commonly used to express algorithms. uage gradually progresses from English towards a Algorithms ean also be expressed as flowcharts or as Nassi-Scheidermann diagrams. A flowchart isa pictorial representation of an algorithm. 4. 1. How to Write Pseudocode What exactly iy Pyeudocode? There seems to be a general misunderstanding of what actually constitute pseudocode. At one extreme, are programmers and authors who use mostly English-like statements to express their algorithms, For example. Read the first numbe Read the next number Compare numbers If he first number ts greater than the second then print first number Otherwise, print the second number At the other extreme, are those who write algorithms code (such as C or Pascal stater “pscudocode’ ing undiluted programming language nts) and call it pseudocode, Here is one such example of int munbert, manbe cout << “Please enter the first number cin>> number! cour << “Please enter the second number?" cin >> number? if (numberd > number2) cout << number << endl. else cour< number? << endl i ‘end matin The above is written in undiluted C code, We could take the code as written, add a line or two the pre-processor area and execute it on any C/C++ compiler. To a C novice, this is pure mumbo jumbo. The whole purpose of writing algorithms is to develop « solution that is easily understood by all and one that can be readily translated into aay programming language, The constructs in aan algorithm, therefore should not be specific to any one programming language. ‘The reader should not have to be familiar with a progeamming language in order to understand the solution. For this reason, the universally-accepted format for pseudocode is code that includes some English as well as common programming constructs that are well understood. For example, Accept x. Read xy Hoe > yy then OR If (sey) then Display result Print result Read and print are English words, but they are also common to many programming languages. The /f statement is also easily understood in English and is also a construct that is used in most programming languages for decision-making. Some words that are acceptable for input and output in pseudocode are stated below LINPUT OUTPUT. Get Display Accept | Print Input Output Read Always Use the Correct Terminology The algorithm is not a different emtity from the pseudocode or the Nlowchart, Pscudocode and flowchart are simply ways of representing or expressing algorithms, So it is incorrect to say. write an algorithm, a flowchart and pseudocode to solve a given problem. A flowehart is an orithm, likewise is pseudocode. So instead, we should say. write an algorithm using (or/in) pseudocode and/or flowchart to, Flowcharts versus Pscudocode: A frequently asked question is when do we use pseudocode and when ix it better to use flowcharis? Jnswer For experienced programmers, flowchart versus pseudocode is a matter of preference. Most prefer pseudocode, However. beginner prog ners should be required to use both pseudocode and Mowehart 1 represent their algorithms, While pseudocade is more concise and closely resembles the programming language, the flowchart gives a good view of the structure and flow of the logic. Beginners tend to find it easier to follow the logic in a flowchart than that of pscudocode, It is easier to visualize the connection between the statements. However, long, complex solutions ate better represented as pseudocode, rather than flowehart, which would be Jong and cumbersome to navigate To illustrate pseudocode and flowchart representations, let us represent the solution for the problem involving average, first in pseudocode, then in Nowehart form. Reeall that in Chapter we revised the solution to make it more efficient, The revised solution, written in pseudocode would look something like this: 26 This algorithm finds the average of three numbers Start read num, num2, num3 Average © (num! + num? Print averag Stop num3) > 3 Notice that the pseudocode version is quite similar to what we had before. It contains less English-like statements and a bit more general programming construets. Note also that we have retained the assignment symbol in our pseudocode. This is important in terms of the logic. In such statements, we are assigning values to variables; we are NOT equating the operation on the right with the variable on the left, Different programming languages use different symbols for assignment. In Pascal, the “:=" symbol is used, while in C the "=" symbol is used. This means assignment in C and the equate symbol is * 43.2. Floweharts Flowchart use special geometrical objects to designate the basic steps of a program, which are: input, processing and output. A parallelogram is used to represent the input operation, as well as the output operation, and a rectangle is used to represent a processing/assignment statement. A diamond is used 10 represent a decision (if-then-else) structure. An elliptical shape is used to represent the terminal indicators, START or STOP. Directional arrows are used to indicate the flow of the logic in the algorithm, The four basie shapes are: aT Oo saa InpuvOurput Processing’ Assignment Start/Stop Decision Below are examples of how the various control structures are depicted in a flowchart Seque | A doa B do B No VON es c HC is rue then dok D L Live doD Loop (Repe While ¥ is true doG G 28 Flowchart version of the Average Algorithm Read mu The example above, uses only the sequential structure, Let us look at an example that involves a decision statement. Both the pseudocode and flowchart versions of the solutions will. be presented. Problem 10 Design an algorithm that accepts two values, the hourly rate and the number of hours worked by ait emplovee. If the munber of hours exceeds 40, then the excess hours should he paid at an overtime rate of twice the hourly rate. Caleutate the wages (including overtime, ifany) due to the employee, The first step is to define the problem as follows: PROCESSING OUTPUT Rate, hours- | T. tead rate, hours-worked wages worked 2. Calculate overtime pay, iPany 3. Calculate wages 4._print wages The nest step is to create Sample dats and then do a manual solution Sample data: 10.0045 The first data item is $10.00 that represents the hourly rate and the second is 45 that represent the number of hours worked. The manual solution i left as an exercise for the student A possible pseudocode version of the algorithm would look like this: Algorithm Wages This algorithm calculates the wages fineluding overtime) due to an employee based on the number of hours worked. Read rate, hours-worked Basic-Pay = rate * 40 Overtime — hours-worked — 40 If (overtime > 0) then, Waves = Basic-Pay + (overtime * 2* rate) Else Wages = rate * hours-worked Print wages Stop. 30 The flowchart version of the Wages problem would look like this START Read rate, hour worked a Basic-Pay — hours- worked * 40 + ‘Overtime ~ hours-worked — 40) Wages ~ Basie-Pay (overtime * 2* rate) No Ways = rate * hhours- worked. . Print Wages stor 31 The next problem is an example of a situation where the fowehart representation can become complex. Sequential, looping and nested decision structures are used Design an algorithm that reads 1 list of students test scores and determines the letter grade that corresponds to each test score, according to the following table: Test Seore Range Letter Grade 0-100 N 779 | B 60-69 1 Below 60 1D The input list is terminated by a value of 1, which is used as a sentinel, Print each test score and the corresponding leer grade The fist step is to define the problem: INPUT PROCESSING OUTPUT test-score read test-score Test score, for each test score, determine Letier grade corresponding letter grade print test-seore & letter 1 fape rade The next step is to create sample data, Note that the problem did not state the actual number of test scores in the list. For this problem, we do not need to know how many scores th However. in another scenario, if we need to know the exact number of data items in the input list. we have to count them as each item is read. We read the data until the end of the list is reached. A value of -1 indicates the end of the list. The —I is not valid data, it is merely an indicator, to let us know that there is no more data in the input list. This valuc is called a ventine!, \ sentinel can be any value that does not represent valid data in the context of the problem. We can choose any number of input values for our sample list, For example, Sampl 75.43 S087 7291 35-1 input data: The manual solution will be lefi as an exercise for the reader, The following is the solution algorithm in pseudocode: Algorithm Grades This algorithm reads test scores and determines the letter grade for each scove Read test-score While (test-score #-1) do I(lest-score * 80 and test-score = 100) then {Validate the input data} Lottergrade € *A Else Ir(test-seore < 80 and test-score >= 70) then Lettergrade €°B" Else IP (test-score = 70 and test-score =~ 60) then Lottergrade € °C Else If(test-score < 60 and test-score > 0) then Lette End-lt End-If Print test-score. lettergrade Read test-score End-while Stop Note the indentation which highlights the structure of the logic and the flow of control of the if statements and the while loop. The structure will be more evident in the flowchart version of the corithm, Flowchart Version . L oO oO P Yes oo, . | Letergrade~ BF sn? Lettergrade Ye D Print Lettergrade It can be seen that the flowchart above is quite complex and the logic is somewhat difficult to navigate. In such circumstances, the programmer may find it easier to represent the algorithm as pseudocode, using appropriate indentation to show the logic and to delineate the control structures, In problems where the Nowchart cannot fit on a single page, a special symbol called a connector is used to connect sections of the flowchart over multiple pages. The connector symbol is a small circle with a number or letter inscribed therein, for example Flowehart | Section 1 Flowehart Section 2 a Flowchart Section 3 4.4. The Structured Programming Concept The main goal of structured programming is to structure the flow of control in such @ Way that the execution sequence is as close as possible to the reading sequence. The structure of a program is determined by the constructs used to direct the flow of control. This enforces a discipline on the programmer in terms of the control structures that can be used and in the manner in whieh they are used [Tremblay & Bunt]. Stuetured programs are designed using three basie contro! structures i Sequence 2. Selection 3. Repetition Algorithms that are carefully designed using only these control structures are much more readable and maintainable. The “go to” statement should be avoided at all cost when writ algorithms, as it tends to make the solution very unstructured. The resulting code or flowel becomes very difficult to decipher and resembles spaghetti, Hence, the term, “Spaghetti code” DO’s AND DON’TS WHEN WRITING PSELDOCODE, Use the assignment symbol ( € ) in assignment statements instead of the equal sign, Use meaningful variable names Use indentation to show the logic and scope of contral structures. 4. Insert comments to clarify meaning of blocks of code. Do Not 1. Use language-specific constructs such as case. sivitch statements or for loops in the » —_ pseudocode.‘Construets such as while, repeat and if-then-else are sufficiently general and can therefore be used in the pseudocode. Keywords such as reaclln, writeln, prim, seanf should not be used, 2. Attempt to write Pascal code before writing the algorithm, ‘That is, do not execute the program first and then try to write the algorithm afterwards, based on the program code. “This is a very bad practice and is essentially a waste of time. 36 Chapter 5 TEST THE ALGORITHM FOR CORRECTNESS: USING TRACE TABLES Problem-Solving Step 5 5.0. Tracing the Algorithm Checking the algorithm to see if it works is @ very important step in the problem-solving process. This must always be done before the program is translated into programming language, This is a discipline that hepinner programmers must lear and practice. Teachers should endeavour to enforce this practice by making it a requirement for students to show the trace of their algorithms, before they get on the computers in the lab, We can check to see if our algorithm produces the desired results by tra the algorithm, using some chosen test data. through the logic of Steps in Tracing an Algorithm. 1. Choose simple input test cases (data sets) which are valid. Two or three test cases are usually sufficient 2, Establish what the expected result should be for each test case, That is, do a manual solution beforehand, 3. Create a table of all the variables used in the algorithm, 4. “Walk” the first test ease through the algorithm, keeping a step-by-step record of the content of each variable in the table as the data passes through the logic until the algorithm reaches its logical end. 5. Check that the expected result established in Step 2 matches the actual result developed in Step 4. 6 Repeat the process using a different set of test data. Example: Trace the following algorithm using two data sets Prohlem 12 Super Six is the name of a junior cricket team. The coach of Super Six has hired you to design a program to provide him with statistics after each match, Design an algorithm that reads a list consisting of the number of runy seored by each batsman in the team. There are 6 batsmen in the team, Compute and print the average number of runs scored by the team. Algorithm Average Score This algorithn computes the average number of runs scored by a cricket team. Start Total-runs © 0 1 2. Count © 1 fused to keep track of the number of times the loop is executed) 3. While (count <= 6) a. Input runs b.Total-runs € Total-runs + runs, 37 c Count € count +1 4. Eni-While 5S. Average-Runs © Total-runs +6 6 Display Average-Runs Stop. We have numbered the statements to make reference to them easier. Step 1: Choose 2 or 3 sets of test data Test Data Set 1 AG 1850901 Test Data Set 2 67 102 13000 Step 2: Establish what the expected result should be: Manual Solution gives an expected result off 20.67 runs for data set 1 and 30.3 runs for data set 2 Step 3: Create a table of all the variables used in the algorithm Keep track of the contents of each variable in the table as each statement in the algorithm is executed Insn jetion | Count | Runs in Execution I 0 2 1 3. While (eount = 6) 3a 146 3b 46 Total | Average- | Output Fotal-runs © 0 Runs Runs ‘ 2. Conn € 1 b Ti runs € Toval-runs * runs fe ' a 6. Count € count 11 3e 3 | 4. End-white 3 14 I] S Average-Rums € Totaltuns = 6 1 a 6. Display Avera = 7 t 6. Display A\ 3b 133 7. Stop Runs 3 0 a. Test Data Test Data Set 1:46 18 > —— 50901 3c 6 b. Test Data Test Data Se 3a l W2 1B 000 6 20.67 The actual result of the trace matches the expected result from our manual solution for the first {est case. A second trace of the algorithm, using test data 2 is left as an exercise for the students, An accurate trace will result in a match in the expected and actual results for the second set of test data, We can then conclude that the algorithm yields the correct results. SL. Cho ing Appropriate Vest Data It is important that we test our algorithms using a wide range of data values (including extreme cases) that will test every segment of the code. Some algorithms can give the correct solution with one set of data and incorrect solution with another set of data. This depends on the flow of control within the algorithm and which seetion the data actually traverse, As an example, let us look at the following pseudocode segment read A.B if(A > B ) then inerement N else decrement N Tf we use different sets of test data for this code in which the valuc of A is always greater than the value of B, then the else statement will never be executed. Since the else alternative is never be tested, errors in that section of the code could go undetected for quite some time. So the appropriate set of test data for these kinds of problem should be one set which tests the if alternative and another set that tests the efye alternative. The following test data would be appropriate for the code segment above: Data set 1 3) Data set 2 935 The following test data would not be appropriate because A would greater than B in both cases and the alternative statement would never be tested. Data set 27 Data set 2 935 Let’s trace another algorithm to see if we can deteet any errors. Algorithm Large Count Given a list of 20 positive integers, this algorithm counts the mumber of values that are smaller than the first value Set count to 0 Set No-of- Values to 0 get first-number 39 While (No-of-Values < 20) do the following: get next-number increment No_of-Values. if next-number « first-number then inerement count cend-wh print stop. st-number, count For the sake of brevity, we will revise the 20 The trace is shown on the next page. Trace of Algorithm Large Count: Test data set | s 2B 4 Test data set 2: 8 7 Z The expected result for data set 1 ix: Sand 2 Instruction | Count Values | First in number Execution da 40 Next number gorithm to read a maximum of S numbers instead of Algorithm Large Count Given a list of 5 positive integers this algorithm counts the number of values that are smatler than the first value. Set count to 0 Set No-of-Values to 0 get first-number While (No-of-Values < 5) do the following: a. get next-number b. increment No_of-Values if (next-number number) then inerement count end-while first An error is detected when No-OF-Values is 4. The algorithm attempts to execute the loop, only to find that there is no more data in the input list. The data set has the correct number of integers, that is, 5, so there must be an error in the logic, with respect to the variable No-OF-Values. A closer examination of the logic reveals that the error occurred because we initialized No-Of- Values to 0 belore entering the loop. The input list consists of 5 data items and we read the first number before we entered the loop. Therefore we should either increment No-Of-Values before we enter the loop or simply initialize the variable to 1 to reflect the fact that the first number was read outside the loop. So we ean revise the algorithm as follows: Revised Algorithm Large Count Given a list of 20 positive imegers, this algorithm counts the number of values that are smaller than the first value. Set count to 0 get first-number Set No-of-Values to | {initialize the variable to 1 instead of 0} While (No-of- Values « 20) do the following: get next-number nerement No_of-Values if next-number < first-number then increment count end-while print First-number, count stop. ‘alues as zero and revise as follows: Alternatively. we could leave the initial value of No- Set No-ofValues to 0 Get first-number Increment No-of-Values While (No-of-Values < 20) do the following: This method however, would be less efficient. As an exercise, the reader should trace the algorithm using data set 2 and see if any more errors are detected. Hint: a second trace should reveal another error. 4 Chapter 6 LIST PROCESSING USING ARRAYS 6.0. What is an Array So far, we have been using what is called simple data types in our algorithms, That is, the data Values we manipulated were unrelated and stored in separate variables. For example, in the problem, we used three variables, aum/, num2, num3. These variables are independent aver of cach other in terms of where they are stored in memory and also in terms of what type of data they store. Man/ could store an integer value: sum? could store a real value, Num! could be stored at location 101 in memory and num2 could be stored at location 1S10. It doesn’t matter An array however, is a more complex data type, in that; it is a structure which contains not just fone data value, but multiple data values, all of the same type. That is, the values are all inte or all floating point numbers or are all characters. Also, the values are stored in contiguous (that is, adjacent) memory locations. So if the first value is stored at location 100, then second valu would be stored at location 101, the third value at location 102 and so on An avray is a data structure that is used to store a fixed number of data items all of the same type. The items (or elements) of the array are organized in sequence and can be accessed directly by specil'ying their positions in the sequence, using an index or subscript. IPonly one index is used, the array is called a one-dimensional array. If more than one index is used, the array is called a multi-dimensional array, One-dimensional arrays are list structures (or Vectors), two-dimensional arrays are table structures (or matrices), At this level, we are only concemed with one-dimensional arrays. Multi-dimensional arrays are outside the scope of this course and will be addressed in advanced programming courses 4 one-dimensional array ean be represented as follows: TEMP [1] ++ _ Pater values stored TEMP [2] Tin adjacent memory TEMP] 73 locations TEMP |4] (29 TEMP [5] 30 TEMP [50] ‘To refer to the 2" temperature value, 28 we would specify its position in the array as a subscript of the array name, That is Temp [2] x Subscript or index (that is, the position of the item in the array) Temp is the name of the array. 2 indicates the location of the value 28. Arrays are sometimes called subscripted variables, because the values stored in the locations of aan array are accessed via the subscript or index of the array Arrays are typically used to store and process a list of items. That is why, in some texts, manipulation of arrays is sometimes referred to as list processing. Example A program is requited to read a list of temperature values and find their mean. Two Possible Solutions: (i) the list is short, say 3 temperature value templ. temp2, temp3 we may use 3 different variables, say (ii) If the listis Fong, say 120 temperature values, it would be cumbersome and awkward to use 120 different variables. Arrays are used to solve these types of problems 6.1. Accessing the Elements ofan Array ments of an array ean be accessed individually by specilying the name of the array, followed by the index or subseript, which identities the position of the element in the sequence. Therefore, when manipulating arrays, a special variable must be declared as the index of the array, & single letter (such as i, j, ork) is commonly used as array index. Using the index, the ay elements can be manipulated in the same way that we manipulate ordinary variables. For example, we ean assign an initial value to an array, we ean read a value into an array location, we can display values stored in arrays, and we can perform arithmetic and logical operations on the clements in an attay, ‘Traversing the array (that is, access each element in a sequential manner) requires a loop structure. Examples of this will follow 6. tializing Arrays Initial values can be as locations or by use of an assi locations of the array 4st 60 0. i ied 10 array locations either by reading values directly into the ment statement. Let's say for example, that we want to set all 10 tially. We would write Setito Repeat 10 times list fi] €0 increment t cend-repeat The first time the loop is executed, i= | and list [1] would be assigned 0. The second time through the loop i ~ 2 and list [2] would be assigned 0 The third time through the loop. location. that is list [10] is assis i = 3 and list [3] would be assigned and so on, until the last ned 0. When manipulating arrays, a special variable must he declared for use ay the index of the array It is better to wse short variable names, such as single letiers of the alphabet for the index or subscript. 6.1.2. Reading Values into an Array IF the number of values to be read is known beforehand, we use a counted loop (that is, repeat nes). If the number of values is unknown, we use a conditional loop (that is, while some condition is true do). The case of the known number of items: To read 10 values into the array temp: Set ito 1 Repeat 10 times read temp|if { get next value and store it in location temp|il } increment i fadd I 10 index to get to the next array location} end-repeat Iv'the input data was say, 21 23 26 26 22 27 29 26 24 26 First time through the loop, i 1, the value 21 is stored in temp [1] Second time through the loop. i= 2. the value 23 is stored in temp [2] Third time through the loop, i 3. the value 25 is stored in temp [3] Fourth time through the loop. i ~ 4, the value 26 is stored in temp [4] and so on until the last location temp| 10] is filled with the value 26 Mier the loop has been executed 10 times, the array would look like this; list 1 2 3 4 5 6 7 9 10 [2b [24 [26 The top numbers represent the index ar subscript of the array, the bottom numbers are the data values stored in the various locations. 44 The Case of the Unknown number of Hems: Consider the following problem Write an algorithm that reads a list of integers from the inpua stream and stores the values in an array called Positive Num. The list is terminated by a sentinel value of “1 Here, the number of items to be read is unknown, so we use @ conditional loop as follows: Set ito} Read number White (monber is not equal to 1) do the following, Positive Numfi] Emunber {store current number in ari Increment i {add 1 10 index to get to n Read number fread next number} End-while Num of Stems € 6-1 uy location) ext location} The loop will execute until number receives a value of 1, The 1 will not be stored in the array. The last statement stores the actual number of data items read in the variable Num_of Items. This value will be needed in future if we need to print the data values o traverse the array for any other purpose. 6.1.3. Displaying Array Values Writing or printing values stored in arrays is similar to reading values into arrays, the case of writi ept that, in we would already’ know the actual number of items stored in the array Therefore, we can simply use a counted loop as in the example below Setjt0 1 Repeat 10 times display tempfi] increment j end-repeat Alternatively, if we stored the actual number of items read in a variable called Num of Items, we could display the items in array /isr as follows: Setjtol While (f-<~ Numiof_ttems) do the following Display tis} Increment j End-while 6. 4. Traversing Arrays Traversing an array simply means, moving through the array in a sequential mann each clement, in order to manipulate the elements in one way or another. For example, an array nts, or when we search the list for a particular item, or when cular order. In traversing an array, we must establish a loop and visiting, is traversed when we print the elem wwe sort the list of items in a parti within the loop in order to get to the next element increment the index A classic example of traversing an array is to perform a linear search, A linear search involves examining cach element in the array. one by one, starting with the first element and comparing eaeh clement with the item/value being search for, The search ends when a match is found of when the end of the array is reached. The following is an algorithm for performing a linear search of an array Algorithin Linear Search This algorithm searches a list for the presence of an item called, target In this cave, target is ant integer value. A Boolean variable Found is set to true if the sarget vatue iy found, otherwise Found is set to false Set Size 10 50 {maxinnun no of elements in the array} Set Target to 27 Set indes to | Set Found to false while ((Pound is false) AND (index <= Size)) if(list{index| — target) then fif value iy found set the flag to true} set Found to true else inerement index fotherwise, move on to the next element in the array} end-while if (found = true) then display * found at location”, index arg else display “Target not found™ stop. An Array Processing Example: Design an algorithm that ready a list of students test scores and determine the number of students who failed the test. A student iy deemed to have failed if his/her seare is less than the class average. The list is terminated by a value of 999, Print the class average as well ay the umber of students who failed 46 Defining Diagram Input Processing Output [ListoFtest- / 1. Read rest seores Average scores 2, Caleulate average | Number-Failed score 3. Count number of scores that are less than the average 4. Printaverage, number-failed Algorithm Test-Report This algorithm reads a list of test scores and determines the number of scores that fall below the class average, Variables Used: scores is the artay which stores the test scores, / is the index to the stores the total scores, Number-Failed stores the number of students who failed the t ray, sum a Setito] Set sum to 0 Set Number-Pailed to 0 Read num While (num not equal to 999) do the followin Scoresfi] © num {store each data value in the array} Sum € sum + scoresfi] {compute the sum of the scores} Increment i Jadvance to the next location in the array} Read num Fnd-while Set No-of-ftems to i average € sum + No-of-Items {Traverse array to count how many values are less than average! set index t0 1 Repeat No-of items times feounted loop} IF (scores [index] « average) then Number-Failed € Number-Failed > | End-if Increment index End-repeat Display “The average test seore is", average Display “The number of students who failed is:”, Number-Tailed Stop. a7 6.2. Points to Note when Manipulating Arrays Ins illegal to refer to an element outside the array bounds. For example, if the size ofan array semp is declared to be 50, then it would be ille print temp [51] Al to have a statement such as Therefore, when looping through an array, the subscript should never go below 1 and should always be less than or equal to the total number of elements in the array. So temp [-1] would be an illegal reference, since the index is negative Some programming languages such as C require that the first element in an array start at subscript 0, and the last element at subscript SIZE-1, Other languages such as Pascal require that the initial subscript be 1 and the last element is at subscript SIZE. For the purposes of an algorithm, which should he language-independent. it is recommended that array subscripts start at 1. This makes it easier lor the beginner to comprehend. All the elements in an array must be of the same type. That is, all integers, or all real numbers, or all charact The size of the array is fixed when the arra exampl yy is declared in a programming language. For an array may be declared to have 100 locations. This does not mean that there are 100 elements in the array. This means that 100 locations are reserved in memory for & particular array or list. Depending on the number of data items in the input Hist, all 100 locations may not be used, I there are 75 data items, then only 75 locations of the array will have data: if, on the other hand, there are 100 data items, then all 100 locations will be used. The algorithm should keep track of the number of data items stored in the array and manipulate the list aecordingly, There must also be a means of determining which locations have values and which are empty as Chapter 7 ‘THE TOP-DOWN DESIGN METHODOLOGY What is Top-Down Design? The Top-Down Design Approach or Modular Programming as it is sometimes called involves breaking & problem into a set of smaller problems, called sub-problems or modules, followed by breaking each sub-problem into a set of tasks, then breaking each task into a set of actions. This is called a “divide and conquct” approach, When faced with a complex problem, it is easier to break the problem down into smaller, more manageable sections and tackle each section as a separate entity, rather than trying to solve the large problem in on Sub-problem-| | Sub-Problem-n J l ] 7 oN Vaxkl Tak? Task ost hak a | | | A stub-problem is a set of related tasks. A task is a set of related actions. An action isa basic instruction that needs no further refinement. For example, an action might be a simple instruction such as, add nvo numbers. The process of dividing the problem into sub-problems or modules and breaking them down into smaller units is called stepwise refinement One advantages of modular programming is that when a problem has been decomposed into smaller sub-problems, each sub-probl m can be solved as a single entity. However, the solution of each individual sub-problem does not necessarily solve the larger problem. There must be cohesion between the modules. That is, there must be a mechanism for communicating between the different sub-problems. This mechanism will he discussed in Section 7.2. The concept of top-down design with stepwise refinement is best explained by looking at several examples. 49 Prohiem 1 Turn on a light in a room. This is a fairly simple problem that involves two simple tasks. The problem can be decomposed as follows: Sub-problem 1: locate switch fone task, one action) Sub-problem 2: depress switeh fone ask, one action) Both sub-problems comprise one task and each task constitutes on action, Problems such as this are too simple to apply the top-down design method. ‘The method is usually applied to more complex problems like the one below Problem 2 Mom asks Jan to prepare dinner for the family tonight. Jan plans the menu, which includes haked chicken, rice and peas and coleslaw, As mealtime approaches, Jan begins 10 feel overwhelmed at the task of preparing a large meal for the family. So she decides to adapt a divide and conquer” approach, She solicits the help of her two sisters, Monica and Fla and Jogether they prepare the meal. She divided the problem of preparing the meal into the three smaller problems 1, Prepare baked chicken 2. Cook rice and peas 3 Prepare coleslaw Jan asked Monica to do the baked chicken, and Flo to do the coleslaw. Jan decides to do the rive and peas herself. In order to avoid contusion in the kitchen, Jan directs the order in which each dish should be prepared. She first called on Monica to prepare the chicken and put in the oven for baking. After Monica exits the kitchen, Jan starts preparing the rice and peas. Afier the rice and peas is cooked, Jan calls on Flo to begin preparing the coleslaw. When the coleslaw was completed, Flo returns control of the kitchen back to Jan. Jan continues to direct the various tasks until the dinner was completed. This isa classic example of the “divide and conquer” approach to problem-solving. The problem of preparing dinner comprises multiple tasks or Sub-problems: Sub-problem 1: Prepare baked chicken Sub-problem 2: Cook rice and peas Sub-problem 3: Prepare coleslaw Each sub-problem can be further sub-divided into a set of tasks. For example, a possible set of tasks associated with prepare baked chicken might be: clean chicken, cut chicken into quarters zason chicken bake chicken Some of the above tasks can be further divided into a set of actions. For example, a possible set of actions far the clean chicken might be: Action remove giblets remove any excess feathers squeeze lime juice over chicken wash chicken in cold water. above steps need no further refinement, as they each represent a single instruction or a basic operation, Some tasks may comprise a single action, For example, the fourth task, hake the chicken, is a basic operation that needs no further refinement, That is, the task itself constitutes a single action. Likewise, in less complex problems, some sub-problems may themselves ile task, as We Saw in Problem | constitute a ‘The refinement of tasks 2 and 3 in the problem above is left as an exercise for the student Preparation of the complete meal requires coordination between the various modules, namely. Jan, Monica and Flo, Jan plays the role of the coordinator. She decides the order in which each dish is © be prepared and calls the appropriate module to take control of the kitchen at the appropriate time, She presents (displays) the meal (that is, the output) to the Family when all the tasks have been completed. In programming terms, we refer to Jan as the Main module and to Flo and Monica as sub-programs. The main module issues a call to the sub-program to perform a particular function. Upon completion of that funetion, the sub-program returns control to the module that called it, Any module can issue call to any other module, depending on the logic of the program. In our dinner example, we could reorganize the logic such that Jan calls Monica to prepare the chicken and upon completion, Monica calls Flo to do the coleslaw, before Monica ultimately returns control to Jan. The two scenarios can be illustrated ay follows Moniea He 4 Prepare Baked Chicken Prepare Baked Prepare Chicken olestany + — Flo * Pre Coleslaw Seenurio # Scenario 2 In the real-life scenario presented above, we defined several sub-problems, each comprising multiple tasks. In modular programming however, this is not strictly allowed. The general rule is that each module should perform a single task. Tasks which involve multiple actions should be treated as sub-progiams or modules. Hierarchy Charts The diagrams above are called hierarchy charts, or structure charts. A hierarchy chart is 1 tree- like structure that shows visuallly the rekttionships hetween the modules of @ program, The root of the tree (the top box) represents the controlling or main module. The next level shows the modules that are called directly by the main module, while the next level shows those modules whieh are called by the ones above them, and, so on and so forth. The saying. “a picture is worth a thousand words”, holds true here. One look at a hierarchy chart for a given problem will reveal immediately, which module is the main module and also the position af all the other modules, as well as the Now of control between the modules. The hierarchy chart does NOT tell you what tasks are to be performed within a module: neither does it tell you the order in which the modules are executed. It simply tells you which modules exist and which module calls which other module, It is a good practice to draw hierarchy charts of all modular problems before writing the algorithm Let us look at a programming example, We will demonstrate how a problem ean be decomposed inio smaller problems, how we represent the sub-problems in a hierarchy chart and then how we establish communication between the various modules, Problem 3 Given a list of students test scores, find the highest and lowest score ay well as the average Four sub-problems can be identified here 1. Sub-problem 1 read list af lest scores 2. Sub-problem 2 find the highest score 3. Sub-problem 3 find_the lowest score 4. Sub-problem 4 find the average The hierarchy chart for the modules above would look something like this: Find Highest Find Lowest Find Score Score Aver Read test | The main module will be read the input data and pass it to each of the sub-programs. The subprograms will in tum perform their tasks and return the results to the main module, where they will be printed. Only modules or sub-programs are included in the hierarchy chart. The actions are not. The actions are shown in the algorithm, General Rule: In modular programming, a module should be comprised of statements that contribute to a single, specific task 7.2. How to Sub-Divi jc a Problem into Modules When decomposing @ large. complex problem, it is sometimes difficult to decide what exactly should comprise a module. This is where the defining diagram ean be really helpful, Recall that the defining diagram fists all the major tasks that must be performed in order t0 solve the problem, Let us look at the defining diagram for Problem 3 above. ining Diagram: Input Processing Output Read test scores Find the highest seore | Lowest Find the lowest score Average Find the av 5. Print hist aw List of test- scores we scare est, lowest, There are 5 main things that must be done in order to solve this problem. How do we decide which of the tasks above should be a module in our program? The easiest thing would be to make cach task in the defining diagram a module, However, this approach might not be very efficient. In some problems, @ task might be fairly simple and requires a single action, For example, read mont, num2, mun3 In such cases, we do not need to make the task a module, as the aetion can easily be done by the main module, Where the task is involves multiple actions. such a task is a candidate for a module. For ex validating each test score read. Therefore, it would be reasonable to declare the read rest scores task as a module. Also, find the highest score is a task that involves several actions; it is a sub- nple, the read test scores task involves reading the data into an array and problem in itself. Therefore. it should be treated as a module in the solution, Likewise, find dre lowest score and find the average. Print highest, lowest, average is a simple task that involves a single action, so this task does not become a module, but instead ean be an action in the main module, If the task itself is fairly complex, it should be further refined and broken down into more than one module, Consider for example, our dinner problem earlier. Recall that Moniea’s job was to prepare the baked chicken and this module involved several tasks, some of which were fairly complex. One complex task was that of yeaoning the chicken. This involves assembling a variety of herbs and spices and then applying them to the chicken in a special manner. So Monica decides to solicit the help of her grandmother to prepare the seasoning, When Monica was called on to prepare the chicken, she in tum, called Grandma (a subordinate module), who set about preparing the herbs and spices. At Monica's request, Grandma prepared the seasoning and then passed it on to Monica, Grandma then exited the kitchen, This scenario can be represented in a new hierarchy chart as follows: Prepare Baked Chicken Grandm: Prepare Seasoning Modules Calling other Modules: © module calling other modules. Just as the all another module. There is an art in deciding The above scenario is an example of a subordin main module ean call a module, any module can whether to break down any particular module further into its own sub-problems. The general that a module should be comprised of statements that contribute to a single, speci task. For example, it would be okay to have a module that prompts the user to enter input data, reads the data and then checks the validity of the data, since all three actions contribute to the specific task of reading the input data, On the other hand, a module that sorts names in alphabetic order and then searches far the presence of the name “Brown” is performing two specific tasks. This module would be very complex and would make the module less cohesive, It would be better to separate the tasks and write one module to sort the names and another module to search for the name. Terminology for Modules: Different pro: lat re ramming lang mnt names for modules in a program, In some wes, such as Pascal, they are referred to as fimtetions and procedures. In C, they are erred t0 as fionetiony. Other languages may refer to them as subroutines or methods. When writing algorithms, modules are referred t0 as stb-algorichnss ages use dif Steps in Modularisation 1. Define the problem, 2. Prom the processing section, identify the tasks that will determine the modules that will make up the program, Each non-trivial task should constitute a module. 3. Construct a hierarchy chart showing the modules and the relationship between them, 4 the algorithm for the main module in either pseudocode or Nowehart, The main algorithm should include the initialization of variables used in main, appropriate logic to call cach module in the correct sequence to perform their various tasks, and the printing of results, if the printing is straightforward, 5. Develop sub-algorithms for each module, including any parameters that may be passed to and from the modules, 6. Test the algorithm for corre tw check if the logic is correct ss. Trace the main a ithm and each module separately 74, — Representing Modules in Pseudocode and Flowehart Representing a modular solution in pseudocode is similar to what we did before when we were writing algorithms in Chapter 4. The only diffe rithm, we ‘write a main algorithm as well as an algorithm for each sub-problem or module, The algorithm for cach sub-problem is called a suh-algorithm. Each module will issue a eall to (invoke) the module subordinate to it when a particular task is to be performed. The last statement in the subordinate module is Return, indicating that the program is not ending. being returned to the calling module, The main module is the only one that terminates with a Stop or End statement, This will be illustrated in the pseudocode below. The following is the pseudocode solution for the test-scores problem in problem 3 ence is that instead of writi but instead, comirol is Algorithm Test Score Analysis This algorithm read test scores and finds the highest, the lowest and the average test score. This is the main algorithm, Call Read Data, Call Highest call module to find highest score} Call Lowest tnext, call module to find lowest score Call Average teal! module 10 compute average} Print high, low. aver Stop. Sub_Algorithm Read_ Data This module reads and validate test scores and stores them in an array called scores. itol Read test-score While there is data do the following: If (test-score > 100 OR test-seore < 0) then {check if the data is valid) Display “Error Message: invalid data” else Seoresfi] € test-score —fsvore each vatid data value in the array} End-if Incr Read test-seore End-while Size © i Return venti fadvance to the next location in the array Sub-Algorithm Highest This module searches a list t0 find the highest test score Set index to 2 Set high to scores] {assume the first value in the array iv the highest, initially} While (index < Size) do If (scoresfindex] > high) then High € scores{index} End-if Index € index + 1 Fnd-while Return high frenwn the result to the calling module} Sub-Algorithm Average This algorithm finds the average test score Set sum to 0 Setito | While (1 <> size) do the following: sum € sum +scoresfi] _{ compute the sum of the scores | i€i+l end-while average € sum + size return average {return average to the main program where it will be printed} The pseudocode for the sub-algorithm Lowest is similar to that of Highest, except that we test for seores less than fow In the Flowehart representation of a modular solution, we draw a separate flowchart for each module. The Moweharting symbol for a sub-algorithm is a rectangle with a bar across the top. Phat is fF As in the pseudocode representation, the sub-algorithms terminate with a return statement, The symbol is similar to the StarvStop symbol, The flowchart representation for the problem above is shown helow MAIN MODULE READ DATA MODULE (san (sm) TT TT Y i > | a, Set Size Wi Red score Rerum Notice how straightforward the main algorithm is. The flowchart versions of the remaining modules are left ay exercises for the reader. Can you imagine how complex the flowchart would be if we attempt to solve this problem without modularization? 7.5. Communication between Modules Modules may be written as separate independent entities, meaning that no variables are shared between the main module and the sub-algorithm, However, there are many instances when it is necessary to share information among modules in a program. There are several mechanisms to facilitate information flow between modules. These include: + Global variables ©The passing of parameters Global variables constitute data that is declared in the main program and can be used or accessed by all the modules of the program, This is an easy way to share data among the modules, however, because every module in the program have access to and can change global variables, undesirable consequences can result, if they are not used properly Parameters are data items that are passed as input to the culled module by the calling module Values may also be transferred back to the calling module from the called module upon completion of its task. NOTE: The use of global variables and parameter passing are outside the scope of this course. Students will therefore not be required to implement these concepts in their programming problems. All that is required at this stage is for them to he able to apply the top-down design approach to complex problems. That is, take a complex problem, decompose it into relevant modules construct a hierarchy chart and develop the algorithm for the individual modules. 7.6. Advanta es of the Top-Down Design Method 1, It makes the problem solution more manageable. It is easier to comprehend the solution of a smaller and less complicated problem than to grasp the solution of a large and complex problem. 2. This easier to test segments of solutions, rather than the entire solution at once. This method allows one to test the solution of exch sub-problem separately until the entire solution has been tested. It is often possible to simplity the logival steps of each sub-problem, so that when taken asa whole, the entire solution has less complex logic and hence easier to develop, A simplified solution takes less time 10 develop and will be more readable. ae The progeam will be easier to maintain Chapter 8 FROM ALGORITHMS TO PASCAL PROGRAMS A GUIDE TO PROGRAM IMPLEMENTATION. The hardest part of programming is now over. This is where the fan begins 8.0, Introduct on The final phase in the development of a program is the Program Implementation phase. This phase involves: Step I Translate the algorithm into a specific prog: Step 2: Execute the program on the computer Step 3: Maintain the program. amming language, Recap: Let us refresh our memory on what we have done so far. Given a problem, we first tried to get an understanding of what was required. We did this by constructi proceeded to outline a solution for the problem, Then, we looked at alternative ways of solving the problem. Afier refining and evaluating our solutions, we chose the most efficient solution and then proceeded to represent that solution in the form of pseudocode or flowchart. Having produced an algorithm, we tested it for comectness by tracing through the logie with different sets of test data. IY any errors were found, we corrected the errors, a defini Having done all that, we now have a working solution and are ready to execute it on the computer. The hardest part of programming is now over. Now the fun begins, This is where we speak directly to the computer and tell it to execute our instructions and produce our expected results. In order to exccute it on the computer, we have to first translate our algorithm into a Ianguage that is meaningful to the computer. The next section will illustrate how this is done. & Translate the Algorithm into a Specific Programming Language Vranslati language is like Jearniny Langu it ina different ta an algorithm into a programmit age. We know what we want to say (via the algorithm), we just have to find out how to say Once we learn how to communicate in a computer language, all we how to speak a foreign have to do is take our algorithm and sequentially translate cach instruction into the programming language. This produces 4 computer program that we can then execute on the computer, Picee of cake isn tit! The programming language chosen for this course is Pascal, Why Pascal’? It's simple, that’s, why. but there’s more fo it than that. Pascal was designed by Professor Nicklaus Wirth in 1968. Ih was specitfical ed as.a tool to te language for bey des ch programming to beginners. Pascal is a re nner programmers because 60 (i) tis well-structured. ii) [is easy to implement Gili) The syntax (grammar) is easy to learn and follow iv) Itencourages the programmer to adopt a disciplined approach to programming. Some may argue that Pascal is not the language of choice in many real-world programming environments today. While this may be true, it cannot be used as a valid argument for teaching other languages such ay CC in this particular course. This is an introductory programming course. Upon completion of this course, students are not expected to become fully competent programmers who are ready to be employed as professional programmers, Before we translate our algorithm into Pascal, we have to first leam the structure and syntax of the language. By syntax, we mean the rules of the language that govern the grammatical issues such as the vocabulary, word placement and punctuation, Since Pascal is a language for communicating with a computer, the rules are somewhat different from those of human- interaction languages such as English or French, For example, there is a limit on the number of characters that « Pascal word ean have. Just as most languages have certain variants, called dialects, so does the Pascal lai version approved by the International Standard Organization (ISO) is referred to as Pascal. Other variants inelude Turbo Pascal and Think Pascal, In this course, only st Pascal will be used. The syntax of the language must be strictly adhered to when writing program code. 8.2. Structure of a Paseal Program A Pascal program hats three distinet parts the program heading the program block the program terminator (a period), The program heading is a single statement beginning with the word program. The heading assigns « name to the program and lists the input and output streams in parentheses. The program block is the body of the program. It consists of the Pascal statements for executing the algorithm, The block is divided into wo distinet parts: 1. the variable declaration seetion where all the variables and data structures used by the program are delined, 2 the statement section is where all the action statements of the prog statement section is encapsulated within begin and end statements ram are specified. The Begin and end are examples of keywords used in Pascal. Keywords (or reserved words) are words that have special meaning in Paseal and can only be used in the predefined context. That is, they cannot be used as variable names or in any other context. Other keywords are: program, type, var, const, read, write, readin, write In, 61 Refer to any Pascal textbook for a list of all Pascal reserved words. Pascal Program Template Program name (inp, ouput) Definition Variable declaration section. label declarations const definitions type definitions procedure/finetion declaration {Main Program} begin statement: statement; statement: end. The keywords are highlighted in bold, Not all the categories need appear in any given program For example, in this course we are not concerned with the implementation of modules, so the procedure and function declarations can be ignored for now. 8.3. Pascal Syntay ina Nutshell Declaring Variables Variables must always be declared in the variable declaration section prior to their use in the program, Variables are declared in Pascal by specifying the keyword var followed by a list of variables, a semi-colon and the data type. For example. var pum]: integer average: real: Data Types \ data type isa collection of elements that are all formed and treated the same way. For example integers, real numbers, characters, Boolea types. Pasca keywords to identify’ the various data types. strings are all d uses the followin Data Type Keyword Integer integer Real real Character char string, Surin, * Non-standard Boolean [boolean 2 Pascal is referred to as a strongly typed langua: store values of one type, A variable must be declared with a single data type a ype that was dee! ze because it requires that & variable ean only id the mixing of red can be stored in the data types is not allowed. That is, only values of the variable Uver identifiers are names crea mmer, These include variable names, the program name, names of symbolic constants or names of sub-programs. The rules governing user identifiers in Standard Pascal are as follows: + an identifier must start with an alphabetic character (upper or lower case) + it can be composed of only alphabetic characters or a mixture of alphabetic and numeric characters, commonly called alphanumeric = No special characters are allowed (like &, 4 ter. ted by the prog: Some variants of Pascal allow the underscore ch + The identifier may be of any length, but standard Pascal only recognizes the first 8 chatacters to determine uniqueness. Examples of valid user identifiers are: temp, value Number of ltems, X, X + Reserved words or Pascal keywords cannot he used as identifiers = Pascal is NOT case-sensitive, Therefore, there is no distinction between the identifiers Number and number, for example. They are considered to be the same. Punctuation: Every Paseal statement (except begin) is terminated by a semi-colon, The last statement in the program (that is, the end statement) is terminated by a period, The Assignment Symbol: In Paseal the assignm symbol is “:=", This corresponds to the “€ “in our pseudocode, Begin aid end delimiters: The begin/end keyword pair is used to delimit the body of the program as well as logical blocks within the program. For example, when multiple statements are to be executed within a while loop, such statements are encapsulated within a begin/end pair. For every begin in a program, there must be a corresponding end statement. Comment Comments are used to document a program internally, to aid in the understanding of the program statements and sements. Comments in Pascal are enclosed within curly braces {....}. Comments are ignored by the Paseal compiler. ‘That is, they do not affect the logic of the program or the syntax in any way. They are only there to allow the programmer to make notations about the The best way to learn any programming language is to look at a simple program and note the common features. Let us take one of the algorithms we developed in previous chapters and see how it translates into Pascal 8.4. Translating Pseudocode into Pascal Code The first step in translating an algorithm into Pascal code is to make @ list of all the variables used in the algorithm and determine their type. That is, the type of values that each variable is to store. In the algorithms, we were not 00 concerned ahout the types of variables we used, so we did not explicitly declare them in the algorithms. However, most programming languages require that variables be declared explicitly before they are used The nest step is to translate each statement in the algorithm into its Pascal equivalent. We will now illustrate how this is done. We will use the algorithm for calculating the average of three numbers for our first illustration, Translation of the Average Problem: The first step is to list all the variables and their types. There are three variables in this algorithm, um, nun? andl nun. They are all of integer-type. Pseudocade Paseal © Program Average (input, output); Algorithm Averagi {This algorithm finds the average of three This algovithm finds the average of three numbers} numbers var Start num, num2, num3: int get num. num2, num Average € (num + num2 + num3)= 3 | readin (numt, num2. Display “The average is", average average = (num | +num Stop. writeln (The avera Wwe iss", average): Lo Notice the close correspondence between the pseudocode version sind that of the Pascal version Both solutions have a header. a body and a terminator, The start/stop pair in the algorithm translates into begin’end in Pascal. The format of the statements in the algorithm has a direct relation with that of the Pascal code. This makes translation fairly easy, All we have to do is took at each statement in the pseudocode and ask, “how can F sav this in Paseat?” We can illustrate this step by step as follows = What is the format of the header in Pascal? 64 Every Paseal program begins with the keyword program, followed by the name of the program and the input/output streams in parentheses. Our algorithm is called Averawe, so we can use the same name for the program to get program Average (input, output); * A glance at the Pascal template will show that the next step is to declare our variables. In our algorithm, we did not declare all the variables. However, we must do so in the Pascal program, + What is the equivalent of “start” in Paseal? Answer: Begin. So we write begin in our progr = Vext, how do we inpua (read) values in Pascal? Answer: use read or readin. So we look up the format of the read/readin write that in our program, + How do we perform arithmetic operations in Pascal? Answer: The arithmetic operators in Pascal are pretty similar to those in mathematics, with a few exceptions — multiplication is the asterisk (*) and division is the slash () + What is the assignment symbol in Pascal? Juswer: ‘The symbol is “=:" So now all we have to do is rewrite the assignment statement, using the Pascal constructs. That is, average == (num|+num2+num3)/3: + How do we display resulis’messages tn Pascal? Answer: we use the write or writeln statement. Just like we did for the read statement, we look up the format of the write writeln statement + Finally. how do we end a Pascal program? Insiwer: by the keyword, “end” followed by a period. fement and Just like that we have translated our algorithm into a Paseal program. Note that the pseudocode version of the pre pre gorithm was not designed to correlate with the Pascal pgramming language in particular. This algorithm is easily translatable into any structured ygramming language. That is why it is very important to write algorithms that are well- structured, This makes translation much easier Let us look at another example. To illustrate a few more Pascal constructs, we will use the algorithm developed in Chapter 2 for counting the number of integers that are larger than the first The variables used in the program are: count, No-of-Values, first-number, next-number. The Variables are all of integer type. Standard Pascal does not allow special characters in variable names, so we will remove the hyphen from the names and replace as follows: NoOfValues, firstNumber, nextNumber 80) and (testscore <= 100) then Lettergrade = °A" if (lestscore < 80) and (testscore > 70) then. Lettergrade = "B’: else stscore < 70 and (testscore >= 60) then Lotteryrade == °C"; Lettergrade > “D* writeln (testscore, lettergrade end: Jif test score is invalid} readin ( testscore); cond: Jend of while loop { end, fend program | Points to Note in this Example: In the nested if statements all the matchit The variable fesascore is else's are in line with the corresponding ifs not hyphenated as in the algorithm. * Compound statements are enclosed within begin’end blocks The symbol for “not equral” is The format of the # and while statements closely resembles that of the algorithm, That's ‘okay. This format is used by many other languages. including English: it is not peculiar tw Paseal 85, Summary The above treatment of the Pascal pr is not intended to be viewed as “all ne needs to know about the programming language”. This was a mere overview of the basic tures of the language to facilitate an illustration of the algorithm translation process. There are many other Pascal constructs that the student needs to lear, For example, how 1 represent arrays in Pascal as well as various other syntax rules. The reader is advised to refer to texts on (ment of the syntax of the language, Several the Pascal language to gain a comprehensive tn such texts are recommended in Appendix B. 68 Chapter 9 PROGRAM EXECUTION ON THE COMPUTER 9.0, Steps in Executing Program on the Computer: create source code 1 2. compile source program 3. Tink the modules 4. run (execute) program maintain program. 12 the source code involves the translation of the algorithm into a programming ze. This process should first be done manually on paper. The resulting Pascal program is then entered into the computer using a suitable text editor. Most language compilers provide their own editing features. The source code (as it is now called) is then stored in a file with the appropriate extension. Most Paseal compilers use the .pas extension. At the completion of this process, we should have @ complete Pascal program, ready for compilation Student interaction with the computer begins at this s the student te interact with the c ¢. Up until now, there is no need for mputer for the purpose of programming. The algorithm must nd tested, then translated into a programming language on paper, before they first be developed 20 on the computer There is nothing to be gained by introducing beginner programmers to the compiler on the computer before they learn how 10 develop and translate algorithms into a programming language. It is simply a waste of time and computer resources Compiling the source cade is the process of translating the souree code into object code, Object code is the machine langage equivalent of the source code. During the compilation process the syntax of the source code is checked to ensure conformity with the rules of the language. If syntax errors are found, these are reported. Syntax errors result in incomplete compilation. The errors must be correeted and the program must be re-compiled. This process is repeated until the code is free of syntax errors. A common misconception is that the sole purpose of the compiler is to check For errors. While this may be a resultant function, the primary purpose of the compiler is to tanslate the soure: code into object code, Most compilers do perform error detection during the translation process inking the Modules: A compiled abject program is not ex modules to f module éy done by a link editor or link-loader. The resulting executable module is then loaded into memory where it ean then be executed. tutable by itself. It needs to be combined with other system an executable image that can be loaded into memory. The process of linking the ) Appendix A PROGRAMMING EXERCISES For each of the following problems: deine the problem «design a solution algorithm in pseudocode or flowchart trace the solution using two valid test cases Examples of Algorithms Using only Sequential Statements: I A program is required to read a VAT rate as a percentage and the prices of five items The program should calculate the total price of the items before tax and then the VAT payable on those items. The VAT payable is computed by applying the VAT rate percentage to the total price, Both the total price before tax and the VAT payable are to be printed as output, (47 = value-added tar) 2. A sales company pays its employees strictly on a commission from sales, The input data consists of the employee's ID (a 4-digit number), followed by the amounts of each sale that the employee made within the past week. There are a total of 60 employees. The commission rate is 3.45 percent. Design a program that reads and adds up the sales total for each employee and compute the commission for each employee. Examples of Algorithms using Sequential and Selection Statements: 3. Design an algorithm that will receive the weight of a parcel in kilograms and determine the delivery charge for that parcel. Calculate the charges as follows: Parcel Weight (kg) Cost Per Kilogram (5) <2.Sky 3.60 per ku 2.85 per ki 2.45 per ke 4. Construct an algorithm that accepts three integers and report which of them are positive. Your output should be in the form of a single sentence. For example, “The first and third numbers are positive Examples of Menu-Driven Programs: 5. Construct an algorithm that will read two integers and an alphabetic code (A. B.C or D) from the keyboard, If the code entered is “A”, compute the sum of the two numbers. If the code is “B’, compute the difference (first ninus second) of the two numbers, If the code is C. compute the product of the two numbers. If the code is *D*. and the second number is non-zero. compute the quotient (first divided hy second). The pros display the two numbers, the code and the computed result jam is to then 4 6 Write an algorithm that allows the user to convert measurements from either feet to metres. or minutes to hours, or degrees Fahrenheit to degrees Celsius. Design the algorithm so that it displays a menu of options and allow the user to select one of the options, depending on what conversion he/she requires, The available options are: Display this menu I 2. Convert minutes to hours 3. Comvert feet to metres 4. Convert Fahrenheit to Centigrade 5. Quit. Use the following conversion table: J foot = 0.3048 metre Celsius = S/9¢F — 32) 60 minutes = T hour Examples of Algorithms using Sequential, Selection and Repetition Statements A program is required to print all the even numbers between 1 and 50. \ program is required to read a list of students’ test scores and print the IDs of all Students who failed. A student is deemed to have failed if his/her test score fall below fly pereent (50%). Each record in the input list consists of the student's ID, followed by his test score. The last record in the list contains an ID of 0. This is to be used as the sentinel value Examples of Programs using Arrays 9. Write an algorithm that reads a list of numbers and reduces each value in the list by 3. Print the values in the modified list, A value of 999 marks the end of the list. 10, A program is required to read a list of names and ages of contestants in a beauty pageant, and print the names of all the eligible contestants. A contestant is deemed eligible if she is less than 25 years old. Print also the names of the contestants who are younger than 18 yeurs. There are 50 contestants in the list. “Zine: store the names and ages in separate arrays Examples of Modular Programming Draw the hierarchy chart Jor each of the problems below Write a program that reads a list of integers, representing students” test scores, ranging from 0 10 100, Your program should compute and print the range of test scores. The range is defined as the difference between the highest and the lowest test scores,

You might also like