You are on page 1of 238

Program Design Concepts

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

Program Design Concepts

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

Computer Power Institute

iii

Program Design Concepts

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

Computer Power Institute

PDCLGA001b

Introduction

Program Design Concepts

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.

Self test icon


To help reinforce what you have learned, you will be asked a number of questions at different stages during the course. You can try to find the answers by looking up the relevant Sections in this Learning Guide.

Timer icon
This icon indicates an estimated study time for a topic.

Hot tip icon


This icon indicates a valuable tip, hint or note.

PDCLGA001b

Computer Power Institute

Program Design Concepts

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

150 300 60 60 60 30 90 300 60 60 60 60 60 30

vi

Computer Power Institute

PDCLGA001b

Introduction

Program Design Concepts

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

30 300 120 120 10 30 5 45 120 5 125 120 120

PDCLGA001b

Computer Power Institute

vii

Program Design Concepts

Introduction

viii

Computer Power Institute

PDCLGA001b

Program Design Concepts

Section 1: Program Development

1.0
OBJECTIVES
1. 2. 3. 4. 5.

SECTION 1 PROGRAM DEVELOPMENT

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

Computer Power Institute

1-1

Section 1: Program Development

Program Design Concepts

TOPIC 1: THE SYSTEMS DEVELOPMENT LIFE CYCLE


20 mins Programmers do not work in isolation. They work in a development team that includes systems analysts, systems designers, marketing specialists, project managers, qualityassurance engineers, and many others, to generate a computer solution to a problem. We will briefly look at the Systems Development Life Cycle (SDLC), and see how programmers fit in to the big picture. The systems life is defined simply as the useful life of the system. Figure 1-1 shows an idealised picture of a full system life cycle, including developmental and postdevelopmental activities.

NOTE: The actual programming activities play a very small part in the total work.

Problem identifier (User) Requirement and objective (User)

Fact finding (User & Analyst) Problem Definition (Analyst) Initial analysis (Analyst) (Analyst)

1 INITIATION STAGE (Investigation & Feasibility Study)

System Analysis and Design

Strategic Plan

2 DESIGN STAGE (Detailed Analysis and Design) 3 DEVELOPMENT STAGE

System Production and Running

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)

4 IMPLEMENTATION STAGE 5 MONITORING STAGE

Review (Analyst or others) Maintenance (programmers)

Figure 1-1. A Systems Life Cycle

1-2

Computer Power Institute

PDCLGA001b

Program Design Concepts

Section 1: Program Development

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

Computer Power Institute

1-3

Section 1: Program Development

Program Design Concepts

STAGES OF A SYSTEMS LIFE CYCLE

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.

Is it cost justified to proceed to the next phase?

NO

YES DESIGN STAGE

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.

Is it cost justified to proceed to the next phase?

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.

Figure 1-2 (Part 1 of 2). Description of a Systems Life Cycle

1-4

Computer Power Institute

PDCLGA001b

Program Design Concepts

Section 1: Program Development

Is it cost justified to proceed to the next phase?

NO

YES IMPLEMENTATION STAGE

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.

Is it cost justified to maintain the solution?

NO

YES MONITORING STAGE

STAGE 5

Monitor, Enhance and Maintain the system solution. Modify if necessary

YES

Replace with another solution?

NO

End
Figure 1-2 - (Part 2 of 2). Description of a Systems Life Cycle

PDCLGA001b

Computer Power Institute

1-5

Section 1: Program Development

Program Design Concepts

TOPIC 2: THE IMPORTANCE OF STANDARDS


20 mins

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.

A Brief History of Standards


Standards have been around a long time. Relics from ancient civilizations such as Babylon and ancient Egypt provide ample evidence that standardization was being used as far back as seven thousand years ago. The earliest Standards were the physical Standards for weights and measures. They provided a single reference point against which all other weights and measures in that society could be compared. As trade and commerce developed, written documents evolved which set down mutually agreed Standards for products and services such as agriculture, ships, buildings, weapons and so on.

Standards in Contemporary Society


It was not until the latter years of the 19th Century that the value of standardization in specifications, materials, testing and conformance was recognized as a national priority. By 1900, standardization was flourishing, and has now become intrinsic to the workings of our modern society. It has extended far beyond its original industrial focus to include consumer safety, occupational health, and a myriad of other topics. Standards are the tools we use to organize our technical world, and the measures we employ to establish norms for management procedures. Indeed, Standards have become such integral components of our economic, social and legal systems that they are often taken for granted and their crucial role in a modern society is not often recognized.

Standards in Everyday Life


In the real world, Standards provide enormous social and economic benefits safety, inter-changeability, economic efficiency, quality, reliability the list is endless. But their benefits are so commonplace that they are often taken for granted. The best way to illustrate their value is by giving some everyday examples.

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

Computer Power Institute

PDCLGA001b

Program Design Concepts

Section 1: Program Development

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.

Imagine a World without Standards


Do Standards really make that much of a difference? Ask any overseas traveller who has to carry a suitcase full of adaptors from country to country. These plugs were all specified in the days before international standardization was widely recognized, and they are a daily reminder of the universal value of Standards. Similarly, try connecting your computer to a phone system in any other country but the one in which you bought it.

Programming Standards at Computer Power


Programmers are required to adhere to the programming standards of the organisation they are working for. These standards may vary from organisation to organisation, but only in a superficial way. At Computer Power, we insist that all programming students follow the standards set out in the Program Development Routine Reference Manual (PDRRBA002), which was issued to you when you began this module. The Program Development Routine (PDR) is Computer Powers standard for program development methodology. The PDR is the standard that you will adhere to as a student at Computer Power. It sets out the steps that you are required to follow in the PDCLGA001b Computer Power Institute

1-7

Section 1: Program Development

Program Design Concepts

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.

List the ten steps associated with the PDR.

1 2 3 4 5 6 7 8 9 10
3. What is the definition given for an algorithm, used in a programming context?

The Activity Solution can be found at the end of this Section.

1-8

Computer Power Institute

PDCLGA001b

Program Design Concepts

Section 1: Program Development

TOPIC 3: THE PROGRAM DEVELOPMENT ROUTINE


Programming is nothing more or less than writing out the series of steps a computer must perform to accomplish a specific task. A computer carries out its functions by following the instructions contained within a computer program. Structured programming is described as a software development technique that uses three standard control structures: 15 mins

Sequence Selection Iteration

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

Computer Power Institute

1-9

Section 1: Program Development

Program Design Concepts

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

Analyse the Problem

Sign off on sub problems

Step 2

If OOP solution model objects

Sign off on model

Step 3

Step 4

Create Data Table

Sign off on Data Table

Step 5

Write Algorithm in Pseudocode

Sign off on algorithm

No Step 6

Algorithm Desk Check OK?

Yes Step 7
Create a Variables Table and Data Flow Table

Step 8

Step 9

Compile, Run and Test the Program

No

Program Desk Check OK?

Yes Step 10
Update Documentation
MAINTENANCE PHASE

Yes

Program needs enhancement?

No End

Sign off on Project

Figure 1-3. The Program Development Routine

1-10

Computer Power Institute

PRODUCTION PHASE

Convert Algorithm into code

DESIGN PHASE

Develop VTOC

Sign off on VTOC

PDCLGA001b

Program Design Concepts

Section 1: Program Development

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

Computer Power Institute

1-11

Section 1: Program Development

Program Design Concepts

TOPIC 4: THE CONCEPT OF STRUCTURED PROGRAMMING


10 mins Structured programming is a general term referring to computer programming that produces programs with clean flow, clear design, and a degree of hierarchical modular structure. A computer program can be thought of as consisting of a set of tasks. In a structured program, any task that is too complex to be described is simply broken down into a set of smaller component tasks, until the tasks are sufficiently small and selfcontained to be easily understood. Structured programming revolutionised program design in the 1970s by establishing a structured framework for representing the solution, and eliminating the unconditional jump, known as a GOTO statement, to direct the flow of control in a program. A GOTO statement tells the computer to jump from one place in the program to another to find instructions. As a program becomes more complex, following the thread of the program becomes almost impossible. To understand what happens in a program that uses GOTO instructions, each path has to be followed, remembering to backtrack and follow any alternatives. It takes only a few of these paths to become intertwined before it is very difficult to keep track of the logic of the solution. This style of programming has been called spaghetti code. Structured programming was created to cut through this confusion. The principal idea behind structured programming is the concept of divide and conquer. Structured programming incorporates three main concepts:

the Structure Theorem top-down development modular design

The Structure Theorem


The Structure Theorem states that it is possible to write any computer program by using only three basic control structures. A control structure, as the name suggests, is a structure that controls the way something operates. Traffic lights are a type of control structure in that they are a structure for controlling traffic flow. In a similar way, algorithm control structures control the way you move through an algorithm. An algorithm is simply a method of solving a problem by following a set of pre-planned steps. A cooking recipe is an example of an algorithm. As we have already discussed, the control structures used in writing an algorithm for a computer program are:

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

Computer Power Institute

PDCLGA001b

Program Design Concepts

Section 1: Program Development

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.

Figure 1-4. Hierarchical representation of top-down design methodology

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

Computer Power Institute

1-13

Section 1: Program Development

Program Design Concepts

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

Computer Power Institute

PDCLGA001b

Program Design Concepts

Section 1: Program Development

TOPIC 5: AN INTRODUCTION TO ALGORITHMS


Structured programming techniques require a program to be properly designed before coding begins. It is this design process that results in the construction of an algorithm. 10 mins

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

Computer Power Institute

1-15

Section 1: Program Development

Program Design Concepts

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

Computer Power Institute

PDCLGA001b

Program Design Concepts

Section 1: Program Development

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.

Explain the term spaghetti code. _______________________________________________________________________ _______________________________________________________________________ _______________________________________________________________________ _______________________________________________________________________

PDCLGA001b

Computer Power Institute

1-17

Section 1: Program Development

Program Design Concepts

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

Computer Power Institute

PDCLGA001b

Program Design Concepts

Section 1: Program Development

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

Computer Power Institute

1-19

Section 1: Program Development

Program Design Concepts

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

Computer Power Institute

PDCLGA001b

Program Design Concepts

Section 1: Program Development

SELF TEST ANSWERS


1. If errors are not detected early in the development process, then it costs more to fix them later in the coding phase and the damage is more widespread. 1. Analyse the Problem 2. If OOP, model objects to be used in solution 3. Develop a VTOC 4. Create a Data Table 5. Write the Algorithm in Pseudocode 6. Desk-check the Algorithm 7. Create a Variables Table and Data Flow Table 8. Convert the Algorithm into Code 9. Compile, Run and Test the program 10. Update the Documentation 3. Spaghetti code is a term used to describe a program that uses GOTO statements to make unconditional jumps in which the flow of execution diverges from the normal top-tobottom sequence without being the result of a selection or repetition control structure. It is code that is difficult to understand and maintain. Sequence Selection Repetition 5. Modular design is connected to top-down development because the steps or subtasks into which the programmer breaks up the program solution will form the modules of the program. An algorithm must

2.

4.

6.

be clear, precise and unambiguous give the correct solution in all cases eventually end.

PDCLGA001b

Computer Power Institute

1-21

Section 1: Program Development

Program Design Concepts

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

Computer Power Institute

PDCLGA001b

Program Design Concepts

Section 1: Program Development

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

Computer Power Institute

1-23

Section 1: Program Development

Program Design Concepts

1-24

Computer Power Institute

PDCLGA001b

Program Design Concepts

Section 2: Defining the problem and presenting the solution

2.0
OBJECTIVES
1. 2. 3. 4. 5. 6.

SECTION 2 DEFINING THE PROBLEM AND PRESENTING THE SOLUTION

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

Computer Power Institute

2-1

Section 2: Defining the problem and presenting the solution

Program Design Concepts

TOPIC 1: PROBLEM DEFINITION AND ANALYSIS


10 mins In the Program Development Routine (PDR) outlined in the Program Development Routine Reference Manual, there are ten steps in the development of a computer program. The very first step is analysing the problem. The problem should be analysed in enough detail and clarity to enable a solution to be found. Analysing the problem involves carefully reading and re-reading the problem until you understand completely what is required. Quite often, additional information will need to be sought to help resolve any ambiguities or deficiencies in the problem specifications. For example, suppose you are asked to work out the area of a farm paddock. You would be unable to proceed unless you knew what shape the paddock was. You would need to go back to the person who posed the problem for more details. When you analyse any problem in detail, you will divide its large overall task into a series of sub-tasks. This is the divide-and-conquer technique that programmers use to deal with the size and complexity of a problem by breaking it up into a hierarchy of modules. The result is a computer program that is easier to develop, implement and maintain. Problem analysis can be sub-divided into three main components: 1. 2. 3. Output requirements of the problem Input requirements of the problem Processing steps required for transforming the input into output.

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

Computer Power Institute

PDCLGA001b

Program Design Concepts

Section 2: Defining the problem and presenting the solution

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?

Variables and constants are described in more detail in Topic 2.

Required Processing Steps


Having determined the output and input requirements, you should now be able to define the steps required to produce the output from the input, and the order in which they should occur. If required, you should break the processes down to sub-tasks until each step is a simple task. If you are developing an object oriented solution the client scenario and the list of subtasks created in step one are used to create the object model. The input/output and processing steps are then assigned to particular objects in the model.

PDCLGA001b

Computer Power Institute

2-3

Section 2: Defining the problem and presenting the solution

Program Design Concepts

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.

Elementary Data Types


An elementary data item is one that contains a single variable representing a single item of information that is always treated as a unit. These data items are usually classified into data types. A data type consists of a set of data values. The most common elementary data types are:

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

Computer Power Institute

PDCLGA001b

Program Design Concepts

Section 2: Defining the problem and presenting the solution

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

Computer Power Institute

2-5

Section 2: Defining the problem and presenting the solution

Program Design Concepts

TOPIC 3: WHAT IS PSEUDOCODE?


5 mins Pseudocode literally means false code. It is a form of English that has been formalised and abbreviated to look like a high-level computer language. It represents the statements of an algorithm written in English. There are other ways of representing an algorithm, such as a flowchart or more specialised charts and diagrams. We will have an introductory study of flowcharts later in Topic 5 in this section, but the Computer Power Programming Standards specifies the use of pseudocode, written with a word processor, to represent an algorithm. There is no standard format for pseudocode, but this Learning Guide will follow the following conventions: 1. 2. 3. 4. 5. Statements are written in simple English and are computer language neutral. (They are not specific to any language) Each instruction is written on a separate line. Key words1, verbs and control statements are written with an initial upper case letter. Statements that form part of a repetition loop are indented consistently by 3 spaces to indicate that they form a logical grouping. In a similar way, statements belonging to a selection group are indented by 3 spaces to clearly distinguish the alternative processing paths.

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

Computer Power Institute

PDCLGA001b

Program Design Concepts

Section 2: Defining the problem and presenting the solution

TOPIC 4: PSEUDOCODE AND BASIC COMPUTER OPERATIONS


In this section we will introduce key words used in pseudocode to represent six basic computer operations. Each operation can be represented as a straightforward English instruction, with key words and indentation to signify a particular control structure. The six basic computer operations are: 1. 2. 3. 4. 5. 6. A computer can receive information. A computer can output information. A computer can perform calculations. A computer can assign a value to a variable. A computer can compare two pieces of information, and use the result to select one of two actions. A computer can repeat a group of actions. 15 mins

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

Computer Power Institute

2-7

Section 2: Defining the problem and presenting the solution

Program Design Concepts

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

Table 2-1. Mathematical Operations

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

Computer Power Institute

PDCLGA001b

Program Design Concepts

Section 2: Defining the problem and presenting the solution

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

Computer Power Institute

2-9

Section 2: Defining the problem and presenting the solution

Program Design Concepts

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

Computer Power Institute

PDCLGA001b

Program Design Concepts

Section 2: Defining the problem and presenting the solution

TOPIC 5: PSEUDOCODE AND THE STRUCTURE THEOREM


The Structure Theorem forms the basic framework for structured programming. It states that it is possible to write any procedural computer program by using only three basic control structures. Traffic lights are a type of control structure in that they are a structure for controlling traffic flow. In a similar way, algorithm control structures control the way you move through an algorithm. Sometimes the algorithm control structures are called algorithmic constructs. The word construct as used in this sense, is created by the contraction of the two words control and structure. Algorithmic constructs control how you go about solving a problem. They can be thought of as the rules that you must follow to guide you through the steps of a problem solution. The three control structures used in programming are Sequence, Selection and Repetition. We will see how these are represented in pseudocode. 1. Sequence The sequence control structure is the straightforward execution of one processing step after another. In pseudocode we represent this construct as a sequence of pseudocode statements.
Statement Statement Statement Statement a b c d

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

Computer Power Institute

2-11

Section 2: Defining the problem and presenting the solution

Program Design Concepts

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

Computer Power Institute

PDCLGA001b

Program Design Concepts

Section 2: Defining the problem and presenting the solution

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

Computer Power Institute

2-13

Section 2: Defining the problem and presenting the solution

Program Design Concepts

(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

The repetition control structure is covered in greater detail in Section 5.

2-14

Computer Power Institute

PDCLGA001b

Program Design Concepts

Section 2: Defining the problem and presenting the solution

TOPIC 6: USING A FLOWCHART TO REPRESENT AN ALGORITHM


In the PDC module, we will be focusing on the use of pseudocode to represent an algorithm. However, an algorithm can be represented also by a flowchart, which is a diagrammatic form that has a high graphic impact. People can usually grasp flowchart algorithms quite readily. A flowchart is useful for presenting an algorithm to a simple problem or for presenting a simple overview solution of a complex problem, especially to non-programmers or beginners. Flowcharts are easy to sketch by hand but we recommend using the flow chart and arrowed line Auto Shapes which you will find in Microsoft Word. Additionally if you are familiar with Microsoft Visio you may use that to create your flowcharts. You are being introduced to flowchart ideas because you may find it easier to work with the diagrammatic format in contrast to lines of printed words, which is the format of pseudocode. The flowchart was the original method of writing an algorithm, but pseudocode is a popular method in use today because it does not have the distraction of drawing shapes and lines. Additionally more advanced ways of representing complex interactions found in modern software have been developed and have largely replaced flowcharts. We still use flow charts in PDC as they are easier to learn than some of these newer methods. A flowchart is a simple diagram that illustrates the stages or steps the computer must complete to solve the problem. In some ways, a flowchart is like a road map. You start at the top of the chart, at oval labelled Start and follow the flow lines until you reach the oval labelled End. Along the way, you will find the various tasks that must be completed. Any flowchart can be built up solely from sequence, selection, and repetition constructs. Example 2.1 Create an algorithm to update account balances, entered from the keyboard, with an interest payment calculated at a rate of 8%pa for balances less than 10,000, and at a rate of 10% for 10,000 or more. Print the account statement. You need to allow for accounts to be processed until no more exist. Write the algorithm as a flowchart. An analysis of this problem shows the output is a printed statement with a balance that has had an interest added to it. The inputs are the account balance and the interest rate. The required processing is to calculate the interest earned, depending on the balance in the account. The solution in point form would be: 1. 2. 3. 4. 5. 6. Input account balance from the keyboard. If account balance is less than 10,000, use 8%pa rate; otherwise 10%pa rate. Calculate interest using appropriate interest rate. Add interest amount to current balance. Print account statement. Repeat steps 1 to 5 while there are more accounts to be processed. 60 mins

PDCLGA001b

Computer Power Institute

2-15

Section 2: Defining the problem and presenting the solution

Program Design Concepts

Figure 2-1 is the flowchart for this example.


Start

Get acco un t balan ce

Yes
Let interes t rate = 8%
account balance < 10,000?

No
Let interes t rate = 10%

Compute interes t

Add interest to balance

Print account s tatement

Yes

M o re acco un t s ?

No
End

Figure 2-1. Flowchart for Example 2.1

2-16

Computer Power Institute

PDCLGA001b

Program Design Concepts

Section 2: Defining the problem and presenting the solution

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

Computer Power Institute

2-17

Section 2: Defining the problem and presenting the solution

Program Design Concepts

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

Any Input or Output operation

Input account balance

---------------------------------------------------------------------------------------------------------Processing, e.g., calculation (any other non-input/output tasks)

Calculate Interest at 10%

----------------------------------------------------------------------------------------------------------

Decisions or branch points

balance < 10,000 ?

----------------------------------------------------------------------------------------------------------

Connects parts of a flowchart

----------------------------------------------------------------------------------------------------------

To indicate the sequence of steps and the direction of flow

---------------------------------------------------------------------------------------------------------Figure 2-2. Flowchart symbols

2-18

Computer Power Institute

PDCLGA001b

Program Design Concepts

Section 2: Defining the problem and presenting the solution

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.

Using Microsoft Office Word 2007 to create flowcharts


We will briefly go over the use of Microsoft Word 2007 to create flowcharts and where to locate the required shapes. You will be creating flowcharts later in this section. The flowchart and lines auto shapes are accessed in Word 2007 by selecting the Shapes item from the ribbon. As shown in Figure 2-3.

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

Computer Power Institute

2-19

Section 2: Defining the problem and presenting the solution

Program Design Concepts

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

Figure 2-4. Flowchart showing sequence

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

Figure 2-5. Flowchart showing selection

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

Computer Power Institute

PDCLGA001b

Program Design Concepts

Section 2: Defining the problem and presenting the solution

stop looping ?

loop processing

N
loop processing
stop looping ?

Type A - Trailing decision loop

Type B - Leading decision loop

Figure 2-6. Flowcharts showing two types of repetition

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

Figure 2-7. Trailing decision loop for data entry

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

Computer Power Institute

2-21

Section 2: Defining the problem and presenting the solution

Program Design Concepts

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.

Start Input balance

More transac tions ?

Y
Input transaction

transaction processing to update account balance

Print account statement

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.

The Activity Solution can be found at the end of this Section

2-22

Computer Power Institute

PDCLGA001b

Program Design Concepts

Section 2: Defining the problem and presenting the solution

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

Figure 2-9. Flowchart for Question 1

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.

HINT: The Input/Output box comes before the Processing box.

PDCLGA001b

Computer Power Institute

2-23

Section 2: Defining the problem and presenting the solution

Program Design Concepts

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

Computer Power Institute

PDCLGA001b

Program Design Concepts

Section 2: Defining the problem and presenting the solution

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

Computer Power Institute

2-25

Section 2: Defining the problem and presenting the solution

Program Design Concepts

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.

Construct a flowchart for the correct algorithm for Questions 9, 10.

2-26

Computer Power Institute

PDCLGA001b

Program Design Concepts

Section 2: Defining the problem and presenting the solution

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

Computer Power Institute

2-27

Section 2: Defining the problem and presenting the solution

Program Design Concepts

SELF TEST ANSWERS


1. 1. 2. 3. 4. 5. 6. 2. (a) (b) 3. (a) (b) (c) 4. (a) (b) 5. 6. 7. A computer can receive information. A computer can output information. A computer can perform arithmetic. A computer can assign a value to a variable. A computer can compare two pieces of information and select one of two actions. A computer can repeat a group of actions. Read Get or Accept Print Write Display Initialise =

If .. Then .. Else .. EndIf Sequence, Selection and Repetition 3, 5, 7, 9, 11

2-28

Computer Power Institute

PDCLGA001b

Program Design Concepts

Section 2: Defining the problem and presenting the solution

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)

The loop will not terminate.

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

Computer Power Institute

2-29

Section 2: Defining the problem and presenting the solution

Program Design Concepts

11.
Start

Answer = 'Y'

Answer = 'Y' ?

Y
Get balance

Get interest

Let balance = balance + 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

Computer Power Institute

PDCLGA001b

Program Design Concepts

Section 2: Defining the problem and presenting the solution

13.
Start

Let count = 0

Let sum = 0

Count < 25 ?

Y
Get score

Let sum = sum + score

Let count = count + 1

Calculate average

Display average

End

14.

Your solution should be similar to the following.


Get name Get age Let heart rate = 0.8*(220 age) Display name, heart rate

15.

Your solution should be similar to the following.


If exam score >= 60 Then Display Pass Else Display Fail EndIf

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

Computer Power Institute

2-31

Section 2: Defining the problem and presenting the solution

Program Design Concepts

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.

Algorithm for Example 2.1 written in pseudocode.


Update and print account statement Repeat Get account balance If account balance < 10,000 Then Let interest rate = 8% Else Let interest rate = 10% EndIf Compute interest Add interest to balance Print account statement Until no more account balances END

Activity 2-2
1.
Start

Get number1

Get number2

Let result = number1 + number2

Display result

End

2-32

Computer Power Institute

PDCLGA001b

Program Design Concepts

Section 2: Defining the problem and presenting the solution

2.
Start

Get num1

Get num2

No

num1 bigger than num2 ?

Yes

bigger number = num2

bigger number = num1

Display bigger number

End

3.
Start

Initialise weekly total to zero

Get exam score

Add exam score to weekly total

more exam scores ?

N Display weekly total

End

PDCLGA001b

Computer Power Institute

2-33

Section 2: Defining the problem and presenting the solution

Program Design Concepts

4.
Start

Initialise weekly total = 0

Get exam score

Valid score ?

Y Add exam score to weekly total

More scores? N Display weekly total

End

2-34

Computer Power Institute

PDCLGA001b

Program Design Concepts

Section 2: Defining the problem and presenting the solution

5.
Start

Initialise weekly total to zero Initialise exam count to zero

Get exam score

No
Valid score ?

Yes
Add exam score t o weekly t ot al

Increment exam count by 1

Yes
More exam scores ?

No Calculate average

Display average

End

PDCLGA001b

Computer Power Institute

2-35

Section 2: Defining the problem and presenting the solution

Program Design Concepts

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

The variable count is initialised to 1, which is the first odd number.

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.

Display sum of even numbers 2 to 20.


Start

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

Computer Power Institute

PDCLGA001b

Program Design Concepts

Section 3: Sequence Control Structures

3.0
OBJECTIVES
1. 2. 3.

SECTION 3 SEQUENCE CONTROL STRUCTURES

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

Computer Power Institute

3-1

Section 3: Sequence Control Structures

Program Design Concepts

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

Computer Power Institute

PDCLGA001b

Program Design Concepts

Section 3: Sequence Control Structures

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

Computer Power Institute

3-3

Section 3: Sequence Control Structures

Program Design Concepts

Example 3.1 Add three numbers


A program is required to read three numbers, add them together, and print their total. Although this is only a simple problem, we will treat it as if it were complex in order to illustrate the process of applying the first few steps of the PDR, because it is better to start doing this with a simple problem before tackling a more complex problem. (As we are looking at a structured solution we will ignore the object oriented step. Remember in an object oriented solution step 2 would involve object modelling) Step 1: Analyse the Problem, identifying the Sub-problems. Obtain three numbers Add the three numbers together Print the total of the three numbers These steps are sufficient to establish the requirements of the problem. You must be absolutely confident that you know what is to be done in the program before you attempt to establish how it is done. A problem well defined is a problem half solved. Step 3: Develop a VTOC.

Main

Read in 3 numbers

Add three numbers together


Figure 3-2. VTOC for Example 3.1

Print total of 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.

INPUT number 1 number 2 number 3

PROCESSING total

OUTPUT

Figure 3-3. Incomplete Data Table for Example 3.1

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

Computer Power Institute

PDCLGA001b

Program Design Concepts

Section 3: Sequence Control Structures

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.

INPUT number 1 number 2 number 3

PROCESSING Read three numbers Add numbers together

OUTPUT total

Figure 3-4. Data Table for Example 3.1

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

Computer Power Institute

3-5

Section 3: Sequence Control Structures

Program Design Concepts

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

Computer Power Institute

PDCLGA001b

Program Design Concepts

Section 3: Sequence Control Structures

Lets create another List of Sub-problems, VTOC and Data Table for a problem, and follow that with another activity.

Example 3.2 Find average temperature


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. Again, this is a simple problem, but we will treat it as if it were complex in order to illustrate the process of applying the first three steps of the PDR. Step 1: Analyse the Problem, identifying the Sub-problems. Obtain the maximum and minimum temperatures Calculate the average temperature Display the average temperature

Step 3: Develop a VTOC.

Main

Get max and min temps

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:

INPUT max temp min temp

PROCESSING

OUTPUT avg temp

Figure 3-6. Incomplete Data Table for Example 3.2

PDCLGA001b

Computer Power Institute

3-7

Section 3: Sequence Control Structures

Program Design Concepts

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:

INPUT max temp min temp

PROCESSING Prompt for temperatures Get maximum and minimum temperatures Calculate average temperature

OUTPUT avg temp

Figure 3-7. Data Table for Example 3.2

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

Figure 3-8. Diagram for Activity 3-2

List of Sub-problems

3-8

Computer Power Institute

PDCLGA001b

Program Design Concepts

Section 3: Sequence Control Structures

Step 3: Develop a VTOC.

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

The Activity Solution can be found at the end of this Section.

PDCLGA001b

Computer Power Institute

3-9

Section 3: Sequence Control Structures

Program Design Concepts

45 mins

TOPIC 2: WRITING A SOLUTION ALGORITHM INVOLVING THE SEQUENCE CONTROL STRUCTURE


Writing a solution algorithm continues the challenging and creative Design Phase in the life cycle of program development. This is Step 5 of the Program Development Routine (PDR). Using the three basic control structures defined in the Structure Theorem (sequence, selection, repetition), you attempt to establish how the processing will take place. The Structure Theorem was covered in Section 2 in this Learning Guide. The first attempt at writing an algorithm usually does not result in a working finished product. Steps may be left out, or some that are included may later be altered or deleted. Pseudocode is useful in this trial and error process, because it is relatively easy to add, delete or alter an instruction using a word processor. Another important thing to remember is that there is not just one correct solution algorithm to a problem there will nearly always be more than one equally correct solution especially if it is a complex problem. However, it is good practice always to attempt to find the most elegant and efficient algorithm, and accept that there could be justifiable variations to a good algorithm. Do not hesitate to alter algorithms, or even to discard one and start again, if you are not completely satisfied with it. Initially, you are likely to have many false starts in designing an algorithm, but remember, if the algorithm is not correct, then the program will never be correct. A coded program will not miraculously fix up a faulty algorithm. It is important that you not be too anxious to start coding until the necessary steps of defining the problem and designing the solution algorithm have been successfully completed. In the following couple of pages we will look at solution algorithms for the examples in Topic 1, where VTOCs and Data Tables were created. These examples require solutions that involve only sequence control structures. There are no decisions or loops, which will be covered in the next two Sections of this Learning Guide.

3-10

Computer Power Institute

PDCLGA001b

Program Design Concepts

Section 3: Sequence Control Structures

Solution algorithm for Example 3.1


A program is required to read three numbers, add them together, and print their total. The solution algorithm is developed from the VTOC and the Data Table.

Main

Read in 3 numbers

Add three numbers together


Figure 3-9

P rint t ot al of numbers

INPUT number 1 number 2 number 3

PROCESSING Read three numbers Add numbers together

OUTPUT total

Figure 3-10

The solution algorithm


Add three numbers Read number1, number2, number3 Let total = number1 + number2 + number3 Print total End

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

Computer Power Institute

3-11

Section 3: Sequence Control Structures

Program Design Concepts

The solution algorithm for Example 3.2


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 solution algorithm is developed from the VTOC and the Data Table.

Main

Get max and min temps

Compute average
Figure 3-11

Display average

INPUT max temp min temp

PROCESSING Prompt for temperatures Get maximum and minimum temperatures Calculate average temperature

OUTPUT avg temp

Figure 3-12

The solution algorithm


Find average temperature Prompt for temperatures Get max temp, min temp Let avg temp = (max temp + min temp) / 2 Display avg temp End

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

Computer Power Institute

PDCLGA001b

Program Design Concepts

Section 3: Sequence Control Structures

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

Get all dimensions

Calculations
Figure 3-13

Display time

INPUT block length block width house length house width

PROCESSING Prompt for block measurements Get block measurements Prompt for house measurements Get house measurements Calculate mowing area Calculate mowing time
Figure 3-14

OUTPUT mowing time

The solution algorithm


Now write a solution algorithm before turning to the Activities Solutions at the end of this Section. The first line of the solution giving the algorithm a name is shown next as your starting point.
Find mowing time

The Activity Solution can be found at the end of this section.

PDCLGA001b

Computer Power Institute

3-13

Section 3: Sequence Control Structures

Program Design Concepts

45 mins

TOPIC 3: DESK-CHECKING A SOLUTION ALGORITHM INVOLVING THE SEQUENCE CONTROL STRUCTURE


After a solution algorithm has been constructed it must be tested for correctness. This is Step 6 of the Program Development Routine (PDR). This step is necessary because most major logic errors occur during the development of the algorithm, and if not detected, these errors would be passed to the coded program. It is much easier to detect errors in pseudocode than in the corresponding program code where your attention is focused on the syntax of the code rather than the logic of the solution. Desk-checking is the process of stepping through the algorithm line by line to check that its logic is correct and that expected outcomes are achieved. Desk-checking the solution algorithm to ensure accuracy can prevent many frustrating hours being wasted during the testing of the coded program, plus significantly reduce the cost in dollar terms. In this learning guide and in subsequent modules you will be desk checking the majority of your algorithm which is good practice as a beginner to programming and helps you layout your design before coding. In an actual real-world project only critical parts of an algorithm would be manually desk checked. These would usually be sections with complex logic or mission critical application code. The algorithm testing process involves desk-checking the algorithm with some test data. You walk through the logic of the algorithm exactly as a computer would, keeping track of all major variable values on paper. You are running the program in the sense that your brain is like the brain of the computer, carrying out the steps in the algorithm exactly as they are written. The desk-checking process should be recorded on paper in some sort of methodical way, which you will learn how to do shortly. Most computer programs require input of some sort in order to produce output. Since a desk check requires you to simulate the computer, you must have input data to operate on. Such data is called test data, and you choose it according to well-established rules.

Rules for choosing test data


1. The data must be comprehensive. Ideally, this means it should cover all possible situations that might occur when the program is running. It should test all possible paths through the algorithm. For very complex programs, the number of possible paths could run into the millions, so checking all of them might not be possible within time or budget constraints. In that case, one has to prioritise which combinations of paths to test. It certainly will be possible to check all possible paths in any algorithm studied in this module. The data should test error situations. There should be deliberate errors in the test data to see whether the algorithm can handle them. Be wary of zero because division by zero is not allowed. In Section 2 in this Learning Guide, there is a sample flowchart (Figure 2-6) illustrating the logic of a trailing decision loop used for a data validation process. The data should test boundary conditions in a selection construct. For example, suppose an employee gets paid overtime once they have worked more than 40 hours. The figure of 40 is a boundary value. In this case, the test data should contain values that are either side of the boundary value (e.g., 41 and 39) as well as the boundary value itself (40).

2.

3.

3-14

Computer Power Institute

PDCLGA001b

Program Design Concepts

Section 3: Sequence Control Structures

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.

Steps in the algorithm testing process


There are three steps to follow when desk-checking an algorithm: 1. 2. Create a Test Data Table choosing input test data, and then work out what the expected results should be for each test data set. Refer to Step 6 in the PDR. Draw up a suitable Desk-check Table on a piece of paper. A sample Desk-check Table is shown in Figure 1-7 in the PDR document. Walk the test data through the algorithm statement by statement, keeping a record on paper of the contents of each variable, until the algorithm reaches its logical end. Repeat the walk-through process using the other test data cases. Finally, check that the actual results developed in Step 2 match the expected results established in Step 1.

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.

Desk-check of Example 3.1


The solution algorithm is:
Add three numbers Read number1, number2, number3 Let total = number1 + number2 + number3 Print total End

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

Second data set

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

Computer Power Institute

3-15

Section 3: Sequence Control Structures

Program Design Concepts

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

Second data set


Steps 1 2 3 number 1 40 number 2 41 number 3 42 VARIABLES total 123

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

Computer Power Institute

PDCLGA001b

Program Design Concepts

Section 3: Sequence Control Structures

Desk-check of Example 3.2


The solution algorithm (as developed in the previous topic and repeated here)
Find average temperature Get max temp, min temp Let avg temp = (max temp + min temp) / 2 Display avg temp End

Draw up a Test Data table


Choose two sets of input test data for each of the input variables. Establish the expected result of the output variable for each test data set.

First data set

INPUT max temp min temp max temp

30 10 40

EXPECTED OUTPUT avg temp 20

Second data set

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.

Desk-check Average temperature


First data set

VARIABLES Steps 1 2 3

Second data set

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

Section 3: Sequence Control Structures

Program Design Concepts

Desk check of Activity 3-3


The solution algorithm (as developed in the previous topic)
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

Draw up a Test Data table


Choose two sets of input test data for each of the input variables. Establish the expected result of the output variable for each test data set.

First data set

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

EXPECTED OUTPUT mowing time 60

Second data set

mowing time

80

3-18

Computer Power Institute

PDCLGA001b

Program Design Concepts

Section 3: Sequence Control Structures

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.

Desk-check Find Mowing Time


First data set
Steps 1 2 3 4 5 6 7 8 block length block width house length VARIABLES house block width area house area mowing area mowing time

Second data set


Steps 1 2 3 4 5 6 7 8 block length block width house length VARIABLES house block width area house area mowing area mowing time

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-19

Section 3: Sequence Control Structures

Program Design Concepts

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

Computer Power Institute

PDCLGA001b

Program Design Concepts

Section 3: Sequence Control Structures

VTOC

Data Table

INPUT

PROCESSING

OUTPUT

The solution algorithm

PDCLGA001b

Computer Power Institute

3-21

Section 3: Sequence Control Structures

Program Design Concepts

Test Data table

INPUT First data set

EXPECTED OUTPUT

Second data set

Desk-check table First data set

VARIABLES

Steps 1 2 3 4 5 6 7 8

Second data set

VARIABLES

Steps 1 2 3 4 5 6 7 8

3-22

Computer Power Institute

PDCLGA001b

Program Design Concepts

Section 3: Sequence Control Structures

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

Computer Power Institute

3-23

Section 3: Sequence Control Structures

Program Design Concepts

The solution algorithm

Test Data table

INPUT First data set

EXPECTED OUTPUT

Second data set

Desk-check table First data set

VARIABLES Steps 1 2 3 4 5 6 7 8

Second data set

3-24

Computer Power Institute

PDCLGA001b

Program Design Concepts

Section 3: Sequence Control Structures

VARIABLES Steps 1 2 3 4 5 6 7 8

PDCLGA001b

Computer Power Institute

3-25

Section 3: Sequence Control Structures

Program Design Concepts

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

Computer Power Institute

PDCLGA001b

Program Design Concepts

Section 3: Sequence Control Structures

The solution algorithm

Test Data table

INPUT First data set

EXPECTED OUTPUT

INPUT Second data set

EXPECTED OUTPUT

PDCLGA001b

Computer Power Institute

3-27

Section 3: Sequence Control Structures

Program Design Concepts

Desk-check table First data set

VARIABLES

Steps 1 2 3 4 5 6 7 8

Second data set

VARIABLES

Steps 1 2 3 4 5 6 7 8

3-28

Computer Power Institute

PDCLGA001b

Program Design Concepts

Section 3: Sequence Control Structures

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

Computer Power Institute

3-29

Section 3: Sequence Control Structures

Program Design Concepts

The solution algorithm

Test Data table


INPUT First data set EXPECTED OUTPUT

INPUT Second data set

EXPECTED OUTPUT

3-30

Computer Power Institute

PDCLGA001b

Program Design Concepts

Section 3: Sequence Control Structures

Desk-check table First data set


VARIABLES

Steps 1 2 3 4 5 6 7 8

Second data set


VARIABLES

Steps 1 2 3 4 5 6 7 8

PDCLGA001b

Computer Power Institute

3-31

Section 3: Sequence Control Structures

Program Design Concepts

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

Computer Power Institute

PDCLGA001b

Program Design Concepts

Section 3: Sequence Control Structures

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

Get Name and Age

Calculate ideal heart rate

Display ideal heart rate

Data Table

INPUT Name Age

PROCESSING Get name and age Calculate ideal heart rate using the appropriate formula

OUTPUT Ideal heart rate

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

Get all dimensions

Calculations

Display time

PDCLGA001b

Computer Power Institute

3-33

Section 3: Sequence Control Structures

Program Design Concepts

Data Table

INPUT block length block width house length house width

PROCESSING Prompt for block measurements Get block measurements Prompt for house measurements Get house measurements Calculate mowing area Calculate mowing time

OUTPUT 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

VARIABLES Steps 1 2 3 max temp 30 min temp 10 20 avg temp

Second data set

VARIABLES Steps 1 2 3 max temp 40 min temp 20 30 avg temp

3-34

Computer Power Institute

PDCLGA001b

Program Design Concepts

Section 3: Sequence Control Structures

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

Second data set


Steps 1 2 3 4 5 6 7 block length 40 block width 30 house length 20 VARIABLES house block width area 20 1200 400 800 80 house area mowing area mowing time

PDCLGA001b

Computer Power Institute

3-35

Section 3: Sequence Control Structures

Program Design Concepts

3-36

Computer Power Institute

PDCLGA001b

Program Design Concepts

Section 4: Selection Control Structures

4.0
OBJECTIVES
1. 2. 3. 4. 5.

SECTION 4 SELECTION CONTROL STRUCTURES

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

Computer Power Institute

4-1

Section 4: Selection Control Structures

Program Design Concepts

TOPIC 1: BOOLEAN EXPRESSIONS


60 mins The selection control structure was introduced in Section 2 as the second construct in the Structure Theorem. This structure represents the decision-making capabilities of the computer. You use the selection control structure in pseudocode to illustrate a choice between two or more actions, depending on whether a condition is true or false. Selection control structures use boolean expressions, which consist of elements and relational operators.

Relational Operators
The relational operators and their meanings are shown in Table 4-1:

Operator = < <= > >= <>

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

Table 4-1. Common Relational Operators

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.

Using Relational Operators in Boolean Expressions


Relational operators are used in boolean expressions. Boolean expressions are used in the Selection Control structure and it is very important that you understand them. Expressions such as number of days < 30 can be given a value True or False. This type of expression is called a boolean expression. A boolean expression is one that contains only one of two possible values True or False. Computers can appear to make a decision by evaluating a boolean expression, that is, determining whether it is true or false. This is what gives computers their ability to appear to be intelligent. Boolean expressions are a part of Boolean Algebra, which was named after a nineteenth-century English mathematician called George Boole.

4-2

Computer Power Institute

PDCLGA001b

Program Design Concepts

Section 4: Selection Control Structures

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

My course hours variance is currently positive

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.

The AND Rule


If two conditions are combined using the AND connector, then both conditions must be true for the combined condition to be true. We can use a truth table to illustrate this AND rule (See Table 4-2). For two boolean variables A and B, each of which can be either true or false, there are 4 possible outputs:

SEPARATE INPUT A B true true true false false true false false

COMBINED OUTPUT A and B true false false false

Table 4-2. The AND truth table

PDCLGA001b

Computer Power Institute

4-3

Section 4: Selection Control Structures

Program Design Concepts

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

COMBINED OUTPUT A or B true true true false

Table 4-3. The OR truth table

4-4

Computer Power Institute

PDCLGA001b

Program Design Concepts

Section 4: Selection Control Structures

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 and Y <= 2

X > 5 or Y <= 2

Make sure you understand the logic of the following:

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

Computer Power Institute

4-5

Section 4: Selection Control Structures

Program Design Concepts

The Order of Precedence Rule


It is possible to have a mixture of AND and OR conditions in the one boolean expression. If a mixture is encountered then there has to be some way of deciding which condition is evaluated first. This is where the order of precedence rule is invoked. The rule states that:

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

y < > 10 True

AND AND

z=8 False

When this is evaluated first

True

AND

False

False
Figure 4-1

and then combined with this

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

Computer Power Institute

PDCLGA001b

Program Design Concepts

Section 4: Selection Control Structures

Case 2: Evaluating the AND component first.

x=2 True

OR OR

y < > 10 True

AND AND

z=8 False

True

OR

False

When this is evaluated first

and then Figure 4-2 combined with this

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

Computer Power Institute

4-7

Section 4: Selection Control Structures

Program Design Concepts

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

Computer Power Institute

PDCLGA001b

Program Design Concepts

Section 4: Selection Control Structures

TOPIC 2: VARIATIONS OF THE SELECTION CONTROL STRUCTURE


We will put some of that Boolean logic into practice by looking at the selection control structure. Variations of the selection control structure are: 1. 2. 3. one-alternative selection two-alternative selection multiple-alternative selection 60 mins

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

Computer Power Institute

4-9

Section 4: Selection Control Structures

Program Design Concepts

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

account balance 200 600 1000

service charge

5 2 500 499 500 501


Table 4-4

ACTIVITY 4-6
Study this partial algorithm and complete Table 4-5.
gamma = 30 If alpha < beta Then Let gamma = gamma * gamma EndIf

alpha 5 50 99 500 501

beta 10 40 100 500 500


Table 4-5

gamma

4-10

Computer Power Institute

PDCLGA001b

Program Design Concepts

Section 4: Selection Control Structures

Using Complex Boolean Expressions in an if Statement


You can form more complex boolean expressions out of simpler ones by combining boolean expressions using the operators AND and OR to yield a complex boolean expression. A complex boolean expression is one that contains a combination of two or more conditions, each connected with AND or OR. The Order of Precedence Rule to determine which pair is evaluated first was explained in the previous Topic and will be invoked in this situation. Complete Activity 4-7 to practise evaluating a complex boolean expression.

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

((X<7)OR(Y=2)) AND (Z>5)

PDCLGA001b

Computer Power Institute

4-11

Section 4: Selection Control Structures

Program Design Concepts

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

Computer Power Institute

PDCLGA001b

Program Design Concepts

Section 4: Selection Control Structures

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

Computer Power Institute

4-13

Section 4: Selection Control Structures

Program Design Concepts

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

Computer Power Institute

PDCLGA001b

Program Design Concepts

Section 4: Selection Control Structures

TOPIC 3: ALGORITHMS USING THE SELECTION CONTROL STRUCTURE


60 mins Let us look at some programming examples that use the selection control structure. In each example, we will use the three-steps that were outlined in Section 3 - the problem will be analysed, a solution algorithm will be developed, and the algorithm will be tested. Inputs and outputs are underlined, and processing verbs double underlined. Example 4.1 Read three characters

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.

INPUT char1 char2 char3

PROCESSING Prompt for characters Accept three characters Sort three characters Display three characters
Table 4-10. Data Table for Example 4.1

OUTPUT char1 char2 char3

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

Computer Power Institute

4-15

Section 4: Selection Control Structures

Program Design Concepts

The Swapping Process


The following diagram should help understand the swapping process. Think of the variables as cups that have a letter in them. When another letter is put into a cup it replaces the letter that was in there. A cup can have only one letter in it at a time and that is why you have to have a temporary location to store a value. As an example, let the two characters be S and B in that order (char1 = S and char2 = B). Step 1: Compare char1 and char2.

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

Step 3: Put the value of char2 into the char1 cup.

B
char1 char2
Figure 4-5

S
temp

4-16

Computer Power Institute

PDCLGA001b

Program Design Concepts

Section 4: Selection Control Structures

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.

The solution algorithm


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
Compare char1 and char2. If char1 is bigger than char2, then swap them around using the temporary location temp. If char1 is smaller than char2, leave them as they are.

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.

Display on the screen char1, char2, char3 End

Now that we have developed an algorithm we have to test it to check it gives the right results.

PDCLGA001b

Computer Power Institute

4-17

Section 4: Selection Control Structures

Program Design Concepts

The algorithm testing process


We will use the test data in Table 4-11.

First data set

INPUT char1 K char2 G char3 B char1 char2 char3 S Z A

EXPECTED OUTPUT char1 B char2 G char3 K char1 char2 char3 A S Z

Second data set

Table 4-11. Test Data Table

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

Computer Power Institute

PDCLGA001b

Program Design Concepts

Section 4: Selection Control Structures

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

Table 4-12. First data set

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

Computer Power Institute

4-19

Section 4: Selection Control Structures

Program Design Concepts

VARIABLES char1 char2 char3 temp

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

Table 4-13. Second data set

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

OUTPUT cust name tax amt total amt

4-20

Computer Power Institute

PDCLGA001b

Program Design Concepts

Section 4: Selection Control Structures

The solution algorithm Step 5 in the PDR


The solution algorithm requires a multiple-alternative If statement to calculate the amount of tax.
Process customer record Read cust name, purch amt, tax code If tax code = 0 Then Let tax amt = 0 ElseIf tax code = 1 Then Let tax amt = purch amt * 0.03 ElseIf tax code = 2 Then Let tax amt = purch amt * 0.05 Else Let tax amt = purch amt * 0.07 EndIf Let total amt = purch amt + tax amt Print cust name, tax amt, total amt End

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.

The algorithm testing process


First data set INPUT cust name Mick purch amt 10.00 tax code 0 cust name purch amt tax code Mary 20.00 2 EXPECTED OUTPUT cust name Mick tax amt 0 total amt 10.00 cust name tax amt total amt Mary 1.00 21.00

Second data set

Table 4-15. Test Data Table

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

VARIABLES tax amt total amt

Steps 1 Mick 10.00 2 If tax code = 0 is True 3 4 5

0 0 10.00

Table 4-16. First data Set

PDCLGA001b

Computer Power Institute

4-21

Section 4: Selection Control Structures

Program Design Concepts

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

VARIABLES tax amt total amt

1.00 21.00
Table 4-17. Second data set

Here is another example. Example 4.3 Calculate employees pay

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

Computer Power Institute

PDCLGA001b

Program Design Concepts

Section 4: Selection Control Structures

Analyse the Problem, identifying the sub-problems.


Get the employees number, hourly pay rate and number of hours worked Validate hours worked and hourly rate Calculate weekly pay for valid input data Print output data
Table 4-18. The List of Sub-problems for Example 4.3

Develop a VTOC
Main

Initialise

Process

Finalise

Initialise Variables

Read input data

Validate input data

Calculate pay

Print output

Figure 4-7. VTOC for Example 4.3

Create a Data Table


Creating the Data Table for this problem involves identifying the inputs and outputs (nouns and adjectives), and then the actions (verbs) to constitute the simple processing steps in the right order.

INPUT emp no pay rate hrs worked

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

Table 4-19. The Data Table for Example 4.3

Write the Algorithm in Pseudocode


The solution algorithm to this problem requires a series of simple If statements and a nested If statement. A nested If statement is simply an If .. EndIf statement inside another. After the employee details have been input, the variables pay rate and hrs worked must be validated (that is, checked that they are valid values within the range specified in the question the hours worked is to be not more than 60 and the hourly rate is to be not more than 25). To facilitate this task, another variable called valid input fields will be used to indicate to the program whether or not these input fields are valid. If at least one of them is found to be out of range then an appropriate message is to be placed into a variable called error message.

PDCLGA001b

Computer Power Institute

4-23

Section 4: Selection Control Structures

Program Design Concepts

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.

The solution algorithm for example 4.3


Compute employee pay Set valid input fields to true Set error message to blank Read emp no, pay rate, hrs worked If (pay rate Let error Let valid Print emp EndIf > 25) Then message = Pay rate exceeds 25.00 input fields = false no, pay rate, hrs worked, error message The INITIALISE phase of the algorithm

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

The PROCESS phase of the algorithm.

Print emp no, pay rate, hrs worked, emp weekly pay EndIf End

The FINALISE phase of the algorithm

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

Computer Power Institute

PDCLGA001b

Program Design Concepts

Section 4: Selection Control Structures

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

1 Response Total If (response<0) or (response>30) (True or False) total Printed message 15

2 31

3 20

4 10

Table 4-20

PDCLGA001b

Computer Power Institute

4-25

Section 4: Selection Control Structures

Program Design Concepts

TOPIC 4: THE CASE CONTROL STRUCTURE


30 mins The case control structure is another way of representing a multiple-alternative If .. Then .. ElseIf .. Then .. ElseIf .. Then .. EndIf control structure, which often looks cumbersome. The case control structure can be directly translated into many highlevel programming languages, but not all. Nevertheless, it is important to have an understanding of it. The Case statement extends the basic selection control structure to a choice between many values. Several alternative logical paths can be represented in the one case structure, and it is therefore less cumbersome than a multiple-alternative If .. Then .. ElseIf .. Then .. ElseIf .. Then .. EndIf control structure. You represent a Case Statement in pseudocode using the keywords CaseOf and EndCase, and the multiple values are indented, as follows:
CaseOf single variable value 1 : statement block 1 value 2 : statement block 2 . . . value n : statement block n value other : statement block other EndCase

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

Computer Power Institute

PDCLGA001b

Program Design Concepts

Section 4: Selection Control Structures

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.

Watts Brightness (in lumens)

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.

tax exempt type 1 tax type 2 tax type 3 tax

(0%) (3%) (5%) (7%)

PDCLGA001b

Computer Power Institute

4-27

Section 4: Selection Control Structures

Program Design Concepts

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.

INPUT cust name purch amt tax code

PROCESSING Read customer details Compute tax amount Compute total amount Print customer details
Table 4-23. Data Table for Example 4.4

OUTPUT cust name tax amt total amt

The solution algorithm


The solution algorithm will use a case statement to calculate the amount of tax.
Process customer record Read cust name, purch amt, tax code CaseOf tax 0 : Let 1 : Let 2 : Let 3 : Let EndCase code tax amt tax amt tax amt tax amt = = = = 0 purch amt * 0.03 purch amt * 0.05 purch amt * 0.07

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

Computer Power Institute

PDCLGA001b

Program Design Concepts

Section 4: Selection Control Structures

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

The solution algorithm


You will need to use an If construct to validate the integer input. You should be able to base your answer on Example 4.3 above, so refer back to it if you need help. Create a variable called valid integer that can be used as a flag, and a variable called message to hold the day of the week or the out of range message. The solution algorithm will use a CASE statement to match the day of the week to the valid integer, and place the day of the week in a message that is displayed on the screen.

The algorithm testing process


Use the test data in Table 4-24 to desk-check your algorithm.
First data set Second data set Third data set Fourth data set INPUT int number 1 int number 4 int number 0 int number 10 EXPECTED OUTPUT message Monday message Thursday message Number not in range 1 - 7 message Number not in range 1 - 7

Table 4-24. Test Data Table

PDCLGA001b

Computer Power Institute

4-29

Section 4: Selection Control Structures

Program Design Concepts

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

Computer Power Institute

PDCLGA001b

Program Design Concepts

Section 4: Selection Control Structures

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

Discount rate 50% 40% 33% 25% 0%

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

Computer Power Institute

4-31

Section 4: Selection Control Structures

Program Design Concepts

Sub-problems

VTOC

4-32

Computer Power Institute

PDCLGA001b

Program Design Concepts

Section 4: Selection Control Structures

The Data Table

INPUT

PROCESSING

OUTPUT

The solution algorithm

PDCLGA001b

Computer Power Institute

4-33

Section 4: Selection Control Structures

Program Design Concepts

The algorithm testing process Test Data table

First data set

article price price code

INPUT 10.00 Q

EXPECTED OUTPUT

Second data set

article price price code

100.00 A

Third data set

article price price code

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

Computer Power Institute

PDCLGA001b

Program Design Concepts

Section 4: Selection Control Structures

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

Computer Power Institute

4-35

Section 4: Selection Control Structures

Program Design Concepts

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

Computer Power Institute

PDCLGA001b

Program Design Concepts

Section 4: Selection Control Structures

The Data Table

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

Computer Power Institute

4-37

Section 4: Selection Control Structures

Program Design Concepts

The algorithm testing process Test Data table


INPUT First data set EXPECTED OUTPUT

Second data set

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

Computer Power Institute

PDCLGA001b

Program Design Concepts

Section 4: Selection Control Structures

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

Computer Power Institute

4-39

Section 4: Selection Control Structures

Program Design Concepts

The Data Table


INPUT PROCESSING OUTPUT

The solution algorithm

4-40

Computer Power Institute

PDCLGA001b

Program Design Concepts

Section 4: Selection Control Structures

The algorithm testing process Test Data table


INPUT First data set EXPECTED OUTPUT

Second data set

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

Computer Power Institute

4-41

Section 4: Selection Control Structures

Program Design Concepts

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

Computer Power Institute

PDCLGA001b

Program Design Concepts

Section 4: Selection Control Structures

The Data Table


INPUT PROCESSING OUTPUT

The solution algorithm

PDCLGA001b

Computer Power Institute

4-43

Section 4: Selection Control Structures

Program Design Concepts

The algorithm testing process Test Data table


INPUT First data set EXPECTED OUTPUT

Second data set

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

Computer Power Institute

PDCLGA001b

Program Design Concepts

Section 4: Selection Control Structures

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

Computer Power Institute

4-45

Section 4: Selection Control Structures

Program Design Concepts

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

Computer Power Institute

PDCLGA001b

4-46

Program Design Concepts

Section 4: Selection Control Structures

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

(a) (b) (c) (d)

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

((X<7)OR(Y=2)) AND (Z>5) T AND T = T T AND F = F F AND T = F T AND T = T

(a) (b) (c) (d)

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

(K<>15)AND((L>10)OR(M<30)) T AND T = T T AND T = T F AND F = F F AND T = F

Activity 4-8
zone 2 4 1 3 OUTPUT 2000 ERROR 1000 3000

PDCLGA001b

Computer Power Institute

4-47

Section 4: Selection Control Structures

Program Design Concepts

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

Computer Power Institute

PDCLGA001b

4-48

Program Design Concepts

Section 4: Selection Control Structures

Activity 4-12
The Data Table

INPUT int number

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

The PROCESS phase of the algorithm

The algorithm testing process First data set

The FINALISE phase of the algorithm

VARIABLES valid integer message int number

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

Computer Power Institute

4-49

Section 4: Selection Control Structures


Second data set
VARIABLES valid integer Message int number

Program Design Concepts

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

Third data set


VARIABLES valid integer message int number

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

Fourth data set


VARIABLES valid integer message int number

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

Computer Power Institute

PDCLGA001b

4-50

Program Design Concepts

Section 5: Repetition Control Structures

5.0
OBJECTIVES
1. 2. 3. 4.

SECTION 5 REPETITION CONTROL STRUCTURES

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

Computer Power Institute

5-1

Section 5: Repetition Control Structures

Program Design Concepts

60 mins

TOPIC 1: REPETITION USING THE WHILE .. ENDWHILE CONTROL STRUCTURE


The solution algorithms developed so far stop after the input and processing of just one set of values. However, most programs require the same logic to be repeated for several sets of data. An example of this is Question 2 in the Checkpoint activities for the previous Section where you wanted to process of a batch of exams scores. The most efficient way to deal with this situation is to establish a looping structure in the algorithm that will cause the processing logic to be repeated the required number of times. The repetition of a sequence of instructions is also referred to as looping or iteration. In Section 2, three formats of the Repetition Control Structure were introduced. The first of these is the While .. EndWhile construct. Its format in pseudocode is:
While condition p is true statement block EndWhile

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

Computer Power Institute

PDCLGA001b

Program Design Concepts

Section 5: Repetition Control Structures

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

Computer Power Institute

5-3

Section 5: Repetition Control Structures

Program Design Concepts

VTOC

The Data Table

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

Body of the loop


This IF statement defends against division by zero

5-4

Computer Power Institute

PDCLGA001b

Program Design Concepts

Section 5: Repetition Control Structures

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

The basic pattern of an algorithm to process records in a sequential file

PDCLGA001b

Computer Power Institute

5-5

Section 5: Repetition Control Structures

Program Design Concepts

ACTIVITY 5-1 (CONTINUED)


To test the solution algorithm for Example 5.1, pass the test data in Table 5-1 through the solution algorithm, statement by statement, and check that the output results match the expected results. Draw up your own desk-check table. Test Data table
1 record 2 record sentinel record
nd st

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:

total females enrolled in PDC, total students enrolled in PDC.

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

Computer Power Institute

PDCLGA001b

Program Design Concepts

Section 5: Repetition Control Structures

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.

INPUT student record ID name address postcode gender course code

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

Table 5-2. The Data Table for Example 5.1

In this example we will use:

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.

The solution algorithm


Process student enrolments Set total females to zero Set total students to zero Read student record While Not EOF If module code = PDC Then print student details increment total students If gender = female Then increment total females EndIf EndIf Read student record EndWhile Print total females Print total students End FINALISE phase INITIALISE phase Priming Read

Process this record while the End Of File is not reached

Read next record

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

Computer Power Institute

5-7

Section 5: Repetition Control Structures

Program Design Concepts

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

1 record 2 record 3 record


rd nd

st

INPUT module code DWS gender Female module code PDC gender Female module code PDC gender Male
Table 5-3

EXPECTED OUTPUT total females total students

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.

The Activity Solution can be found at the end of this Section.

5-8

Computer Power Institute

PDCLGA001b

Program Design Concepts

Section 5: Repetition Control Structures

Validating Input Data using While .. EndWhile


A common use of the While .. EndWhile repetition construct is to execute an error routine that forces the user to enter another value if an invalid input value is detected. While statements used for this purpose contain a loop control specification that evaluates an input value. The loop body will be executed only if the input value is invalid. In the following algorithm segment, an input value that is less than or equal to 100 is required, so anything greater than 100 will cause the error routine to be executed. The program control will remain in the loop body until a value less than or equal to 100 is entered.
Validate input Prompt for number Get number While number > 100 prompt operator to enter number less than or equal to 100 Get number EndWhile Control will End remain in the loop while there is an invalid input value

PDCLGA001b

Computer Power Institute

5-9

Section 5: Repetition Control Structures

Program Design Concepts

60 mins

TOPIC 2: REPETITION USING THE REPEAT .. UNTIL CONTROL STRUCTURE


The Repeat .. Until structure is similar to the While .. EndWhile structure, in that a group of statements is repeated in accordance with a specified condition. However, where the While .. EndWhile structure tests the condition at the beginning of the loop, the Repeat .. Until structure tests the condition at the end of the loop. This means that the statements within the loop will be executed at least once. The statements will continue to be repeated until the condition becomes true. The format of the Repeat .. Until structure is:
Repeat statement block Until condition is true

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.

Validating Input Data using Repeat .. Until


In the following algorithm segment, an input value that is less than 100 is required, so an input value greater than 100 will cause the program control to remain in the loop body until a value less than or equal to 100 is entered.
Validate input Repeat Prompt for number less than or equal to 100 Get number Until number <= 100 End Control will not exit the loop until a valid input value is entered

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

Computer Power Institute

PDCLGA001b

Program Design Concepts

Section 5: Repetition Control Structures

Example 5.3

Lucky Customer (Uses a simple Repeat .. Until algorithm)

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

Table 5-4. Data Table for Example 5.4

In this example we will use:

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

Computer Power Institute

5-11

Section 5: Repetition Control Structures

Program Design Concepts

The solution algorithm using Repeat .. Until


Process inventory records Set total low stock items to zero Print Low Stock Items heading Repeat Read inventory record If (item number < > zero) Then If (stock figure < 20) Then print item number, item description, stock figure increment total low stock items EndIf EndIf Until (item number = zero) Print total low stock items End

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

The Activity Solution can be found at the end of this Section.

5-12

Computer Power Institute

PDCLGA001b

Program Design Concepts

Section 5: Repetition Control Structures

TOPIC 3: FIXED-NUMBER REPETITION USING THE FOR .. ENDFOR CONTROL STRUCTURE


Fixed-number repetition occurs when the exact number of loop iterations is known in advance. You can use this construct to repeat a statement or group of statements for a specific number of times. The execution of the loop is controlled by a loop index. The loop index changes automatically, in ascending order it is not changed by a statement in the algorithm.
Loop control specification

60 mins

The key words For .. EndFor are used as follows:

For loop index changing from initial value to final value statement block EndFor Body of the Loop

The For .. EndFor loop consists of two parts:

a loop control specification a loop body.

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

Computer Power Institute

5-13

Section 5: Repetition Control Structures

Program Design Concepts

Example 5.5

Fahrenheit-Celsius conversion (Uses a For .. EndFor loop)

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

tests temperature automatically

count at the beginning of each pass to ensure that count

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

Computer Power Institute

PDCLGA001b

Program Design Concepts

Section 5: Repetition Control Structures

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

INPUT f temp 32 f temp 96.8 f temp 100 f temp 212


Table 5-6

EXPECTED OUTPUT c temp 0 c temp 36 c temp 37.8 c temp 100

The Activity Solution can be found at the end of this section

PDCLGA001b

Computer Power Institute

5-15

Section 5: Repetition Control Structures

Program Design Concepts

TOPIC 4: USING REPETITION FOR PROCESSING ARRAYS


30 mins An ordinary variable can hold only one piece of data at a time, such as a number or a name. The moment you try to store another piece of data in a variable, the old data in the variable is immediately replaced by the new data. Unlike variables that have been encountered so far in this Learning Guide, an array is a single variable name that can hold one or more pieces of data, as long as each piece of data is the same data type, such as integer. Data types were studied in Section 2.

Figure 5-1. Analogy of an array a collection of cards

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

Computer Power Institute

PDCLGA001b

Program Design Concepts

Section 5: Repetition Control Structures

ACTIVITY 5-5
Consider the following array and the data that it contains shown in Table 5-7.

name[1] name[2] name[3] name[4] name[5] name[6] name[7] name[8]

Lisa Steve Mike Isabella Peter Lauren Stephanie Rod


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

Computer Power Institute

5-17

Section 5: Repetition Control Structures

Program Design Concepts

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

OUTPUT scores 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

Computer Power Institute

PDCLGA001b

Program Design Concepts

Section 5: Repetition Control Structures

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

Computer Power Institute

5-19

Section 5: Repetition Control Structures

Program Design Concepts

The Data Table


INPUT PROCESSING OUTPUT

The solution algorithm

5-20

Computer Power Institute

PDCLGA001b

Program Design Concepts

Section 5: Repetition Control Structures

The algorithm testing process


Test Data table
INPUT First data set EXPECTED OUTPUT

Second data set

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

Section 5: Repetition Control Structures

Program Design Concepts

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

Computer Power Institute

PDCLGA001b

Program Design Concepts

Section 5: Repetition Control Structures

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

Computer Power Institute

5-23

Section 5: Repetition Control Structures

Program Design Concepts

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

Computer Power Institute

PDCLGA001b

Program Design Concepts

Section 5: Repetition Control Structures

ACTIVITY SOLUTIONS
Activity 5-1
The Data Table

INPUT name exam score

PROCESSING Enter student details Print student details Compute average score Print average score

OUTPUT name exam score 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

VARIABLES averag e 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

Computer Power Institute

5-25

Section 5: Repetition Control Structures

Program Design Concepts

Activity 5-2
Desk-check table

Step s 1 2 3 4 5 6 7 8 9 10 11 12 13

total female s in PDC 0

total student s in PDC 0

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

Computer Power Institute

PDCLGA001b

Program Design Concepts

Section 5: Repetition Control Structures

Activity 5-4

VARIABLES tempe rature count f temp c temp

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

Initialise Fill array

Process

Finalise

Calculate Average

Count numbers above average

PDCLGA001b

Computer Power Institute

5-27

Section 5: Repetition Control Structures

Program Design Concepts

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

Computer Power Institute

PDCLGA001b

Program Design Concepts

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

Computer Power Institute

6-1

Section 6: Modularisation

Program Design Concepts

TOPIC 1: THE CONCEPT OF MODULARISATION


10 mins Throughout the previous sections we have emphasised that to design a solution algorithm, you must: 1. 2. 3. 4. 5. analyse the problem, dividing it into sub-problems, develop a VTOC, create a Data Table, create an algorithm that uses a combination of sequence, selection and repetition control structures, and test that the algorithm works properly.

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

Computer Power Institute

PDCLGA001b

Program Design Concepts

Section 6: Modularisation

The Modularisation Process


The division of a problem into smaller subtasks or modules is a relatively simple process. When you are analysing the problem, write down the activities or processing steps to be performed. These activities are then grouped together to form more manageable tasks or functions, which will eventually form modules. The emphasis when analysing the problem must be to concentrate on which tasks or functions need to be performed. Each function will be made up of a number of activities, all of which contribute to the performance of a single task. Some important facts:

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.

The Master Control Module


Since each module performs a single specific task, there must be a module to provide the overall master control that ties all the modules together and coordinates their activity. This master control module should show the main processing functions and the order in which they are to be performed. It should also show the flow of data and the major control structures, be easy to read, be of manageable length, and show sound logic structure. Generally, you should be able to read a pseudocode master control module and see exactly what is being done at any point in the program. The master control module and its subordinate modules should now be represented in a VTOC Diagram, which is explained in the next topic.

PDCLGA001b

Computer Power Institute

6-3

Section 6: Modularisation

Program Design Concepts

TOPIC 2: VTOC DIAGRAMS IN MODULAR PROGRAMS


30 mins After the tasks have been grouped into modules, you should present them graphically in a VTOC a Visual Table Of Contents. In modularised programs, the VTOC shows not only the names of all the modules but also their hierarchical relationship to each other.

Figure 6-1. Hierarchical representation of modules VTOC

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

Computer Power Institute

PDCLGA001b

Program Design Concepts

Section 6: Modularisation

Example 6.1

Calculate employees pay

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.

Compute employee pay

Initialise

Process a record

Finalise

Validate input fields

Calculate employee pay

Figure 6-2. VTOC for Example 6.1

PDCLGA001b

Computer Power Institute

6-5

Section 6: Modularisation

Program Design Concepts

The Data Table


INPUT emp no pay rate hrs worked PROCESSING Read employee details Validate input fields Calculate employee pay Print employee details OUTPUT emp no pay rate hrs worked emp weekly pay error message

Figure 6-3. The Data Table for Example 6.1

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

Computer Power Institute

PDCLGA001b

Program Design Concepts

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

Finalise Close file Display closing message End

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.

Create patient account

Compute accommodation charges

Compute theatre charges

Compute pathology charges

Compute sundries charges

Print patient account

Figure 6-4. Partially completed VTOC for Example 6.3

PDCLGA001b

Computer Power Institute

6-7

Section 6: Modularisation

Program Design Concepts

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.

Create patient account

Compute accommodation charges

Compute theatre charges

Compute pathology charges

Compute sundries charges

Print patient account

Calculate doctors charges

Calculate anaesthetists charges

Calculate facilities charges

Calculate TV charges

Calculate telephone charges

Figure 6-5. Completed VTOC for Example 6.3

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

Computer Power Institute

PDCLGA001b

Program Design Concepts

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

Computer Power Institute

6-9

Section 6: Modularisation

Program Design Concepts

TOPIC 3: STEPS IN MODULARISATION


5 mins Top-down modular design is quite simple if you carry out the following steps every time you are presented with a programming problem. 1. 2. Analyse the problem by identifying the sub-problems. Group the activities into subtasks or functions to determine the modules that will make up the program. Remember that a module is one section of a program dedicated to the performance of a single function. Note that not all the activities may be identified at this stage. Only the modules of the first level of the VTOC may be identified, with other more subordinate modules developed later. Using the template of Initialise, Process, Finalise construct a VTOC to illustrate the modules and their hierarchical relationship to each other. After dividing the problem into its three components input, output and processing create a Data Table. Establish the logic of the master control module of the algorithm in pseudocode. It should contain calls to the major processing modules of the program, and should be easy to read and understand. Write the pseudocode for each successive module in the VTOC. The solution is complete when the pseudocode for each module on the lowest level of the VTOC has been developed. Desk-check the solution algorithm. This is achieved by first desk-checking the master control module and then each subordinate module in turn. Desk-checking involves creating a Test Data Table and a Desk-check Table. The Test Data Table contains significant values that are needed to test the logic of the algorithm.

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

Computer Power Institute

PDCLGA001b

Program Design Concepts

Section 7: Object Oriented and Event Driven Algorithms

7.0
OBJECTIVES
1. 2.

SECTION 7 OBJECT ORIENTED AND EVENT DRIVEN ALGORITHMS

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

Computer Power Institute

7-1

Section 7: Object Oriented and Event Driven Algorithms

Program Design Concepts

TOPIC 1: OBJECT ORIENTED ALGORITHMS


120 mins Prior to the introduction of object oriented programming (OOP), structured programming which we have been looking at up until now was the main type of software development. Object oriented programming was created in response to the increasing complexity of solutions which became difficult to efficiently create using structured programming concepts alone. Object oriented programming allows more complex real-world models to be easily translated in computer code. It does this by more tightly integrating the variables which represent an object and the code that manipulates the variables or properties associated with that object. For example, in pure structured programming you may have a variable named Car1 which represents a car. If you wanted to state that Car1 has 4 wheels you would need to create another variable named, Car1_number_of_wheels. There would need to be an additional variable for each property of Car1 you wanted to represent. What if you wanted to pass all the information dealing with Car1 to a function for processing. You would have to pass Car1, the variable representing the number of wheels it has and any other variables representing properties separately. What if you passed the number of wheels Car3 has by mistake. What if the variable passed isnt a type of car? How do you identity the code relating to Car1? The solution to these problems is called object oriented programming. You can now define an object which has a unique name like Car. Car can have properties fields comprised of variables representing characteristics about the object such as the number of wheels it has. These variables can be fundamental data types or other objects. It can have methods or functions which are able to perform actions on the data in the object. The properties and functions are called members. You create an instance of an object by using the definition of the object you have created as a template. In many computer languages this object template is known as a class. You can create any number of instances of an object. Each instance of the object created is unique and can have unique properties. In pseudo code you would represent the creation of an object from an object template as: Instantiate Car named Cadillac or Create Cadillac of type Car Remember each object we design is also a new data type. The words used make it clear we are creating an item which has the data type of the object we specify. Without specifying the type of object the variable we have created has no meaning. We do not need to do this with fundamental data types as it is clear from how they are used in the pseudo code what type of data they represent. If there was only one Car in the application you could even use the Car object directly in the pseudocode without explicitly instantiating it, but that can make the code less clear. Unless we are illustrating the object in general it is preferable to use a different variable name. This also makes it easier to add other cars into the solution later if required.

7-2

Computer Power Institute

PDCLGA001b

Program Design Concepts

Section 7: Object Oriented and Event Driven Algorithms

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

Computer Power Institute

7-3

Section 7: Object Oriented and Event Driven Algorithms

Program Design Concepts

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

Computer Power Institute

PDCLGA001b

Program Design Concepts

Section 7: Object Oriented and Event Driven Algorithms

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

Computer Power Institute

7-5

Section 7: Object Oriented and Event Driven Algorithms

Program Design Concepts

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

Computer Power Institute

PDCLGA001b

Program Design Concepts

Section 7: Object Oriented and Event Driven Algorithms

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

Computer Power Institute

7-7

Section 7: Object Oriented and Event Driven Algorithms

Program Design Concepts

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

Computer Power Institute

PDCLGA001b

Program Design Concepts

Section 7: Object Oriented and Event Driven Algorithms

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

Section 7: Object Oriented and Event Driven Algorithms

Program Design Concepts

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:

Bank.Main() Bank. Menu() Client. Enter_ Details() Account. Current_ Balance()

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

Computer Power Institute

PDCLGA001b

Program Design Concepts

Section 7: Object Oriented and Event Driven Algorithms

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

Computer Power Institute

7-11

Section 7: Object Oriented and Event Driven Algorithms

Program Design Concepts

Within the Client.write() method the following code would appear:


Client.Write() write ClientID write name write address End

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

Computer Power Institute

PDCLGA001b

Program Design Concepts

Section 7: Object Oriented and Event Driven Algorithms

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

Computer Power Institute

7-13

Section 7: Object Oriented and Event Driven Algorithms

Program Design Concepts

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

Computer Power Institute

PDCLGA001b

Program Design Concepts

Section 7: Object Oriented and Event Driven Algorithms

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

Computer Power Institute

7-15

Section 7: Object Oriented and Event Driven Algorithms

Program Design Concepts

count Steps 1 2 3

Withdrawal _Amount 200.00

VARIABLES Account[Count]. current_Balance 1456.00

1 Call Account[count]. Withdrawal Current_Balance = Current_Balance withdrawal_Amount

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

Computer Power Institute

PDCLGA001b

Program Design Concepts

Section 7: Object Oriented and Event Driven Algorithms

TOPIC 2: EVENT DRIVEN ALGORITHMS


5 mins Unlike sequential code, event driven code waits for an event to occur. This event may be as a result of user interaction, for instance a mouse click. When the event occurs a specific function within the application is normally triggered. Execution then proceeds as per normal structured rules within the function. The function can call other functions as a result of the event or trigger events itself. Once all the code relating to the event has been run, the application then returns to a wait state until the next event occurs. In a lot of situations event driven and OOP may be combined. Normally an event driven algorithm consists of a group of functions that begin with the event which triggers them. For example: When_Mouse_clicked Display Mouse x and y coordinates in task bar End Function When_F1_key_pressed Call AddBook Call DisplayBookList End Function It is important to note that in both OOP and event driven algorithms structured programming is still the main type of code used in the functions within the classes or event driven applications.

PDCLGA001b

Computer Power Institute

7-17

Section 7: Object Oriented and Event Driven Algorithms

Program Design Concepts

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

Computer Power Institute

PDCLGA001b

Program Design Concepts

Section 7: Object Oriented and Event Driven Algorithms

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

Computer Power Institute

7-19

Section 7: Object Oriented and Event Driven Algorithms

Program Design Concepts

ACTIVITY SOLUTIONS
Activity 7-1

Bank.Main()

Initialise Bank Initialise Accounts Initialise Clients Bank.Load() Account. Withdrawl()

Bank. Menu() Bank. End() Bank.Save() Account. Current_ Balance()

Account. Deposit()

Client. Enter_ Details()

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

Computer Power Institute

PDCLGA001b

Program Design Concepts

Section 8: Appendix A

APPENDIX A GENERAL ALGORITHM EXAMPLES

GENERAL ALGORITHM EXAMPLES


In this appendix you will find a number of general pseudocode solutions to a selection of typical business programming problems. All of the features covered in this Learning Guide have been incorporated into these examples. The examples can be easily converted for use in an object oriented environment by creating objects which implement the functionality demonstrated in the examples, for example a Report object. You should read through these examples and study them carefully to follow the logic expressed in them. They may be of use as a reference in subsequent programming modules. You will need to refer back to this Learning Guide while studying other programming modules. In the PDC exam, you will not have to know how to write an algorithm for a complex programming problem like these examples, but you should be able to understand segments of an algorithm. In Section 5 you were introduced to a general solution algorithm for the processing of sequential files. The priming Read before the While condition, together with the subsequent Read within the loop immediately before the EndWhile statement, form the basic framework. 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 Call Initial processing Read first record While more records exist Call Process this record Read next record EndWhile Call Final processing End

Priming Read

Subsequent Read

PDCLGA001b

Computer Power Institute

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.

Process Sequential File

Initial Processing

Process This Record


Figure A-1

Final Processing

The master control module would now look like this:


Process sequential file Call initial processing Read first record While more records exist Call Process this record Read next record EndWhile Call final processing End

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

Computer Power Institute

PDCLGA001b

Program Design Concepts

Section 8: Appendix A

Example 1 Report Generation with Page Break


Most reports require page heading lines, column heading lines, detail lines, and total lines. Reports are also required to skip to a new page after a predetermined number of detail lines have been printed. A typical report might look like that shown in Figure A-2:

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

CUSTOMER NUMBER 12345 12346

ACCOUNT BALANCE 300.50 400.50 ---------200 150 4300.00

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

Initialise variable fields

Process this record

Print report totals

Print detail line

Accumulate total fields

Print page headings


Figure A-3

PDCLGA001b

Computer Power Institute

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

Subordinate Modules Level 1


Initialise variable fields Set accumulators to zero Set pagecount to zero Set max detail lines to designated value Set linecount to max detail lines End Process this record Perform necessary calculations (if any) Call Print detail line Call Accumulate total fields End Print report totals Build total lines Print total lines End

A-4

Computer Power Institute

PDCLGA001b

Program Design Concepts

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

Computer Power Institute

A-5

Section 8: Appendix A

PDCLGA001b

Example 2 Report Generation with Single-Level Control Page Break


Printed reports that also produce control break total lines are very common in business applications. A control break total line is a summary line for a group of records that contain the same record key. This record key is a designated field on each record, and is referred to as the control field. The control field is used to identify a record or a group of records within a file. A control break occurs each time there is a change in value of the control field. Thus, control break total lines are printed each time a control break is detected. Reports that print control break totals can be categorised as being either single-level or multiplelevel control break reports depending on whether there is one control field or more than one control field. Here is a single-level control break report.

23/02/xxx9

NATIONAL COMPUTER COMPANY SALES REPORT BY SALESPERSON Salesperson Name Mary Smith Product Number Quantity Sold

Page 1

Salesperson Number 1001

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

10.00 20.00 30.00 10.00 35.00

20.00 40.00 60.00 120.00 20.00 35.00 55.00 175.00

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

Computer Power Institute

PDCLGA001b

Program Design Concepts

Section 8: Appendix A

VTOC

Produce single level control break

Initialise variable fields

Process this record

Print control total line

Print report totals

Print detail line

Accumulate control totals

Reset control totals

Print page headings


Figure A-4

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

Computer Power Institute

A-7

Section 8: Appendix A

PDCLGA001b

Solution algorithm Master Control Module


Print single level control break Call Initialise variable fields Read first record Set prev control field to control field While Not EOF If (control field <> prev control field) Then Call Print control total line EndIf Call Process this record Read next record EndWhile Call Print control total line Call Print report totals End

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

Computer Power Institute

PDCLGA001b

Program Design Concepts

Section 8: Appendix A

Subordinate Modules Level 1


Initialise variable fields Set control total accumulators to zero Set report total accumulators to zero Set pagecount to zero Set linecount to max detail lines Set max detail lines to designated value End Process this record Perform necessary calculations (if any) Call Print detail line Call Accumulate control totals End Print control total line Set prev control field to control field Build control total line Print control total line Print blank line (if required) Increment linecount Call Reset control totals End Print report totals Build report total line Print report total line End

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

Computer Power Institute

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.

Example 3 Array Processing


An array is a data structure that is made up of a number of variables that all have the same data type, for example, all the exam scores for a module. The individual data items that make up the array are referred to as the elements of the array. They are assigned a single data name, for example, scores (the name of the array). A subscript or an index can distinguish the individual elements of an array from each other. The subscript indicates the position of the element within the array. For example, scores[3] points to the third element in the array scores. Arrays are an internal data structure in that they are required only for the duration of the program in which they are defined. They are a very convenient mechanism for storing and manipulating a collection of similar data items in a program. You should be familiar with the operations most commonly performed on them. We will develop pseudocode algorithms for the most typical operations performed on arrays:

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

Computer Power Institute

PDCLGA001b

Program Design Concepts

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

Computer Power Institute

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

Computer Power Institute

PDCLGA001b

Program Design Concepts

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

Find the largest of the elements of an array


Find largest element Set index to 1 Set largest element to array[1] While index < max num elements If (array[index + 1] > largest element) Then Let largest element = array[index + 1] EndIf Let index = index + 1 EndWhile Print largest element End

Find the smallest of the elements of an array


Find smallest element Set index to 1 Set smallest element to array[1] While index < max num elements If (array[index + 1] < smallest element) Then Let smallest element = array[index + 1] EndIf Let index = index + 1 EndWhile Print smallest element End

PDCLGA001b

Computer Power Institute

A-13

Section 8: Appendix A

PDCLGA001b

Find the range of the elements of an array


Find range of elements Set index to 1 Set smallest element to array[1] Set largest element to array[1] While (index < max num elements) If (array[index + 1] < smallest element) Then Let smallest element = array[index + 1] Else If (array[index + 1] > largest element) Then Let largest element = array [index + 1] EndIf EndIf Let index = index + 1 EndWhile Print the smallest element followed by largest element End

Find the mean of the elements of an array


Find mean 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 Let mean = sum / max num elements Print mean End

A-14

Computer Power Institute

PDCLGA001b

Program Design Concepts

Appendix B: Checkpoints for Instructor Sign Off

B
Checkpoints sign off
Checkpoint

APPENDIX B CHECKPOINTS FOR INSTRUCTOR SIGN OFF

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.

Checkpoint 1 in Section 3 Check answers

2.

Checkpoint 2 in Section 4 Check answers

3.

Checkpoint in Section 5 Check answers

4.

Checkpoint in Section 7 Check answers

PDCLGA001b

Computer Power Institute

B-1

Appendix B: Checkpoints for Instructor Sign Off

Program Design Concepts

B-2

Computer Power Institute

PDCLGA001b

Program Design Concepts

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

Computer Power Institute

C-1

Appendix C: Glossary

Program Design Concepts

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

Constant Construct Control structures

Counter-controlled loop Data

Data-driven loop Data processing Data structure Data type Data value Debugging Desk-check

C-2

Computer Power Institute

PDCLGA001b

Program Design Concepts

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

Flowchart shape Functional decomposition

Global variables Impossible value

Initialisation Input

PDCLGA001b

Computer Power Institute

C-3

Appendix C: Glossary

Program Design Concepts

Inter-module communication Internal documentation Invalid input Iteration Local variables

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

Object Oriented Programming

C-4

Computer Power Institute

PDCLGA001b

Program Design Concepts

Appendix C: Glossary

Order of Precedence rule

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

Out-of-range Output Priming Read

Procedural Program Programmer Programming language Pseudocode

Range limits Record Repetition

Selection

Sentinel

Sequence Software

PDCLGA001b

C-5

Appendix C: Glossary

Program Design Concepts

Software lifecycle Spaghetti code String Structure Theorem

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

Summation Systems analyst Tallying Test data Top-down development

Unconditional jump

Variable Verb Verb phrase VTOC

C-6

Computer Power Institute

PDCLGA001b

COURSE AND WORKSHOP EVALUATION SHEET


Your comments help us improve course objectives, content, and instruction. Name(optional): __________________________ Course Title: Program Design Concepts Qualification/Shift: ________________________ PDCLGA001b Date: ___________________________________ Institute: ___________________________

Objectives
Did the course/workshop meet its stated objectives?

Yes

No If no, please explain ____________________________________________________________________________


____________________________________________________________________________ ____________________________________________________________________________

Did the course/workshop meet your needs?

Yes

No If no, please explain ____________________________________________________________________________


____________________________________________________________________________ ____________________________________________________________________________

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

Comments and suggestions for improvement


What did you think was most beneficial about the course/workshop? ____________________________________________________________________________ ____________________________________________________________________________ ____________________________________________________________________________ ____________________________________________________________________________ ____________________________________________________________________________ ____________________________________________________________________________ ____________________________________________________________________________ ____________________________________________________________________________
Continued on the next page.

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.

You might also like