Professional Documents
Culture Documents
Disclaimer
While every effort has been made to ensure that the information contained in this courseware is free from errors and omissions and is not misleading in any way, Computer Power (NZ) Limited makes no representations or warranties and is not liable for any loss or damage or injury of any kind (however caused) under any theory of law including negligence resulting from or in any way connected with the use of this courseware.
Copyright 2011
This courseware and the concepts, information and material contained in it are the copyright of Computer Power (NZ) Limited, a Private Training Establishment (PTE) No. 8488 and may not be used or reproduced in whole or in part without the prior written consent of Computer Power (NZ) Ltd. All rights reserved. Edition Released: Publication No.: January 2011 PDCLGA001b
Table of Contents
CONTENTS
SECTION 1: PROGRAM DEVELOPMENT ................................................................1-1 Topic 1: The Systems Development Life Cycle ..................................................1-2 Topic 2: The Importance of Standards ...............................................................1-6 Topic 3: The Program Development Routine .....................................................1-9 Topic 4: The Concept of Structured Programming .............................................1-12 Topic 5: An Introduction to Algorithms ...............................................................1-15 Self Test ............................................................................................................1-17 Self Test Answers ..............................................................................................1-21 Activity Solutions................................................................................................1-23 SECTION 2: DEFINING THE PROBLEM AND PRESENTING THE SOLUTION .......2-1 Topic 1: Problem Definition and Analysis ...........................................................2-2 Topic 2: Data .....................................................................................................2-4 Topic 3: What is Pseudocode? ..........................................................................2-6 Topic 4: Pseudocode and Basic Computer Operations ......................................2-7 Topic 5: Pseudocode and the Structure Theorem ..............................................2-11 Topic 6: Using a Flowchart to Represent an Algorithm ......................................2-15 Self Test ............................................................................................................2-24 Self Test Answers ..............................................................................................2-28 Activity Solutions................................................................................................2-32 SECTION 3: SEQUENCE CONTROL STRUCTURES ...............................................3-1 Topic 1: Applying the First Steps of the PDR to a Problem Involving the Sequence Control Structure .........................................................................3-2 Topic 2: Writing a Solution Algorithm Involving the Sequence Control Structure................................................................................................3-10 Topic 3: Desk-checking a Solution Algorithm Involving the Sequence Control Structure................................................................................................3-14 Checkpoint 1 .....................................................................................................3-20 Activity Solutions ...............................................................................................3-33
Table of Contents
SECTION 4: SELECTION CONTROL STRUCTURES .............................................. 4-1 Topic 1: Boolean Expressions ........................................................................... 4-2 Topic 2: Variations of the Selection Control Structure ....................................... 4-9 Topic 3: Algorithms Using the Selection Control Structure ................................ 4-15 Topic 4: The Case Control Structure ................................................................. 4-26 Checkpoint 2 ..................................................................................................... 4-31 Activity Solutions .............................................................................................. 4-46 SECTION 5: REPETITION CONTROL STRUCTURES ............................................. 5-1 Topic 1: Repetition Using the While .. EndWhile Control Structure.................... 5-2 Topic 2: Repetition Using the Repeat .. Until Control Structure ......................... 5-10 Topic 3: Fixed-number Repetition Using the For .. EndFor Control Structure .... 5-13 Topic 4: Using Repetition for Processing Arrays ............................................... 5-16 Checkpoint 3 ..................................................................................................... 5-22 Activity Solutions .............................................................................................. 5-25 SECTION 6: MODULARISATION ............................................................................. 6-1 Topic 1: The Concept of Modularisation ............................................................ 6-2 Topic 2: VTOC Diagrams in Modular Programs ................................................ 6-4 Topic 3: Steps in Modularisation ....................................................................... 6-10 SECTION 7: OBJECT ORIENTED AND EVENT DRIVEN ALGORITHMS ................ 7-1 Topic 1: Object-Oriented Algorithms ................................................................. 7-2 Topic 2: Event Driven Algorithms ...................................................................... 7-17 Checkpoint 4 ..................................................................................................... 7-18 Activity Solutions ............................................................................................... 7-20
APPENDIX A: GENERAL ALGORITHM EXAMPLES ............................................... A-1 APPENDIX B: CHECKPOINTS FOR INSTRUCTOR SIGN OFF ............................... B-1 APPENDIX C: GLOSSARY ....................................................................................... C-1
ii
Introduction
INTRODUCTION
Programming can be defined as the development of a solution to an identified problem, and the setting up of a series of instructions that will implement this solution. This series of instructions is referred to as the computer program The blueprint or plan for a computer program is known as an algorithm, and can be written and represented in a variety of ways. In Program Design Concepts (PDC) you will learn how to produce an algorithm in pseudocode. Pseudocode uses normal English words to produce a programming look-alike language. Pseudocode literally means false code. Modern software solutions use three basic software design techniques: Structured programming is a general term referring to a set of techniques that produces programs with clean flow, clear design, and a hierarchical modular structure. Object oriented programming uses the concept of abstraction to design objects to model real world situations. The objects generally define the data used in the application and the actions to be performed on this data. Structured programming is used with these actions or functions to provide the actual instructions in the application to manipulate the objects. Event driven programming uses both of these elements and produces applications that respond to events rather than simply running from beginning to end. By the end of this course, you will be able to write and test algorithms in pseudocode for structured, object oriented and event driven applications for a variety of problems for which computer solutions are suitable.
Course objectives
On successful completion of this course, you will be able to:
Understand the principles of Structured Programming, Object Oriented Programming and Event Driven programming techniques Use pseudocode to represent the six basic operations of a computer Analyse and define problems that require the processing of input data to produce output Apply the three basic control structures of Sequence, Selection and Repetition in writing a solution algorithm in pseudocode Test an algorithm for correctness Apply modular design principles Use elementary data types (integer, real, character and Boolean), data structures (record, file, array, string) and objects (classes) in simple examples Use the Program Development Routine as an example of a company standard Understand how to develop algorithms for structured, object oriented and event driven programs.
PDCLGA001b
iii
Introduction
Assessment
Four check points for instructor sign off, all of which must be completed before doing a Minitest. Minitest (using Flash Quiz) - This is marked but does not count toward final assessment. Theory Examination (using Flash Quiz) of 90 minutes duration, contributing 100% to the course mark.
Resources
Program Design Concepts learning guide The Program Development Routine reference manual (PDCLGA001) (PDRRBA002)
Prerequisites
None.
iv
PDCLGA001b
Introduction
HELPFUL INFORMATION
Learning guide layout
This Learning Guide contains different types of study materials as indicated by the following icons.
Reading icon
This icon indicates that you need to read and study the topic. You may also be directed to study Sections of associated reference materials.
Activity icon
When you see this icon, you have the opportunity to experiment with the features previously described by completing a practical exercise.
Timer icon
This icon indicates an estimated study time for a topic.
PDCLGA001b
Introduction
STUDY PLAN
The student plan provided below is a helpful tool in making sure that you complete this course in the time provided. Please be aware that the student plan is based on 5 hours study per day at the institute and that you should be completing at least two hours revision at home.
Day Reference (S = section T = topic) S1 T1 S1 T2 S1 T3 S1 T4 S1 T5 S1 Self Test S2 T1 S2 T2 S2 T3 S2 T4 S2 T5 S2 T6 S2 Self Test 2 S3 T1 Total Time Applying the First Steps of the PDR to a Problem Involving the Sequence Control Structure Writing a Solution Algorithm Involving the Sequence Control Structure Desk checking a Solution Algorithm Involving the Sequence Control Structure Total Time 3 S4 T1 S4 T2 S4 T3 S4 T4 Checkpoint 2 4 Checkpoint 2 S5 T1 S5 T2 S5 T3 S5 T4 Total Time Repetition Using the While End While Control Structure Repetition Using the Repeat Until Control Structure Fixed-number Repetition Using the For EndFor Control Structure Using Repetition for Processing Boolean Expressions Variations of the Selection Control Structure Algorithms Using the Selection Control Structure The Case Control Structure Total Time Topic Subject Time (mins) 20 20 15 10 10 45 120 10 10 5 15 20 60 60 180 60 Dates I will study this content
Date completed
The Systems Development Life Cycle The Importance of Standards The Program Development Routine The Concept of Structured Programming An Introduction to Algorithms Total Time Problem Definition and Analysis Data What is Pseudocode? Pseudocode and Basic Computer Operations Pseudocode and the Structure Theorem Using a Flowchart to Represent an Algorithm
S3 T2
45
S3 T3
45
Checkpoint 1
vi
PDCLGA001b
Introduction
Arrays Checkpoint 3 Total Time 5 Checkpoint 3 S6 T1 S6 T2 S6 T3 S7 T1 S7 T2 6 Checkpoint 4 Total Time The Concept of Modularisation VTOC Diagram in Modular Programs Steps in Modularisation Total Time Object oriented Algorithms Event Driven Algorithms Total Time Total Time 1 Mini Assessment nd 2 Mini Assessment Final Assessment
st
PDCLGA001b
vii
Introduction
viii
PDCLGA001b
1.0
OBJECTIVES
1. 2. 3. 4. 5.
120 mins
On successful completion of this section, you will be able to: Describe the Systems Development Life Cycle Identify the steps in the Program Development Routine Use the Program Development Routine as a standard Explain the concept of Structured Programming Understand a simple Algorithm
TOPICS
1. 2. 3. 4. 5. The Systems Development Life Cycle The Importance of Standards The Program Development Routine The Concept of Structured Programming An Introduction to Algorithms
PDCLGA001b
1-1
NOTE: The actual programming activities play a very small part in the total work.
Fact finding (User & Analyst) Problem Definition (Analyst) Initial analysis (Analyst) (Analyst)
Strategic Plan
Production of diagrams for the problem (Analyst) Logical design (Analyst) Physical design (Designer) Algorithm (Programmer) Coding (Programmer) Code testing (Programmer) System commissioning (Analyst or others) System testing (Analyst or others) System installation (Analyst or others) User Training (Analyst or others) Cut-over from current system (Analyst or others)
1-2
PDCLGA001b
As seen in Figure 1-1, the system development and implementation activities are Stages 3 and 4 in the SDLC. These are the sequence of events to be followed to build the actual software to be used in the computer system. They require a collaborative effort on the part of the people who want to use the system (users) and the computer specialists. This is a repetitive process due to the fact that the customer is rarely completely satisfied with what is initially suggested by the computer specialists. Modifications and enhancements are likely to be requested, even during initial discussions, as well as after the system has been fully implemented (Stage 5 in Figure 1-1). For this reason, each stage is a cycle in its own right, undergoing repetition until everyone agrees, or accepts a compromise, in order to progress. If the analysis and design activities (Stage 1 and 2 in Figure 1-2) are completed thoroughly, then the rest of the work should be no more difficult than, say, performing a well-written piece of music. In real world projects a solution which matches all of the requirements set by the client may never be fully achieved to the satisfaction of that client. The attempt is much easier if what has to be done in the solution is clearly and accurately defined. NOTE: The importance of the analysis and design stages cannot be overemphasised. Any errors or omissions at these stages are amplified later and become increasingly difficult to correct. In smaller software development houses the programmer or developer may take on more of the analysis and design tasks and may be involved in more direct client interaction during the requirements analysis process. The length of the systems life depends upon the nature and volatility of the business. Eventually, these will reduce the effectiveness of the system, no matter how well it initially fulfilled its purpose. As a result, the whole cycle of activities that were performed to implement the system may have to be repeated in order to modify it. This can happen several times until eventually, the basis of a system that has been changed or enhanced several times is no longer sound enough to allow it to be modified further, so a completely new system is implemented to replace it. The whole process starts again, which is why we refer this iterative process as a cycle. This cyclical process is illustrated in Figure 1-2 Description of a Systems Life Cycle, which gives a more detailed view of Figure 1-1.
New Terms
You may be already encountering new terms or computer jargon, which at this stage can be expected. Dont be put off by this gap in your knowledge. Be assured that as you make progress in this module you will soon become familiar with these terms. For help, consult the comprehensive Glossary of Terms at the end of this Learning Guide.
PDCLGA001b
1-3
Start
STAGE 1
INITIATION STAGE
Investigation and Feasibility Study. Analyse the current situation to come to an appreciation of the problem, the causes and the circumstances. Define the problem. Identify and analyse the various options of dealing with the problem. Evaluate each for feasibility, cost and potential benefit. Select two or three of the most advantageous options and evaluate the cost-benefit balance of each. Remember one option is to do nothing.
NO
STAGE 2
Detailed Analysis and Design. Choose the course of action and plan the implementation in detail. Establish time lines, mile-stones, budget and administrative requirements, and standards for required quality of the solution elements. Review all costs and benefits.
NO
YES
STAGE 3
DEVELOPMENT STAGE
Develop and build the solution or construct the means to solve the problem. Evaluate your progress against the planned time lines, mile-stones, budget and quality standards at regular intervals. Develop the ancillary aspects of the solution such as the documentation and training. Review quality outcome.
1-4
PDCLGA001b
NO
STAGE 4
Plan the actual implementation of the solution to ensure a smooth transition. Consult constantly with all involved to ensure suitable support is provided. Remember that change can easily be viewed as threatening. Conduct a post implementation review.
NO
STAGE 5
YES
NO
End
Figure 1-2 - (Part 2 of 2). Description of a Systems Life Cycle
PDCLGA001b
1-5
What is a Standard?
The word standard is used frequently in everyday speech and most often in an imprecise manner, such as Thats fairly standard for the time of year or standard English. However, as a published specification, a Standard has a very precise meaning. The following definition best describes a contemporary Standard. A Standard is a published document that sets out specifications and procedures designed to ensure that a material, product, method or service is fit for its purpose, and consistently performs the way it was intended to. So Standards are vehicles of communication for producers and users. They establish a common language, which defines quality and establishes safety criteria. Costs are lower if procedures are standardized; training is also simplified. Consumers accept products more readily when they can be judged on intrinsic merit.
Order Traffic lights are a simple, global example of the benefits of standardization. Red means stop, amber means caution, green means go. It is the same all around the world. But imagine the effect if the colours were optional.
1-6
PDCLGA001b
Conformity Why does a nut made in Melbourne fit a bolt made in Birmingham? We take it for granted, but it is because international Standards exist, precisely defining the screw and thread sizes. Convenience Consider your computers keyboard. In the early days of typewriters, a host of variations existed, but the QWERTY format, based entirely on technical considerations, soon became standard. Imagine the effect if keyboards had different key configurations. Confidence Every day, millions of people step into lifts, take aeroplane flights, and work in highrise buildings. So how do they know they are safe? Because the architects and engineers who designed them work to the most rigorous engineering Standards. Ease of choice We assume a light bulb will fit a socket. Worldwide, we have just three basic choices to make when buying a light bulb: (a) standard or energy saver? (b) screw or bayonet socket? (c) what wattage? Universality The most universal of all standardized items is the USB (Universal Serial Bus) standard. Wherever you travel, to the remotest outposts of the world, you can be sure that the computer at the local Internet caf will accept the USB plug from your digital camera cable to download your holiday photos to family and friends. Electrical safety Electricity can be the most lethal commodity most of us ever handle, and we are constantly using devices powered by mains voltages. Standardization of the inherent safety characteristics of electrical systems and devices ensures a near 100% safety record.
1-7
development of programs for projects and major practical exercises that require a fully worked solution. In this way, all students who graduate with some level of programming skills will have a reliable and disciplined program development methodology. In practise there are many types of development standards and process in use. The PDR gives you the basic skills that you can build on and will stand you in good stead as you embark on your new career in the Information Technology industry.
ACTIVITY 1-1
Spend no more than 10 minutes now to skim read The Program Development Routine Reference Manual (PDR) that you were issued when you began this module. Refer to it to write answers to these questions. (Make sure you have version 2 or later of the PDR reference manual) 1. What is the Program Development Routine (PDR) for programming students at Computer Power?
2.
1 2 3 4 5 6 7 8 9 10
3. What is the definition given for an algorithm, used in a programming context?
1-8
PDCLGA001b
A purely structured approach results in the development of a program in which a hierarchy of modules is used. Each module has a single entry point and depending on the programming standards used one or more exit points. In object oriented programming the modules may represent methods or functions defined within one or more objects defined in the solution. Regardless of whether the solution is structured, event driven or object oriented, within the module only the three standard control structures are used. In a pure structured solution, control is passed down through the structure without unconditional branches to higher levels of the structure. In an object oriented solution control may pass between the methods or functions of the objects defined in the solution, there does not need to be a hierarchy, although in most cases objects will form some sort of hierarchy. In event driven programming control passes to modules in response to events occurring within the system or from user interaction. We will look at event driven and object oriented design more in section seven. When learning your first programming language it is easy to get the impression that the greatest challenge of solving a problem on a computer is the actual coding translating your ideas into the specific language that will be fed into the computer. This is not the case. The most interesting and challenging part of solving a problem on a computer is formulating the steps of the solution in plain English, as if the instructions were to be given to a human being. Leaping straight into coding without first designing a proper solution usually results in programs that contain many errors. The programmer then needs to spend a significant amount of time and money finding the errors and correcting them. A more successful approach is to design a solution to the program first and test this solution prior to coding. This is the Design Phase of program development, and the tasks associated with it will generate documents that are an important and necessary component of the development of a program. After the successful completion of the Design Phase, the program development enters the Production Phase in which the program is coded in the chosen programming language, compiled, run and tested. Documentation is updated to include any modifications that have been made to the initial Design Phase documents. The final phase is the Maintenance Phase in which the program is maintained and enhanced. At least 80% of programmer effort in most companies is in the maintenance of existing programs, not the construction of new ones. Therefore, it is important to have high quality documentation together with code that is easy to maintain. This allows the ability to test program modifications reliably otherwise a fix to remove one error could easily introduce another error.
PDCLGA001b
1-9
Just as the Systems Development Life Cycle (SDLC) has specific steps, so too does the Program Development Routine (PDR). An overview of the PDR is shown in the form of a flowchart on the next page. See Figure 1-3.
Start
Step 1
Step 2
Step 3
Step 4
Step 5
No Step 6
Yes Step 7
Create a Variables Table and Data Flow Table
Step 8
Step 9
No
Yes Step 10
Update Documentation
MAINTENANCE PHASE
Yes
No End
1-10
PRODUCTION PHASE
DESIGN PHASE
Develop VTOC
PDCLGA001b
The Sign Off points in the PDR are check points in a project where you will present your work to an Instructor for comment and/or signing to enable you to progress to the next step. Although this module, PDC, will be concerned with the details of the first six steps of the PDR (the Design Phase) and the deliverable items relevant to them, a PDC student must study and know the overview features of the PDR as outlined in The Program Development Routine Reference Book (PDRRBA002a). The next module, PC1 Programming Concepts 1 using the Java programming language, will cover all ten steps of the PDR in full. For projects in the programming modules that you do, you will be required to submit for assessment not just the final program code but also the documentation associated with the PDR, which is to be included in accordance with the projects specifications. The only exception to this will be where alternative documentation is required.
PDCLGA001b
1-11
Sequence (one step after another) Selection (choosing one pathway or another decision making) Repetition (repeating one or more steps also called iteration).
Computer scientists have shown that all possible algorithms can be expressed using just these three control structures. These are covered in detail in Section 2.
1-12
PDCLGA001b
Top-down development
A good plan of attack for designing a solution is to break down the task to be accomplished into a few big subtasks, then decompose each big subtask into smaller subtasks, and then replace the smaller subtasks by even smaller subtasks and so on. Eventually the subtasks become sufficiently small enough to allow coding. In top-down design, you first list the major sub-problems that need to be solved, and by solving each of the sub-problems you solve the original problem. In the top-down development of a program design, a general solution to the problem is outlined first. This is then broken down gradually into more detailed steps until finally the most detailed levels have been completed. It is only after this process of decomposition or stepwise refinement that the programmer can start writing the algorithm. This results in a hierarchical structure as shown in Figure 1-4.
The top-down design method produces a good algorithm in the sense that the algorithm is easy to follow, thus making subsequent modifications to it relatively easy to do. This is very important as most programs are changed at some time, and some of them are being changed constantly.
Modular design
The concept of modular design involves grouping tasks together because they all perform the same function (e.g., printing report headings). Modular design is connected directly to top-down development because the steps, or subtasks, into which the programmer breaks up the program solution, will actually form the future modules of the program. Each of these modules has only one entry point, and may have one or more exit points. NOTE: It is preferable to have only one exit point in a module for simplicity and ease of program maintenance; however code efficiency may dictate that multiple exit points are more desirable in some circumstances. In some cases this will be dictated by the preference of the developer, in others the software standards used by an organisation. Be aware you will find examples of code in your later programming modules where either method is used. Within this learning guide only single exit points from modules will be used.
PDCLGA001b
1-13
Remember however you program, good modular design assists in the reading and understanding of the program. The concepts of top-down development and modular design are developed further in section six. Object oriented design alters the process slightly and is covered in section seven.
1-14
PDCLGA001b
What is an algorithm?
The word algorithm has a long history, but since computer programming has come into prominence, its meaning has taken on a new significance. The word itself comes from the name of the ninth-century Arabic mathematician and astronomer Al-Khawarizmi, who wrote a famous textbook on the manipulation of numbers and equations. Today the word algorithm refers to a set of instructions. The instructions to program a VCR to record your favourite program when you are not at home, is like an algorithm. To qualify as an algorithm, a set of instructions must specify the steps to be taken and must give the order in which they are to be performed. Moreover, the instructions must be completely and unambiguously specified. They cannot rely on any intelligence on the part of the person or machine that will be following them. The follower of an algorithm does exactly what the algorithm says definitely no more and no less. An algorithm is like a recipe. It lists the steps involved in accomplishing a task. It can be defined in programming terms as a set of detailed, unambiguous and ordered instructions developed to describe the processes necessary to produce the desired output from a given input. A computer program can be viewed as an elaborate algorithm. An algorithm must
be clear, precise and unambiguous give the correct solution in all cases eventually end.
For example, if you want to instruct someone to use a calculator to add up the prices of items in a shopping trolley, you might write an algorithm like the following shown in Figure 1-5.
Add up Items Turn on calculator Repeat the following instructions Key in dollar amount Key in decimal point Key in cents amount Press the addition key Until all prices have been entered Press equals button Write down total price Turn off calculator End
Figure 1-5. A Sample Algorithm
PDCLGA001b
1-15
The first line of the algorithm is its name, and the last line declares the end. All the lines between these two are indented. The use of indentation is a very important way of highlighting different parts of the logic, and therefore assist readability and understanding. It is expected that algorithms will be typed on a word processor, and it is standard practice to use 3 spaces for indenting in a consistent manner. The easiest method is to use the tab key which can be set to provide indents of 3 spaces in many cases. In this algorithm, the first step is performed once before the repetitive process of entering the prices. After all the prices have been entered and summed by pressing the equals button, the total price can be written down and the calculator can be turned off. These final three activities are also performed only once. Notice that the steps in the repetitive process are indented, to show their subordination to the Repeat statement. This algorithm satisfies the desired list of properties. It lists all the steps in the correct order from top to bottom, in a definite and unambiguous manner, until a correct solution is reached. It then ends. In summary, the purpose of an algorithm is to represent a logical solution to a problem by means of sequence, selection and repetition control structures.
1-16
PDCLGA001b
SELF TEST
45 mins 1. What are possible consequences of not designing a complete and tested solution to a programming problem before moving into the coding phase of program development? _______________________________________________________________________ _______________________________________________________________________ _______________________________________________________________________ _______________________________________________________________________ _______________________________________________________________________ _______________________________________________________________________
2.
Rewrite the ten steps in the Program Development Routine in their correct sequence, using the random sequence in the left-hand column of Table 1-1
Random sequence Write the algorithm in Pseudocode Compile, Run and Test the program Develop a VTOC Update the Documentation Analyse the Problem Desk-check the Algorithm Convert the Algorithm into Code Create a Data Table Create a Variables Table and Data Flow Table If OOP, Model objects to be used in solution 10 1 2 3 4 5 6 7 8 9 Correct sequence
Table 1-1
3.
PDCLGA001b
1-17
4.
The Structured Theorem states that it is possible to write any computer program by using only three basic control structures. What are these control structures? _______________________________________________________________________ _______________________________________________________________________ _______________________________________________________________________ _______________________________________________________________________
5.
How are modular design and top-down development related? _______________________________________________________________________ _______________________________________________________________________ _______________________________________________________________________ _______________________________________________________________________ _______________________________________________________________________
6.
An algorithm is like a recipe with very specific steps to accomplish a task. Enter the first two properties of an algorithm below given the third one is already written in. 1. 2. 3. An algorithm must __________________________________________ An algorithm must __________________________________________ An algorithm must eventually end.
7.
Consider the process of getting up in the morning and going to work. Use the following statements to create an algorithm that simply demonstrates this process. Get dressed Have a shower Get out of bed End Wake up Leave to go to work Kiss spouse/friend/dog Dry yourself Start Have breakfast Pack lunch
1-18
PDCLGA001b
8.
Write simple algorithms to accomplish these two tasks 1. 2. Fill a cars petrol tank with unleaded petrol Set a bedside alarm clock.
In each case, you will need to make certain assumptions, like the starting and finishing points, the controls on the alarm clock, and so on. There are many variations of answers to these problems. Above all, just keep the algorithms simple. Dont be surprised if you have to make several attempts to get it right and to your satisfaction. Check it works by pretending that you are a mindless machine following instructions. Use the example algorithm in Topic 4 above (Adding up prices of items using a calculator) as a guide. Task 1: Fill a cars petrol tank with unleaded petrol. _____________________________________________________________________ _____________________________________________________________________ _____________________________________________________________________ _____________________________________________________________________ _____________________________________________________________________ _____________________________________________________________________ _____________________________________________________________________ _____________________________________________________________________ _____________________________________________________________________ _____________________________________________________________________ _____________________________________________________________________ _____________________________________________________________________ _____________________________________________________________________ _____________________________________________________________________ _____________________________________________________________________ _____________________________________________________________________ _____________________________________________________________________ _____________________________________________________________________ _____________________________________________________________________ _____________________________________________________________________
PDCLGA001b
1-19
Task 2: Set the bedside alarm clock for 6:15am. ____________________________________________________________________ ____________________________________________________________________ ____________________________________________________________________ ____________________________________________________________________ ____________________________________________________________________ ____________________________________________________________________ ____________________________________________________________________ ____________________________________________________________________ ____________________________________________________________________ ____________________________________________________________________ ____________________________________________________________________ ____________________________________________________________________ ____________________________________________________________________ ____________________________________________________________________ ____________________________________________________________________ ____________________________________________________________________ ____________________________________________________________________ ____________________________________________________________________ ____________________________________________________________________ You can check your answers by referring to the Self Test Answers at the end of this Section of the Learning Guide
1-20
PDCLGA001b
2.
4.
6.
be clear, precise and unambiguous give the correct solution in all cases eventually end.
PDCLGA001b
1-21
7.
Certain events must occur in a particular order, for example, we should get out of bed before showering and also there is no point in drying yourself prior to showering. Other events may occur in a different order without affecting the overall solution, for example, we can shower before or after having breakfast. A suggested answer is given as follows. Daily Start Wakeup Get out of Bed Have a shower Dry yourself Get dressed Have breakfast Pack lunch Kiss spouse/friend/dog Leave to go to work End
8.
Possible answer for Task 1: Fill a cars petrol tank with unleaded petrol. Fill petrol tank Stop car at petrol pump Remove car petrol cap Select unleaded nozzle Insert nozzle into petrol tank opening Squeeze nozzle on handle until tank is full Hang up nozzle in pump cradle Replace car petrol cap End
Possible answer for Task 2: Set the bedside alarm clock for 6:15am Set alarm clock Press and hold down alarm set button Press and hold time button until 0615 is displayed Release alarm set button Move switch to alarm mode End
1-22
PDCLGA001b
ACTIVITY SOLUTIONS
Activity 1-1
1. The PDR is the routine to be followed and the requirements to be met in program development work by students at Computer Power. Analyse the Problem, identifying the sub-problems If using object oriented development model object to be used in the solution Develop a VTOC, which is an outline of the solution Create a Data Table Write the Algorithm in Pseudocode Desk-check the Algorithm Create a Variables Table and Data Flow Table Convert the Algorithm into Code Compile, Run and Test the program Update the Documentation 3. In a programming context, an algorithm can be defined as a set of detailed, unambiguous and ordered instructions developed to describe the processes necessary to produce the desired output from given input.
2.
When you have finished this section, update your suggested study plan on pages vi and vii with the actual date you finished.
PDCLGA001b
1-23
1-24
PDCLGA001b
2.0
OBJECTIVES
1. 2. 3. 4. 5. 6.
180 mins
In this Section, we introduce fundamental principles for problem solving and outline the methods that we employ to teach a computer to solve problems for us.
On successful completion of this section, you will be able to: Define and analyse a problem Identify data types Use pseudocode to represent basic computer operations Apply the Structure Theorem Apply the three basic control structures using pseudocode Apply the three basic control structures using a Flowchart
TOPICS
1. 2. 3. 4. 5. 6. Problem Definition and Analysis Data What is Pseudocode? Pseudocode and Basic Computer Operations Pseudocode and the Structure Theorem Using a Flowchart to Represent an Algorithm
PDCLGA001b
2-1
Output Requirements
It may seem odd to start the analysis with the output requirements rather than the input requirements. Lets use an analogy based on a common activity. If you want to bake a cake, you cannot begin to gather the ingredients (the INPUT) until you have decided on the type of cake you want (the OUTPUT). If you want to build a shed, you cannot order the construction materials until you know exactly the type and dimensions of the shed you are going to build. In calculating the area of a farmers rectangular paddock, the output is area. So what is the input? Using our mathematics knowledge learned at school, we know that the input must be the length and width of the paddock. When determining the output requirements of a data-processing problem, the following questions need to be answered:
Where is the output to go? To the screen? To a printer? To a disk file? Should the output begin on a clear screen? On a new page? In a new file? What data must be output? How should the output be displayed? Should there be headings and where should they go? What is the most user-friendly way to present the data? What action is to be taken in the event of an error? If error messages are required, what is the most user-friendly way to present them?
2-2
PDCLGA001b
The term user-friendly as used here literally means friendly to the user. That is, it is easy for the user to read and understand. Although the term is largely self-explanatory, achieving user-friendliness in your programs is a skill that you should strive to acquire as you progress in your programming modules.
Input Requirements
If the output requirements have been carefully and completely specified, then the input requirements often follow fairly readily. In determining input requirements, the following questions will need to be answered:
What variable data will need to be input when the program runs? How will it be obtained? Via the keyboard? From a data file? Variable data is data whose value is not built into the program in advance. For example, if you want to calculate the area of a rectangular paddock, the length and width will need to be input as variable data when the program is run. What fixed data is needed? How will it be obtained? For example, the number of lines per page is fixed data. This is also called a constant. What restrictions may exist on any input data? For example, can certain values be negative? Is there a limit on the size of a particular data value?
PDCLGA001b
2-3
TOPIC 2: DATA
10 mins Programs are written to process data, so you must have a good understanding of how data is stored in a computer, and the nature and structure of this data. All data is stored in a specific and unique location of the computer memory. Each of these locations is given a name, which distinguishes it from any other memory location. The name must be unique, and it should be meaningful and descriptive of the data stored in the location. It is a bit like a seat in a cinema. The seat does not move, but different people will occupy it one at a time during different screenings of a film. Individual items of data can be grouped together into structures or objects to more easily model complex situations. Each of these is also given a unique name within the program. Data can be stored either as a variable, or as a constant. The content of a variable can change during a programs execution, for example, a variable called sum total will increase as more values are added to it. The value of a constant, on the other hand, remains fixed, for example, constant called lines per page that has been given the value 60 will keep this value throughout the program. Data within programs may be an elementary data type or a data structure.
NOTE: Elementary data types may also be referred to as fundamental data types in some languages.
Integer representing a set of whole numbers, positive or negative that is used for arithmetic operations (e.g., 5, 626, 100) Real representing a set of numbers, positive or negative, that may include values before and/or after a decimal point. These are used for arithmetic operations (e.g., 3.14159, 1.414, 2.718) Character representing the set of letters of the alphabet and numerals, plus some special characters that appear on a computer keyboard (e.g., a, s, d, 5, , &, ?). These are not used for arithmetic operations Boolean representing a control flag or switch that may contain one of two possible values true or false. This will be covered in much greater detail in Topic 1 of Section 4.
2-4
PDCLGA001b
Data Structures
A data structure is a collection of other data items. The data items that it contains are its components, which may be elementary data items or even other data structures. In a data structure, data is grouped together in a particular way, reflecting the situation with which the program is concerned. The most common data structures are:
Record a collection of data items or fields that all bear some relationship to one another, for example, a student record may contain the students number, name, address, subjects, and attendance pattern. File a collection of records. For example, a student file may contain a collection of student records. Array a data structure that is made up of a number of variables that all have the same data type and are accessed by the same name, for example, an array called scores may contain a collection of students exam scores that are all the same data type. Access to the individual items in the array is made by naming the element of the array, for example scores [3]. This will be covered in greater detail in Topic 4 of Section 5. String a collection of characters, for example, the string United Nations Organisation may represent an organisations name.
More complex data structures which model real world behaviour are known as objects. Objects are generally self contained and as well as storing variables representing the properties of the object may also contain methods or functions representing the behaviour of the object. For example a Student object would contain the variables representing the student such as number, name and address etc., but may also contain behaviours or methods for enrolling students in courses or analysing a students attendance pattern. The distinction between objects and data structures may be very clear in some programming languages with different keywords used to describe them. In others objects are simply more complex data structures. In practice you may combine fundamental data types or data structures to make new types of structures or objects in any way you like. The resulting composite item creates a new data type. For example you can create variables or constants of the record type shown above. The name you assign this item represents the individual items making up the record as a whole.
PDCLGA001b
2-5
Each set of instructions is written from top to bottom, with only one entry and one exit. Groups of statements may be formed into modules, and the group is given a name. When you write a solution algorithm, you need to keep in mind that you are writing the instructions that will eventually be performed by a computer. As such, they should be able to be easily translated into any programming language. If you use words and phrases in pseudocode that are in line with basic computer operations, then the translation from the pseudocode algorithm to a specific programming language becomes quite simple. Topic 4 will introduce the key words that are used to represent the six basic computer operations. Topic 5 will then apply the key words to the three basic control structures of sequence, selection and repetition associated with the Structure Theorem that was introduced in Section 1.
The key words are verbs and control statements which will be introduced in Topics 4 and 5.
2-6
PDCLGA001b
We will look at each of these operations in turn and introduce the pseudocode key words used to represent them. 1. A computer can receive information. When a computer is required to receive information (input) from a particular source (e.g., a terminal, a disk, or any other device), the verbs Read, Accept and Get are used in pseudocode. Read, Accept and Get are keywords used in pseudocode.
Read is used when the algorithm is to receive input from a record on a file. Get or Accept is used when the algorithm is to receive input from the keyboard.
For example, typical pseudocode instructions to receive information are: (a) (b) (c) (d) Read student name Get date of purchase Read number1, number2 Get tax code
Each example uses a single verb such as Read, followed by one or more nouns to indicate what data is to be obtained.
PDCLGA001b
2-7
2. A computer can output information. When a computer is required to supply information (output) to a device, the verbs Print, Write or Display are used in pseudocode.
Print is used when the output is to be sent to the printer. Write is used when the output is to be written to a file. Display is used if the output is to be displayed on the screen.
Typical pseudocode examples are: (a) (b) (c) Print name, address and postcode Write customer record Display Program Completed
If the program is displaying a message asking a user to input some information, the verb Prompt may be used, for example: Prompt user for account number The next line of code would then get the account number. 3. A computer can perform calculations. Most programs require the computer to perform some sort of arithmetical calculation. In pseudocode, you may use either the symbols for the operation (given in Table 2-1) or the words (e.g., Add, Divide, etc). The following symbols for mathematical operations are used. + * / () = Addition Subtraction Multiplication Division Brackets Equals
NOTE: The asterisk ( * ) is used for multiplication and not the lower case x, and that the forward slash ( / ) is used for division because the division symbol ( ) is not a key on the keyboard. The verb Compute can also be used in pseudocode, as in the following examples:
Compute sales tax = cost price * 0.10 Compute C = (F 32) * 5/9
2-8
PDCLGA001b
The following key words are used for specific arithmetic operations:
Accumulate to produce a cumulative total. Increment to increase the value of a variable by one. Decrement to decrease the value of a variable by one.
4. A computer can assign a value to a variable. There are two pseudocode key words that you use to assign a value to a variable, depending on the situation:
To give an initial value to a variable, the verb Initialise is used. To assign a value to a variable as a result of some processing, use Let and the equals symbol ( = ).
Typical pseudocode examples are: (a) (b) (c) (d) Initialise accumulator totals to zero Let total price = cost price + sales tax Let count = count + 1 (This is the same as increment count by 1) Let balance = balance + interest
The equals symbol ( = ) is used to indicate the assignment of a value to a variable as a result of some processing. The process on the right hand side of the equals sign is completed before assigning the result to the variable on the left hand side where it replaces the value that was there previously. The instruction, Let count = count + 1, appears to defy mathematical reason but it is not treated by the computer as a mathematical equation. Rather, it tells the computer that the result of the calculation, count + 1, is to be stored in the memory cell name on the left, count. Suppose the memory cell count has the data value 10 in it. So the calculation, count + 1, produces the result 11. Because the memory cell, count, appears on the left hand side of the instruction, the computer stores the value 11 there. When it does this, the old value is erased and replaced by the new calculated value of 11. In a similar way, Let balance = balance + interest will result in the data value stored in the memory cell interest being added to the value in the memory cell balance. The result will be placed into the memory cell balance, replacing the old value. NOTE: interest. Another way of expressing it is balance becomes balance +
In practice once you are used to the process, the Let keyword can be left out of the statement without making the meaning less clear.
PDCLGA001b
2-9
5. A computer can compare two pieces of information and use the result to select one of two alternative actions. An important computer operation available to the programmer is the ability to compare two pieces of information and then, as a result of the comparison, select one of the two alternative actions. This ability to compare and select gives the computer its decisionmaking capacity. To represent this operation in pseudocode, special key words are used: If, Then, and Else. The comparison of data is established in the If clause, and the choice of alternatives is determined by the Then or Else options. Only one of these options will be performed. A typical pseudocode example to illustrate this operation is:
If student is part time Then Add 1 to part time count Else Add 1 to full time count EndIf
In this example, the attendance status of the student is investigated, with the result that either the part time count accumulator or the full time count accumulator is increased (incremented by 1). Note the use of indentation to emphasise the Then and Else options, and the use of the EndIf to close the operation. The indentation gives a logical look to the algorithm. The programming concepts associated with selection are covered in the next Topic and more fully in Section 4. 6. A computer can repeat a group of actions. When there is a sequence of processing steps that need to be repeated, two special key words, While and EndWhile, are used in pseudocode. The condition for the repetition of a group of actions is established in the While clause, and the actions to be repeated are listed beneath it and indented. For example:
While student total is less than 50 Read student record Write student name, address to report Add 1 to student total EndWhile
In this example, it is easy to see the statements that are to be repeated, as they immediately follow the While statement and stop at the EndWhile statement. They are indented to show that they are under the logical control of the While. The condition that controls and eventually terminates the repetition (student total is less than 50 in the example above) is established in the While clause. The key word, EndWhile, marks the end of the group of repeated statements. The repetition of a sequence of instructions is referred to also as looping or iteration. The word iteration is used interchangeably with the word repetition. The programming concepts associated with repetition are covered in Topic 5, and more fully in Section 5.
2-10
PDCLGA001b
20 mins
The sequence control structure can be used to represent the first four basic computer operations listed in the previous topic: to receive information, to output information, to perform arithmetic, and to assign values. For example, a typical sequence of statements in an algorithm might read:
Increment page count by 1 Print heading line Initialise linecount to zero Read customer record from customer file
These instructions illustrate the sequence control structure as a straightforward list of steps written one after the other, in a top-to-bottom fashion. Each instruction will be executed in the order in which it appears. The sequence construct is covered in greater detail in Section 3 of this Learning Guide.
PDCLGA001b
2-11
2. Selection The selection control structure is the presentation of a condition and the choice between two actions, with the choice depending on whether the condition is true or false. This construct represents the decision-making abilities of the computer and it is used to illustrate the fifth basic computer operation, namely to compare two pieces of information and to select one of the two alternate actions. It represents the decision making abilities of the computer. In pseudocode, selection is represented by the key words If, Then, Else and EndIf. The If Then Else statement tells the computer to follow one set of instructions in case a condition is true, and a different set of instructions if the condition is false.
If condition p is true Then statement(s) in true case Else statement(s) in false case EndIf
If condition p is true then the statement or statements in the true case will be executed, and the statements in the false case will be skipped. Otherwise (which is the Else statement) the statements in the true case will be skipped and the statements in the false case will be executed. In either case, control then passes to the next process step after the delimiter EndIf. It is called a delimiter because it specifies the limit or end of the selection block of statements. A typical pseudocode example might read:
If age is over 18 Then Display entry permitted Else Display entry NOT permitted EndIf
A variation of the selection control structure is the null (empty) Else structure that is used when a task is performed only if a particular condition is true. The null Else construct is written in pseudocode as:
If condition p is true Then Statement(s) in true case EndIf
NOTE: The key word Else is omitted. This construct tests the condition in the If clause and, if that is found to be true, it performs the statement(s) listed in the Then clause. However, if the initial condition is found to be false, then no action will be taken and processing will proceed to the next statement after the EndIf. The selection construct is covered in greater detail in Section 4 of this Learning Guide.
2-12
PDCLGA001b
3. Repetition The repetition control structure can be defined as the presentation of a set of instructions to be performed repeatedly, as long as a condition is true. The basic idea of repetitive code is that a block of statements is executed again and again, until a condition occurs to terminate it. This control structure is referred to as a loop or iteration. There are three basic formats. (a) One format is the While EndWhile construct, which is written in pseudocode as:
While condition p is true statement block EndWhile
The While loop is called a leading decision loop because the condition is tested before any statements are executed. If the condition in the While statement is found to be true, the following block of statements is executed once. The delimiter EndWhile then triggers a return of control to the re-testing of the condition. If the condition is still true, then the statements are repeated, and so the repetition process continues until the condition is found to be false. Control then passes to the statement that follows the EndWhile statement. The EndWhile is called a delimiter because it specifies the limit or end of the repetition block of statements. It is imperative that at least one statement within the statement block can alter the value of the condition and eventually render it false, because otherwise the logic may result in an endless loop. Getting caught in an endless loop is one of the common problems of a poorly designed algorithm. When a program gets caught in an endless loop, it appears to freeze on the screen. As a last resort, the computer has to be re-booted to get out of the endless loop. Here is an example in pseudocode that represents the repetition control structure:
Initialise student total to zero While student total < 50 Read student record from class file Write student name, address to report file Add 1 to student total EndWhile
The example illustrates a number of points. 1. 2. 3. The variable, student total, is initialised to zero before the While condition is executed. As long as student total is less than 50 (i.e. the While condition is true), the statement block will be repeated. Each time the statement block is executed an instruction within that block (Add 1 to student total) will cause the variable student total to be altered, thus avoiding an endless loop. After 50 iterations, student total will equal 50. This causes the While condition to become false, so the repetition ceases and control goes to the statement after the EndWhile. It is important to realise that the initialising and subsequent incrementing of the variable tested in the condition is an essential feature of the While construct.
4.
5.
PDCLGA001b
2-13
(b)
Another format of the repetition construct is the Repeat Until. This structure is similar to the While structure, in that a group of statements are repeated in accordance with a specified condition. However, unlike the While structure, the RepeatUntil structure tests the condition at the end of the loop. This means that the statements within the loop will be executed once before the condition is tested. If the condition is false, the statements will be repeated Until the condition becomes true. The RepeatUntil structure is written in pseudocode as:
Repeat statement block Until condition is true
You can see that RepeatUntil is a trailing decision loop in that the condition is tested at the bottom of the loop, after the loop statements are executed at least once. In contrast, the While loop is a leading decision loop where the condition is tested at the beginning of the loop, and it is possible that the statements are not executed even once. (c) The third format of the repetition construct is the For EndFor construct, which is used to execute a fixed number of repetitions. The repetition of the loop is controlled by a loop index variable that is automatically updated during each iteration. This variable has a known initial value and a known final value. When the final value is reached, the repetition of the loop ceases. The For EndFor construct is written in pseudocode as:
For loop index changing from initial value to final value statement block EndFor
2-14
PDCLGA001b
PDCLGA001b
2-15
Yes
Let interes t rate = 8%
account balance < 10,000?
No
Let interes t rate = 10%
Compute interes t
Yes
M o re acco un t s ?
No
End
2-16
PDCLGA001b
ACTIVITY 2-1
1. Trace your way through the flowchart shown in Figure 2-1 with the following test data, and complete Table 2-2.
Account Balance 20,000 10,000 9,000 5,000 Rate used Interest New balance More accounts ?
Table 2-2
2.
Convert the flowchart for Example 2.1 to pseudocode. Use a Repeat Until format with an If Then Else statement embedded in it. ___________________________________________________________________ ___________________________________________________________________ ___________________________________________________________________ ___________________________________________________________________ ___________________________________________________________________ ___________________________________________________________________ ___________________________________________________________________ ___________________________________________________________________ ___________________________________________________________________ ___________________________________________________________________ ___________________________________________________________________ ___________________________________________________________________ ___________________________________________________________________ ___________________________________________________________________ The Activity Solution can be found at the end of this Section.
PDCLGA001b
2-17
FLOWCHART SYMBOLS
Flowcharts are constructed from a standard set of shapes. Those shown in Figure 2-2 are some of the more common ones that will be used in this Learning Guide.
SHAPE
FUNCTION
To Begin and End the flowchart
EXAMPLE
--------------
-------------------------------------------------------------
END
----------------------------------------------------------------------------------------------------------
----------------------------------------------------------------------------------------------------------
----------------------------------------------------------------------------------------------------------
2-18
PDCLGA001b
It is important to use the correct shapes for each task with relevant labels written inside them and make sure your flow-lines have arrowheads to indicate the direction of flow if it is other than the normal top-to-bottom and left-to-right flow.
Figure 2-3
If you are using Microsoft Word 2003 at home, you will find the flowchart and lines auto shapes on the drawing toolbar. To use a symbol or line in your flow chart simply click on the symbol or line. The menu will disappear and the cursor will change to a cross. In the case of shapes simply hold down the left mouse button and drag out the shape to the size you require it. With lines simply hold down the left mouse button and draw the line where you want it. If you want multiple versions of the same shape simply copy and paste one you have already added. To add text within the shape, right click on the shape and select Add Text. You can move things around once they are added by left clicking and dragging. Try this out for yourself so you are confident about using Word for this work.. When designing a flowchart you might want to do a quick sketch before creating the flowchart in Word, that is fine. By now, you probably want to know how flowcharts represent the fundamental constructs of sequence, selection and repetition.
PDCLGA001b
2-19
As shown in Figure 2-4, Sequence is represented by the flow-lines connecting the shapes. Start at the START sign and follow the flow-line until you reach a shape with an instruction in it. After carrying out the instruction you flow to the next one. The flow-lines are normally followed from top to bottom and from left to right. However, if arrows are included on a flow-line, then the flow-line is followed in the direction of the arrow.
Start
Input
Process
Selection is represented by the diamond shape with two paths leaving it. The decision in the diamond has a Yes/No answer, and the corresponding flow-line is followed depending on the answer to the question.
Y ?
Task abc
Task xyz
Repetition is represented by a decision diamond that has one of the exit paths returning to a point higher in the flowchart. This return path is called a loop. The question inside the diamond is called the loop control condition. There are two main types of flowchart repetition loops, which for convenience will be referred to as TYPE A and TYPE B.
2-20
PDCLGA001b
stop looping ?
loop processing
N
loop processing
stop looping ?
The Type A loop always executes the statements in the loop at least once. This is because the loop control condition is evaluated at the end of the loop, and the instructions in the body of the loop will have already been executed before then. The algorithm shown for Example 2.1, Figure 2-1 at the start of this topic, is an example of this type. It corresponds to the pseudocode form Repeat Until. It can be referred to as a Trailing Decision Loop. The Type B loop may not always execute the loop instructions even once. This is because the loop control condition comes before the execution of the loop instructions, and a false result at the beginning would mean that the body of the loop is bypassed. This type corresponds to the pseudocode form While. It can be referred to as a Leading Decision Loop. The example shown in Figure 2-7 uses the type A loop, that is, a trailing decision loop.
Input data
No
Data valid ?
Yes
Suppose at a particular point in a program, a user has to enter a data value, and the processing cannot proceed until a valid entry is made. The algorithm must detect an invalid entry and ask the user to re-enter a value. The algorithm must be able to repeat the input/error-check sequence until the user enters a valid value. The type A loop would be best for this, because the instructions in the loop have to be executed at least once.
PDCLGA001b
2-21
For an example that uses a type B loop, that is, a leading decision loop, consider the following situation. Suppose a banking program has to print a statement for a savings account. To do this, it has to input an opening balance, and then process any transactions (deposits or withdrawals) made against the account over the period that the statement covers. The flowchart for this situation is shown in Figure 2-8.
Y
Input transaction
End
Figure 2-8. Leading decision loop for bank account transaction processing
ACTIVITY 2-2
1. 2. Construct a flowchart to input two numbers, add them together, and display the result. Construct a flowchart to input two numbers. If the first number is bigger than the second number, display the first number as the bigger number. Otherwise, display the second number as the bigger number. Construct a flowchart to add up the exam scores of a given group of PDC students each week and display a weekly total. It is not known in advance how many scores are to be added together but there will always be at least one. You have to start off with the weekly total set to zero. Modify the flowchart from Question 3 by adding a selection structure to it to allow only valid scores (which are from 0 to 100 inclusive) to be processed. Modify the flowchart from Question 4, to keep count of how many exam scores are processed to produce the weekly total. Calculate the average by dividing the weekly total by the number of exam scores. Display the average only.
3.
4. 5.
2-22
PDCLGA001b
ACTIVITY 2-3
1. What will be displayed on the screen if the Flowchart in Figure 2-9 is run as a program?
Start
count = 0
Count < 10 ?
Y
count = count + 1
Display count
End
The Activity Solution can be found at the end of this section. 2. Complete the flowchart shown in Figure 2-10. It is to display the odd numbers from 1 to 9 inclusively. The variable count is used to hold the value of the odd numbers of which the first is 1.
PDCLGA001b
2-23
Start
count =
count =
End
Figure 2-10
3.
Construct a flowchart to work out the even numbers from 2 to 20 inclusively, and add them up. The output is to display only the sum of the even numbers.
HINT: You will need to use two variables, say sum to keep a running total and count to hold the value of the even numbers of which the first one is 2
2-24
PDCLGA001b
SELF TEST
60 mins 1. Use the words in the boxes to complete the statements below, describing the six basic computer operations. Perform Compare Repeat Receive Output Select Assign
1. 2. 3. 4. 5. 6. 2.
A computer can _____________ information. A computer can _____________ information. A computer can _____________ arithmetic. A computer can _____________ a value to a variable. A computer can _____________ two pieces of information. and _____________ one of two alternative actions. A computer can _____________ a group of actions.
Select words from the boxes to answer the question below. Write Get Display Read Print Accept
What verb is used in pseudocode to represent a computer receiving information: (a) from a record on a file? ______________ (b) from the keyboard? ______________ 3. Select words from the boxes to answer this question. Write Get Display Read Print Accept
What verb is used in pseudocode to represent a computer outputting information: (a) to the printer? ________________ (b) to a file? ________________ (c) to be displayed on the screen ? ________________ 4. Select from the boxes to answer this question. = Equals Store Initialise Save
What verbs or symbols are used in pseudocode to represent a computer: (a) giving an initial value to a variable? _________ (b) assigning a value to a variable as a result of some processing? ____________ 5. What key words are used in pseudocode to represent a computers ability to compare two pieces of information and select one alternative? _______________________________________________________________
PDCLGA001b
2-25
6.
What are the three basic control structures used in structured programming according to The Structured Theorem? 1. _______________ 2. ________________ 3. _______________
7.
What will be the sequence of numbers output from the segment of an algorithm shown as follows? Initialise index to 0 Initialise number to 1 While index < 5 Add 1 to index Add 2 to number Display number EndWhile
8. 9.
Construct a flowchart of the algorithm given in Question 7 above. Examine the following pseudocode and select your observation about it from the list that follows. Initialise answer to Y While answer = Y Get balance Get interest Let balance = balance + interest Display The New Balance is: Display balance EndWhile (a) (b) (c) (d) The loop will not terminate. The loop will terminate when the user types N. The loop will terminate once the user types any value other than Y. The loop continues to execute while balance is Y.
10.
What modification should be made to the algorithm in Question 9? _______________________________________________________________________ _______________________________________________________________________ _______________________________________________________________________ _______________________________________________________________________
11.
2-26
PDCLGA001b
12.
What is achieved by this segment of pseudocode instructions in the following repetition control structure? Initialise total to zero While total <= 2000 Get purchase price Let total = total + purchase price EndWhile Display Purchases exceed 2000 limit _______________________________________________________________________ _______________________________________________________________________ _______________________________________________________________________ _______________________________________________________________________
13.
Construct a flowchart that is to accept 25 exam scores from the keyboard, and calculate and display their average. The ideal heart rate of a person doing aerobic exercise can be calculated by the formula. 80% of (220 minus age in years). Write a sequence of instructions in pseudocode to get the persons name and age from the keyboard and then display the ideal heart rate on the screen for that person. _______________________________________________________________________ _______________________________________________________________________ _______________________________________________________________________ _______________________________________________________________________ _______________________________________________________________________ _______________________________________________________________________ _______________________________________________________________________
14.
15.
Use the selection control structure to write instructions in pseudocode that will display Pass for an exam score of 60 or more and Fail if the exam score is less than 60. _______________________________________________________________________ _______________________________________________________________________ _______________________________________________________________________ _______________________________________________________________________ _______________________________________________________________________ _______________________________________________________________________ _______________________________________________________________________
PDCLGA001b
2-27
2-28
PDCLGA001b
8.
S ta rt
In d e x = 0
N um b e r = 1
In d e x < 5 ?
Y
In d e x = In d e x + 1
N um b e r = N um b e r + 2
D is p la y n u m b e r
End
9.
(a)
There must be a statement within the statement block to alter the value of the condition and eventually render it false. Otherwise it will result in an endless loop. 10. You must allow for a change to be made to the variable Answer. In this example, we could have the user input a value for Answer immediately before the delimiter EndWhile.
Display balance Get answer EndWhile
PDCLGA001b
2-29
11.
Start
Answer = 'Y'
Answer = 'Y' ?
Y
Get balance
Get interest
Display balance
Get answer
End
12.
This segment of pseudocode keeps a running total of the value of purchases until the accumulated total first exceeds 2000 at which point it stops accepting any more purchase prices and displays the message Purchases exceed 2000 limit.
2-30
PDCLGA001b
13.
Start
Let count = 0
Let sum = 0
Count < 25 ?
Y
Get score
Calculate average
Display average
End
14.
15.
NOTE: In this algorithm, you do not have to write the statement If exam score 60 because that is implied in the Else branch. If exam score is not 60 or greater then it has to be less then 60.
PDCLGA001b
2-31
ACTIVITY SOLUTIONS
Activity 2-1
1. Results of tracing though the flowchart for Example 2.1
Balance 20,000 10,000 9,000 5,000 Rate 10% 10% 8% 8% Interest 2000 1000 720 400 New balance 22,000 11,000 9,720 5,400 More y/n Y Y Y N accounts
2.
Activity 2-2
1.
Start
Get number1
Get number2
Display result
End
2-32
PDCLGA001b
2.
Start
Get num1
Get num2
No
Yes
End
3.
Start
End
PDCLGA001b
2-33
4.
Start
Valid score ?
End
2-34
PDCLGA001b
5.
Start
No
Valid score ?
Yes
Add exam score t o weekly t ot al
Yes
More exam scores ?
No Calculate average
Display average
End
PDCLGA001b
2-35
Activity 2-3
1. 2. This will display the numbers 1 through to 10 on the screen. Display odd numbers from 1 to 9.
Start
count = 1
Count < 10 ?
The variable count is displayed before it is incremented by 2 to produce the odd numbers, which are every second number.
Y
Display count
count = count + 2
End
3.
The variable count is initialised to the value 2, which is the first even number. The variable sum is initialised to zero.
count = 2
sum = 0
NOTE: The decision box is Count < = 20, not just less than because the value 20 has to be included in the cumulative total of a note with text. The variable sum keeps the cumulative total. The variable count is incremented by 2 to produce the even numbers, which are every second number having started with an even number. Finally, the sum is displayed.
Count < = 20 ?
Y
sum = sum + count
count = count + 2
Display sum
End
When you have finished this section, update your suggested study plan on pages vi and vii with the actual date you finished.
2-36
PDCLGA001b
3.0
OBJECTIVES
1. 2. 3.
300 mins
On successful completion of this section, you will be able to: Analyse a problem and develop a solution involving a sequence control structure Write simple algorithms using the sequence control structure Desk-check a developed solution involving a sequence control structure
TOPICS
1. 2. 3. Applying the first Steps of the PDR to a problem involving a Sequence Control Structure Writing a Solution Algorithm involving a Sequence Control Structure Desk-checking the Solution Algorithm involving a Sequence Control Structure
PDCLGA001b
3-1
60 mins
TOPIC 1: APPLYING THE FIRST STEPS OF THE PDR TO A PROBLEM INVOLVING THE SEQUENCE CONTROL STRUCTURE
In Section 2, Topic 1, we looked at problem definition and analysis. In this Section, we will apply those details by working through some examples that will use sequence control structures in their solutions. To refresh your memory, refer again to the Program Development Routine (PDR). The content in this Topic will focus on three of the first four steps of the PDR. For now we will ignore step two which applies if we are working with objects, they will be covered in section seven. A problem needs to be defined in enough detail and clarity to enable a solution to be developed. Remember to divide and conquer when undertaking the initial analysis of a problem. The result of this step will be a List of Sub-problems. Do not attempt to find a solution until the problem has been completely defined. Once the problem has been properly defined and analysed, you usually produce a rough sketch of the steps required to solve the problem. In the solution to any problem, it is necessary to decide whether any steps must come before or after other steps and which steps do not need to be in a certain order. After listing the sub-problems the VTOC is created. The VTOC is a diagrammatic outline of the solution. Start by dividing the solution into three phases the Initialise Phase, the Process Phase and the Finalise Phase. See Figure 3-1. This basic template should be applied to all solutions.
Main
Initialise
Process
Figure 3-1. VTOC Template
Finalise
When we study the concept of modularisation in Section 6 of this Learning Guide we will encounter more complex problems that necessitate the further breakdown of these phases into separate functions or modules, giving a proper name for each. This will create a more complex VTOC. To begin with the sections of the VTOC you create for simpler solutions will represent blocks of code within a single module. Later the blocks of code identified in this way will be placed into their own modules. In these more complicated solutions the Initialise, Process and Finalise may not be as clearly separated as in the simpler solutions we will be looking at in the first sections of this learning guide. After creating the VTOC, we are ready to create the Data Table. This is a useful way of representing the inputs, outputs and the processing steps required to solve the problem. In order to create the Data Table, the problem should be divided into three separate components:
3-2
PDCLGA001b
1. 2. 3.
Input: a list of the source data provided for the problem. Output: a list of the outputs required. Processing: a list of actions needed to produce the required outputs.
In some programming problems, the inputs, the processes and the outputs may not be clearly defined. In such cases it is best to concentrate on the outputs required. Doing this will then decide most inputs, and the way will then be set for determining the processing steps required to produce the desired output. The input and output components of a problem are usually identified by descriptive words such as nouns and adjectives. The processing component of a problem is usually described by actions using verbs and adverbs. When dividing a problem into its three components, you should simply analyse the actual words used in the problem specification, and highlight the descriptive ones (the nouns and adjectives) differently to those that imply actions (verbs and adverbs). You use unique names to represent the variables in the problem and to describe the processing steps. All names should be meaningful and descriptive. The name of the variable should be transparent enough to adequately describe it. The names number1, number2 and number3 are more meaningful for three numbers than the names A, B and C. It is reasonable to use abbreviations where you are fairly certain that they are still meaningful, for example avg for average and num for number. When it comes to writing down the processing component of the Data Table, you should use words that describe the work to be done in terms of single specific tasks. The actions (the verbs and adverbs) are accompanied by their associated objects (the nouns and adjectives). For example Read three numbers.
ACTION ASSOCIATED OBJECTS
At this stage, the processing section should only be a list of what actions need to be performed, not how they will be accomplished. Lets look at a problem involving a sequence control structure and go through the first few steps of the PDR.
PDCLGA001b
3-3
Main
Read in 3 numbers
Step 4: Create a Data Table. To help create a Data Table, underline the nouns and adjectives used in the specification. This will establish the input and output components. Our example would look like this: A program is required to read three numbers, add them together, and print their total. By looking at the underlined nouns and adjectives you can see that the input for this problem is three numbers and the output is the total. Enter these in the Data Table as shown in Figure 3-3.
PROCESSING total
OUTPUT
In order to determine what will constitute the processing action required, underline the verbs and adverbs used in the specification. Use a different colour. They are shown as double underlined here.
3-4
PDCLGA001b
Example 3.1 should now look like this: A program is required to read three numbers, add them together, and print their total. By looking at the double underlined words, it can be seen that the processing verbs are read, add together, and print. These steps can now be added to the Data Table.
NOTE: When writing down a processing verb, the objects or nouns associated with it must be given with them. The Data Table can now be completed as shown in Figure 3-4.
OUTPUT total
The problem has been properly analysed. We now understand the input to the problem, the output to be produced, and the processing steps required to convert the input to the output. The next step is to write the Algorithm. This will be covered in Topic 2, but for now, we will continue to practise using steps 1 to 4 of the PDR.
PDCLGA001b
3-5
ACTIVITY 3-1
Create a List of Sub-problems, a VTOC and a Data Table for the following problem specification: The ideal heart rate of a person doing aerobic exercise can be calculated by an appropriate formula. Write a sequence of instructions in pseudocode to get the persons name and age from the keyboard and then display the ideal heart rate on the screen for that person. List of Sub-problems
VTOC
Main
Data Table
INPUT
PROCESSING
OUTPUT
At this stage you are only concerned with the fact that the ideal heart rate must be calculated, and not how the calculation will be performed. That will come later when the solution algorithm is written see Topic 2. The Activity Solution can be found at the end of this Section.
3-6
PDCLGA001b
Lets create another List of Sub-problems, VTOC and Data Table for a problem, and follow that with another activity.
Main
Compute average
Figure 3-5. VTOC for Example 3.2
Display average
Step 4: Create a Data Table. Firstly, establish the input and output components by underlining the nouns and adjectives in the problem statement, as follows. A program is required to prompt the operator for the maximum and minimum temperature readings on a particular day, accept these readings as integers (whole numbers), and calculate the average temperature and display it on the screen. It is easy to see that the input component is the maximum and minimum temperature readings, and the output is the average temperature. Using meaningful names, these components can be set up in a Data Table as shown in Figure 3-6:
PROCESSING
PDCLGA001b
3-7
Now determine what the processing steps are by double underlining the verbs in the problem statement, as follows. A program is required to prompt the operator for the maximum and minimum temperature readings on a particular day, accept these readings as integers (whole numbers), and calculate the average temperature and display it on the screen. The processing verbs are Prompt, Get, Calculate and Display. Find the objects that are associated with these verbs. The completed Data Table is shown in Figure 3-7:
PROCESSING Prompt for temperatures Get maximum and minimum temperatures Calculate average temperature
Remember that at this stage you are only concerned with the fact that the average temperature must be calculated, and not how the calculation will be performed. That will come later when the solution algorithm is written, which is done in the next Topic.
ACTIVITY 3-2
Apply the steps 1 to 4 of the PDR for a structured solution using the following problem specification: A program is required to prompt for and accept the length and width of a rectangular block of land, and the length and width of the rectangular house that has been built on the block. The algorithm should then compute and display the time required to cut the grass around the house, at the rate of ten square metres per minute. Step 1: Analyse the Problem, identifying the Sub-problems. As part of the process of analysing any problem, it is a good idea to draw a diagram, where appropriate, to help to understand the problem. The following diagram shown in Figure 3-8 will assist you. grass area house
List of Sub-problems
3-8
PDCLGA001b
Main
Step 4: Create a Data Table. Firstly, underline the nouns or objects to establish what are the input and output components in this problem. Fill in the Input and Output columns of the Data Table, using meaningful names for the variables. Secondly, underline the verbs (the actions, the tasks) in the problem statement, and add these with associated objects to the Data Table. Data Table
INPUT
PROCESSING
OUTPUT
PDCLGA001b
3-9
45 mins
3-10
PDCLGA001b
Main
Read in 3 numbers
P rint t ot al of numbers
OUTPUT total
Figure 3-10
There are several important points to consider in this solution algorithm: 1. A name has been given to the algorithm, namely Add three numbers. Algorithm names should briefly describe the function of the algorithm, and are usually expressed as a single verb followed by an object. Other equally meaningful names could have been chosen for this algorithm. The algorithm has an End statement to indicate its finish point. All processing steps between the algorithm name and the End have been indented for readability because they logically belong together. Each processing step in the Data Table relates directly to one or more statements in the algorithm. For instance, Read three numbers in the Data Table becomes Read number1, number2, number3 in the algorithm. Add numbers together becomes
Let total = number1 + number2 + number3.
2. 3. 4.
5.
The equals sign ( = ) is used to assign the value on the right hand side to the variable on the left-hand side. The contents of the variable total will become equal to the sum of the values of the three variables on the right hand side. Or looking at it another way, the sum of the three variables on the right hand side is stored in the variable total on the left-hand side.
Now that the algorithm is complete, the solution should be tested by the process known as desk-checking. This is Step 6 of the PDR, and it is covered in Topic 3.
PDCLGA001b
3-11
Main
Compute average
Figure 3-11
Display average
PROCESSING Prompt for temperatures Get maximum and minimum temperatures Calculate average temperature
Figure 3-12
In this example, the process Calculate average temperature in the Data Table has been expressed in the algorithm as the calculation of a formula whose result is assigned to the variable avg temp. You can now practise what you have learned by doing the following activity.
3-12
PDCLGA001b
ACTIVITY 3-3
A program is required to read in the length and width of a rectangular block of land, and the length and width of the rectangular house that has been built on the block. The algorithm should then compute and display the time required to cut the grass around the house, at the rate of ten square metres per minute. You have already created the VTOC and the Data Table, and they are repeated here for convenience.
Main
Calculations
Figure 3-13
Display time
PROCESSING Prompt for block measurements Get block measurements Prompt for house measurements Get house measurements Calculate mowing area Calculate mowing time
Figure 3-14
PDCLGA001b
3-13
45 mins
2.
3.
3-14
PDCLGA001b
To desk-check the algorithms for our examples in this section, we will choose a few test cases that will follow the paths of the logic in the algorithm. In a real application test data may run to many thousands of items and may have to be automatically generated. The generation of appropriate test data may become a major part of a project.
3.
The algorithm testing process will eliminate most errors, but it still cannot prove that the algorithm is 100% correct. The most you can say is that there are no known errors. Let us test the algorithms written previously in this Section.
Step 1 Draw up a Test Data table. For the sake of simplicity, we will choose two sets of input test data for each of the three input variables, and establish the expected result of the output variable (total) for each test data set. This is shown in Figure 3-15.
INPUT First data set Number 1 Number 2 Number 3 Number 1 10 20 30 40 EXPECTED OUTPUT total 60
total
123
Number 2 Number 3
41 42
Figure 3-15
Step 2 Perform the desk-check using a Desk-check table. The Desk-check Table like the one shown in Topic 4 in the PDR is used to record methodically the output of running the program on paper, passing each test data set through the solution algorithm, statement by statement. Variable names are written at the
PDCLGA001b
3-15
top of the columns. The numbered steps correspond to the instruction execution sequence in the algorithm. A soft copy of the PDR forms is available in the MS Word file PDRforms.doc, which is located in your H:\PDCWORK\ directory. Create a new MS Word document and copy into it the forms that you need to use. To desk-check your algorithm follow these steps: 1. 2. 3. 4. Go to the first line in the algorithm in which a variable has its value changed. Write the name of the variable at the top of the first variables column. In the step row corresponding to the instruction execution sequence in the algorithm, write the value of the variable under its heading name. Go to the next step in the algorithm in which a variable changes its value and do the same.
You continue with this process but you only write the name of each variable once. If you need to show a new value for a variable that has already been encountered, you use the same column as the original and whatever step you are up to. In this way we can track the change in a variable as the program progresses through its instructions. As you go down the algorithm you go also down the Desk-check table. For longer examples add extra pages and add the list of variables to the top of each page as you did with the first page. Lets now do a desk-check on the algorithm for each of the sets of test data. Desk-check Add three numbers First data set
Steps 1 2 3
number 1 10
number 2 20
number 3 30
VARIABLES Total 60
Figure 3-16
Figure 3-17
Step 3 Check results. Check that the expected results (60 and 123) match the actual results as shown in the desk check table the value in the total row in this example. A programmer could now proceed to code the algorithm into a programming language. Steps 7 to 10 of the PDR which involve actual coding will be covered in the next module, PC1 Programming Concepts 1, which uses the Java programming language.
3-16
PDCLGA001b
30 10 40
avg temp
30
min temp
20
Figure 3-18
ACTIVITY 3-4
Using the desk-check tables or drawing up your own, perform a desk-check of Example 3.2 by passing each test data set given on the previous page through the solution algorithm, statement by statement.
VARIABLES Steps 1 2 3
VARIABLES Steps 1 2 3
Check that the actual results of the desk-check match the expected results. The Activity Solution can be found at the end of this Section. PDCLGA001b Computer Power Institute
3-17
INPUT block length block width house length house width block length block width house length house width
30 30 20 15 40 30 20 20
Figure 3-19
mowing time
80
3-18
PDCLGA001b
ACTIVITY 3-5
Using the desk-check tables that follow or drawing up your own, perform a desk-check of the algorithm written for Activity 3-3 (Find mowing time) by passing each test data set given on the previous page through the solution algorithm, statement by statement.
Check that the actual results of the desk-check match the expected results. The Activity Solution can be found at the end of this Section.
PDCLGA001b
3-19
CHECKPOINT 1
150 mins Your solutions to these questions should be set out in the same way as the examples in this section. You must set out your solutions to each question using the framework of the first six steps of the Program Development Routine (PDR) (Excluding step 2 for now). You will need to: 1. 2. 3. 4. 5. Analyse the problem by making a list of the sub-problems. Develop a VTOC, which is an outline of the solution. Create a Data Table after identifying the inputs, the outputs, and the actions that make up the processing component. Write a solution algorithm in pseudocode using only a Sequence Control Structure. Desk-check the solution algorithm.
Complete at least two of the four questions that follow. The extra questions are available to do if you have the time and the incentive. When you have completed two of the four questions, call on an instructor to check over your solutions and discuss with them any issues that are not clear to you. This constitutes the Checkpoint 1 Sign Off.
Question 1
A program is required that will receive two integer items from an operator, and display to the screen their sum (num1 + num2), their difference (num1 num2), their product (num1 * num2), and their quotient (num1 / num2). List of Sub-problems
3-20
PDCLGA001b
VTOC
Data Table
INPUT
PROCESSING
OUTPUT
PDCLGA001b
3-21
EXPECTED OUTPUT
VARIABLES
Steps 1 2 3 4 5 6 7 8
VARIABLES
Steps 1 2 3 4 5 6 7 8
3-22
PDCLGA001b
Question 2
A program is required that will read in a tax rate (as a percentage) and the prices of five individual items. The program is to calculate the total price of all items together before tax and then the tax payable on the total of all those items. The tax payable is computed by applying the tax rate to the total price. Both values (total price before tax and total tax payable) are to be printed as output. List of Sub-problems
VTOC
Data Table
INPUT
PROCESSING
OUTPUT
PDCLGA001b
3-23
EXPECTED OUTPUT
VARIABLES Steps 1 2 3 4 5 6 7 8
3-24
PDCLGA001b
VARIABLES Steps 1 2 3 4 5 6 7 8
PDCLGA001b
3-25
Question 3
A program is required to read in a customers account balance at the beginning of the month, a total of all withdrawals for the month, and a total of all deposits made during the month. A government tax charge of 1% of the value of all transactions made during the month is applied. The program is to calculate the account balance at the end of the month by (i) subtracting the total withdrawals from the account balance at the beginning of the month, (ii) adding the total deposits to it, and (iii) subtracting the government tax. List of Sub-problems
VTOC
Data Table
INPUT
PROCESSING
OUTPUT
3-26
PDCLGA001b
EXPECTED OUTPUT
EXPECTED OUTPUT
PDCLGA001b
3-27
VARIABLES
Steps 1 2 3 4 5 6 7 8
VARIABLES
Steps 1 2 3 4 5 6 7 8
3-28
PDCLGA001b
Question 4
A program is required that will read in values from an employees time sheet, and calculate and print the weekly pay for that employee. The values read in are (i) the total number of regular hours worked, (ii) the total overtime hours worked, and (iii) the hourly wage rate. Payment for regular hours worked is to be computed as rate multiplied by hours. Payment for overtime hours is to be computed at time-and-a-half (i.e., 1 times hourly wage rate). Weekly pay is calculated as payment for regular hours worked plus payment for overtime hours worked. List of Sub-problems
VTOC
Data Table
INPUT
PROCESSING
OUTPUT
PDCLGA001b
3-29
EXPECTED OUTPUT
3-30
PDCLGA001b
Steps 1 2 3 4 5 6 7 8
Steps 1 2 3 4 5 6 7 8
PDCLGA001b
3-31
CHECKPOINT 1 (CONTINUED)
When you have completed two questions, call an instructor to have your solutions signed off and discuss any issues about them. While you are waiting for the instructor to attend to you, continue on with the next section. The instructor sign off sheet is in Appendix B Checkpoints for Instructor Sign Off, at the end of the Learning Guide just before the Glossary. When you have finished this section, update your suggested study plan on pages vi and vii with the actual date you finished.
3-32
PDCLGA001b
ACTIVITY SOLUTIONS
Activity 3-1
List of Sub-problems
Get Name and Age Calculate ideal heart rate using formula Display ideal heart rate
VTOC
Main
Data Table
PROCESSING Get name and age Calculate ideal heart rate using the appropriate formula
Activity 3-2
List of Sub-problems
Obtain the dimensions of the block and the house Calculate the grass area and the time to mow it Display the mowing time
VTOC
Main
Calculations
Display time
PDCLGA001b
3-33
Data Table
PROCESSING Prompt for block measurements Get block measurements Prompt for house measurements Get house measurements Calculate mowing area Calculate mowing time
Activity 3-3
Your solution should be similar to that given as follows.
Find mowing time Prompt for block dimensions Get block length, block width Prompt for house dimensions Get house length, house width Let block area = block length * block width Let house area = house length * house width Let mowing area = block area house area Let mowing time = mowing area / 10 Display mowing time End
Activity 3-4
Desk-check Average temperature First data set
3-34
PDCLGA001b
Activity 3-5
Desk-check Calculate Mowing Time First data set
Steps 1 2 3 4 5 6 block length 30 block width 30 house length 20 VARIABLES house block width area 15 900 300 600 60 house area mowing area mowing time
PDCLGA001b
3-35
3-36
PDCLGA001b
4.0
OBJECTIVES
1. 2. 3. 4. 5.
360 mins
On successful completion of this section, you will be able to: Evaluate boolean expressions Understand single and multiple selection control structures Apply the Order of Precedence rule Write algorithms using variations of the selection control structure Apply the case control structure
TOPICS
1. 2. 3. 4. Boolean Expressions Variations of The Selection Control Structure Algorithms Using The Selection Control Structure The Case Control Structure
PDCLGA001b
4-1
Relational Operators
The relational operators and their meanings are shown in Table 4-1:
Meaning is equal to is less than is less than or equal to is greater than is greater than or equal to is not equal to
NOTE: Here the equals sign ( = ) is used as a relational operator, not as an assignment action as detailed in Section 2 and Section 3.
You will be able to determine from the context which of the two ways is being used.
4-2
PDCLGA001b
The simplest type of boolean expression consists of a comparison of two values using one of the relational operators given in the Table 4-1. This creates what would be called a condition. Evaluating a boolean expression is the same thing as evaluating a condition the result will be either True or False.
ACTIVITY 4-1
Remembering that a boolean expression is one that evaluates to either True or False, evaluate the following expressions. You will find answers to the activities at the end of this Section. 1. 2. 3. 4. 5. 6. 7. 8. 9. 10. 100 > 150 100 <= 150 100 < > 150 100 < 100 Days in February <= 29 Days in June = 31
Days in November > 30 Number of hours allocated to PDC module > 20 This PDC module is studied before PC1 and PC2
You can use AND or OR connectors to combine two or more boolean conditions. However, there are important rules that you have to use when combining two or more boolean conditions. These are the AND Rule, the OR Rule, and the Order of Precedence Rule.
SEPARATE INPUT A B true true true false false true false false
PDCLGA001b
4-3
What this table illustrates is that 1. 2. 3. 4. If A is true and B is true Then (A and B) is true If A is true and B is false Then (A and B) is false If A is false and B is true Then (A and B) is false If A is false and B is false Then (A and B) is false.
Here is an example:
If ((student attendance = part time) AND (student gender = female)) Then Add 1 to female part time count EndIf
In this case, each student record will undergo two tests, one for attendance pattern and the other for gender. Only the students who are both part time and female will cause the variable female part time count to be incremented by one (that is, have 1 added to it). Both conditions have to be true for the whole If statement to be true. If one or both of the conditions are false, then the whole If statement will be false and so the female part time count will remain unchanged. You should be able to see how this conforms to the truth table in Table 4-2. To do that, let attendance pattern be condition A and let gender be condition B.
TIP: It is good practice to put brackets around each of the conditions as we have done in this example. The use of brackets improves the presentation and clarifies the statement .
The OR Rule
If two conditions are combined using the OR connector, then one of the conditions or both of the conditions must be true for the combined condition to be considered true. The combined condition is false only when both conditions are false. We can use a truth table to illustrate the OR rule, as shown in Table 4-3:
SEPARATE INPUT A true true false false B true false true false
4-4
PDCLGA001b
What this table illustrates is that 1. 2. 3. 4. If A is true and B is true Then (A or B) is true If A is true and B is false Then (A or B) is true If A is false and B is true Then (A or B) is true If A is false and B is false Then (A or B) is false.
Changing the AND in the student attendance example on the previous page to OR dramatically changes the outcome from the processing of the If statement.
If ((student attendance = part time) OR (student gender = female)) Then add 1 to fem part time count EndIf
With OR being used, if either one or both of the conditions are true, then the combined condition will be considered true and so the counter will be incremented by one. Only students who are not female and also not part time will be ignored. So the variable fem part time count will be counting male part time students plus female part time students plus female full time students. This is probably not what was intended to happen in this example. Notice the use of brackets to improve the presentation and clarify the logic. To practise the application of these logical operator rules, do Activity 4-2.
ACTIVITY 4-2
Given the following values for X and Y, complete the truth table by correctly filling in the blank cells with True or False.
X 2 5 7 1 9 -3
Y 5 2 -2 0 1 1
X>5
Y <= 2
X > 5 or Y <= 2
if K = 100, then K > 100 is False because 100 is not greater than 100 similarly if K = 100, then K < 100 is False because 100 is not less than 100. However, K < = 100 is True if K = 100, then K < > 100 is False but K < > 90 is True.
PDCLGA001b
4-5
The condition enclosed in brackets is evaluated first, starting with the innermost set of brackets. An AND condition is always evaluated before an OR condition, unless it is enclosed in brackets. If there is more than one AND condition, they are evaluated from left to right. If there is more than one OR condition, they also are evaluated from left to right.
Consider this example. Given that x = 2, y = 5 and z = 7, evaluate whether the following compound statement is True or False.
(x = 2) OR (y < > 10) AND (z = 8)
If there were no order of precedence rule, this compound statement could be evaluated in two different ways. The resulting ambiguity will be demonstrated next. If you evaluate the OR component first, (x = 2) OR (y < > 10), the condition evaluates to True. Remember that True OR True evaluates to True. This result is then combined with AND (z = 8) (which is False because z = 7) to make the whole statement evaluate to False because True AND False evaluates to False. Study Figure 4-1 and Figure 4-2, to see this ambiguity demonstrated diagrammatically. Case 1: Evaluating the OR component first.
x=2 True
OR OR
AND AND
z=8 False
True
AND
False
False
Figure 4-1
Hence, in Case 1, the whole statement evaluates to False. However, if you evaluate the AND section first (i.e., (y < > = 10) AND (z = 8)), and then combine the result of that with OR (x = 2), you get a different result and the whole statement evaluates to True.
4-6
PDCLGA001b
x=2 True
OR OR
AND AND
z=8 False
True
OR
False
True
Hence, in Case 2, the whole statement evaluates to True. Obviously, algorithms must not contain any ambiguity like this. There has to be some way of determining precedence, to decide which of the boolean conditions should be evaluated first, and this is where the Order of Precedence Rule is invoked. It is helpful to use brackets also to indicate which condition is implicitly evaluated first (that is, AND before OR). This emphasises the order of precedence and eliminates any possible ambiguity. Remember that the condition in the inner brackets is evaluated before the condition in the outer brackets. Study these examples. Given that x = 2, y = 5 and z = 7: 1. the statement (x = 2) AND (y < > 10) OR (z = 8) would evaluate to True The AND pair is evaluated first as True, and then the OR is evaluated, giving an overall result of True. 2. the statement (x = 2) OR (y < > 10) AND (z = 8) would evaluate to True The AND pair is evaluated first as False, then the OR is evaluated, giving an overall result of True. 3. 4. the statement (x = 2) AND (y < > 10) AND (z = 8) would evaluate to False These AND pairs are evaluated from left to right, as True and then False. the statement (x = 2) OR (y < > 10) OR (z = 8) would evaluate to True These OR pairs are evaluated from left to right, as True and True again.
PDCLGA001b
4-7
ACTIVITY 4-3
Given that x = 2, y = 5 and z = 7, state whether the following statements are True or False. You will find answers to activities at the end of this Section. 1. 2. 3. 4. 5. 6.
(x = 2) AND (y = 10) OR (z = 7) (x >= 2) OR (y > 0) AND (z = 8) ((x = 2) OR (y = 10)) AND (z < 8) (x > 5) OR (y >= 2) AND (z < 8) (x < > 2) OR (y < 10) OR (z = 8) (x > 2) AND (y <= 5) AND (z = 7)
ACTIVITY 4-4
Evaluate the boolean expressions as True or False, given the values for A, B and C as indicated in the Table. T = True, F = False.
A T T T T F F F F
B T T F F T T F F
C T F T F T F T F
A or B or C
A and B or C
A and B and C
A or B and C
4-8
PDCLGA001b
There is another selection control structure called the case control structure, which however, is not supported by all programming languages. It is covered in Topic 4. 1. One-alternative selection (If Then EndIf) The If Then EndIf structure is used to perform a task if a boolean expression evaluates to true. If the condition is false, then no processing takes place and control passes to the next statement. For example:
If student attendance = part time Then add 1 to part time count EndIf
In this case, the part time count variable will be altered only if the students attendance pattern is part time. Otherwise nothing happens at all. 2. Two-alternative selection (If Then Else EndIf) A two-alternative selection occurs by evaluating a boolean expression and deciding between two alternative paths, depending on whether the result of a condition is true or false. The structure is represented in pseudocode using the keywords If, Then, Else and EndIf. For example:
If account balance < 500 Then Let service charge = 5 Else Let service charge = 2 EndIf
Only one of the paths (the Then path or the Else path) will be followed, depending on the result of the condition in the If clause. The Then path is followed if the result of the condition is true. The Else path is followed if the result of the condition is false.
PDCLGA001b
4-9
ACTIVITY 4-5
Using the segment of an algorithm given, complete Table 4-4.
If account balance < 500 Then Let service charge = 5 Else Let service charge = 2 EndIf
service charge
ACTIVITY 4-6
Study this partial algorithm and complete Table 4-5.
gamma = 30 If alpha < beta Then Let gamma = gamma * gamma EndIf
gamma
4-10
PDCLGA001b
ACTIVITY 4-7
Use this partial algorithm to complete the following table of values. There are 4 sets of values to be passed through the algorithm to produce an output for day and month.
If ((X < 7) OR (Y = 2)) AND (Z > 5) Then day = Monday Else day = Friday EndIf If (K < > 15) AND ((L > 10) OR (M < 30)) Then month = July Else month = March EndIf
Table of values
X a. b. c. d. 2 7 8 6
Y 4 2 3 2
Z 6 5 7 8
day
K 20 10 15 15
L 25 20 10 15
M 30 25 30 15
month
You can use the following two tables to keep track of the True/False value of the boolean expressions to make it easier for you to evaluate the combined If statements.
X<7 a. b. c. d.
Y=2
((X<7) OR (Y=2))
Z>5
PDCLGA001b
4-11
L>10 a. b. c. d.
M<30
((L>10)OR(M<30))
K<>15
(K<>15)AND((L>10)OR(M<30))
3. Multiple-alternative selection (If Then ElseIf Then EndIf) Multiple-alternative selection occurs when one or more ElseIf statements appear following a Then within an If statement. This construct is used when a variable is being tested for multiple values and a different action is to be taken for each of those values. Comparisons are made until a true condition is encountered and then the specified action is executed. This should be clear when you follow this example.
If record code = A Then increment counterA ElseIf record code = B Then increment counterB ElseIf record code = C Then increment counterC Else increment errorcounter EndIf
The execution of the multiple-alternative If statement in the above example proceeds as follows: 1. 2. 3. 4. 5. 6. 7. The first condition (record code = A) is tested. If it is true, counterA is incremented and the rest of the If statement is skipped. If the first condition is false, the second condition (record = B) is tested. If the second condition is true, counterB is incremented and the rest of the If statement is skipped. If the second condition is false, the third condition (record = C) is tested. If it is true, counterC is incremented and the rest of the If statement is skipped. If all conditions are false, the statement following the final Else is executed (the error counter is incremented).
The single quotation marks around the letter being compared to the code variable in the previous example indicate that it is treated as a single character. This distinguishes it from variables A,B or C and makes the pseudo code clearer. Letters and groups of characters can be compared using the = operator in the same way as numbers are.
NOTE: Another way of carrying out this kind of selection is to use a Case statement. Refer to Topic 4 for details. .
4-12
PDCLGA001b
ACTIVITY 4-8
Determine the output from this algorithm when the values for zone are entered as shown in Table 4-6.
Set amount = 100 If zone = 1 Then Let amount = amount * 10 Display amount ElseIf zone = 2 Then Let amount = amount * 20 Display amount ElseIf zone = 3 Then Let amount = amount * 30 Display amount Else Display ERROR EndIf
ZONE 2 4 1 3
Table 4-6
OUTPUT
It is important to realise that when the first true condition is encountered, the task(s) relating to it is/are executed, and then no more testing is done on the remaining conditions. That is, subsequent conditions are tested only when a previous condition is false. Therefore, the order of the condition statements can affect the outcome. Consider an example for allocating a Grade to a Score in accordance with Table 4-7.
SCORE 90 100 80 89 70 79 60 69 0 59
Table 4-7
GRADE A B C D F
PDCLGA001b
4-13
Writing the nested If selection as shown in the algorithm that follows would not produce the correct output. It would categorise all scores as Grade A. Do a desk-check on the algorithm using test data scores of 55, 65, 75, 85, 95 to see the effect. Remember that the statement(s) following the first true condition is executed and the rest of the algorithm is skipped over.
If (score <= 100) Then Let grade = A ElseIf (score < 90) Then Let grade = B ElseIf (score < 80) Then Let grade = C ElseIf (score < 70) Then Let grade = D Else Let grade = F EndIf
Desk-check table
score grade 55 65 75 85 95
Table 4-8
The result would be that each of the scores would receive an A grade because the first If selection tests out to be true in each case, and so no more testing is done after that.
ACTIVITY 4-9
Rewrite the algorithm above so that it assigns the correct grade for each score, and test it with the same test data. Ensure the output is correct. Use the correct indentation and setting out as modelled in the prior example. Desk-check table
score grade 55 65 75 85 95
Table 4-9
4-14
PDCLGA001b
Design an algorithm that will prompt an operator for three characters, accept those characters as input, sort them into ascending order and display them on the screen. Firstly, in accordance with the PDR, analyse the problem by identifying the list of subproblems. Then develop the VTOC and create a Data Table. The Data Table is given in Table 4-10 and you should study it to ensure that you understand it.
PROCESSING Prompt for characters Accept three characters Sort three characters Display three characters
Table 4-10. Data Table for Example 4.1
We will now work on the solution algorithm. The solution algorithm requires a series of If statements, one after the other, to sort the three characters into ascending order. Ascending order means to start with the lowest and go to the highest, that is the order from A to Z. This means that A < B < C <D < X <Y < Z. In this solution, most of the logic of the algorithm is concerned with sorting the three characters into ascending alphabetical order. Basically, the logic goes like this: 1. 2. Compare the first and second variables. If the first variable comes after the second in the alphabet, swap them around by placing the first in a temporary location, and then place the second in the original location of the first variable. Then place the original first variable into the previous location of the second. If the first variable comes before the second, leave them as they are. Using the same rules as for Steps 1 to 3, compare the second and third variables and swap them around if necessary Compare the first and second variables again to cater for the original third variable being the smallest, and swap them around if necessary.
3. 4. 5.
PDCLGA001b
4-15
S
char1
B
char2
Figure 4-3
temp
The value of char1 is bigger than the value of char2 (i.e., S comes after B in the alphabet) so they have to be swapped around to be in ascending order. Step 2: Put the value of char1 into a temporary location (temp).
B
char1 char2
Figure 4-4
S
temp
B
char1 char2
Figure 4-5
S
temp
4-16
PDCLGA001b
Step 4: Put the value that is in the temp cup into the char2 cup.
B
char1
S
char2
Figure 4-6
temp
The letters are now in the correct order B S. Explanatory comments have been added to the right hand side of the following algorithm to help you to understand the logic. This explanation is purely for your benefit to see how and why the values in the variables are swapped around. You would not put comments like this in an algorithm.
Compare char2 and char3, and swap them around if necessary so that the value of char2 is smaller than the value of char3.
char1 has to again be compared with char2 to allow for the case where the original char3 is the smallest of the three.
Now that we have developed an algorithm we have to test it to check it gives the right results.
PDCLGA001b
4-17
Desk-check table
Perform the desk-check by running the program on paper, passing each test data set through the solution algorithm, step by step. To help you keep track of the logic, we will also show the result of the If statements (true or false). The algorithm is repeated on this page to make it easier for you to do the desk-check.
Read three characters Get char1, char2, char3 If (char1 > char2) Then Let temp = char1 Let char1 = char2 Let char2 = temp EndIf If (char2 > char3) Then Let temp = char2 Let char2 = char3 Let char3 = temp EndIf If (char1 > char2) Then Let temp = char1 Let char1 = char2 Let char2 = temp EndIf Display on the screen char1, char2, char3 End
4-18
PDCLGA001b
Char1
char2
char3
VARIABLES temp
Steps 1 K G 2 char1 > char2 is True 3 4 G 5 K 6 char2 > char3 is True 7 8 B 9 10 char1 > char2 is True 11 B 12 G 13
B K
K K G
These results (char1 = B, char2 = G, char3 = K) match the expected results. The algorithm is repeated on this page to make it easier for you to do the desk-check.
Read three characters Get char1, char2, char3 If (char1 > char2) Then Let temp = char1 Let char1 = char2 Let char2 = temp EndIf If (char2 > char3) Then Let temp = char2 Let char2 = char3 Let char3 = temp EndIf If (char1 > char2) Then Let temp = char1 Let char1 = char2 Let char2 = temp EndIf Display on the screen char1, char2, char3 End
PDCLGA001b
4-19
Steps 1 S Z 2 If char1 > char2 is False 3 If char2 > char3 is True 4 5 A 6 7 If char1 > char2 is True 8 A 9 S 10 11 12 13
Z Z S
These results (char1 = A, char2 = S, char3 = Z) match the expected results. Here is another example. Example 4.2 Process customer record
A program is required to read a customers name, a purchase amount for an item and a tax code that is applicable to the item purchased. The tax code has been validated (only valid values used) and is one of the following:
0: 1: 2: 3: tax exempt type 1 tax type 2 tax type 3 tax (0%) (3%) (5%) (7%)
The program must then compute the amount of tax and the total amount due (purchase amount + tax amount), and print the customers name, amount of tax, and the total amount due. Referring to the PDR, you would start at Step 1 and analyse the problem by producing the List of Sub-problems. You would then develop a VTOC and a Data Table, which is the point where the example solution will commence.
INPUT Cust name purch amt tax code PROCESSING Read customer details Compute tax amount Compute total amount Print customer details
Table 4-14. Data Table for Example 4.2
4-20
PDCLGA001b
The tax code has to be 3 at this branch because that is the only value left
Now test the solution algorithm by choosing two sets of input data and establish the expected output for each. Run through the algorithm on paper with the test data to see if the output matches the expected output.
Desk-check table
Perform the desk-check by passing each test data set through the solution algorithm, step by step, and check that the results match the expected output.
cust name
purch amt
tax code
0 0 10.00
PDCLGA001b
4-21
cus purch amt t Steps na me 1 Mar 20.00 y 2 If tax code = 0 is False 3 If tax code = 1 is False 4 If tax code = 2 is True 5 6
tax code
1.00 21.00
Table 4-17. Second data set
A program is required by a company to read an employees number, hourly pay rate and the number of hours worked in a week. The program is then to calculate the employees weekly pay and print it along with the input data. According to the companys rules, no employee may be paid for more than 60 hours per week, and the maximum hourly rate is $25.00. If more than 35 hours are worked, then payment for the overtime hours worked is calculated at time-and-a-half. If the hours worked or the hourly rate is out of range, then the input data and an appropriate message are to be printed, and the employees weekly pay is not to be calculated. This example is slightly more complex because it involves validating the input data, but it will work out properly if we carefully follow the PDR.
4-22
PDCLGA001b
Develop a VTOC
Main
Initialise
Process
Finalise
Initialise Variables
Calculate pay
Print output
PROCESSING Read employee details Validate input values Calculate employee pay Print employee details
OUTPUT emp no pay rate hrs worked emp weekly pay error message
PDCLGA001b
4-23
The employees weekly pay is to be calculated only if the input variables, pay rate and hrs worked, are valid. The solution algorithm is given below, together with an explanation of some of its features. In passing, note that the solution outline indicated in the VTOC (see Figure 4-7) involves the performance of separate tasks (e.g., validate input data). A better solution would be to separate these tasks into modules, but modularisation is not covered until Section 6 where the solution to this example will be reviewed.
If (hrs worked > 60) Then Let error message = Hours worked exceeds limit of 60 Let valid input fields = false Print emp no, pay rate, hrs worked, error message EndIf If valid input fields = true Then If (hrs worked <= 35) Let emp weekly pay Else Let overtime hrs = Let overtime pay = Let emp weekly pay EndIf Then = pay rate * hrs worked hrs worked 35 overtime hrs * pay rate * 1.5 = (pay rate*35) + overtime pay
Print emp no, pay rate, hrs worked, emp weekly pay EndIf End
The algorithm starts off by initialising the valid input fields to true and the error message to blank. The first two If statements test the validity of the input variables pay rate, and hrs worked. If any one or both of them are invalid, the valid input fields is assigned the value of false. The outside If statement of the nested If statement then evaluates the boolean variable valid input fields and executes the inside If statement if it is true. The variable valid input fields is called a boolean variable. A boolean variable is one that contains only one of two possible values, true or false refer to Topic 1 in this Section. A boolean expression is one that has a boolean variable.
4-24
PDCLGA001b
ACTIVITY 4-10
Study the following segment of pseudocode and complete the values in Table 4-20, passing through the 4 different values for the variable response.
Set total = 100 Get response If ((response < 0) or (response > 30)) Then Let total = total 10 Print wrong answer Else Let total = total + 10 Print right answer EndIf
2 31
3 20
4 10
Table 4-20
PDCLGA001b
4-25
The path followed in the case structure depends on the value of the variable specified in the CaseOf clause. If the variable has value 1 then statement block 1 is executed and no more values are tested; it jumps to the EndCase. If it contains value 2 then statement block 2 is executed, and so on. The value other is included as an option in the event that the variable has none of the values in the list. It is important to realise that only one statement block will be executed the one that first matches the value of the CaseOf variable, and if there is no match, it goes to the value other. Let us look at the example used previously.
If record code = A Then increment counterA ElseIf record code = B Then increment counterB ElseIf record code = C Then increment counterC Else increment errorcounter EndIf
We can now rewrite the multiple-alternative If structure with a case structure, as follows:
CaseOf record code A : increment counterA B : increment counterB C : increment counterC other: increment errorcounter EndCase
4-26
PDCLGA001b
The case solution appears to be more readable than the multiple-alternative If statement, but it cannot always be used as a substitute for it. There are two main restrictions:
the case structure is not supported by all languages the case variable can only be a discrete value (that is, an integer or a letter) or a list of discrete values. It cannot be used where you need to test a range of values (for example, < 60 or A to L. Hence, it would not be used in a situation like ACTIVITY 4-9 above, which involves the testing of a range of values.
ACTIVITY 4-11
1. Write a case control structure to display the number of days in the month for a nonleap year using Table 4-21.
Month number 2 4, 6, 9, 11 1, 3, 5, 7, 8, 10, 12
Table 4-21
Number of days 28 30 31
NOTE: Multiple values can be grouped together to cause the execution of the same statement block . 2. Write a case control structure that assigns to the variable lumens the expected brightness of a light bulb depending on its wattage, as shown in the Table 4-22. Assign 1 to lumens if the value of the watts is not in the table.
25 215
40 500
Table 4-22
60 880
75 1000
100 1675
Let us look again at Example 4.2, and use a case statement in its solution. Example 4.4 Process customer record
A program is required to read a customers name, a purchase amount for an item and a tax code that is applicable to the item purchased. The tax code has been validated and will be one of the following:
0. 1. 2. 3.
PDCLGA001b
4-27
The program must then compute the amount of tax and the total amount due (purchase amount + tax amount), and print the customers name, amount of tax, and the total amount due. This is the same Data Table that was shown previously.
PROCESSING Read customer details Compute tax amount Compute total amount Print customer details
Table 4-23. Data Table for Example 4.4
Let total amt = purch amt + tax amt Print cust name, tax amt, total amt End
In the specifications for this problem, it was stated that the tax code has been validated (meaning that only valid values will be input into this construct) so no other value is needed as an alternative.
ACTIVITY 4-12
A program is required to prompt the user to enter an integer (a whole number) and if it is in the range from 1 to 7, the program will display a message giving the day of the week according to the pattern of Monday for 1, Tuesday for 2, Wednesday for 3, and so on. If it is outside the range of 1 to 7, the message Number not in range 1 7 will be displayed. The input data must be validated so that only a valid integer from 1 to 7 is involved in the logic to determine the day of the week.
4-28
PDCLGA001b
Create the Data Table for this problem. Check your answer by comparing it with the solution at the end of this Section.
INPUT
PROCESSING
OUTPUT
PDCLGA001b
4-29
Desk-check table
VARIABLES
Steps 1 2 3 4 5 6 7
First Data Set
VARIABLES
Steps 1 2 3 4 5 6 7
Second Data Set
VARIABLES
Steps 1 2 3 4 5 6 7
Third Data Set
VARIABLES
Steps 1 2 3 4 5 6 7
Fourth Data Set
4-30
PDCLGA001b
CHECKPOINT 2
Your solutions to these questions should be set out in the same way as the examples in this section. You must set out your solutions to each question using the framework of the Program Development Routine (PDR). You will need to: 1. 2. 3. 4. 5. Analyse the problem by making a list of the sub-problems. Develop a VTOC, which is an outline of the solution. Create a Data Table after identifying the inputs, the outputs, and the actions that make up the processing component. Write a solution algorithm in pseudocode. Desk-check the solution algorithm. 150 mins
Complete at least two of the four questions that are available. The extra questions are available to do if you have the time and the incentive. When you have completed two of the four questions, call on an instructor to check over your solutions and discuss with them any issues that are not clear to you. This constitutes the Checkpoint 2 Sign Off.
Question 1
Design an algorithm that will accept the price of an article and a pricing code. The program is then to calculate a discount rate according to the pricing code, and display on the screen the original price of the article, the discount amount and the new discounted price. The pricing code and discount amount are to be calculated as follows:
Pricing code H F T Q Z
Table 4-25
If the pricing code is Z, then the message No discount is to be displayed on the screen. If the pricing code is not H, Q, T, F or Z, then the message Invalid pricing code is to be displayed on the screen.
PDCLGA001b
4-31
Sub-problems
VTOC
4-32
PDCLGA001b
INPUT
PROCESSING
OUTPUT
PDCLGA001b
4-33
INPUT 10.00 Q
EXPECTED OUTPUT
100.00 A
1000.00 Z
Desk-check table
VARIABLES
Steps 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
First Data Set
4-34
PDCLGA001b
VARIABLES
Steps 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
Second Data Set
VARIABLES
Steps 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
Third Data Set
PDCLGA001b
4-35
Question 2
Design an algorithm that accepts a students ID and the students exam score out of 100. Your program is then to match the exam score to a letter grade and print the grade on the screen. Assume that the ID and exam score are valid input values. The letter grade is to be calculated as follows:
Exam Score 90 and above 80 to less than 90 70 to less than 80 60 to less than 70 below 60
Table 4-26
Grade A B C D F
Sub-problems
VTOC
4-36
PDCLGA001b
INPUT
PROCESSING
OUTPUT
The solution algorithm In designing the solution, you may be considering the use of a CASE construct. However, a CASE construct is not suitable for a range of values refer to Topic 4 in this Section.
PDCLGA001b
4-37
Desk-check table
VARIABLES
Steps 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
First Data Set
VARIABLES
Steps 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
Second Data Set
4-38
PDCLGA001b
Question 3
A transaction record on a Sales Commission File contains the retail price of an item sold, a transaction code which indicates the sales commission category for an item, and the employee number of the person who sold the item The transaction code can contain the values S, M or L that indicate that the percentage commission will be 5%, 7% or 10% respectively. Do not assume that only valid codes are input. Construct an algorithm that will read a record from the file, calculate the commission owing for that record, and print the retail price, commission and employee number. Sub-problems
VTOC
PDCLGA001b
4-39
4-40
PDCLGA001b
Desk-check table
VARIABLES
Steps 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
First Data Set
VARIABLES
Steps 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
Second Data Set
PDCLGA001b
4-41
Question 4
A home mortgage authority requires a deposit on a home loan according to the following schedule, shown in Table 4-27
Loan less than 50,000 50,000 to 99,999 100,000 to 199,999 200,000-300,000 Deposit to be paid 5% of loan value 1250 + 7% of loan over 50,000 7000 + 9% of loan over 100,000 14,000 + 11% of loan over 200,000
Table 4-27
Loans in excess of 300,000 are not allowed. Design a program that will accept a loan amount, and then compute and display the required deposit. Assume that only positive loan amounts will be input. Sub-problems
VTOC
4-42
PDCLGA001b
PDCLGA001b
4-43
Desk-check table
VARIABLES
Steps 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
First Data Set
VARIABLES
Steps 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
Second Data Set
4-44
PDCLGA001b
CHECKPOINT 2 (CONTINUED)
When you have completed two questions, call an instructor to have your solutions signed off and discuss any issues about them. While you are waiting for the instructor to attend to you, continue on with the next section. The instructor sign off sheet is in Appendix B Checkpoints for Instructor Sign Off, at the end of the Learning Guide just before the Glossary. When you have finished this section, update your suggested work plan on pages vi and vii with the actual date you finished.
PDCLGA001b
4-45
ACTIVITY SOLUTIONS
Activity 4-1
1. False 6. False 2. True 7. False 3. True 8. True 4. False 9. True 5. True 10. We hope it is true
Activity 4-2
X 2 5 7 1 9 -3 Y 5 2 -2 0 1 1 X>5 false false TRUE false TRUE false Y <= 2 false TRUE TRUE TRUE TRUE TRUE X > 5 and Y <= 2 false false TRUE false TRUE false X > 5 or Y <= 2 false TRUE TRUE TRUE TRUE TRUE
Activity 4-3
1. True 4. True 2. True 5. True 3. True 6. False
Activity 4-4
A T T T T F F F F B T T F F T T F F C T F T F T F T F A or B or C TRUE TRUE TRUE TRUE TRUE TRUE TRUE false (A and B) or C TRUE TRUE TRUE false TRUE false TRUE false A and B and C TRUE false false false false false false false A or (B and C) TRUE TRUE TRUE TRUE TRUE false false false
Activity 4-5
account balance 200 600 1000 < 500 >= 500 500 499 500 501 service charge 5 2 2 5 2 5 5 2 2
PDCLGA001b
4-46
Activity 4-6
alpha 5 50 99 500 501 beta 10 40 100 500 500 Gamma 900 30 900 30 30
Activity 4-7
(a) (b) (c) (d) X 2 7 8 6 Y 4 2 3 2 Z 6 5 7 8 day Monday Friday Friday Monday K 20 10 15 15 L 25 20 10 15 M 30 25 30 15 month July July March March
The following two tables show the evaluation of the boolean expressions for working out whether the combined If selection is True or False
X<7 T F F T
Y=2 F T F T
((X<7) OR (Y=2)) T OR F = T F OR T = T F OR F = F T OR T = T
Z>5 T F T T
L>10 T T F T
M<30 F T F T
((L>10)OR(M<30)) T OR F = T T OR T = T F OR F = F T OR T = T
K<>15 T T F F
Activity 4-8
zone 2 4 1 3 OUTPUT 2000 ERROR 1000 3000
PDCLGA001b
4-47
Activity 4-9
If (score < 60) Then Let grade = F ElseIf (score < 70) Then Let grade = D ElseIf (score < 80) Then Let grade = C ElseIf (score < 90) Then Let grade = B Else Let grade = A EndIf
There is more than one correct way of doing it. The purpose of this activity is to demonstrate that the order of the statements can affect the outcome and you must always desk-check the algorithm.
Activity 4-10
response total If (response<0) or (response>30) total Printed message 1 15 100 False 110 right answer 2 31 100 True 90 wrong answer 3 20 100 False 110 right answer 4 10 100 True 90 wrong answer
Activity 4-11
1.
CaseOf month number 2 : Let number of days = 28 4, 6, 9, 11 : Let number of days = 30 1, 3, 5, 7, 8, 10, 12 : Let number of days = 31 other : display error message EndCase
2.
CaseOf Watts 25 : Let lumens = 40 : Let lumens = 60 : Let lumens = 75 : Let lumens = 100 : Let lumens = 1675 other : Let lumens = 1 215 500 880 1000
EndCase
PDCLGA001b
4-48
Activity 4-12
The Data Table
PROCESSING prompt for integer get integer validate integer determine day of week
OUTPUT message
The solution algorithm Your solution does not have to be exactly like this, but it should be similar.
Day of week Set valid integer to true Set message to blank prompt for integer Get int number If ((int number < 1) OR (int number > 7)) Then Set valid integer to false Let message = Number not in range 1 7 EndIf If valid integer = True Then CaseOf int number 1 : Let message = Monday 2 : Let message = Tuesday 3 : Let message = Wednesday 4 : Let message = Thursday 5 : Let message = Friday 6 : Let message = Saturday 7 : Let message = Sunday EndCase EndIf Display message End The INITIALISE phase of the algorithm
Steps 1 True 2 blank 3 1 4 If (int num < 1) OR (int num >7) is False 5 If valid integer is True 6 Monday
PDCLGA001b
4-49
Step s 1 True 2 blank 3 4 4 If (int num < 1) OR (int num >7) is False 5 If valid integer is True 6 Thursday
Step s 1 True 2 blank 3 0 4 If (int num < 1) OR (int num >7) is True 5 False 6 Number not in range 1 - 7 7 If valid integer is False
Step s 1 True 2 blank 3 10 4 If (int num < 1) OR (int num >7) is True 5 False 6 Number not in range 1 - 7 7 If valid integer is False
PDCLGA001b
4-50
5.0
OBJECTIVES
1. 2. 3. 4.
330 mins
On successful completion of this section, you will be able to: Develop algorithms that use a While .. EndWhile control structure Develop algorithms that use a RepeatUntil control structure Develop algorithms for fixed-number repetition loops using For .. EndFor Apply repetition constructs to the processing of arrays
TOPICS
1. 2. 3. 4. Repetition using the While .. EndWhile control structure Repetition using the RepeatUntil control structure Fixed-Number Repetition using the For .. EndFor control structure Using Repetition for processing Arrays
PDCLGA001b
5-1
60 mins
The loop is known as a leading decision loop because it tests for the condition prior to the execution of the loop, as follows: 1. 2. The logical condition p is tested. If the condition p is true, then the commands within the statement block are executed once. Control then returns to the re-testing of condition p (step 1). The commands within the statement block will continue to be executed so long as the condition p is true. If the condition p is false, then the statement block is bypassed and the control jumps to the next statement after the EndWhile terminator.
3.
The While .. EndWhile control structure consists of two parts: a loop control specification (at the beginning of the loop) and a loop body. The loop control specification contains a boolean expression (see Section 4, Topic 1) that usually consists of 1. 2. 3. an identifier that represents a loop control variable, a relational operator, and an identifier that represents a value to which the loop control variable is compared.
There are two important considerations about which you must be aware when designing a While .. EndWhile loop. 1. The testing of the condition is at the beginning of the loop. This means that the programmer may need to perform some initial processing to adequately set up the condition before it can be tested. The only way to terminate the loop is to render the While condition false. This means you must set up some process within the loop that will eventually change the condition to false. Failure to do this will result in getting trapped in an endless loop a common trap for the unwary.
2.
5-2
PDCLGA001b
Each time the loop control specification executes, the boolean expression is evaluated to see whether it is true or false. As long as the expression evaluates to true, the loop body repeats. When an update of a loop control variable within the loop body causes the boolean expression to evaluate to false, the While .. EndWhile statement is exited. The loop body does not execute after this final evaluation of the boolean expression. In summary, the While .. EndWhile structure will continue to repeat a group of statements while a condition remains true. As soon as the condition becomes false, the construct is exited. Lets look at some examples of the While .. EndWhile construct. Example 5.1 is a problem where it is not known beforehand how many records are to be processed, but the file has a trailer record (a record trailing in last position) known as a flag or sentinel. The sentinel is a special value placed as the last record of the input data to signify the end of the data. It must contain a value that is clearly distinguishable from the other data to be processed. It is referred to as a sentinel because it signals that no more data follows. Example 5.1 Print exam scores (Uses a Priming Read)
A program is required to enter and print a series of names and exam scores for an unknown number of students enrolled in the Structured Programming Concepts module. The class average is to be computed and printed at the end of the report. Scores can range from 0 to 100. The last entry is to be a blank name and a score of 999 to indicate the end of the input data. This last score is not to be included in the calculations.
ACTIVITY 5-1
Analyse the problem carefully to identify the sub-problems and develop the VTOC. Underline the nouns and adjectives to identify the inputs and outputs. Underline the verbs to identify the processing tasks. Create the Sub-problems, VTOC and Data Table for this example. Sub-problems
PDCLGA001b
5-3
VTOC
INPUT
PROCESSING
OUTPUT
We will now continue developing a solution for Example 5.1. The solution algorithm In this example we need:
a While .. EndWhile structure to control the entry of names and exam scores, an accumulator for total scores, and an accumulator for the total number of students.
Print examination scores Set total students to zero Set total score to zero Get name, exam score While (exam score <> 999) Add 1 to total students Print name, exam score Add exam score to total score Get name, exam score EndWhile If (total students > zero) Then average score = total score / total students Print average score EndIf End Initialise variables
Loop control specification
5-4
PDCLGA001b
This solution algorithm is a typical example of the basic algorithm design for processing sequential records of data. There is an unknown number of records, so a sentinel value (999 in this example) is used to terminate the loop. The sentinel is used in the While clause (While exam score <> 999). The While test condition cannot be evaluated until at least one exam score has been entered into the loop control variable. Hence, the initial processing that sets up the condition is a Read statement immediately before the While clause (Get name, exam score). This is known as a Priming Read, and its use is extremely important when processing sequential records. This Read statement primes the test variable (i.e., gives it its first value) to make the loop start working. It is analogous to pouring water into a pump (priming the pump) to make it start pumping. The algorithm will require another Read (or Get) statement, within the body of the loop. Its position is also important. The sentinel record must not be included in the calculation of average score, so each time an exam score is entered, it must be tested for a 999 value before further processing can take place. For this reason, the Read statement is placed at the end of the loop, immediately before the EndWhile, so that the value of the loop control variable can be tested when control returns to the While condition at the top of the loop. As soon as the record with the sentinel value has been entered, control will exit from the loop and go to the next statement after the EndWhile. The Priming Read before the While condition and the subsequent Read within the loop immediately before the EndWhile statement form the basic framework for a While .. EndWhile repetition in pseudocode. In general, all algorithms using a While .. EndWhile construct to process a sequential file should have the same basic pattern, as follows:
Process sequential file Initial processing Read first record While more records exist Process this record Read next record EndWhile Final processing End
PDCLGA001b
5-5
INPUT name Lisa exam score 70 name Pete exam score 80 name exam score 999
Table 5-1
EXPECTED OUTPUT name Lisa exam score 70 name Pete exam score 80 average score 75
The Activity Solution can be found at the end of this Section. Example 5.2 Process student enrolments (Uses EOF and Not EOF)
We will now look at an example that reads in records from a sequential file that has a special character, called EOF, to indicate the end of the file (EOF = End Of File). This character is added to the end of the file automatically by the computer when the file was first created. A sequential file has its records in a fixed sequence, like the carriages of a train. Continuing this metaphor, the EOF is like the Guards Van. A program is required that will read a file of student records, and select and print only those students enrolled in a module called Program Design Concepts. Each student record contains student ID, name, address, postcode, gender, and module code. The module code for Program Design Concepts is PDC. Two totals are to be printed at the end of the report:
NOTE: There is no sentinel record (like 999 in the previous example) for this student file. In cases like this, the term Not EOF can be used in the following form While Not EOF. EOF means End Of File.
While Not EOF
5-6
PDCLGA001b
By expressing the condition in this way, you leave it up to the computer to indicate to the program that there are no more records in the file. When an attempt is made to read a record and no more records exist, a signal is sent to the program to indicate that there are no more records. When this happens, the While Not EOF loop control condition is rendered false thus causing the control to jump out of the loop.
PROCESSING Read student records Select student records Print selected records Compute total females enrolled Compute total students enrolled Print totals
OUTPUT selected student records total females in PDC total students in PDC
a While .. EndWhile structure to perform the repetition, an IF statement and a nested IF statement to select the required students, and accumulators for the two total fields.
This solution algorithm uses the same basic framework as the previous example. A nested If statement was used to determine the required selection logic.
PDCLGA001b
5-7
The algorithm testing process Three student records should be sufficient to test this algorithm. Since student ID, name, address, and postcode are not operated upon in this algorithm, they do not need to be in the input data sets. Test Data table
st
INPUT module code DWS gender Female module code PDC gender Female module code PDC gender Male
Table 5-3
1 2
ACTIVITY 5-2
Pass the test data through the solution algorithm, statement by statement, and check that the output results match the expected results. Draw up your own Desk-check Table.
5-8
PDCLGA001b
PDCLGA001b
5-9
60 mins
You can see that Repeat .. Until is a trailing decision loop in that the condition is tested at the bottom of the loop and so the statements are executed at least once. In contrast, the While .. EndWhile loop is a leading decision loop where the condition is tested at the beginning of the loop, and it is possible that the statements are not executed even once.
There are two other considerations about which you need to be aware. 1. Repeat .. Until loops are executed when the condition is false. It is only when the condition becomes true that repetition ceases. Thus the logic of the condition clause of the Repeat .. Until structure is the opposite of the While .. EndWhile structure. For example:
2.
While Not EOF is equivalent to RepeatUntil EOF While (score < >999) is equivalent to RepeatUntil (score = 999)
The statements within a Repeat .. Until structure will always be executed at least once. As a result, there is no need for a Priming Read. Only one Read statement at the beginning of the loop is used.
5-10
PDCLGA001b
Example 5.3
A petrol station manager has decided to give a prize to the customer who purchases the 500th litre of petrol in a day. A program is needed to accept the number of litres of petrol purchased by each customer and keep a running total. When the 500th litre is sold, an appropriate message is displayed.
Find lucky customer Initialise total litres to zero Repeat Prompt for litres purchased by customer Accept litres purchased by customer Add litres purchased to total litres Until (total litres >= 500) Display This customer has purchased the 500th litre End
The majority of examples given in this Learning Guide will use the While .. EndWhile construct in preference to the Repeat .. Until construct because in most cases we do not wish to process the statements in the loop if the test condition fails. We will use the Repeat .. Until on the occasions when we need to process the loop statements at least once. Example 5.4 Process inventory items
A program is required to read a series of inventory records that contain item number, item description and stock figure. The last record in the file has an item number of zero. The program is to produce a Low Stock Items report by printing only those records that have a stock figure of less than 20 items. A heading is to be printed at the top of the report and the total number of low stock items is to be printed at the end. The Data Table
INPUT inventory record item number item description stock figure PROCESSING Print Heading Read inventory records Select low stock items Print low stock records Print total low stock records OUTPUT heading selected records item number item description stock figure total low stock items
a Repeat .. Until structure to perform the repetition, an If statement to select stock figures of less than 20, an accumulator for total low stock items, and an extra If, within the Repeat loop, to ensure the sentinel record is not processed.
PDCLGA001b
5-11
This solution algorithm has a simple structure, with a single Read statement at the beginning of the Repeat .. Until loop and an extra IF statement within the loop to ensure that the sentinel record (item number = 0) is not printed and added to the total number of low stock items.
ACTIVITY 5-3
To practise your skill of writing a While .. EndWhile construct, complete the following algorithm that uses a While .. EndWhile structure for the problem in Example 5.4. The solution algorithm using While .. EndWhile
Process inventory records Set total low stock items to zero Print Low Stock Items heading
5-12
PDCLGA001b
60 mins
For loop index changing from initial value to final value statement block EndFor Body of the Loop
The loop control specification determines the number of times the body of the loop executes. When the value of the loop index variable equals the final value, the body of the loop executes for the final time. The For statement will: 1. 2. initialise the loop index to the required starting value. increment the loop index by 1 automatically for each pass through the loop. Remember, you do not have a statement inside the body of the loop that will modify the value of the loop index counter it is changed automatically, in ascending order. test the value of the loop index at the beginning of each loop to ensure that it is within the stated range of values. terminate the loop when the loop index has exceeded the specified final value.
3. 4.
A fixed-number repetition construct will perform the initialising, incrementing and testing of the loop counter automatically. It will terminate the loop once the required number of iterations has been executed.
PDCLGA001b
5-13
Example 5.5
A weather station receives 15 temperatures expressed in degrees Fahrenheit. A program is to be written that will accept each Fahrenheit temperature, convert it to Celsius and display the temperature in Celsius to the screen. After 15 temperatures have been processed, the words All temperatures processed are to be displayed on the screen. The Data Table
INPUT f temp (15 temperatures) PROCESSING Prompt for temperatures Get Fahrenheit temperatures Convert temperatures Display Celsius temperatures Display screen message OUTPUT c temp (15 temperatures)
Table 5-5
The solution algorithm The use of a For .. EndFor loop will require a loop counter (temperature count) to process the repetition.
Fahrenheit to Celsius conversion For temperature count changing from 1 to 15 Get f temp Compute c temp = (f temp 32)*5/9 Display c temp EndFor Display All temperatures processed End
NOTE: The For statement: initialises temperature count to 1 and increments it by 1 automatically for each pass through the loop. There is no statement needed to increase the loop control variable, such as temperature count =
temperature count + 1
it is within the range 1 to 15 terminates the loop once temperature exceeded 15.
has
A requirement of the fixed-number repetition loop structure is that the exact number of input data items or records needs to be known in advance. For this reason, fixed-number repetition loops are used extensively with arrays. Arrays will be the focus of study in the next Topic.
5-14
PDCLGA001b
ACTIVITY 5-4
The algorithm testing process Use the following test data shown in Table 5-6 to desk-check the algorithm given for Example 5.5. Test Data table
1 record nd 2 record th 14 record th 15 record
st
PDCLGA001b
5-15
An array can be thought of as a collection of cards that can all have something different written on each of them but it must be the same type of data on each. The name of the collection is the group name for all the cards and each card is referred to by its position number in the collection. The array is a data structure in which we store a collection of data items of the same type (e.g., all the integer exam scores for a class). By using an array, you can associate a single variable name, such as scores, with the entire collection of data. The individual elements of the array can then be accessed by the use of an index or subscript beside the name of the array, for example scores[3]. The index indicates the position of an element within an array. For example, scores[3] points to the third element of the array scores.
NOTE: Some programming languages use zero as the first index in an array, in which case in the programming code scores[2] would be the third item in the scores array in the last example. In algorithms which are meant to be language neutral the index should indicate which item is being referred to. Often when coding, due to programming language syntax, slight differences may exist between an algorithm and the way it needs to be implemented in a particular programming language .
5-16
PDCLGA001b
ACTIVITY 5-5
Consider the following array and the data that it contains shown in Table 5-7.
Show the value of the following: name[3] name[5] name[6] name[8] name[1] The Activity Solution can be found at the end of this section You may often need to process the elements of an array in sequence, starting with the first element. This can be accomplished in pseudocode with a For .. EndFor loop, which was covered in Topic 3. Study the following example. Example 5.6 Process exam scores
Design a program that will receive 18 scores from a Structured Programming exam, compute the group average, and display all the scores and the group average on the screen.
PDCLGA001b
5-17
The Data Table Identify the inputs, outputs and processing tasks, and complete the Data Table shown in Table 5-8.
INPUT scores
PROCESSING Get exam scores Compute average score Display scores Display average score
Table 5-8
The solution algorithm This is an example of a fixed-number repetition loop because we know that there are exactly 18 exam scores. You will need to consider the following requirements:
an array (scores ) to store the exam scores, an index [index] to identify each element in the array, a For .. EndFor loop to accept the scores, a For .. EndFor loop to display the scores to the screen.
Process exam scores Set total score to zero For index changing from 1 to 18 Prompt for score Get scores[index] Let total score = total score + scores[index] EndFor Compute average score = total score / 18 For index changing from 1 to 18 Display scores[index] EndFor Display average score END Display all the scores from the array Put all the scores into the array
5-18
PDCLGA001b
ACTIVITY 5-6
Design a solution algorithm that will prompt for and get 100 integers and read them into an array. It must count the number of integers that are greater than the average value of all the integers in the array. The algorithm is to display the average value and the number of the integers that are greater than the average. Sub-problems
VTOC
PDCLGA001b
5-19
5-20
PDCLGA001b
Desk-check table
VARIABLES
Steps 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
First Data Set
VARIABLES
Steps 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
Second Data Set
The Activity Solution can be found at the end of the section. PDCLGA001b Computer Power Institute
5-21
CHECKPOINT 3
150 mins These four self test questions should consolidate the groundwork developed in the previous sections of this Learning Guide by putting all the control structures together. The algorithms that you develop will use a combination of sequence, selection and repetition constructs. You must set out your solutions to each question using the framework of the Program Development Routine (PDR). You will need to: 1. 2. 3. 4. 5. Analyse the problem by making a list of the sub-problems. Develop a VTOC, which is an outline of the solution. Create a Data Table after identifying the inputs, the outputs, and the actions that make up the processing component. Write a solution algorithm in pseudocode. Desk-check the solution algorithm.
A soft copy of PDR forms is available in the Microsoft Word file H:\PDCWORK\PDRFORMS.DOCX, which is located in your home directory. Create a new Microsoft Word document and copy into it the forms that you need to use. You can modify the forms to suit specific situations.
5-22
PDCLGA001b
Question 1
Each record in a file of student records contains the students ID, name, age, gender, address and attendance pattern (full time F/T or part time P/T). Design a solution algorithm that will read the file, and produce a report of all female students who are enrolled part time. The report is to be headed PART TIME FEMALE STUDENTS and is to show the students ID, name, address, and age.
Question 2
Design a program that will read a file of sales records and produce a sales report. Each record in the file contains a customers ID, name, a sales amount, and a validated GST code. The GST code is to be applied to the sales amount to determine the sales tax due for that sale, as shown in Table 5-9.
GST Code 0 1 2 GST Rate 0% 5% 10%
The report is to print a heading SALES REPORT, and detail lines listing the customers ID, name, sales amount, sales tax, and total amount due including sales tax.
Question 3
Design a solution algorithm that will read a file of student exam results and produce a STUDENT EXAM RESULTS report. Each exam record contains the student ID, name and exam score (out of 50). The program is to calculate for each student the exam score as a percentage and to print the students ID, name and exam score (out of 50) and letter grade on the report. The letter grade is determined as follows: A = 90 to 100% B = 80 to 89% C = 70 to 79% D = 60 to 69% F = 0 to 59%.
Question 4
The Domestic Gas Supply Company records its customers gas usage figures on a Customer Usage File. Each record on the file contains the customer number, customer name, customer address and gas usage expressed in cubic metres. The company bills its customers according to the following rate:
if the customers usage is 60 cubic metres or less, a rate of $2.00 per cubic metre is applied,
if the customers usage is more than 60 cubic metres, a rate of $1.75 per cubic metre is applied for the first 60 cubic metres, and $1.50 per cubic metre for the remaining usage. Design a solution algorithm that will read the Customer Usage File and produce a report listing each customers number, name, address, gas usage and the amount owing. At the end of the report, print the total number of customers and the total amount owing to the company.
PDCLGA001b
5-23
CHECKPOINT 3 (CONTINUED)
When you have completed all four questions, call an instructor to have your solutions signed off and discuss any issues that are not clear to you. This constitutes the Checkpoint 3 Sign Off. While you are waiting for the instructor to attend to you, continue on with the next section. The instructor sign off sheet is in Appendix B Checkpoints for Instructor Sign Off, at the end of the Learning Guide just before the Glossary. When you have completed this section, update your suggested study plan on pages vi and vii with the actual date you finished.
5-24
PDCLGA001b
ACTIVITY SOLUTIONS
Activity 5-1
The Data Table
PROCESSING Enter student details Print student details Compute average score Print average score
Desk-check table
Step s 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
total students 0
total score
name
exam score
0 Lisa 70 While exam score <> 999 is True 1 70 Pete 80 While exam score <> 999 is True 2 150 999 While exam score <> 999 is False IF total students > zero is True 75
PDCLGA001b
5-25
Activity 5-2
Desk-check table
Step s 1 2 3 4 5 6 7 8 9 10 11 12 13
modul e code
VARIABLES gender
DWS While Not EOF is True IF module code = PDC is False PDC While Not EOF is True IF module code = PDC is True 1 IF gender = female is True 1 PDC While Not EOF is True IF module code = PDC is True 2 IF gender = female is False While Not EOF is False
female
female
male
14 15 16 17
Activity 5-3
The solution algorithm using WHILE .. ENDWHILE
Process inventory records Set total low stock items to zero Print Low Stock Items heading Read inventory record While item number not = zero If (stock figure < 20) Then print item number, item description, stock figure increment total low stock items EndIf Read inventory record EndWhile Print total low stock items End
This solution, using WHILE .. ENDWHILE, has a Priming Read, and another Read at the end of the loop just before the EndWhile. When a record containing an item number of zero is read, the While condition becomes false and the looping ceases.
5-26
PDCLGA001b
Activity 5-4
Step s 1 1 2 32 3 0 4 2 5 96.8 6 36 7 3 th skip down to the 14 record 8 14 9 100 10 37.8 11 15 12 212 13 100 14 16 no more loop processing
Activity 5-5
name[3] name[5] name[6] name[8] name[1] Mike Peter Lauren Rod Lisa
Activity 5-6
List of Sub-problems
Enter the integers into the array Calculate the average Display the average and the number of integers that are greater than the average
VTOC
Main
Process
Finalise
Calculate Average
PDCLGA001b
5-27
Data Table
INPUT 100 integer values PROCESSING Read integer values Calculate average value Count how many numbers above avg Display average value Display how many numbers above avg OUTPUT average integer count
Solution algorithm
Process integer array Set integer total to zero Set integer count to zero For index changing from 1 to 100 Prompt for integer Get numbers[index] Let integer total = integer total + numbers[index] EndFor Let average = integer total / 100 For index changing from 1 to 100 If (numbers[index] > average) Then add 1 to integer count EndIf EndFor Display average, integer count End
5-28
PDCLGA001b
Section 6: Modularisation
6.0
OBJECTIVES
1. 2. 3.
SECTION 6 MODULARISATION
45 mins
On successful completion of this section, you will be able to: Apply modularisation to the process of dividing a problem into subtasks Use a VTOC diagram to represent a modularised program structure Develop algorithms that use a modularised structure
TOPICS
1. 2. 3. The Concept of Modularisation VTOC Diagrams in Modular Programs Steps in Modularisation
PDCLGA001b
6-1
Section 6: Modularisation
The problems and solution algorithms presented so far have all been relatively simple. As programming problems increase in complexity, it becomes more difficult to consider the solution as a whole. So you must first identify the major tasks to be performed in the problem, and then divide the problem into sections that represent those tasks. These sections can be considered subtasks or functions. After the major subtasks in the problem have been identified, then you may need to look at each of them to identify further subtasks within them, and so on. The process of identifying the major tasks and then subtasks within them, is known as topdown design or function decomposition. By using this top-down design methodology, you are adopting a modular approach to program design. That is, each of the subtasks or functions will eventually become a module within the algorithm or program. Within an object oriented solution, which you will look at in the next section, we will use abstraction to break the system being analysed down further into objects which model that system. In this case these modules become part of the objects that are used to implement the solution. The code with these modules which are referred to as methods or member functions is implemented in structured code as before. A module can be defined as a section of an algorithm that is dedicated to a single function. It is a group of executable instructions with a single point of entry and at least a single point of exit. The use of modules makes the algorithm simpler, more systematic, easier to understand, and more likely to be free of errors. Since each module represents a single task, you can develop the solution algorithm task by task, or module by module, until the complete solution has been devised. The modules can also be tested individually which simplifies the testing process. Top-down design methodology allows you to concentrate on the overall design of the algorithm without getting too involved with the details of the lower-level modules. Another benefit of top-down design is that modules, once identified and written, can be re-used or independently modified if necessary. When an object oriented solution is implemented the objects created and therefore the methods they contain can be reused in later projects in the same way.
6-2
PDCLGA001b
Section 6: Modularisation
A module must be large enough to perform its task, and must include only the operations that contribute to the performance of that task. It should have a single entry and at least one exit with a top-to-bottom sequence of instructions. The name of the module should describe the work to be done as a single specific function.
The convention of naming a module by using a verb followed by an object is particularly important here, as it helps to identify the specific function that the module has been designed to perform. Also, the careful naming of modules using this convention makes the algorithm easier to follow. For example, typical module names might be:
Print page headings Calculate Tax Validate input data
By using meaningful module names such as these, you can automatically describe the task that the module has been designed to perform, and anyone reading the algorithm can easily see what the module is supposed to do.
PDCLGA001b
6-3
Section 6: Modularisation
The concept of VTOC diagrams that you are already familiar with, can now be extended to programs that are broken up into modules. Each box in the tree-like diagram represents a module in the program, and the lines connecting them represent the relationship of each module to others. The box at the top of the VTOC is the master control module. On the next level are the modules that are called directly from the master control module, that is, the modules immediately subordinate to the master control module. On the next level are the modules that are subordinate to the modules on the first level, and so on. A module will pass control to a subordinate module when it is ready for that module to perform its task. The first module is said to call the subordinate module, and is therefore referred to as the calling module. The subordinate module would be referred to as the called module. On completing its specific task, the called module returns control back to the calling module.
6-4
PDCLGA001b
Section 6: Modularisation
Example 6.1
A program is required by a company to read an employees number, pay rate and the number of hours worked in a week. The program is then to compute the employees weekly pay and print it along with the input data. The program is to continue reading employee details until there are no more records on the file. According to the companys rules, no employee may be paid for more than 60 hours per week, and the maximum hourly rate is 25.00 per hour. If more than 35 hours are worked, then payment for the overtime hours worked is calculated at time-and-a-half. If the hours worked field or the hourly rate field is out of range, then the input data and an appropriate message are to be printed and the employees pay is not to be calculated. List of sub-problems
Read employee details Validate input data Calculate weekly pay Print details Continue process until there are no more records left
Table 6-1. List of sub-problems for Example 6.1
VTOC The basic template of Initialise, Process, Finalise is used as the framework for the three Level 1 modules. The Process a record module can itself be divided into two separate modules at Level 2 for the sake of simplicity Validate input fields and Calculate employee pay. See Figure 6-2.
Initialise
Process a record
Finalise
PDCLGA001b
6-5
Section 6: Modularisation
Solution algorithm using modules By breaking the tasks into manageable modules, you can concentrate on the logic of the master control module, leaving the details of the lower level modules till later. The variable valid input fields will be used as a control flag to control the calculation of the employees pay in the Level 2 module. Master control module
Compute Call Call Call End employee pay Initialise Process a record Finalise
Subordinate modules
Initialise Display opening message Open file Initialise valid input fields to true Read emp no, pay rate, hrs worked End Process a record While Not EOF Call Validate input fields If (valid input fields = true) Then Call Calculate employee pay Print emp no, pay rate, hrs worked, emp weekly pay Else Set valid input fields to true EndIf Read emp no, pay rate, hrs worked EndWhile End Validate input fields Set error-message to blank If (pay rate > 25) Then Let error message = Pay rate exceeds 25 Let valid input fields = false Print emp no, pay rate, hrs worked, error message EndIf If (hrs worked > 60) Then Let error message = Hours worked exceeds limit of 60 Let valid input fields = false Print emp no, pay rate, hrs worked, error message
6-6
PDCLGA001b
Section 6: Modularisation
EndIf End Calculate employee pay If (hrs worked <= 35) Let emp weekly pay Else Let overtime hrs = Let overtime pay = Let emp weekly pay EndIf End Then = pay rate * hrs worked hrs worked 35 overtime hrs * pay rate * 1.5 = (pay rate * 35) + overtime pay
By writing the solution algorithm as separate modules, the readability of the solution has been greatly improved. The master control module will call its subordinate modules when it wants to pass control to them. When processing is complete in the called module, control will pass back to the next line in the calling module. Example 6.2 Create patient account
Following is the pseudocode of a module that produces accounts for patients upon their discharge from hospital. The module is named Create patient account, and it calls several modules subordinate to it. We will examine the VTOC, which would have been created first, for this example.
Create patient account Call Compute accommodation charges Call Compute theatre charges Call Compute pathology charges Call Compute sundries charges Call Print patient account End
This module calls on a series of other modules to perform the task of generating a hospital patients account. The module passes control to another module that performs a specific task. When the modules task is finished, it passes control back to the next line in the calling module. The VTOC as developed so far would have looked like that shown in Figure 6-4.
PDCLGA001b
6-7
Section 6: Modularisation
One of the called modules may call other modules that are subordinate to it. For example, the Compute theatre charges module may need to call other modules to help it complete its task. It may call subordinate modules named Calculate doctors charges, Calculate anaesthetists charges, and Calculate facilities charges. Similarly, Compute sundries charges may need to call two subordinate modules, Calculate TV charges and Calculate telephone charges. When we reveal these modules to the next level of the VTOC, it looks like that shown in Figure 6-5.
Calculate TV charges
A note about variables and functions In practice a program may consist of many or even hundreds of modules. the examples we have looked at assume the variables we are using are common to all the modules involved in the algorithm. However it is good programming practice not to share variables in this way as it make applications difficult to maintain and debug. We do this by only using a variable where it is required. If it is needed in another part of the application we pass the variable to the function where it is needed. You can implement this in your algorithm by using the passing keyword in your pseudo code.
Call Compute Theatre Charges passing Patient ID
This makes it clear that the Compute Theatre Charges function uses the Patient ID which is passed to it. A function can also return a value to the calling code, perhaps the result of a calculation. You can make this clear by using the keyword Return in your pseudo code in the function returning the value. For example:
Calculate Invoice Code to calculate Invoice Total Return Invoice Total End
The pseudo code which calls the function can use the value returned by the function directly. For example:
InVoiceTotal = Call Calculate Invoice passing Patient ID
6-8
PDCLGA001b
Section 6: Modularisation
This example passes the Patient ID to the Calculate Invoice function and stores the value returned in the InvoiceTotal variable. You will find these techniques useful when working on your actual coding modules, they will not be in the PDC exam.
PDCLGA001b
6-9
Section 6: Modularisation
3. 4.
5.
With more complex solutions where a module may be called from multiple locations within the same solution VTOC diagrams may become overly complex. At that point it may be more convenient to divide the solution over multiple VTOCs or have VTOCs which represent different levels of detail in the solution. In practice more complex solutions especially those implementing object oriented design are normally represented by more recent standards such as UML diagrams which you will be looking at in the UML (Unified Modelling Language) module.
6-10
PDCLGA001b
7.0
OBJECTIVES
1. 2.
245 mins
On successful completion of this section, you will be able to: Understand abstraction and object modelling and apply it to the creation of algorithms using objects to implement object oriented solutions Understand how to express an algorithm for an event driven solution
TOPICS
1. 2. Object Oriented Algorithms Event Driven Algorithms
PDCLGA001b
7-1
7-2
PDCLGA001b
Once the Car object is created you access its members using dot notation: Cadillac.number_of_wheels = 4 If you wish to call a member function, you can use the call syntax as used previously. Call Cadillac.clean or just Cadillac.clean You can pass values to member functions as shown in the previous section.
Call Cadillac.set_value passing sale price
You can separate multiple values you want to pass to the member function using commas. Call Cadillac.sold passing buyer, sale price In later programming modules in a solution design you may need to remove an instance of an object you have created to conserve memory for example:
Delete Cadillac
This removes the instance of the Car named Cadillac. It does not remove the Car object template and more Cars can be created later in the code. The new object data type can be used anywhere in the pseudo code a fundamental data type can be used. Thats how we will be using OOP, but what is it? OOP may be seen as a group of cooperating objects as opposed to the more conventional structured model we have seen up until now where a program is seen as a list of tasks (modules) to perform. In OOP each object is capable of receiving data, processing data and sending data to other objects. Each object can be seen as independent with a distinct role or responsibility for implementing part of the overall model. The modelling of complex processes is known as abstraction as the objects we create can be viewed as a virtual (simulated) concept of how that part of the model works. The actions (functions or operators) performed on the objects are closely associated with the object and unlike in structured programming are defined as part of the object definition itself. We will not look at the detailed concepts of OOP here; you will cover those in your other programming modules and you do not need them to model objects. The concepts in this section are just to get you started so you can simply design your solution while you are learning to program. We will look at simple problems in this section. Interactions between objects in larger solutions can be complex to describe and UML (Unified Modelling Language) which you will learn in a later module is a better tool for this.
PDCLGA001b
7-3
Object Modelling
In this section we will focus on the process of breaking the problem down into discrete objects to create a model and then generating the pseudo code to describe the objects methods. The PDR which we have used up to this point can still be used, but it is used in a slightly different way. In many of the exercises you will complete during your course the objects and the design of the application will be provided for you. At some point though, you will need to know how to decompose a list of functional requirements or a scenario into objects which you can use to implement your solution. When a solution model is complete you should find that responsibilities for representing parts of the solution have been assigned to specific objects. We will only cover the process of breaking requirements down into a model briefly in this learning guide, as entire books have been written on the subject. Often there is no one correct way and it depends how each developer abstracts the items in the model. You will have an opportunity to do this practically shortly and again in checkpoint 4. Actual solutions are often more complex than this and may require several iterations to arrive at an appropriate model. Do not be concerned if you cannot pick it up straight away. It can be quite enjoyable to break down everyday systems and see how they work. Object oriented modelling differs from the development process used for structured programming in that while we still create variables to describe the data used in our solution, we divide the solution up into objects which perform a specific task. The objects now contain these variables as data members which represent the properties of the class and functions which represent the behaviour or actions the class can take either on its own data or those of a different class to which it has access. We often decide on the objects behaviour and properties to include in our solution by analysing a set of user requirements presented in a scenario. For Example: Giro Bank Ltd would like to implement a computer based account management system for their banks to enable them to manage their clients accounts more effectively. They would like the system to be able to store the clients account number, name and address. Each client should have an account identified by the account number in which the current balance is stored. It will be possible to make deposits or withdrawals from the account and obtain the account balance. A user is to be able to enter clients details. This looks similar to the way we began analysing the solution when we were working with a structured solution. In fact we can apply the same step of the PDR at this point. Step 1 - Analyse the Problem Identifying the Sub-Problems The sub problems from the above scenario translate to the following:
Store client account number, name and address Make deposit into account Make withdrawal from account Obtain account balance Enter clients Details
The sub problems determine the scope of the model, which is the range of things the model needs to do. Our completed model should perform each of these tasks. The
7-4
PDCLGA001b
requirements in the above scenario are quite simple now, later we will add a couple of extra requirements to make the scenario more realistic. At this point in a structured solution we would have much or our basic solution outlined. In OOP though we get much more information from the functional requirements which we can use to model our objects. This is the power of OOP it allows us to capture much more detail in our solution. We model objects in step 2 of the PDR. Step 2 - If OOP, Model objects to be used in solution We model the objects at this point in the PDR as the way in which the objects are responsible for implementing their part of the solution determines the way the later steps are performed. The language used to describe the system in the requirements being modelled is used to break the system down into its component parts. Each type of item appearing in the description represents a different part of the model. The component parts of the English language shown here have been included in the glossary if you need clarification of what each of them represents. This step can be further broken down into the following stages. Stage A: Make a list of nouns or noun phrases appearing in the scenario or situation Stage B: Remove any nouns or noun phrases which are duplicated, not relevant or outside the system being modelled. This can be quite subjective but should leave you with a list similar to this: Giro Bank Ltd account number Make withdrawal accounts name Current balance banks address Enter client details clients Get account balance system Make Deposit
You also need to consider scope of the project. The scenario mentions that Giro Bank would like to implement the system for their banks, plural. Think about most banks, can you access your account from any branch? In most cases this is Yes. In this model we will assume we can discard the Giro Bank item and retain banks, in some scenarios there may need to be information about individual branches stored as well. In that case the noun which describes the organisation as a whole may be more appropriate.
NOTE: Sometimes during the analysis phase of a real-life project you may need to confirm details of a scenario or obtain additional information from the client. For example items such as the need for a branch number to be added to bank may be identified by further consultation with the client .
PDCLGA001b
7-5
System is not required as it describes the solution as a whole, but could be required as a class on a larger project with many program components. Stage C: Identify verbs in the scenario Clearly some of these nouns and noun phrases can also be verbs depending on context. We need to identify items which describe actions we are performing in the scenario; these will be assigned to the objects as methods later. These include: Make withdrawal, Make Deposit, Enter client details. Stage D: Identify any items that represent fundamental values This includes account number, name, address, account balance, these will later form properties of the objects. Stage E: Change any plural or possessive version of a noun to its singular equivalent. This should leave: account bank
client
Stage F: If necessary change any nouns remaining to give them more descriptive or appropriate names. In this case the remaining nouns are suitable object names giving: account bank client These will be the objects making up your solution. Stage G: Place the nouns you identified describing the properties of the objects with the correct object. Although it is quite clear in this case, where it is specified in the scenario, other times you will need to decide based on functionality later in the design which we will see shortly. This should give: Bank Account account balance Client account number name address Notice the Client object contains the account number, how do we relate the client to their account at the Bank?. We will resolve this in stage I shortly. Stage H: Place any verbs or noun phrases/verb phrases identifying actions in the appropriate objects. These are the actions to be performed on the objects. (Remember this is simplified example). We have identified these by placing the braces after the method name. This makes it clear they are methods not properties. Normally actions to be performed on the
7-6
PDCLGA001b
property are placed within the object which owns that property. For example a withdrawal on an account object affects the account balance of that account. This gives us the following: Bank Account account number account balance deposit() withdrawal() current_balance() Client account number name address enter_details() Notice we have simplified the method names, it is obvious we are dealing with client details and the action expressed by the verb so Make is unnecessary once we have added the methods withdrawal() and deposit(). You could leave it in if you wanted to. This is the basic outline of our model. Sometimes models can undergo large changes through the development of the finished system. You might notice that the Bank class looks a little empty for now. Stage I: Add other abstract and functional requirements. We now have to consider how the model will actually work. There would be additional methods to add data to objects we create in our solution, such as the Client and Account objects i.e. Client details from file, database or keyboard and numerous other considerations, these have been omitted in this example. Only entry of client details is included as that was shown in the scenario. In this case as we need to be able to match a particular account to a particular client, the account number is currently only in the Client object. You would have encountered relationships set up between fields in tables in your Design and Build a Database module, in that case creating relationships between tables in a database. In this case the use of account number in both Client and Account establishes a relationship between each client and their account. This gives us the following model: Bank Account account number account balance deposit() withdrawal() current_balance() Client account number name address enter_details()
PDCLGA001b
7-7
This however only allows one account per client. With your own bank I am sure you can have more than one account with them. With OOP it often helps to look at how things work in real situations. Having established the main framework for the model you can now implement these sort of functional details. The way to solve this problem is to give each Client a unique ID which is also stored with each account to identify the Client who owns it. The account number is removed from the Client object and the ClientID is added to the account class. Each client may now have multiple accounts. What will the main module in the solution be? What will control everything else? The clue is in the items we changed from plural to singular (or from a possessive noun). Remember clients and accounts, this implies the system needs to store multiple accounts and information on multiple clients. What is holding this information? Thats right, the Bank. The overall changes are shown here: Bank Accounts Clients Main() Account clientID account number account balance deposit() withdrawal() current_balance() Client clientID name address enter_details() The bank now has members which are able to store objects representing multiple Accounts and Clients. These can be arrays or more complex data structures. The main method for the solution is located here as obviously the Bank object needs to be created first and the Client and Account information added to it. We have also adapted the basic model to allow clients to have multiple accounts. This process is similar to the first two steps of creating a structured solution; effectively we are processing the list of sub tasks to create a solution outline, which in object oriented modelling is represented by individual objects. The analysis and design of the required code within the methods in the classes would proceed as before as with structured program design. Step 3 Create the VTOC In OOP the VTOC is slightly different. The overall structure of the solution is based on the class outline created in Step 2. The layout of the VTOC may represent the sequence of execution in some solutions, in others where the sequence of execution may be based on user interaction the sequence may no longer be clear. You may wish to create a separate VTOC for different parts of a solution. Remember we are not representing the objects on the VTOC, we are representing the sequence of execution or possible paths in the execution.
7-8
PDCLGA001b
There are many more details to actually coding in OOP languages which will complicate the issue at this point. We will keep things simple. The main requirement is that before you use an object you must create an instance of it. This is known as instantiation of an object, it is like initialising a variable. In this case before we can add any information to the client and account details we need to initialise the Bank object to enable us to store them. We will assume that the Account and Client Details are to be stored in arrays. With the information provided we can create a VTOC as shown in figure 7-1.
Bank.Main()
Initialise Bank
Account. Withdrawl()
Account. Deposit()
Account. Current_Balance()
Client. Enter_Details()
Initialise Accounts
Initialise Clients
Figure 7-1
As with our structured examples the first method to be called will be our main method. While some languages allow the Main function outside of an object, here we assume that Main() is part of the Bank object as would be the case in a Java application. The Initialise Bank item simply refers to the actions that occur when the application first starts. It does not at this point represent a separate module in the application but a discrete section of code in Main(), much as the case with the simpler structured examples you looked at earlier. In a more complex example you would create a separate initialise method as part of the class. What we would be representing then would be a special function which is part of an object which is responsible for initialising it when it is first created. You will learn about this when producing programming code in later modules. As the only things initialised in Bank are the Client and Account arrays, these are shown as subordinate to the Initialise Bank item. Again this does not mean they are separate modules. Once the initialisation of the Bank object is complete the Account Withdrawal() and Deposit() methods may be called along with the Client Enter_Details() method. These methods can be called in any order. In a more complete example a menu method could be provided to the user from the Bank.Main() method. This would allow the user to access the allowed operations in the solution and choose the one they wished to perform. Lets assume we have added the following requirement to the Scenario to illustrate this point: PDCLGA001b Computer Power Institute
7-9
The user should be able to access a menu after the application starts to enable them to make withdrawals and deposits and enter the client details. Selecting an option on the menu should end the application.
The VTOC for the solution would now look similar to the following:
Initialise Bank
Initialise Accounts
Initialise Clients
Account. Withdrawl()
Account. Deposit()
Bank. End()
Figure 7-2
We have assumed that a method has been added to Bank to exit the application. As you can see adding functionality to the objects we have modelled quickly complicates the VTOC. What we have represented here are the possible actions occurring in the solution at a given point. The hierarchy is no longer determined by the list of subtasks alone. The Bank.Menu() method effectively becomes the Process section of the application. The user will most likely be given the option to choose another menu item once the action they have performed is complete. At some point it may become too complicated to show all the interactions occurring in the solution. You can then divide the VTOC into separate parts or each item in the VTOC can then simply describe a section of the solution generally. As the description of the solution becomes more complex a move to a standard such as UML is usually made as there are more complex behaviours in the solution which also need to be expressed in the model. The following examples assume the requirement for a menu has become one of the system requirements. Step 4 Create the Data Table The next step is quite straightforward at this point as we have described most of the items required when we created our model. The data table can represent the solution as a whole or it may represent individual objects within the solution. For example the following data table represents the solution as a whole:
INPUT Account number Deposit amount Withdrawal amount Name Address ClientID Menu Selection PROCESSING Initialise Accounts Initialise Client Get current balance Enter Client Details Display user menu Get user menu selection Make deposit Make withdrawal End application OUTPUT Account Balance Menu options
7-10
PDCLGA001b
It is not clear from this what actions occur in which object. It simply provides a summary of the required data and the processing which occurs. We have added processing steps to account for user interaction with the menu. Separating the data table gives a clearer indication of object responsibility. Notice that displaying the current balance output by the account object is the responsibility of the Bank object. The method to get the balance is part of the Account object. Bank
INPUT Menu Selection PROCESSING Initialise Accounts Initialise Clients Display user menu Get user menu selection End application OUTPUT Display Account Balance Menu options
Account
INPUT Account number Deposit amount Withdrawal amount ClientID PROCESSING Get current balance Make deposit Make withdrawal OUTPUT Account balance
Client
INPUT Name Address ClientID PROCESSING Enter Client Details OUTPUT
The Inputs are the information provided to the objects to enable the processing steps to be completed. Remember this is a very simplified solution. We have not so far specified the mode of storage of the client and account records. No provision has been made for creating or loading and saving client or account records. So far in this example, we have assumed they are provided. Some of you will have also noticed transactions are not recorded. In a complete solution each object is normally responsible for inputting and outputting its properties. This means that if the properties an object has change, only the code in the object needs to be changed. For example in pseudo code you might represent the writing of client details to a file as:
Client.write()
This would write the content of that client to the file. In our case as the client details are in an array it would be represented in the following way:
Clients[x].write()
Where x is the number of a valid index in the array. This would write the client details stored at index x in the array to the file. X would be set using a suitable loop. This code would appear in the Bank objects Main method or in additional methods added for this purpose within Bank.
PDCLGA001b
7-11
Reading would simply require a Client.read() method to be added and a check for EOF to be added within the loop. Additionally a counter representing the number of records read or written would be added as a property in Bank. If you add a property such as phone number to the Client object only the write (and read) methods need to be updated. All the other code which uses it would be unchanged. Modelling your solutions in this way makes it much easier to update or maintain the code produced from your algorithm later on. Just before moving on to design the pseudo code lets add this requirement to the project: The solution is to read and write account and client records to and from files. The records are to be read when the application first starts and automatically saved when the application ends. If we place the code in the Bank object to read and save the files in the initialise and end processes identified in the VTOC we will not need to modify the VTOC. If you decided to add extra methods to carry out these tasks you would also need to update the VTOC. The modified data tables appear as follows: Bank INPUT Menu Selection PROCESSING Initialise Accounts Initialise Clients Display user menu Get user menu selection Load Records Save Records End application OUTPUT Display Account Balance Menu options
Account
INPUT Account number Deposit amount Withdrawal amount ClientID Account Balance PROCESSING Get current balance Make deposit Make withdrawal OUTPUT Account balance Account number Current balance Client ID
Client
INPUT Name Address ClientID PROCESSING Enter Client Details OUTPUT Name Address ClientID
7-12
PDCLGA001b
Since we are not recording the deposit and withdrawal transactions the account balance for each account will need to be read and written when the accounts are loaded and saved therefore it becomes an input and output in Account. If we were storing the account transactions the current balance could be recalculated by iterating through the deposits and withdrawals made on the account. It is good practice not to save values which can be easily recalculated. In this case to simplify the solution we are simply storing the account balance. Step 5 Write Algorithm in Pseudocode We can now write the algorithm. This will involve adding code to the methods identified in step 2 and any additional processing steps identified in step 4. This is done object by object, creating pseudo code for the objects methods. The pseudocode appears on the following pages, notice the use of underscores in the variable names makes the code easier to read. Capitalising the words making up the variable names without spaces between the words is also effective.
Bank.Main() Initialise Accounts of type Account Initialise Number_of_Accounts = 0 While Not EOF Accounts[Number_of_Accounts].Read() Increment Number_of_Accounts End While Initialise Clients of type Client Initialise Number_of_Clients = 0 While Not EOF Clients[Number_of_Clients].Read() Increment Number_of_Clients End While Bank.Menu() End Bank.Menu() While Input <> F10 Display Bank Menu Display (F1) Account Withdrawal Display (F2) Account Deposit Display (F3) Enter Client Details Display (F4) Get Current Balance Display (F10) End Application Get Input Case of Input F1 : Prompt User for Account Number Get Account Number Prompt User for Withdrawal_Amount Get Withdrawal_Amount For Count Increasing From 1 to Number_Of_Accounts If Accounts[Count].AccountNumber = Account Number Then Call Accounts[Count].Withdrawal() passing Withdrawal_Amount End If End For F2 : Prompt User for Account Number Get Account Number Prompt User for Deposit_Amount Get Deposit_Amount For Count Increasing From 1 to Number_Of_Accounts If Accounts[Count].AccountNumber = Account Number Then
PDCLGA001b
7-13
Call Accounts[Count].Deposit() passing Deposit_Amount End If End For F3 : Prompt user for ClientID Get ClientID For Count Increasing From 1 to Number_Of_Clients If Clients[Count].ClientID = ClientID Then Call Clients[Count].Enter_Details() End If End For F4 : Prompt User for Account Number For Count Increasing From 1 to Number_Of_Accounts If Accounts[Count].AccountNumber = Account Number Then Display Accounts[Count].Current_Balance() End If End For F10 : Bank.End() other : Display Invalid Input EndCase Loop End Bank.End() For Count Increasing From 1 to Number_of_Accounts Accounts[Count].Write() End For For Count Increasing From 1 to Number_of_Clients Clients[Count].Write() End For End Account.Withdrawal() Current_Balance = Current_Balance Withdrawal_Amount End Account.Deposit() Current_Balance = Current_Balance + Deposit_Amount End Account.Current_Balance() Return Current_Balance End Account.Read() Read ClientID Read Account_Number Read Current_Balance End Account.Write() Write ClientID Write Account_Number Write Current_Balance End Client.Read() Read ClientID Read Name Read Address End
7-14
PDCLGA001b
Client.Write() Write ClientID Write Name Write Address End Client.Enter_Details() Prompt user for Name Get Name_Input Name = Name_Input Prompt user for Address Get Address_Input Address = Address_Input End
In this solution the arrays for the account and client details are initialised and the records loaded. Following this the Menu is displayed. The user would use Function keys to access the menu options. Because of the way the menu is displayed and the loop is implemented, the menu is redisplayed after each user selection. This is suitable for a text based interface. In an Event driven application a separate method would be responsible for each user interaction with the menu and the menu would remain displayed throughout normally via a GUI (Graphical User Interface). Notice in the Bank.Menu method we get the account number or client ID and use that to locate the account of client details to modify. Think about this, the client will give their details (Their client ID or their account number) to the person they are interacting with at the bank. Neither the client or the bank employee know the array location the details are stored at and the array location may change if more records are added. Methods are called to modify or retrieve the properties for each object, meaning each object has full ownership of its own properties. In the full solution there would be additional options to add clients to the system and assign new accounts to them. There would also be additional code to ensure valid account numbers and client Ids were used and that no file errors occurred. Step 6 Desk Check the algorithm Test Data Table The test data in an OOP solution is nearly always the properties of one or more classes. Objects are in most cases tested separately and the results of passing specific data to and from methods is usually tested. In this case test data would comprise enough Client and Account records to make sure methods that read, save and edit client records are working correctly. Desk Check Table Using the test data you would then choose a section of code (normally a method in an object) and test it individually. For example the following desk check tests a call to the Account.Withdrawal() method.
PDCLGA001b
7-15
count Steps 1 2 3
1256.00
ACTIVITY 7-1
The section of our solution involving the loading of client and account details in the Bank.Main() method and the saving of the files in Bank.End() is a bit untidy. We would like to separate the loading and saving of files into the appropriate methods of the Bank object. No other objects should need modification. This will also enable the files to be loaded and saved at other points in the solution if required. You need to: 1. Create and modify the VTOC in Figure 7-2 showing where the new methods are called from. 2. Create pseudo code showing the modified Bank.Main() and Bank.End() methods 3. Create pseudocode showing the new Bank.Load() and Bank.Save() methods. No other changes should be required. Activity solutions may be found at the end of this section. This is just an introduction to object modelling and object oriented design. Using OOP it is possible to very accurately model a real world solution to a problem. In most cases the objects in the real world situation become the objects in your solution. As you look at the object models used to create classes in your later programming modules think about the way the model in each example has been abstracted and anything you may have done differently in the same situation.
7-16
PDCLGA001b
PDCLGA001b
7-17
CHECKPOINT 4
120 mins Your solutions to these questions should be set out in the same way as the examples in this section. You must set out your solutions to each question using the framework of the Program Development Routine (PDR). You will need to: 1. 2. 3. 4. 5. 6. Analyse the problem by making a list of the sub-problems. Model the Objects. Work through the steps outlined in this section. Develop a VTOC, which is an outline of the solution. Create a Data Table after identifying the inputs, the outputs, and the actions that make up the processing component. Write a solution algorithm in pseudocode. Desk-check the solution algorithm. The sections of code which locate specific records for the user are to be tested (See scenario below). Use three sets of data for each test.
You will find blank PDR documents in the PDRforms.docx file located in the H:\PDCWORK folder on your home drive. When you have completed the question, print out your answer, call on an instructor to check over your solutions and discuss with them any issues that are not clear to you. This constitutes the Checkpoint 4 Sign Off. The signoff sheet is in Appendix 2 at the end of this learning guide. When checkpoint four is successfully completed you may book for a mini for this module.
7-18
PDCLGA001b
Question 1
Highland Park library provide library services to the residents of a Suburb of a large metropolitan city. The Library has grown from a small community based organisation to a large library with over 200000 books and 7600 members. The manual systems that they are using can no longer cope with demand. The solution for the new library management system they would like you to design needs to be able to do the following: The details of all the books in the library catalogue are to be stored in a file. Each Book record needs to include the catalogue number, publishers name, authors name, title, edition number and ISBN10 number. Details of library members are also to be stored in a file. The member record is to include ID number, first name, last name, address, phone number and email address. When the solution starts the records for the books and the members are to be loaded. The user is to be able to add book and member details from a menu, when the new entry is complete the entry is to be saved automatically. The user is to be able to edit particular book and member details; these should be saved automatically as before. In case the user forgets to save their work, the solution will save the data automatically when the application ends. The user is to be able to view particular book and member details after entering the member number or ISBN10 code of the book. To start with only the part of the solution involving the book and member information will be completed. Later the module which controls lending from the library will be added. It is important that the solution is as easy to maintain as possible and duplication of code is avoided where possible.
PDCLGA001b
7-19
ACTIVITY SOLUTIONS
Activity 7-1
Bank.Main()
Account. Deposit()
Bank.Main() Initialise Accounts of type Account Initialise Number_of_Accounts = 0 Initialise Clients of type Client Initialise Number_of_Clients = 0 Bank.Load() Bank.Menu() End Bank.Load() While Not EOF Accounts[Number_of_Accounts].Read() Increment Number_of_Accounts Loop While Not EOF Clients[Number_of_Clients].Read() Increment Number_of_Clients Loop End Bank.End() Bank.Save() End Bank.Save() For Count Increasing From 1 to Number_of_Accounts Accounts[Count].Write() Loop For Count Increasing From 1 to Number_of_Clients Clients[Count].Write() Loop End
7-20
PDCLGA001b
Section 8: Appendix A
Priming Read
Subsequent Read
PDCLGA001b
A-1
Section 8: Appendix A
PDCLGA001b
This basic solution algorithm forms the framework for almost all commercial business programs. It does not include processing the page headings, control breaks, total lines or special calculations. However, you can easily incorporate these requirements by expanding and modularising the general solution as shown in Figure A-1.
Initial Processing
Final Processing
The module Process this record can be extended as required for the processing of a particular programming problem. We will use this basic program structure to develop solution algorithms to some common business programming applications.
A-2
PDCLGA001b
Section 8: Appendix A
23/02/xxx9
NATIONAL CLOTHING COMPANY CURRENT ACCOUNT BALANCES CUSTOMER NAME Beryls Boutique Suzies CUSTOMER ADDRESS The Mall, Bourke 493 Picnic Road, Albert Park ---------------------------Total customers on file Total customers with balance owing Total balance owing
Figure A-2
Page 1
Our general solution algorithm for processing a sequential file can be extended by the addition of new modules that cater for these report requirements. VTOC
Print report program
PDCLGA001b
A-3
Section 8: Appendix A
PDCLGA001b
After the VTOC has been established, the solution algorithm can be developed in pseudocode.
Solution algorithm
Master Control Module
Print report program Call Initialise variable fields Read first record While Not EOF Call Process this record Read next record EndWhile Call Print Report Totals End
A-4
PDCLGA001b
Section 8: Appendix A
Level 2
Print detail line If (linecount >= max detail lines) Then Call Print page headings EndIf Build detail line Print detail line Increment linecount End Accumulate total fields Increment accumulators as required End
Level 3
Print page headings Increment pagecount Print heading lines Print column heading lines Print blank line (if required) Set linecount to zero End
This general pseudocode can now be used as a framework for any report program that requires page breaks.
PDCLGA001b
A-5
Section 8: Appendix A
PDCLGA001b
23/02/xxx9
NATIONAL COMPUTER COMPANY SALES REPORT BY SALESPERSON Salesperson Name Mary Smith Product Number Quantity Sold
Page 1
Price
Value
1002
John Brown
1032 2 1033 2 1044 2 Sales total for Mary Smith 1032 2 1045 1 Sales total for John Brown Report sales total
Table A-1
NOTE: A control break total line is printed each time the salesperson number changes . There are two things that you must consider when designing a control break program: 1. The file to be processed must have been sorted into control field sequence. In the example above the file was sorted into ascending sequence of salesperson number. If the file has not been sorted, erroneous results will occur. Each time a record is read from the input file, the control field on the current record must be compared with the control field on the record just printed. If the control fields are different, a control break total line must be printed for the previous set of records, that is, before the current record is processed.
2.
The general solution algorithm that was developed for Example 1 can be extended by the addition of two new modules to incorporate a single-level control break. These modules are named Print control total line and Reset control totals.
A-6
PDCLGA001b
Section 8: Appendix A
VTOC
All control break report programs will require the following variables: 1. A variable named prev control field that will hold the control field of the previous record. To cater for the first record, the statements after the first Read statement will set the prev control field to the value read into the control field. One or more variables to accumulate the control break totals. A variable to accumulate the report totals.
2. 3.
PDCLGA001b
A-7
Section 8: Appendix A
PDCLGA001b
There are three points in this master control algorithm that are essential for a control break program to function correctly: 1. When the first record is read, the control field is assigned to the variable prev control field. This will prevent the control totals printing before the first record has been processed. The variable prev control field is updated as soon as a change in the control field is detected. After the end of the file has been detected, the module Print control total line is called. This will then print the control break totals for the last record or set of records.
2. 3.
A-8
PDCLGA001b
Section 8: Appendix A
Level 2
Print detail line If (linecount >= max detail lines) Then Call Print page headings EndIf Build detail line Print detail line Increment linecount End Accumulate control totals Increment control total accumulators End Reset control totals Add control total accumulators to report total accumulators Set control total accumulators to zero End
Level 3
Print page headings Increment pagecount Print heading lines Print column heading lines Print blank line (if required) Set linecount to zero End
PDCLGA001b
A-9
Section 8: Appendix A
PDCLGA001b
Notice that when a control total line is printed, the module Reset control totals is called. This module will add the control totals to the report totals and reset the control totals to zero for the next set of records. This general solution algorithm can now be used as a framework for any single-level control break program.
reading values into the elements of an array a linear search of an array a binary search of an array writing out the contents of an array.
Reading values into the elements of an array The reading of a series of values from a file into an array can be represented by a simple While .. EndWhile loop. The loop should terminate when either the array is full or the input file has reached the end-of-file. Both these conditions can be catered for in the condition clause of the While .. EndWhile loop. In the following pseudocode algorithm, the array name is array, the subscript is index, and the value being put into the element of the array is input value. The maximum number of elements that the array can hold is placed in max num elements.
Read values into array Initialising variables Set max num elements to designated value Set index to zero Priming read Read first input value While ((input values exist) AND (index < max num elements)) Let index = index + 1 Body of loop to Let array[index] = input value read next value Read next input value until no more EndWhile exist. End
A-10
PDCLGA001b
Section 8: Appendix A
A linear search of an array A common operation on arrays is to search the elements of an array for a particular data item. A linear search involves looking at each of the elements of the array, one by one, starting with the first element. The search will continue until the element being looked for is found or the end of the array is reached. The pseudocode algorithm for a linear search of an array will require a program flag named element found. This flag, initially set to false, will be set to true if the current element is that data item being looked for. The required data item is stored in the variable input value, and max num elements contains the total number of elements in the array.
Linear search of an array Set max num elements to designated value Set element found to false Set index to 1 While ((NOT element found) AND (index <= max num elements)) If (array[index] = input value) Then Set element found to true Else Let index = index + 1 EndIf EndWhile End
A binary search of an array When there are a large number of elements in an array and the elements are sorted into ascending sequence, a more efficient method of searching the array is a binary search. A binary search locates the middle element of the array first, and determines if the element being searched for is in the first half or second half of the table. The search then points to the middle element of the relevant half table, and the comparison is then repeated. This technique of continually halving the area under consideration is continued until the data item being searched for is found or its absence is detected. In the following algorithm, a program flag named element found is used to indicate whether the data item being looked for has been found. The variable low element indicates the bottom position of the section of the table being search, and high element indicates the top position. The maximum number of elements that the array can hold is placed in the variable max num elements.
PDCLGA001b
A-11
Section 8: Appendix A
PDCLGA001b
The binary search will continue until the data item has been found or there can be no more halving operations (that is the low element is not less than the high element).
Binary search of an array Set element found to false Set low element to 1 Set high element to max num elements While ((NOT element found) AND (low element <= high element)) Let index = (low element + high element) / 2 If (input value = array[index]) Then Set element found to true Else If (input value < array[index]) THEN Let high element = index 1 Else Let low element = index + 1 Endif Endif EndWhile End
Writing out the contents of an array The elements of arrays are often used as a series of accumulators of data, to be written to a report. Writing out the contents of an array can be represented by a simple While .. EndWhile loop. In the pseudocode algorithm, the name of the array is array and the subscript is index. The number of elements in the array is represented by max num elements.
Write values of array Set index to 1 While (index <= max num elements) Write array[index] Let index = index +1 EndWhile End
A-12
PDCLGA001b
Section 8: Appendix A
Algorithms that manipulate arrays The following algorithms involve the manipulation of arrays. Assume that the contents of array and max num elements have been established. Find the sum of the elements of an array
Calculate sum of elements Set sum to zero Set index to 1 While index <= max num elements Let sum = sum + array[index] Let index = index + 1 EndWhile End
PDCLGA001b
A-13
Section 8: Appendix A
PDCLGA001b
A-14
PDCLGA001b
B
Checkpoints sign off
Checkpoint
Each question attempted in the checkpoints must be produced according to the standards outlined in the Programmers Development Routine learning guide All checkpoints must be signed off before approval is given to do the exam (minimum 2 of the 4 questions must be completed for checkpoint 3)
Date
Instructor Signature
1.
2.
3.
4.
PDCLGA001b
B-1
B-2
PDCLGA001b
Appendix C: Glossary
C
Accumulation Algorithm Array Boolean expression Boolean variable Boundary condition
APPENDIX C GLOSSARY
The process of adding up a series of data values. A set of detailed, unambiguous and ordered instructions developed to describe the processes necessary to produce the desired output from a given input. A data structure made up of a number of data items that all have the same data type and are accessed by the same name. A statement that can be evaluated only to true or false. A variable that can contain only one of two possible values true or false. A condition that tests a data value in order to separate it into two different processing categories. If the condition is true, the value is processed in one way; if it is false, the value is processed in a different way. A data value that appears in the test for a boundary condition. See also boundary condition. A point in an algorithm where a decision is made about which of two alternative actions to take. See also selection. Any letter, number, punctuation symbol or special symbol that appears on a computer keyboard. A group of keyboard characters that logically belong together, e.g., PDC Module. A structure that extends the selection control structure from a choice from two values to a choice from multiple values. It is equivalent to a multiple-alternative If statement. Converting a program design into actual instructions in a chosen programming language. program
Boundary value Branch point Character Character string CASE control structure
Coding
PDCLGA001b
C-1
Appendix C: Glossary
Compiler
A program that translates a high-level language program into machine language before it can be executed. A compiler is itself a computer program. It accepts a program written in a high-level language (for example, C) as input, and generates a corresponding machine-language program as ouput. A question that must be answered as part of a selection or repetition construct. The question is phrased so that it always has a Yes/No or True/False answer. A data item with a name and a value that remains the same during the execution of the program. A word derived from the two words control and structure. The Structure Theorem states that it is possible to write any program using only three basic control structures: sequence, selection, and repetition. A loop that is executed a set number of times as determined by a memory cell counter. Information, in the form of numbers, characters or characters strings, which a computer program needs in order to perform a task. A loop whose execution continues while there is still data to be processed, and ceases once the data runs out. The calculations and operations performed on data to transform it from input into output. A collection of elementary data items. A set of values and a set of operations that can be performed on those values. One piece of data, such as a single number or single character. Finding and fixing errors in a computer program. A pencil and paper check carried out on an algorithm to work out whether it is working correctly.
Condition
Data-driven loop Data processing Data structure Data type Data value Debugging Desk-check
C-2
PDCLGA001b
Appendix C: Glossary
Elementary data item End-of-data flag End-user EOF Event-driven Execution External documentation File Flowchart
One that contains a single variable that is always treated as a unit. An impossible or invalid data value that signals the end of a series of input data values. See also sentinel. A person who makes use of a computer program to help them carry out business tasks. End Of File A program that is controlled by events such as the click of a mouse-button or a choice made from a menu. The term used to describe the running of a program. A manual of instructions that is provided to an end-user of a program to explain how to use a program. A collection of related records. A diagrammatic representation of an algorithm that uses standard shapes to represent particular instruction types and flow lines to connect the shapes together. An expression, phrase or clause written in a flowchart shape to describe the action that is to take place at that point in the algorithm. A shape used on a flowchart to represent a particular type of action. The division of a problem into separate tasks or functions as the first step towards designing the solution algorithm. Each function will be dedicated to the performance of a single specific task. Variables that are known to the whole world of the program. Compare with local variables. A value that, because of its incorrect size, cannot be possible for this variable (for example, the number 13 is impossible as the month entry for a date). Giving an opening value to a memory cell in a program. The data that goes into a program.
Flowchart label
Initialisation Input
PDCLGA001b
C-3
Appendix C: Glossary
The flow of data between modules. The comments that go inside a program with the code to explain how it works. Input that is not allowable for that type of data (for example, input of the letter E when asked to enter a number). See repetition. Variables that are defined within the module in which they are referenced, and they are not known outside that module. Compare with global variables. An error in an algorithm that results in the algorithm producing incorrect output caused by incorrect logic. A group of instructions in an algorithm that is repeated. See also repetition. The condition that controls whether or not a loop continues to be executed. See also loop and condition. Periodic alterations to a program to make it work better, or to satisfy changed user requirements. The controlling module of a solution algorithm that ties all the modules together and coordinates their activities. Grouping tasks together because they all perform the same function. Modular design is directly connected to top-down development, because the tasks into which you divide the problem become the modules of the program. A section of an algorithm dedicated to the performance of a single specific task. It has a single entry point and a single exit point. An algorithm construct in which one of the three basic constructs (sequence, selection or repetition) is within another of the three constructs. The part of speech that is used to name a person, place, thing, quality, or action and can function as the subject or object of a verb Object-oriented programming (OOP) is a programming paradigm that uses "objects" and their interactions to design applications and computer programs. Programming techniques may include features such as information hiding, data abstraction, encapsulation, modularity, polymorphism, and inheritance. It was not commonly used in mainstream software application development until the early 1990s. Many modern programming languages now support OOP.
Logic error Loop Loop control condition Maintenance Master control module Modular design
Module
Nested constructs
Noun
C-4
PDCLGA001b
Appendix C: Glossary
Used for evaluating a boolean expression, it states that the condition enclosed in brackets is evaluated first, starting with the innermost set of brackets. If there are no brackets, an AND condition is always evaluated before an OR condition. If there is more than one AND condition, they are evaluated from left to right. If there is more than one OR condition, they also are evaluated from left to right. Used to describe a data value that is not within a programs range limits. The data that comes out of a program. A read statement that appears immediately before the WHILE .. ENDWHILE condition in a solution algorithm. This statement primes the test variable to make the loop start working. A program in which tasks are carried out in a pre-determined order: data input, processing of the data, data output. A set of instructions that a computer must carry out in order to perform a task. A person who writes computer programs. A language used to write computer programs, which uses a subset of normal language plus abbreviations and symbols. A subset of English that has been formalised and abbreviated to look like a computer language. Keywords and indentation are used to signify particular control structures. The lower and upper values between which valid data values for a particular program must lie. A collection of data items or fields that all bear some relationship to each other. A control structure that allows a set of instructions to be performed repeatedly as long as a condition is true. Also known as iteration. A control structure that allows decisions to be made in an algorithm by evaluating a condition. The decision is made between two actions, depending on whether the condition evaluates to true or false. A special record placed at the end of valid data to signify the end of that data. It is also known as a trailer record. See also end-of-data flag. A control structure that determines the order in which instructions in an algorithm are performed. Collective term given to programs that run on a computer system. Computer Power Institute
Selection
Sentinel
Sequence Software
PDCLGA001b
C-5
Appendix C: Glossary
The stages in the life of a computer program or set of computer programs. A term used to describe programs that contain a number of unconditional jumps. See also unconditional jump. A collection of characters. The Structure Theorem states that it is possible to write any computer program by using only three basic control structures: sequence, selection, and repetition. A method of writing programs so that each instruction obeys the Structure Theorem. Structured programming also incorporates top-down development and modular design. The process of adding a series of data values. A professional who works with end-users to ensure that a data-processing problem is clearly defined. The process of adding a series of data values. Data values used to test whether an algorithm is working as it should. The division of a problem into separate tasks as the first step towards designing the solution algorithm (functional decomposition). The programmer develops an algorithm that incorporates the major tasks first, and only considers the more detailed steps when all the major tasks have been completed. A feature of an algorithm in which flow of execution diverges from the normal top-to-bottom sequence without being the result of a selection or repetition construct. A collection of memory cells that store a particular data item. A word that represents an action or a state of being. Go, Get, Load, Save, and exist are examples of verbs A sentence using a verb with a noun as the subject of the verb for example: Load Record Visual Table Of Contents - a diagram that shows the name of each module in the solution algorithm and its hierarchical relationship to the other modules.
Structured programming
Unconditional jump
C-6
PDCLGA001b
Objectives
Did the course/workshop meet its stated objectives?
Yes
Yes
Course/Workshop Evaluation
How would you rate: Course/Workshop content Quality of instruction Overall satisfaction Relevance of Activities Suitability of Training Facilities Quality of Facilitation Usefulness of Learning Guide(s) Usefulness of Resources Poor 1 1 1 1 1 1 1 1 Fair 2 2 2 2 2 2 2 2 Good 3 3 3 3 3 3 3 3 Excellent 4 4 4 4 4 4 4 4
What did you think was least beneficial about the course/workshop? ___________________________________________________________________________ ___________________________________________________________________________ ___________________________________________________________________________ ___________________________________________________________________________ ___________________________________________________________________________ ___________________________________________________________________________ Please identify by topic any information that should be added, deleted or improved (e.g. form, clarity, pace, depth, sequence) and explain. ___________________________________________________________________________ ___________________________________________________________________________ ___________________________________________________________________________ ___________________________________________________________________________ ___________________________________________________________________________ ___________________________________________________________________________ Please add any extra comments you may have in the space below. ___________________________________________________________________________ ___________________________________________________________________________ ___________________________________________________________________________ ___________________________________________________________________________ ___________________________________________________________________________ ___________________________________________________________________________ ___________________________________________________________________________ ___________________________________________________________________________ ___________________________________________________________________________ ___________________________________________________________________________ ___________________________________________________________________________ ___________________________________________________________________________ ___________________________________________________________________________ ___________________________________________________________________________ ___________________________________________________________________________ ___________________________________________________________________________ Thank you for taking the time to complete this form, we use the information gathered to continually review and improve the courses and workshops to make them as relevant and useful as possible.