115
ICTPRG405 Automate Processes Learner Guide

ICTPRG405 Automate Processes - WordPress.comExpressing algorithms . Described below are two common ways to express the structure of an algorithm: 1 Pseudo code 2 Flowcharts . Pseudo

  • Upload
    others

  • View
    1

  • Download
    0

Embed Size (px)

Citation preview

Page 1: ICTPRG405 Automate Processes - WordPress.comExpressing algorithms . Described below are two common ways to express the structure of an algorithm: 1 Pseudo code 2 Flowcharts . Pseudo

ICTPRG405

Automate Processes

Learner Guide

Page 2: ICTPRG405 Automate Processes - WordPress.comExpressing algorithms . Described below are two common ways to express the structure of an algorithm: 1 Pseudo code 2 Flowcharts . Pseudo

© Copyright, 2016 by North Coast TAFEnow

Date last saved: 9 February 2016 by Smart, RebeccaHunt, Caitlin Version: 1.0 # of Pages = 115

Enter name of writer – Content writer and course adviser

TAFEnow Resource Development Team – Instructional and graphic

design

Copyright of this material is reserved to the Crown in the right of the State of New South Wales.

Reproduction or transmittal in whole, or in part, other than in accordance with the provisions of the Copyright Act, is

prohibited without written authority of North Coast TAFEnow.

Disclaimer: In compiling the information contained within, and accessed through, this document ("Information")

DET has used its best endeavours to ensure that the Information is correct and current at the time of publication but

takes no responsibility for any error, omission or defect therein. To the extent permitted by law, DET and its

employees, agents and consultants exclude all liability for any loss or damage (including indirect, special or

consequential loss or damage) arising from the use of, or reliance on, the Information whether or not caused by any

negligent act or omission. If any law prohibits the exclusion of such liability, DET limits its liability to the extent

permitted by law, to the re-supply of the Information.

Third party sites/links disclaimer: This document may contain website contains links to third party sites. DET is not

responsible for the condition or the content of those sites as they are not under DET's control. The link(s) are

provided solely for your convenience and do not indicate, expressly or impliedly, any endorsement of the site(s) or

the products or services provided there. You access those sites and use their products and services solely at your

own risk.

Page 3: ICTPRG405 Automate Processes - WordPress.comExpressing algorithms . Described below are two common ways to express the structure of an algorithm: 1 Pseudo code 2 Flowcharts . Pseudo

Contents Getting Started .................................................................................................................................. i

About this unit .................................................................................................................................................................... i

Elements and performance criteria ............................................................................................................................. i

Icon Legends....................................................................................................................................................................... ii

Topic 1 – Identify algorithm structures ........................................................................................... 1

What is an algorithm? ...................................................................................................................................................... 1

Typical computer operations ....................................................................................................................................... 5

Topic 2 – Introduction to developing algorithms......................................................................... 27

Analysis – defining the problem ...............................................................................................................................28

Design – defining the solution and creating an algorithm .............................................................................29

Desk-checking the solution ........................................................................................................................................46

Refining the solution .....................................................................................................................................................54

Topic 3 – Develop and verify script language for an Algorithm .................................................. 57

Creating and executing a first script ........................................................................................................................57

Syntax ..................................................................................................................................................................................59

Reserved words ...............................................................................................................................................................60

Syntax errors .....................................................................................................................................................................60

Elements of syntax for JavaScript .............................................................................................................................65

Syntax for structured programming constructs ..................................................................................................69

Translating from pseudo code ...................................................................................................................................74

The Document Object Model (DOM) .......................................................................................................................81

Example from Notes 2 ...................................................................................................................................................85

Programming the HTML 5 canvas ............................................................................................................................86

Topic 4 – Document script or code ................................................................................................ 97

Types of documentation ..............................................................................................................................................97

User documentation ................................................................................................................................................... 102

Answers to Activities .................................................................................................................... 108

Page 4: ICTPRG405 Automate Processes - WordPress.comExpressing algorithms . Described below are two common ways to express the structure of an algorithm: 1 Pseudo code 2 Flowcharts . Pseudo
Page 5: ICTPRG405 Automate Processes - WordPress.comExpressing algorithms . Described below are two common ways to express the structure of an algorithm: 1 Pseudo code 2 Flowcharts . Pseudo

i | P a g e I C T P R G 4 0 5 _ L G _ V 1

T A F E n o w

Getting Started

About this unit

This unit describes the performance outcomes, skills and knowledge required to write scripts

to automate solutions, by using basic scripting processes, and application specific scripting

options.

Elements and performance criteria

Elements define the essential outcomes of a unit of competency. The Performance Criteria

specify the level of performance required to demonstrate achievement of the Element. They

are also called Essential Outcomes.

Follow this link to find the essential outcomes needed to demonstrate competency in this

Unit: http://training.gov.au/Training/Details/ICTPRG405

Page 6: ICTPRG405 Automate Processes - WordPress.comExpressing algorithms . Described below are two common ways to express the structure of an algorithm: 1 Pseudo code 2 Flowcharts . Pseudo

ii | P a g e I C T P R G 4 0 5 _ L G _ V 1 T A F E n o w

Icon Legends

Learning Activities

Learning activities are the tasks and exercises that assist you in gaining a

clear understanding of the content in this workbook. It is important for you

to undertake these activities, as they will enhance your learning.

Activities can be used to prepare you for assessments. Refer to the

assessments before you commence so that you are aware which activities

will assist you in completing your assessments.

Readings (Required and suggested)

The required reading is referred to throughout this Learner Guide. You will

need the required text for readings and activities.

The suggested reading is quoted in the Learner Guide, however you do not

need a copy of this text to complete the learning. The suggested reading

provides supplementary information that may assist you in completing the

unit.

Reference

A reference will refer you to a piece of information that will assist you with

understanding the information in the Learner Guide or required text.

References may be in the required text, another textbook on the internet.

Self-check

A self-check is an activity that allows you to assess your own learning

progress. It is an opportunity to determine the levels of your learning and to

identify areas for improvement.

Page 7: ICTPRG405 Automate Processes - WordPress.comExpressing algorithms . Described below are two common ways to express the structure of an algorithm: 1 Pseudo code 2 Flowcharts . Pseudo

1 | P a g e I C T P R G 4 0 5 _ L G _ V 1

T A F E n o w

Topic 1 – Identify algorithm structures

What is an algorithm?

Let’s begin by thinking of an algorithm as a recipe. A recipe defines how to take a set of

ingredients, apply a variety of processes to those ingredients (in a prescribed order) to

produce a finished product.

A recipe will include instructions on how to prepare the ingredients, which ingredients to mix

together into which containers, how to cook the ingredients, at what temperature to cook

them, how long to cook them and what to do once they are cooked.

Page 8: ICTPRG405 Automate Processes - WordPress.comExpressing algorithms . Described below are two common ways to express the structure of an algorithm: 1 Pseudo code 2 Flowcharts . Pseudo

2 | P a g e I C T P R G 4 0 5 _ L G _ V 1 T A F E n o w

Features of a good algorithm

Algorithms must be precise and unambiguous

This will enable the programmer to code the algorithm into instructions for a computer

without having to guess what should be done by the program. An algorithm should describe

all of the essential features of the solution.

An algorithm is a correct description of the solution to a problem

This statement essentially tells us two things. Firstly, we have a problem. It is vital that we

understand the problem before we start describing a solution with our algorithm. There is

little value to writing an algorithm that is based on a poorly understood problem. Any

program written from that algorithm will fail to solve the problem. Secondly, we must

describe the solution correctly with our algorithm. We may be able to arrive at the best

possible solution to a problem, but if we fail to represent that solution correctly in our

algorithm, any programs written from it will not work as we had planned. There is little point

writing code from an algorithm that does not represent the solution correctly.

Programs should deal gracefully with errors

A program should not ‘die’ or ‘hang’ because of errors such as not finding a file, or the user

entering the letter ‘A’ rather than the number ‘1’. Your program should include a course of

action for all possible situations. For example, if the user tries to open a file which does not

exist, a good program might give an error message, and then offer to create a new file.

An algorithm might only specify the essential features of a solution, and not the details of

error handling. It will then be up to the programmer to enhance the algorithm accordingly.

Useful algorithms are guaranteed to end

Some algorithms may give a solution to a problem in theory, but in practice will fail to

produce a solution in a reasonable time. In extreme cases, the algorithm may take an infinite

amount of time to produce a result. If we write a program that cannot end (because it was

based on an algorithm that did not end) and run that program on our computer, the only way

to stop the program would be to terminate the program.

The most common cause of a program not ending is an error (a ‘bug’) in either the algorithm

or the program that produces an infinite loop.

Page 9: ICTPRG405 Automate Processes - WordPress.comExpressing algorithms . Described below are two common ways to express the structure of an algorithm: 1 Pseudo code 2 Flowcharts . Pseudo

3 | P a g e I C T P R G 4 0 5 _ L G _ V 1

T A F E n o w

There are some special cases where a program is purposely designed not to end, typically

where the program is controlling an external device or system (for example a mobile phone,

or an aircraft flight-control system).

Algorithms should be efficient

Efficiency can be measured in terms of amount of memory used, the number of operations

performed, the frequency of input/output operations and so on. An efficient algorithm will

consume less of the computer’s resources than an inefficient algorithm.

Computer programs should be user friendly

Programs should offer some information and feedback to the operator and should be written

with the user in mind. A computer program that is not user friendly will not find many users,

and may greatly aggravate those required to use it. Issues include what prompts should be

used, window layout, menu design, how information is presented and so on.

Expressing algorithms

Described below are two common ways to express the structure of an algorithm:

1 Pseudo code

2 Flowcharts

Pseudo code

Pseudo code is structured English used for describing algorithms. The purpose of pseudo

code is to provide a means of specifying algorithms that is independent of any particular

programming language. It allows the program designer to focus on the logic of the algorithm

without the distraction of programming language rules.

Pseudo code should be:

> Precise — the writer and all subsequent readers will understand exactly what is required

to be done.

> Concise — pseudo code removes the necessity for verbose, essay-like instructions

containing vague or ambiguous language.

> Language independent — the programmer is free to implement an algorithm in the

syntax of any chosen procedural programming language (the ‘target’ language).

Page 10: ICTPRG405 Automate Processes - WordPress.comExpressing algorithms . Described below are two common ways to express the structure of an algorithm: 1 Pseudo code 2 Flowcharts . Pseudo

4 | P a g e I C T P R G 4 0 5 _ L G _ V 1 T A F E n o w

There is a wide variation in pseudo code syntax, but the main thing is that the meaning is

readily understood and unambiguous. Organisations that use pseudo code often develop an

in-house standard which defines the structure, constructs and keywords that may be used by

their designers.

Here are some keywords commonly used in pseudo code to indicate input, output, and

processing operations:

Table 1

Pseudo code key word Indicates

Input GET, READ, OBTAIN, ACCEPT

Output PRINT, DISPLAY, SHOW

Initialise SET, ASSIGN, INIT

Add one INCREMENT

Misc FIND, SEARCH, SELECT, SORT

Here is a simple example of pseudo code that represents what we might do on Saturday

morning:

Wake Up

Perform morning things

IF it is raining THEN

Watch TV

ELSE

Play golf

ENDIF

Get ready for lunch

Page 11: ICTPRG405 Automate Processes - WordPress.comExpressing algorithms . Described below are two common ways to express the structure of an algorithm: 1 Pseudo code 2 Flowcharts . Pseudo

5 | P a g e I C T P R G 4 0 5 _ L G _ V 1

T A F E n o w

Flowcharts

Flowcharts are a diagrammatic method used to represent processes. The basic symbols used

in flowcharts will be introduced as we explore how to represent the three basic algorithmic

constructs of sequence, selection and iteration.

Figure 1: Flowchart example: Saturday morning

Yes No

START

Wake up

Have breakfast

Raining?

Play golf Watch TV

Have lunch

END

Page 12: ICTPRG405 Automate Processes - WordPress.comExpressing algorithms . Described below are two common ways to express the structure of an algorithm: 1 Pseudo code 2 Flowcharts . Pseudo

6 | P a g e I C T P R G 4 0 5 _ L G _ V 1 T A F E n o w

Typical computer operations

One way to think about what computers do is the ‘Input-Process-Output’ model. This simple

model says that computers perform three basic types of operations:

1 They take inputs from a variety of different sources.

2 They process these inputs in a variety of ways.

3 They output the results of the processing to a variety of different devices.

Accepting inputs

Inputs may come from a variety of sources, such as, keystrokes from a keyboard, a mouse

action, a file stored in the computer, sounds from a microphone and numerous others. An

example is shown below, where the user is prompted for their surname, and the computer

reads it into a variable.

Table 2

English-like statements Example programming instructions

Prompt user for surname surname = raw_input('Enter your Surname')

Producing outputs

Outputs may be a file to be stored on disk, information to display on a screen, information to

be printed, sounds to be sent to speakers etc. In the example below, the text ‘Hello World’ will

be sent to the output device (e.g. a computer screen).

Table 3

English-like statements Example programming instructions

Print the message Hello

World

print ‘Hello World’

Page 13: ICTPRG405 Automate Processes - WordPress.comExpressing algorithms . Described below are two common ways to express the structure of an algorithm: 1 Pseudo code 2 Flowcharts . Pseudo

7 | P a g e I C T P R G 4 0 5 _ L G _ V 1

T A F E n o w

Assigning values to variables

A computer is able to store data values like numbers and text in memory. Programming

languages allow you to access memory using named variables.

For example, the statement:

x = 6

places the number 6 into a variable called x. The variable x will (when the program executes)

be a location in the computer’s memory. Thankfully, you don’t need to worry about where the

number is stored, or how it is represented — you only need to perform processing with the

variable. As the name suggests, the actual data stored in a variable may change during the

execution of a program or script.

Variables can store numbers or text. The basic data types are numbers and text.

> Numbers can be whole numbers (called integers) such as 2, 27 and 139 or real numbers

(numbers that contain an integer and a fraction shown as one or more decimal places)

for example 12.3 and 0.0027.

> Text can be single characters such as ‘A’, ‘g’, ‘Y’ or a string of characters such as ‘Hello

World’.

In the example below, the variable called ‘total’ is set to zero; this is a way of telling the

computer to store the value 0 in the memory location or variable called total.

Table 4

English-like statements Example programming instructions

Set the total to 0 total = 0

The name you give to a variable may refer to a storage location that is only one byte in size or

a location that is many bytes in size. You should always use meaningful names for variables in

algorithms to improve the readability of the algorithm and its resulting program. This is

particularly important in large and complex programs.

Page 14: ICTPRG405 Automate Processes - WordPress.comExpressing algorithms . Described below are two common ways to express the structure of an algorithm: 1 Pseudo code 2 Flowcharts . Pseudo

8 | P a g e I C T P R G 4 0 5 _ L G _ V 1 T A F E n o w

Performing arithmetic

Computers can perform the arithmetic operations of adding, multiplying, dividing,

subtracting and exponentiation. An example is the following statement which is a way of

telling the computer to multiply the number of items and the price, placing the result into the

variable called total.

Table 5

English-like statements Example programming instructions

set total to items times price total = items * price

Perform alternative actions

Computers can compare the values stored in memory and execute different instructions

depending on the result of the comparison. This action is referred to as selection — that is,

selecting different courses of action depending upon some condition. An example is the

following statement which is a way of telling the computer to make the decision to print

either the word Pass or the word Fail depending on whether the value stored in the variable

called mark is greater than 49.

Table 6

English-like statements Example programming instructions

IF mark is greater than 49

THEN

print Pass

ELSE

print Fail

if mark > 49:

print 'Pass'

else:

print 'Fail'

Repeating operations

Computers can execute the same set of instructions over and over again. This is commonly

referred to as iteration, repetition or looping. There are several types of iteration that can be

used depending on what you want the computer to do. A loop can be constructed to execute

the same set of instructions for a certain number of times or to execute the set of instructions

while a condition is true. For example, while the total stays above 0 the computer is to

continuously subtract the new purchase amount from the total.

Page 15: ICTPRG405 Automate Processes - WordPress.comExpressing algorithms . Described below are two common ways to express the structure of an algorithm: 1 Pseudo code 2 Flowcharts . Pseudo

9 | P a g e I C T P R G 4 0 5 _ L G _ V 1

T A F E n o w

Table 7

English-like statements Example programming instructions

WHILE total greater than 0

subtract new purchase from

total

ENDWHILE

while(total > 0):

total = total – new_purchase

Sequence, selection and iteration

These constructs are used to control the flow of program execution and provide a means for

precisely specifying which instruction will be performed at any given time during the

execution of the program. Let’s look at how these constructs are used to create pseudo code

and flowcharts.

Sequence

Sequence is where one task is performed sequentially after another.

In pseudo code, each task is on a separate line and has the same indentation as the other tasks

in the sequence. The tasks are executed one after the other beginning with the task at the top

of the sequence and ending with the task at the bottom of the sequence.

In a flowchart, the symbol representing a task in the sequence is a rectangle. Typically, tasks

are executed from the top task to bottom task. To ensure that the correct order of tasks is

followed in a sequence of tasks, a line with an arrow at one end indicates the flow of tasks

through a sequence. An oval is often used to indicate the start and end of the flowchart.

Here are some examples of sequences written in pseudo code and drawn in a flowchart.

Page 16: ICTPRG405 Automate Processes - WordPress.comExpressing algorithms . Described below are two common ways to express the structure of an algorithm: 1 Pseudo code 2 Flowcharts . Pseudo

10 | P a g e I C T P R G 4 0 5 _ L G _ V 1 T A F E n o w

Table 8 Sequence example 1: Feeding the cat

Pseudo code Flowchart

Get cat food out of cupboard

Get cat food bowl

Put cat food into bowl

Place bowl on ground

Call cat

The following example is a simple problem that a computer can solve, rather than a general

process from everyday life.

Page 17: ICTPRG405 Automate Processes - WordPress.comExpressing algorithms . Described below are two common ways to express the structure of an algorithm: 1 Pseudo code 2 Flowcharts . Pseudo

11 | P a g e I C T P R G 4 0 5 _ L G _ V 1

T A F E n o w

Table 9 Sequence example 2: Adding two numbers

Pseudo code Flowchart

PROMPT 'Enter value for x:'

READ x

PROMPT 'Enter value for y:'

READ y

SET result = x + y

DISPLAY result

LEARNING ACTIVITIES ACTIVITY 1

Write an algorithm that describes

> Cutting a piece of steak with a knife and fork.

Selection

This is where a choice is made between alternative courses of action. Selection is also known

as ‘branching’. In pseudo code, selection is represented by the IF-THEN-ELSE construct. The

simplest form is shown below.

Page 18: ICTPRG405 Automate Processes - WordPress.comExpressing algorithms . Described below are two common ways to express the structure of an algorithm: 1 Pseudo code 2 Flowcharts . Pseudo

12 | P a g e I C T P R G 4 0 5 _ L G _ V 1 T A F E n o w

Table 10

Pseudo code Flowchart

IF condition

THEN

<block>

ENDIF

Table 11 Selection example 1: Feeding the cat

Pseudo code Flowchart

IF cat bowl empty THEN

Feed cat

ENDIF

The condition is an expression that will either be true or false. This expression is usually the

result of a comparison operation.

For example, the condition:

hoursWorked > 40

Page 19: ICTPRG405 Automate Processes - WordPress.comExpressing algorithms . Described below are two common ways to express the structure of an algorithm: 1 Pseudo code 2 Flowcharts . Pseudo

13 | P a g e I C T P R G 4 0 5 _ L G _ V 1

T A F E n o w

compares the value of the variable hoursWorked to the constant value 40. If hoursWorked has

a value of, say, 70 then this condition will be TRUE, because 70 is indeed greater than 40. If

hoursWorked contains the value 30 then of course the condition will be FALSE. If

hoursWorked contains the value 40 then the condition is also FALSE.

Here are some more examples of conditions using each of the comparison operators:

Table 12

Condition Meaning

x == 3 x is equal to 3

y != 0 y is not equal to 0

cashEarned >

cashSpent

cashEarned is greater than cashSpent

temperature <

100

temperature is less than 100

count <= 10 count is less than or equal to 10

pressure >= 1500 pressure is greater than or equal to 1500

IF condition THEN

(sequence 1)

ELSE

(sequence 2)

ENDIF

If the condition is true, sequence 1 is performed; otherwise, sequence 2 is performed.

Note 1: You do not need the ELSE part. The ELSE keyword and ‘sequence 2’ are optional.

Page 20: ICTPRG405 Automate Processes - WordPress.comExpressing algorithms . Described below are two common ways to express the structure of an algorithm: 1 Pseudo code 2 Flowcharts . Pseudo

14 | P a g e I C T P R G 4 0 5 _ L G _ V 1 T A F E n o w

Note 2: Notice that the sequences for the IF and the ELSE parts are indented the same

amount. As mentioned earlier, this ‘style’ is very common and allows you to see the logic of

the algorithm more easily. A very good programming habit to adopt is to decide upon a

standard style and stick to it when writing algorithms.

Selection is represented in flowcharts using the diamond symbol as shown below:

Table 13 Selection example 2: Overtime due?

Pseudo code Flowchart

IF hours > 40 THEN

Calculate Overtime

ENDIF

IF condition THEN

(Block 1)

ELSE

(Block 2)

ENDIF

Page 21: ICTPRG405 Automate Processes - WordPress.comExpressing algorithms . Described below are two common ways to express the structure of an algorithm: 1 Pseudo code 2 Flowcharts . Pseudo

15 | P a g e I C T P R G 4 0 5 _ L G _ V 1

T A F E n o w

Table 14 Selection example 3: Feeding the cat

Pseudo code Flowchart

IF cat bowl empty THEN

Feed cat

ELSE

Point cat at bowl

ENDIF

Table 15 Selection example 4: Pass or fail?

Pseudo code Flowchart

IF test mark > 50 THEN

DISPLAY 'pass'

ELSE

DISPLAY 'fail'

ENDIF

In the example above, note that ‘fail’ is displayed if the test mark equals 50.

In Selection example 1 and Selection example 2, at least one action is performed. In example

2, it doesn’t matter what the actual test mark is a message will be displayed. The test mark

simply determines which alternative message is displayed.

Page 22: ICTPRG405 Automate Processes - WordPress.comExpressing algorithms . Described below are two common ways to express the structure of an algorithm: 1 Pseudo code 2 Flowcharts . Pseudo

16 | P a g e I C T P R G 4 0 5 _ L G _ V 1 T A F E n o w

There may be times we want something done when a condition is met but don’t want

anything done if the condition is not met. This action is performed by the following construct:

IF condition THEN

<block>

ENDIF

Iteration

Iteration is the process of repetition, also known as ‘looping’. Iteration allows a program to do

something again and again, or perform similar operations on multiple items. Here is a simple

loop that ‘counts’ from one to ten:

SET count = 1

WHILE count <= 10 DO

DISPLAY count

count = count + 1

ENDWHILE

DISPLAY 'bang!'

The important things to note are:

> This code will display 1 2 3 4 5 6 7 8 9 10 bang!

> When the end of the loop is reached, the algorithm jumps back to the start again.

> There is a loop variable, (called ‘count’ in this case) that changes with each cycle of the

loop. For this example, the count variable is simply incremented (increased by 1) at the

end of the loop.

> The loop condition determines when the loop will end (or alternatively, when it will keep

going!). In this case, the condition is 'count <= 10', and the loop will be entered (or

continue) when this condition is true.

> When count reaches 11, this condition becomes false, and so the loop is exited. The next

statement to be executed will be the one immediately after the loop.

Here’s another example. Suppose you have developed an algorithm to compute the pay of an

individual worker, taking into account the hours worked, and the hourly rate of pay. The

calculation might look like this:

SET pay = hoursWorked * hourlyRate

WRITE pay

Page 23: ICTPRG405 Automate Processes - WordPress.comExpressing algorithms . Described below are two common ways to express the structure of an algorithm: 1 Pseudo code 2 Flowcharts . Pseudo

17 | P a g e I C T P R G 4 0 5 _ L G _ V 1

T A F E n o w

But now, what if you want to compute the pays of all workers in the company? You can do this

by wrapping a loop around the original algorithm, something like this:

FOR EACH worker DO

SET worker.pay = worker.hoursWorked * hourlyRate

WRITE pay

ENDFOR

Now the same calculation is repeated for each worker. The notation ‘worker.pay’ means the

pay for that particular worker.

Types of loops

Most computer languages provide three types of looping statement, which are the:

1 Pre-test loop — also known as the WHILE loop

2 Post-test loop — e.g. the REPEAT/UNTIL or DO/WHILE loops

3 Counting loop — also known as the FOR loop.

In fact, we can get by with only the WHILE loop, but these other loops help to make our code

simpler and our intentions clearer.

There are several things you need to consider when deciding upon the best way to construct

loops. What conditions should exist for entry into a loop? Do you want to execute the loop

instructions for a particular number of times? If you control a loop based upon some condition

being true, how will you modify the condition so that it becomes false (so the loop can stop)?

Answering these questions will assist in selecting the most appropriate loop for the problem

you are solving.

There are a few different types of loops, however, all loops can be described using the WHILE

loop. The WHILE loop executes the instructions inside the loop if some condition(s) is true and

continues executing the instructions whilst the condition(s) remain true.

The REPEAT/DO loops will execute a block of instructions at least once before testing the

condition(s) to see if it executes the same block of instructions again.

The FOR loop is a counting loop. It performs the instructions inside the loop a certain number

of times. The REPEAT/DO and the FOR loops are usually included in pseudo code and other

algorithmic languages because they are often implemented in programming languages.

Page 24: ICTPRG405 Automate Processes - WordPress.comExpressing algorithms . Described below are two common ways to express the structure of an algorithm: 1 Pseudo code 2 Flowcharts . Pseudo

18 | P a g e I C T P R G 4 0 5 _ L G _ V 1 T A F E n o w

The WHILE construct is used to specify a loop with a test at the top of the loop. In pseudo

code, the beginning and ending of the loop are commonly denoted by the two keywords

WHILE and ENDWHILE. The general form is:

WHILE condition DO

<block>

ENDWHILE

This is how it works. The loop is entered only if the condition is true. If the condition is true,

the sequence is performed. After the sequence has been performed, the condition is checked

again. If the condition is still true, the sequence is performed again. This process continues

until the condition is false.

Table 16

Pseudo code Flowchart

WHILE water in

saucepan DO

Boil water for 10

seconds

ENDWHILE

Repeat-until loop

This loop is similar to the WHILE loop except that the test is performed at the bottom of the

loop instead of at the top. Two pseudo code keywords, REPEAT and UNTIL are used. The

general form is:

Page 25: ICTPRG405 Automate Processes - WordPress.comExpressing algorithms . Described below are two common ways to express the structure of an algorithm: 1 Pseudo code 2 Flowcharts . Pseudo

19 | P a g e I C T P R G 4 0 5 _ L G _ V 1

T A F E n o w

Table 17

Pseudo code Flowchart

REPEAT

<Block>

UNTIL condition

The sequence in this loop is always performed at least once, because the test is performed

after the sequence has already been executed. After the sequence is performed, the condition

is tested and if required, the loop repeats.

FOR

This loop is a specialised construct in which an index variable is automatically initialised,

incremented and tested. Two pseudo code keywords, FOR and ENDFOR are commonly used.

The general form is:

FOR condition

block

ENDFOR

At the start of the loop, the index variable is set to the starting value. At the end of each

iteration, the index variable is automatically incremented. (Note: Incrementing refers to

increasing the value of a variable, i.e. adding a number to a variable. The default increment is

usually 1. The loop repeats until the index value reaches the finish value.

Page 26: ICTPRG405 Automate Processes - WordPress.comExpressing algorithms . Described below are two common ways to express the structure of an algorithm: 1 Pseudo code 2 Flowcharts . Pseudo

20 | P a g e I C T P R G 4 0 5 _ L G _ V 1 T A F E n o w

Table 18

Pseudo code Flowchart

FOR Index = START_VALUE to

FINAL_VALUE

<Block>

ENDFOR

Structured programming

Constructing algorithms

Any problem that can be solved by a computer can be solved using just three basic constructs

of sequence, selection and iteration.

1 Sequence — this is where one task is performed after another in predefined order

2 Selection — this is where a condition is tested and different tasks are performed

depending on whether the test is true or false.

3 Iteration — this is where tasks are perform repeatedly for a certain number of times or

until some condition is met.

Page 27: ICTPRG405 Automate Processes - WordPress.comExpressing algorithms . Described below are two common ways to express the structure of an algorithm: 1 Pseudo code 2 Flowcharts . Pseudo

21 | P a g e I C T P R G 4 0 5 _ L G _ V 1

T A F E n o w

It is a remarkable result from computer science that these basic constructs can be used to

implement any programming problem!

The basic constructs of sequence, selection and iteration can be embedded within each other,

and this is made clear by use of indentation. Nested constructs should be clearly indented

from their surrounding constructs.

LEARNING ACTIVITIES ACTIVITY 2

Design an algorithm that prints any of these properties of the integer entered.

Divisible by 4,

Divisible by 2,

Odd.

Page 28: ICTPRG405 Automate Processes - WordPress.comExpressing algorithms . Described below are two common ways to express the structure of an algorithm: 1 Pseudo code 2 Flowcharts . Pseudo

22 | P a g e I C T P R G 4 0 5 _ L G _ V 1 T A F E n o w

Nesting IF constructs

The IF-THEN-ELSE construct can be nested inside another IF-THEN-ELSE construct.

Table 19

Pseudo code Flowchart

IF cat whining for food THEN

IF cat bowl empty THEN

Feed cat

ELSE

Point cat at food

ENDIF

ENDIF

Here we first test to see if the cat is whining for food. If it isn’t, we simply end the testing. If the

cat is whining for food then we will execute the other IF-THEN-ELSE construct:

IF food bowl empty THEN

Feed the cat

ELSE

Point cat at food bowl

ENDIF

Page 29: ICTPRG405 Automate Processes - WordPress.comExpressing algorithms . Described below are two common ways to express the structure of an algorithm: 1 Pseudo code 2 Flowcharts . Pseudo

23 | P a g e I C T P R G 4 0 5 _ L G _ V 1

T A F E n o w

Pseudo code—nested constructs 1. (What is the maximum temperature up until midnight?)

Table 20

Task Performance Standard

SET maxTemp = -100

REPEAT

READ temp

IF temp > maxTemp THEN

SET maxTemp = temp

ENDIF

READ time

UNTIL time == MIDNIGHT

PRINT maxTemp

In the above example, the IF construct is nested within the REPEAT construct, and therefore is

indented.

LEARNING ACTIVITIES ACTIVITY 3

Write an algorithm to print the multiples of 6 from 20 to 70.

Page 30: ICTPRG405 Automate Processes - WordPress.comExpressing algorithms . Described below are two common ways to express the structure of an algorithm: 1 Pseudo code 2 Flowcharts . Pseudo

24 | P a g e I C T P R G 4 0 5 _ L G _ V 1 T A F E n o w

Designing algorithms

A simple method for designing a simple program could be:

1 Understand the problem or requirements.

2 Identify the inputs and the outputs and decide what variables are needed.

3 Determine the calculations/computations that are required to produce the output.

4 To construct the algorithm, start by assigning input values to the variables.

5 Then perform the computations.

6 Generate the output.

7 When there are processes to be repeated, add loops.

8 When decisions are to be made, use selection.

Algorithm pre-conditions

Often there are pre-conditions that must be met for an algorithm to function correctly.

Let’s look at a recipe/algorithm one may use to boil an egg:

1 Put sufficient water in a saucepan to cover the egg.

2 Place saucepan on the stove.

3 Bring the water to boil.

4 Place egg in saucepan and leave for 3 minutes.

5 Remove saucepan from stove and remove egg from saucepan.

The pre-conditions to the process of boiling an egg could be:

> an egg to boil

> the water to boil it in

> heat to make the water boil

> a saucepan to hold the water.

Page 31: ICTPRG405 Automate Processes - WordPress.comExpressing algorithms . Described below are two common ways to express the structure of an algorithm: 1 Pseudo code 2 Flowcharts . Pseudo

25 | P a g e I C T P R G 4 0 5 _ L G _ V 1

T A F E n o w

Without having all these pre-conditions, the result of executing the boil egg algorithm will not

be the one we want.

SELF CHECK CHECK 1

Check your understanding, I can now:

> Describe algorithms steps in sequences

> Describe decisions in an IF statement

> Describe iterations in a WHILE or REPEAT structure

Page 32: ICTPRG405 Automate Processes - WordPress.comExpressing algorithms . Described below are two common ways to express the structure of an algorithm: 1 Pseudo code 2 Flowcharts . Pseudo
Page 33: ICTPRG405 Automate Processes - WordPress.comExpressing algorithms . Described below are two common ways to express the structure of an algorithm: 1 Pseudo code 2 Flowcharts . Pseudo

27 | P a g e I C T P R G 4 0 5 _ L G _ V 1

T A F E n o w

Topic 2 – Introduction to developing algorithms Before we start looking at developing algorithms, think about why we need them. Algorithms

in programming/scripting language create a set of instructions for a computer to execute. The

whole point of writing computer programs or scripts is to make the computer do work for us.

As obvious as it sounds, it is important to understand that the computer doesn’t magically

know what we want it to do. We need to create precise instructions.

If you don’t know what you actually want to achieve with an algorithm, or if you don’t

accurately describe in the algorithm what you want done, the program written from it won’t

do what you need it to do.

So how do we transform a problem into a computer program that executes a solution to that

problem?

Page 34: ICTPRG405 Automate Processes - WordPress.comExpressing algorithms . Described below are two common ways to express the structure of an algorithm: 1 Pseudo code 2 Flowcharts . Pseudo

28 | P a g e I C T P R G 4 0 5 _ L G _ V 1 T A F E n o w

SDLC Models

1 Analyse: Define the problem.

2 Design: Define the solution and create the algorithm.

3 Code: Write the instructions in a computer language.

4 Test and debug: Ensure the program produces expected results.

5 Document: Write user and technical documentation.

This very simple view of the whole process serves as a starting point for understanding how

good software programs are developed. The process can be quite complicated, especially for

large-scale software development. In this reading we will be focusing on relatively simple

algorithms and be concerned mainly with Steps 1 and 2: Analyse and Design.

Analysis – defining the problem

It is vital that before we do anything else we analyse exactly what it is that we need the

computer to do.

What is the problem we are trying to solve or what task do we want the computer to perform?

The most important step in finding the correct solution is to fully understand the problem.

Often there is a temptation to start writing the algorithm before the problem is fully

understood. Resist this temptation, as it often leads to focusing on implementation issues

rather than the functional issues that the problem presents. Implementation issues involve

how you will do something while functional issues refers to what it is that you are trying to do.

If you don’t have enough information to solve the problem, try refining the program

specifications. Ask:

> where the input comes from (keyboard, file, mouse, other?)

> what format it is in (numbers, text, a combination of both)?

> what the required outputs are and how will they be presented?

Identify the processing that will turn the inputs into the required outputs.

Page 35: ICTPRG405 Automate Processes - WordPress.comExpressing algorithms . Described below are two common ways to express the structure of an algorithm: 1 Pseudo code 2 Flowcharts . Pseudo

29 | P a g e I C T P R G 4 0 5 _ L G _ V 1

T A F E n o w

Design – defining the solution and creating an algorithm

One part of finding a solution is to read the functional specifications of the problem and try to

answer the following questions.

> What are the inputs to the algorithm? Where do they come from? What type of input is it,

e.g. numbers or text?

> What is the expected output from the algorithm?

> What program blocks (algorithmic constructs/ control structure) can be recognised

(sequence, selection, iteration)?

> How is the solution composed from these blocks, i.e. how are the blocks sequenced or

nested?

> What variables can be recognised? What are their initial and final values?

Example 1: Store discounts algorithm

The Bush Lane clothing store is about to have a sale with all items in store discounted by 10%.

In addition to this discount, when a customer spends more than $200 in the store they will

receive a further 10% discount. The store manager would like a script to be written to do the

calculations for the sales people.

The sales person will enter the total price of the goods purchased by the customer. The

program will print the individual discounts, the total discount, and the discounted sale price.

Let’s look at what we need to do to write an algorithm that will do the correct calculations for

the problem.

First, can we identify the inputs?

The specification states that that the total price of goods purchased will be entered.

Next, what is the expected output?

We would assume that the discounted total price is what the sales people would most require.

But do they need to see any information about the discounts applied? If so, should the total

discount be displayed or, when applicable, both discounts (the 10% store-wide and the over

$200 discount)?

Page 36: ICTPRG405 Automate Processes - WordPress.comExpressing algorithms . Described below are two common ways to express the structure of an algorithm: 1 Pseudo code 2 Flowcharts . Pseudo

30 | P a g e I C T P R G 4 0 5 _ L G _ V 1 T A F E n o w

Let’s assume that the store manager would like sales people to see:

> the original sale price entered

> the store-wide discount amount

> the over $200 discount amount

> the total discount amount

> the discounted total price.

From the inputs and outputs we can start identifying variables that our solution requires.

Table 21

Input Original sale price

Outputs

Original sale price, store wide discount amount, over $200

discount amount, total discount amount and total discount

price.

Once you are clear on the inputs and outputs needed, you then look at ways to process the

input to produce the output. Our first go at the problem breaks it into three general parts:

1 accepting inputs

2 processing the inputs

3 generating the output

These three stages represent a simple model for computer data processing as shown below:

Inputs → Processing → Outputs

By dividing the problem up into these basic phases, we now have three smaller programming

problems to solve.

Start with broad statements, and then refine the code

A good way to start is to use a top-down approach: to start with very broad statements and

refine each statement until it is a step that can be easily coded. Let’s begin our algorithm

design by using three basic steps of the input-process-output model:

Page 37: ICTPRG405 Automate Processes - WordPress.comExpressing algorithms . Described below are two common ways to express the structure of an algorithm: 1 Pseudo code 2 Flowcharts . Pseudo

31 | P a g e I C T P R G 4 0 5 _ L G _ V 1

T A F E n o w

Algorithm 1.0

GET inputs

PROCESS

DISPLAY outputs

We know what inputs and outputs are required, and we can describe the process a little more

clearly with the phrase ‘calculate discounts’. Inserting these refinements gives us:

Algorithm 1.1

GET originalSalePrice

CALCULATE discounts

DISPLAY originalSalePrice

DISPLAY storeWideDiscount

DISPLAY over200Discount

DISPLAY totalDiscount

DISPLAY discountSalePrice

Now let’s now turn our attention to what processing needs to be done to calculate the

discounts. We need to calculate the store-wide discount, the extra discount for purchases over

$200, the total discount, and the discounted sale price. So we will now expand the general

‘calculate discounts’ step with these refined steps:

Algorithm 1.2

GET originalSalePrice

calculate storeWideDiscount

calculate over200discount

calculate totalDiscount

Page 38: ICTPRG405 Automate Processes - WordPress.comExpressing algorithms . Described below are two common ways to express the structure of an algorithm: 1 Pseudo code 2 Flowcharts . Pseudo

32 | P a g e I C T P R G 4 0 5 _ L G _ V 1 T A F E n o w

calculate discountSalePrice

DISPLAY originalSalePrice

DISPLAY storeWideDiscount

DISPLAY over200Discount

DISPLAY totalDiscount

DISPLAY discountSalePrice

Firstly, we need to calculate the store-wide discount. This is fairly easy. The storeWideDiscount

is 10% of the originalSalePrice. How do we calculate 10% of something? We simply multiply

the originalSalePrice by 0.1 (0.1 is 10 divided by 100).

So the store-wide discount is calculated with the statement:

SET storeWideDiscount = originalSalePrice * 0.1

Now let’s see what we need to do to calculate the over200Discount amount. First, we

need to see if the originalSalePrice is over $200. If it is, we will set the

over200Discount amount to 10% of the originalSalePrice, otherwise we will set it to

0.

Using selection statements

A selection statement can deal with this task. Let’s start with creating the test to determine if

the originalSalePrice is greater than $200. We will use the > symbol to indicate a test for

‘greater than’ as it is commonly used in programming and scripting languages to represent

this type of test.

IF originalSalePrice > 200 THEN

Now add the statements for when the test evaluates to true:

IF originalSalePrice > 200 THEN

SET over200Discount = originalSalePrice * 0.1

and finally, add the statements to the ELSE part for when the test evaluates to false:

Page 39: ICTPRG405 Automate Processes - WordPress.comExpressing algorithms . Described below are two common ways to express the structure of an algorithm: 1 Pseudo code 2 Flowcharts . Pseudo

33 | P a g e I C T P R G 4 0 5 _ L G _ V 1

T A F E n o w

IF originalSalePrice > 200 THEN

SET over200Discount = originalSalePrice * 0.1

ELSE

SET over200Discount = 0

ENDIF

Now that we have calculated both discounts let’s add our refined pseudocode to the right

place in our algorithm.

Algorithm 1.3

GET originalSalePrice

SET storeWideDiscount = originalSalePrice * 0.1

IF originalSalePrice > 200 THEN

SET over200Discount = originalSalePrice * 0.1

ELSE

SET over200Discount = 0

ENDIF

calculate totalDiscount

calculate discountSalePrice

DISPLAY originalSalePrice

DISPLAY storeWideDiscount

DISPLAY over200Discount

DISPLAY totalDiscount

DISPLAY discountSalePrice

Page 40: ICTPRG405 Automate Processes - WordPress.comExpressing algorithms . Described below are two common ways to express the structure of an algorithm: 1 Pseudo code 2 Flowcharts . Pseudo

34 | P a g e I C T P R G 4 0 5 _ L G _ V 1 T A F E n o w

Would it have mattered if we placed the IF-THEN-ELSE construct before we set the

storeWideDiscount?

Not at all. The calculations for the storeWideDiscount and the over200Discount are

independent of each other. That is, they do not rely on each other for determining their

values. You should always check to see that you have assembled your blocks of code and

sequences in the correct order!

The final pieces of processing are to add the two discount amounts to calculate the

totalDiscount and to subtract that from the originalSalePrice to determine the

discountSalePrice. The final processing steps can be achieved with the following

statements:

SET totalDiscount = storeWideDiscount + over200Discount

SET discountSalePrice = originalSalePrice—totalDiscount

Would it matter if we swapped the order of these statements?

It most certainly would! The discountSalePrice depends on both the

originalSalePrice and the totalDiscount. If you don’t calculate the totalDiscount

first, then the discountSalePrice will not include the discount amounts and would be

incorrect.

Let’s now complete the algorithm by inserting these final two statements.

Algorithm 1.4

GET originalSalePrice

SET storeWideDiscount = originalSalePrice * 0.1

IF originalSalePrice > 200 THEN

SET over200Discount = originalSalePrice * 0.1

ELSE

SET over200Discount = 0

ENDIF

SET totalDiscount = storeWideDiscount + over200Discount

SET discountSalePrice = originalSalePrice — totalDiscount

Page 41: ICTPRG405 Automate Processes - WordPress.comExpressing algorithms . Described below are two common ways to express the structure of an algorithm: 1 Pseudo code 2 Flowcharts . Pseudo

35 | P a g e I C T P R G 4 0 5 _ L G _ V 1

T A F E n o w

DISPLAY originalSalePrice

DISPLAY storeWideDiscount

DISPLAY over200Discount

DISPLAY totalDiscount

DISPLAY discountSalePrice

Note: We could display each piece of information immediately after we have set the value

rather than display it all at the end. It does not really matter—either method would work. To

separate processing steps from output steps when it has no bearing on how the solution

performs can make it simpler to error check and modify the code later.

Let’s look at another problem, starting with the statement of the problem.

Example 2: Test results algorithm

Matraville College need an algorithm to find the average of five test results. The operator at

the keyboard will input the total marks possible for the test followed by the five test results.

The college would like to have displayed on the screen: the marks input, the percentage for

each test result and the average of the test results as a percentage.

Remember to write a simple version of the algorithm using a few general steps.

Algorithm 2.0

GET inputs

PERFORM calculations

PRINT outputs

Now refine each step adding a few details to each part.

Page 42: ICTPRG405 Automate Processes - WordPress.comExpressing algorithms . Described below are two common ways to express the structure of an algorithm: 1 Pseudo code 2 Flowcharts . Pseudo

36 | P a g e I C T P R G 4 0 5 _ L G _ V 1 T A F E n o w

Table 22

Algorithm 2.0 Algorithm 2.1

GET inputs GET marks possible

PERFORM calculations GET test marks

Calculate test mark percentages

Calculate average percentage

DISPLAY outputs DISPLAY original test marks input

DISPLAY test marks as percentages

DISPLAY average percentage

Identify where the control structures of sequence, selection and iteration could be used.

Table 23

Algorithm 2.1 Identify constructs

GET marks possible GET marks possible

GET 5 test marks Loop?

CALCULATE 5 test mark percentages Loop?

CALCULATE average percentage Calculate average mark

DISPLAY 5 original test marks input Loop?

DISPLAY 5 test marks as percentages Loop?

DISPLAY average mark as percentage DISPLAY average mark as percentage

Continue the process of refinement until each part is well defined. Let’s look at refining the

step GET 5 test marks. We could simply write five separate statements as follows.

GET test mark 1

GET test mark 2

Page 43: ICTPRG405 Automate Processes - WordPress.comExpressing algorithms . Described below are two common ways to express the structure of an algorithm: 1 Pseudo code 2 Flowcharts . Pseudo

37 | P a g e I C T P R G 4 0 5 _ L G _ V 1

T A F E n o w

GET test mark 3

GET test mark 4

GET test mark 5

This seems fine—but what if we had 100 test marks? It would be tedious writing a GET

statement 100 times! The GET test mark statements are examples of repetitive tasks that

we should be able to express in a loop.

Table 24

Single statements Replace with loop

GET test mark 1 Loop to GET 5 test marks

GET test mark 2

GET test mark 3

GET test mark 4

GET test mark 5

When loops are involved, you should decide which type of loop to use.

FOR loops are counting loops and since we know how many results to process, a FOR loop will

suit our situation.

WHILE loops are used when a condition must be met before the statements within the loop

are executed.

A REPEAT loop is used when the statements contained in the loop are to be executed at least

one time before testing the condition.

It is definitely worthwhile identifying any processing that can be done with a loop, as it

reduces the number of individual statements that need to be written and adds flexibility into

the algorithm. But how do we construct these loops to process data?

Let’s try constructing the loop to GET the 5 test marks. We will use a FOR loop to GET the 5

marks.

Page 44: ICTPRG405 Automate Processes - WordPress.comExpressing algorithms . Described below are two common ways to express the structure of an algorithm: 1 Pseudo code 2 Flowcharts . Pseudo

38 | P a g e I C T P R G 4 0 5 _ L G _ V 1 T A F E n o w

FOR counter = 1 TO 5

GET mark

ENDFOR

This seems to make sense, but let’s see what happens. The first time through the loop we get

the first number and place it into a variable called mark. The next time through the loop we

get the second number and place it in the same variable called mark.

But wait a minute, didn’t we just store the second mark in the same place that we stored the

first mark? That means we have overwritten the first mark with the second mark before we

have had a chance to use the first mark. The first mark is now gone! This is not correct. We

want to get all 5 marks then do some processing with each of them later on. So how do we

use a loop to get the 5 marks? The secret is the array.

Using arrays

Before finalising the design of our algorithm it is worth looking at the data structure called an

array.

An array is like a suburban street. The elements that make up the suburban street are the

houses. Each house doesn’t have its own unique name but simply a number that is unique in

that street. The street has a name like ‘Smith’. To refer to any one house in that street we use

the street name and house number such as ‘10 Smith Street’. This is a simple way of saying

‘the 10th house in street called Smith’.

An array is similar in that it is essentially a group of variables that share a common name. Each

variable can be referred to by the array name and its own unique number called the index.

In our problem we have five marks to deal with. Each mark has the same data type; they are all

numbers. We can think of individual variables that we might have called mark1, mark2,

mark3, mark4 and mark5 as elements of the array called marks.

To refer to the first test mark (the variable we may have called mark1) in the array called

marks, we can use the notation marks[1]. To refer to the second test mark, the variable we

may have called mark2, we would use marks[2]. The number enclosed in the brackets [ ] is

the index to the array and is similar to the house number in the street analogy. Referring to

individual locations in an array using the name and an index variable within a loop is the

preferred way to process large amounts of data.

Page 45: ICTPRG405 Automate Processes - WordPress.comExpressing algorithms . Described below are two common ways to express the structure of an algorithm: 1 Pseudo code 2 Flowcharts . Pseudo

39 | P a g e I C T P R G 4 0 5 _ L G _ V 1

T A F E n o w

Note that unlike suburban streets that start the house numbers at 1, most programming

languages start the numbering of array items or elements at 0. So the first element in the array

is array[0], not array[1].

Let’s revisit our attempt to get the five marks using the FOR loop, but this time we will use an

array to store the marks instead of individual variables or a single variable. We will assume that

the array called marks is able to store the five values and that they are indexed from 0 to 4

(that is 0,1,2,3,4 are the 5 index values for this array). We will use the variable called counter

as the index to the array.

FOR counter = 0 TO 4

GET marks[counter]

ENDFOR

This looks similar to what we had before, but this time we are using an array marks[ ] rather

than a single variable mark, and we are using the variable called counter as the index to the

array. Let’s analyse what will happen here.

The first time through the loop, the variable called counter is set to the value of 0. The loop

tests to see if the counter is up to the end value of 4. It isn’t, so the instructions inside the loop,

the GET marks[counter] instruction, is now executed. When we replace the variable name

counter with its current value of 0, we should note that the actual array element we are

placing the first mark into is marks[0]. Good, the first test mark is now in the array and is

stored in the location marks[0].

Since all the statements in the loop have been executed, the FOR loop adds one to the

variable counter so that it now has the value of 1 and the loop starts again. It checks if counter

(current value 1) has gone beyond the end value of 4. It hasn’t, so the GET marks[counter]

instruction is executed again. This time, when we replace the variable name counter with

its value of 1, the actual array element we are referring to is marks[1], which is not the same

array element we placed the first number into marks[0]. How clever! The loop would

continue executing the instructions for counter values up to and including the value 4. When

the counter becomes 5, the loop would be exited.

Example 2 continued

Let’s finish our algorithm for Example 2, but this time we will use arrays rather than individual

variables where applicable. Here is our earlier version.

Page 46: ICTPRG405 Automate Processes - WordPress.comExpressing algorithms . Described below are two common ways to express the structure of an algorithm: 1 Pseudo code 2 Flowcharts . Pseudo

40 | P a g e I C T P R G 4 0 5 _ L G _ V 1 T A F E n o w

Table 25

Algorithm 2.1 Identify constructs

GET marks possible GET marks possible

GET 5 test marks Loop?

CALCULATE 5 test mark percentages Loop?

CALCULATE average percentage Calculate average percentage

DISPLAY 5 original test marks input Loop?

DISPLAY 5 test marks as percentages Loop?

DISPLAY average percentage DISPLAY average percentage

Now let’s create the loops and refine the statements.

We will use an array called marks to store the original marks entered and an array called

marksPer to store the calculated percentage value of the marks. The variable called index

will be the loop control variable and the index to the arrays. The forward slash symbol / will be

used to represent the mathematical operation of division.

Algorithm 2.2

GET marksPoss

FOR index = 0 TO 4

GET marks[index]

ENDFOR

FOR index = 0 TO 4

SET marksPer[index] = marks[index]/marksPoss * 100

ENDFOR

SET totalPercent = 0

FOR index = 0 TO 4

SET totalPercent = totalPercent + marksPer[index]

ENDFOR

SET averagePercent = totalPercent/5

FOR index = 0 TO 4

Page 47: ICTPRG405 Automate Processes - WordPress.comExpressing algorithms . Described below are two common ways to express the structure of an algorithm: 1 Pseudo code 2 Flowcharts . Pseudo

41 | P a g e I C T P R G 4 0 5 _ L G _ V 1

T A F E n o w

DISPLAY marks[index]

ENDFOR

FOR index = 0 TO 4

DISPLAY marksPer[index]

ENDFOR

DISPLAY averagePercent

You may have noticed an extra loop added to the algorithm after the statement SET

totalPercent = 0, shown in italics. The purpose of this loop is to accumulate the total

percentage marks so that we can calculate the average percentage mark.

Could we have included this processing (cumulative total percentage marks) in the loop that

calculates and stores the individual marks in the MarksPer array? The answer is yes!

You may have noticed the same FOR loop appears in several places in the solution. Further

refinements can be made to our algorithm by combining the processing performed in some

of the loops.

Let’s try adding the code that accumulates the total percentage marks to the loop that

calculates and stores the individual percentage marks. While we are at it, we will also combine

the display of the marks and the display of percentage marks into a single loop.

Algorithm 2.3

GET marksPoss

FOR index = 0 TO 4

GET marks[index]

ENDFOR

SET totalPercent = 0

FOR index = 0 TO 4

SET marksPer[index] = marks[index] / marksPoss * 100

SET totalPercent = totalPercent + marksPer[index]

ENDFOR

SET averagePercent = totalPercent / 5

FOR index = 0 TO 4

DISPLAY marks[index]

Page 48: ICTPRG405 Automate Processes - WordPress.comExpressing algorithms . Described below are two common ways to express the structure of an algorithm: 1 Pseudo code 2 Flowcharts . Pseudo

42 | P a g e I C T P R G 4 0 5 _ L G _ V 1 T A F E n o w

DISPLAY marksPer[index]

ENDFOR

DISPLAY averagePercent

Note that we could also move the processing from the calculation loop (the second FOR loop)

to the input loop (the first FOR loop). It is preferable to keep these separate, unless efficiency

or some other reason compels you to combine them. (The reason for this is to ‘modularise’

programs into at least three basic sections—input, processing and output.) If we did combine

all possible loops into a single loop, the resulting algorithm could be as follows:

GET marksPoss

SET totalPercent = 0

FOR index = 0 TO 4

GET marks[index]

SET marksPer[index] = marks[index] / marksPoss * 100

SET totalPercent = totalPercent + marksPer[index]

DISPLAY marks[index]

DISPLAY marksPer[index]

ENDFOR

SET averagePercent = totalPercent / 5

DISPLAY averagePercent

The modular approach

When finding a suitable solution for more complex problems it is beneficial to use a modular

approach in addition to top-down design. This involves constructing an algorithm where

some lines of pseudocode may represent quite involved and complex processing steps.

Rather than breaking those steps down further and further until you have statements that

represent a few lines of actual code, they can be left as a complex process. Complex processes

may be represented as separate functions to be performed in the solution. This enables us to

transform a very complex problem into a set of smaller problems.

Page 49: ICTPRG405 Automate Processes - WordPress.comExpressing algorithms . Described below are two common ways to express the structure of an algorithm: 1 Pseudo code 2 Flowcharts . Pseudo

43 | P a g e I C T P R G 4 0 5 _ L G _ V 1

T A F E n o w

The details contained within the functions are temporarily ignored, allowing you to focus your

thinking on providing a solution at a higher level. When the solution at the abstract (higher)

level is deemed sufficient, you can then turn your focus to defining the details of the lower

level functions. These functions can be thought of as small sub-programs that interact with

other code and sub-programs to perform a small part of the overall processing.

Let’s look at another example.

Example 3: Income and tax algorithm

Bush Lane stores need an algorithm to calculate annual income and taxation information.

They need to calculate the annual gross income and the tax payable for the year for each

employee. Each employee is paid monthly and records are kept on a monthly basis.

Let’s start with the basic input-process-output model.

GET inputs

PROCESS

DISPLAY outputs

Now, refine the process part and modularise the required processes, as follows.

Main algorithm

GET income for each month

calculate gross income

SET tax = calculate_total_tax(income)

DISPLAY gross income

DISPLAY tax

The details of how the tax will be calculated are hidden, allowing a focus on the higher-level

problem. The function itself will be defined elsewhere in the algorithm.

Note: Functions are typically represented by adding opening and closing parentheses ( ) to

the end of the name of the function.

Page 50: ICTPRG405 Automate Processes - WordPress.comExpressing algorithms . Described below are two common ways to express the structure of an algorithm: 1 Pseudo code 2 Flowcharts . Pseudo

44 | P a g e I C T P R G 4 0 5 _ L G _ V 1 T A F E n o w

The function in the above example has the variable name income between the parentheses.

This indicates that the value of the variable 'income' will be input to the function. This is

referred to as ‘passing a parameter’ to the function. The function is passed the value of the

variable making it available for the function to process. You may pass more than one

parameter to a function in the following manner:

SET dinnerIngredients = buy_groceries(grocery_list, funds)

In the above example, the dinnerIngredients will be provided by the function buy_groceries().

The function requires the list of items to buy (grocery_list) as well as the money (funds) to pay

for them. The parameters to be passed to the function are usually separated by commas.

Let’s define the calculate_total_tax(income) function in pseudocode:

FUNCTION calculate_total_tax(income)

SET taxRate = get_tax_rate(income)

SET totalTax = income * taxRate

RETURN totalTax

ENDFUNCTION

Notice the last line in the function. 'RETURN totalTax' is the way we indicate that the

function is to pass the value we stored in the variable totalTax back to the main algorithm.

Most functions will return a value that can be used to assign to a variable, pass to another

function, or for some other purpose. The returned value is usually a variable that contains the

result of processing (such as the value of the variable totalTax calculated by the above

function), or a status code indicating an event or situation has occurred, such as an error. The

returned value from the calculate_total_tax() function has been assigned to the

variable called tax in our main algorithm.

Page 51: ICTPRG405 Automate Processes - WordPress.comExpressing algorithms . Described below are two common ways to express the structure of an algorithm: 1 Pseudo code 2 Flowcharts . Pseudo

45 | P a g e I C T P R G 4 0 5 _ L G _ V 1

T A F E n o w

Now let’s define the calculate_gross_income() function:

FUNCTION calculate_gross_income()

SET grossIncome = 0

FOR each month in payMonths

grossIncome = grossIncome + month.income

ENDFOR

RETURN grossIncome

ENDFUNCTION

Using objects

We will not discuss the details of object oriented programming in this module. However, even

if you don't create your own classes and objects, you still need to access the methods and

properties of the inbuilt Python types.

The example above is meant to suggest that there is a set of objects called payMonths, and

we go through them one at a time. One of the properties of these objects is the income for

that month, and we access it using the notation month.income.

Here is a simpler example. A door has properties such as height, width, thickness and weight.

Each door has these properties but the value that each door has for height, width, thickness

and weight may be different. We may want to do things with a door such as open, close or

lock it.

Let us suppose that someone has written a class for doors, and has created an object of that

type called ‘door’. The following example shows how access to the properties of an object can

be shown in pseudocode.

SET door.height = 2200

SET door.width = 820

SET doorPaintArea = door.height * door.width

To access methods such as closing and locking the door we could write:

CALL door.close()

DISPLAY door closed message

CALL door.lock()

DISPLAY door locked message

Page 52: ICTPRG405 Automate Processes - WordPress.comExpressing algorithms . Described below are two common ways to express the structure of an algorithm: 1 Pseudo code 2 Flowcharts . Pseudo

46 | P a g e I C T P R G 4 0 5 _ L G _ V 1 T A F E n o w

CALL is a common pseudocode keyword that is used to indicate that a sub-process is to be

invoked. The sub-process is similar to a function, in that the details of what the sub-process

does are hidden from the main code. They can differ from functions in that sub-processes may

not return any value after completing the instructions contained within it.

Desk-checking the solution

At various stages of the development of complex algorithms it is important that the solution is

checked to ensure that it actually works.

Testing is designed to check the logic of the algorithm and the smaller components that

compose the entire solution. Testing should always be done at various stages of refinement to

ensure that the original logic is still intact and effort is not wasted refining an algorithm that is

logically incorrect.

You can check the algorithm by following the instructions you have created using different

sets of inputs. This is often referred to as desk-checking the solution.

Begin by selecting a set of sample inputs and manually calculate the expected output. Then,

desk-check the algorithm using the sample inputs. This is the process of recording the value of

each variable as you execute the statements in your algorithm (pretend you are the

computer). After executing your algorithm in this manner, compare the results you obtained

from your algorithm with those you manually calculated earlier. Are they the same? If not, you

have probably either a logic error in your algorithm, incorrectly calculated the result or missed

changing a variable during the desk-checking. Also, be sure to use different sets of test data to

demonstrate the correctness of your algorithm.

Desk-check example: Marks algorithm

Let’s try this on a simple algorithm that accepts a number of marks to be entered from an

operator, accepts the actual mark values from the operator and displays the average of the

marks entered. Here is the algorithm:

SET totalMarks = 0

GET numberOfMarks

WHILE numberOfMarks > 0

GET mark

Page 53: ICTPRG405 Automate Processes - WordPress.comExpressing algorithms . Described below are two common ways to express the structure of an algorithm: 1 Pseudo code 2 Flowcharts . Pseudo

47 | P a g e I C T P R G 4 0 5 _ L G _ V 1

T A F E n o w

SET totalMarks = totalMarks + mark

SET numberOfMarks = numberOfMarks — 1

ENDWHILE

SET averageMark = totalMarks / numberOfMarks

DISPLAY averageMark

First, decide on the test data. To begin with, let’s test this algorithm with two marks: 70 and

80. Manually calculate the result you expect your algorithm to produce:

averageMark = (70 + 80)/2

averageMark = 150/2

averageMark = 75

Next, construct a table to record the values of variables as we execute the instructions in the

algorithm:

Table 26

Current value

totalMarks

numberOfMarks

mark

averageMark

Now, execute the instructions in the algorithm and record changes to the values of the

variables:

SET totalMarks = 0

Record the assignment of 0 to the variable totalMarks in the table:

Page 54: ICTPRG405 Automate Processes - WordPress.comExpressing algorithms . Described below are two common ways to express the structure of an algorithm: 1 Pseudo code 2 Flowcharts . Pseudo

48 | P a g e I C T P R G 4 0 5 _ L G _ V 1 T A F E n o w

Table 27

Current value

totalMarks 0

numberOfMarks

mark

averageMark

Execute the next instruction:

GET numberOfMarks

The number of marks in the test data set we are using is 2. Record this:

Table 28

Current value

totalMarks 0

numberOfMarks 2

mark

averageMark

WHILE numberOfMarks > 0

Conduct the test for the WHILE loop. Check the value in the variable numberOfMarks

(currently it is 2). Is this value > 0? It certainly is! The test to enter the loop is successful, so let’s

execute the instructions in the loop.

GET mark

The first mark in the test data is 70. Record the value in the table:

Page 55: ICTPRG405 Automate Processes - WordPress.comExpressing algorithms . Described below are two common ways to express the structure of an algorithm: 1 Pseudo code 2 Flowcharts . Pseudo

49 | P a g e I C T P R G 4 0 5 _ L G _ V 1

T A F E n o w

Table 29

Current value

totalMarks 0

numberOfMarks 2

mark 70

averageMark

SET totalMarks = totalMarks + mark

Substitute the current values to the variables on the right-hand side of the assignment

statement:

SET totalMarks = 0 + 70

This simplifies to:

SET totalMarks = 70

Now perform the assignment and record the new value in the table:

Table 30

Current value

totalMarks 70

numberOfMarks 2

mark 70

averageMark

SET numberOfMarks = numberOfMarks — 1

Again, substitute the current values for variables on the right-hand side of the assignment

operator and perform the calculation:

SET numberOfMarks = 2 — 1

Now record the new value for numberOfMarks:

Page 56: ICTPRG405 Automate Processes - WordPress.comExpressing algorithms . Described below are two common ways to express the structure of an algorithm: 1 Pseudo code 2 Flowcharts . Pseudo

50 | P a g e I C T P R G 4 0 5 _ L G _ V 1 T A F E n o w

Table 31

Current value

totalMarks 70

numberOfMarks 1

mark 70

averageMark

Now we are at the end of the WHILE loop. Back we go to the top of the loop and conduct the

test for the WHILE loop again.

WHILE numberOfMarks > 0

Is numberOfMarks > 0? The value 1 is greater than 0! So through the loop again:

GET mark

The second mark in the test data is 80. So let’s now change the table value:

Table 32

Current value

totalMarks 70

numberOfMarks 1

mark 80

averageMark

SET totalMarks = totalMarks + mark

Substituting the values for totalMarks and mark gives:

SET totalMarks = 70 + 80

So, totalMarks should now be assigned the value 150. Let’s change the value in the table:

Page 57: ICTPRG405 Automate Processes - WordPress.comExpressing algorithms . Described below are two common ways to express the structure of an algorithm: 1 Pseudo code 2 Flowcharts . Pseudo

51 | P a g e I C T P R G 4 0 5 _ L G _ V 1

T A F E n o w

Table 33

Current value

totalMarks 150

numberOfMarks 1

mark 80

averageMark

SET numberOfMarks = numberOfMarks — 1

Substitute the current values for the variables on the right-hand side of the assignment

operator:

SET numberOfMarks = 1 — 1

So numberOfMarks is assigned the value 0. Perform the assignment by recording the new

value:

Table 34

Current value

totalMarks 150

numberOfMarks 0

mark 80

averageMark

Now we are at the end of the WHILE loop:

ENDWHILE

Off we go to the top of the loop and conduct the test for the WHILE loop again:

WHILE numberOfMarks > 0

Is numberOfMarks > 0? The value 0 is NOT greater than 0! The test to enter the loop fails so

we do not execute the instructions in the loop and we now execute the first instruction

immediately after the loop:

SET averageMark = totalMarks / numberOfMarks

Let’s get the current values from the table and perform the calculation:

Page 58: ICTPRG405 Automate Processes - WordPress.comExpressing algorithms . Described below are two common ways to express the structure of an algorithm: 1 Pseudo code 2 Flowcharts . Pseudo

52 | P a g e I C T P R G 4 0 5 _ L G _ V 1 T A F E n o w

SET averageMark = 150 / 0

Trying to simplify this produces an unexpected result!

We are trying to divide a number by 0. This is not a legal mathematical operation (dividing any

number by 0 produces an undefined result). Also, we are supposed to be dividing this number

by 2—the number of marks in our set of test data. We may have found a logic error in the

algorithm and it is now time to return to finding a correct solution before attempting to code

the algorithm.

This error could be corrected if a separate loop control variable is used instead of using the

variable holding the original number of marks as the loop control variable.

Here is the re-designed algorithm that uses the variable marksToProcess as the loop

control variable:

SET totalMarks = 0

GET numberOfMarks

SET marksToProcess = numberOfMarks

WHILE marksToProcess > 0

GET mark

SET totalMarks = totalMarks + mark

SET marksToProcess = marksToProcess — 1

ENDWHILE

SET averageMark = totalMarks / numberOfMarks

DISPLAY averageMark

Once the new solution has been created, another desk-check would be performed with the

same test data to verify that the original problem has been addressed in the new version of

the algorithm and that it now produces the correct results.

Page 59: ICTPRG405 Automate Processes - WordPress.comExpressing algorithms . Described below are two common ways to express the structure of an algorithm: 1 Pseudo code 2 Flowcharts . Pseudo

53 | P a g e I C T P R G 4 0 5 _ L G _ V 1

T A F E n o w

Walk-throughs

In environments where larger software systems are developed, a walk-through is often

performed at various stages of algorithm development. A walk-through is a process of

following paths through the algorithms (determined by input conditions and choices made

along the way). The main purpose is to analyse the programmer’s logic and assumptions, and

to identify errors (not fixes) in the algorithms being developed.

Conducting a walk-through during software development can expose logic errors,

inefficiencies and basic design flaws in algorithms before investing considerable effort in

coding and testing.

Walk-throughs are often done by teams, with a co-ordinator, the original designer and other

programmers/designers. The original designer ‘walks through’ the algorithm explaining to the

other members of the team how the solution works and how it addresses the problem. This

review process may provide the original designer with different ideas and viewpoints to

consider as well as exposing design flaws.

A good overview of the walk-through process on systems developed by several people can be

found at the website of the computer scientist and mathematician Dr Jodi Paul, at:

http://www.jodypaul.com/SWE/WT/walkthroughs.html.

The purpose of performing desk-checking and walk-throughs is to find the answer to the

following question. Does the proposed solution meet the specifications?

If the answer is no, remove any identified errors in the algorithm from the first-cut version and

incorporate the changes to the refined algorithm. Don’t be too concerned if your solution

does not work correctly the first time round. Many first-cut solutions don’t. You may need to

go through the process of designing, testing and refining several times before you arrive at a

correct and suitable solution to the problem. The software development process is a

repetitive and circular methodology.

If the answer is yes (that the proposed solution does meet the specifications) you can begin

the process of further refinement if required—coding the algorithm in a programming or

scripting language and testing the code generated.

Page 60: ICTPRG405 Automate Processes - WordPress.comExpressing algorithms . Described below are two common ways to express the structure of an algorithm: 1 Pseudo code 2 Flowcharts . Pseudo

54 | P a g e I C T P R G 4 0 5 _ L G _ V 1 T A F E n o w

Refining the solution

When refining the solution there is often the temptation to add little bits of functionality or

leave out unnecessary features. You may need to ask yourself a few questions before going

down this path.

Checklist for refining

Does the solution meet the basic requirements?

You must first and foremost meet the basic requirements of the problem. Only then can you

consider what additional features may (or may not) be required now and in the near future.

Might the solution work in another context?

You may also consider generalising the solution you found, for use in a variety of different

circumstances. Be sure first that it is actually worthwhile generalising your solution—the extra

time and effort to do so may not pay off in additional usage.

Does the solution work in typical environments?

You also need to consider if the chosen solution is practical for the typical environments it will

be used in. If you have relied on special features of a language that are only available in

perhaps UNIX, how will the solution be implemented in Windows? Where practical, devise a

solution that is platform-independent.

Using prototypes

The use of prototypes in software development is where a sample or cut-down version of the

program is developed to enable the users and designers to get a feel for how the final product

will look and perform.

Prototyping is especially useful when the program or system is very complex, or when the

program specifications have not yet been finalised. It provides the developer with the means

to resolve issues such as screen design, menu systems processing steps and output design,

before all the final details of the program are specified.

Page 61: ICTPRG405 Automate Processes - WordPress.comExpressing algorithms . Described below are two common ways to express the structure of an algorithm: 1 Pseudo code 2 Flowcharts . Pseudo

55 | P a g e I C T P R G 4 0 5 _ L G _ V 1

T A F E n o w

Factors to consider for refinement

Cost

The cost of the solution could be measured in terms of dollars, including the hours needed to

develop and implement the solution and the hardware and other supports the solution

requires.

Another measure of cost is in terms of computing resources. For example, consider resources

such as: the amount of CPU time required to execute the solution, the amount of RAM

required, the number of input / output operations required, and the number of data

transmission packets required.

Efficiency

We can measure the efficiency of an algorithm in two general ways: space efficiency and time

efficiency. An algorithm that is space efficient uses the least amount of computer memory and

other storage space to solve the problem. An algorithm that is time-efficient uses the least

amount of time to solve the problem. Time may also be measured in terms of the number of

instructions the computer must perform to solve the problem. Often there is a trade-off

between space and time efficiency. For example, an algorithm can often be made more time

efficient by using more memory, or vice versa.

Security

Security in networked environments has become particularly important as networks are

increasingly used for financial transactions.

Most programming languages provide mechanisms for changing attributes and permissions

for files. You should ensure that the program you are writing does not contravene any data

protection policies that may be in place in organisations that will use your program. Changing

file sensitive information to unauthorised users can be disastrous!

Also, keep in mind that user rights and permissions largely determine what can and cannot be

done by a program. Protect the programs you create by providing suitable protection on the

program itself so that only authorised users can execute sensitive or potentially dangerous

programs.

Page 62: ICTPRG405 Automate Processes - WordPress.comExpressing algorithms . Described below are two common ways to express the structure of an algorithm: 1 Pseudo code 2 Flowcharts . Pseudo

56 | P a g e I C T P R G 4 0 5 _ L G _ V 1 T A F E n o w

Usability

An excellent solution to a problem will not be very useful if no one can use it. Think about how

you will interact with the users of your program. A program that is not very user-friendly will

soon be replaced by one that is.

Accessibility

Closely related to usability, accessibility refers to the ease with which the software can be used

by the full range of potential users. This may include people who have a visual, auditory,

physical or cognitive impairment. Is the interface and output the best for the users of your

program? Would some users be inconvenienced by the way your program accepts input or

displays output?

Interoperability

In software, this refers to programs having the capability to read and write the same file

formats and/or use the same protocols for communication.

Can your program code be easily combined with other programming tools such as VBScript to

create complete applications? Are the files you create able to be interpreted correctly by other

scripts or applications when required?

SELF CHECK CHECK 2

Check your understanding:

> I can analyse a problem

> I can design a solution

> I can desk check a solution

> I can use a structured walk through

Page 63: ICTPRG405 Automate Processes - WordPress.comExpressing algorithms . Described below are two common ways to express the structure of an algorithm: 1 Pseudo code 2 Flowcharts . Pseudo

57 | P a g e I C T P R G 4 0 5 _ L G _ V 1

T A F E n o w

Topic 3 – Develop and verify script language for an Algorithm

Creating and executing a first script

After you have designed your program using flow charts or pseudo code, making a script is a

multi-step process of:

1 Creating your script as a text document using a text editor,

2 Editing the script in a web browser,

3 Opening the script in a web browser,

4 Observing the script output,

Page 64: ICTPRG405 Automate Processes - WordPress.comExpressing algorithms . Described below are two common ways to express the structure of an algorithm: 1 Pseudo code 2 Flowcharts . Pseudo

58 | P a g e I C T P R G 4 0 5 _ L G _ V 1 T A F E n o w

5 Checking the script for errors,

6 Returning the editor to fix errors.

Software

Suitable software for editing scripts include:

> Any text editor, e.g. Windows Notepad.

> Be sure to change the Save As Type to ‘All files’ and use the .htm extension

> HTML editors, such as Coffee Cup Free HTML editor, Adobe Dreamweaver, Notepad++.

The script below occurs in the file Example1.htm in the Resources.zip

<!DOCUMENT html>

<html> <head> <title>My first script</title> <script language="JavaScript"> function first() { document.write('hello world'); } </script> </head> <body onload="first()"> </body> </html>

This is a simple web page containing a script.

The code in red is the script we have created.

Now we can execute this script.

Open the file in a browser (file- Open – browse to the file) - OK

If your browser tried to block the page, go to

> Tools-Internet Options-Advanced – (scroll down to Security)

> Make sure “Allow active content to run in files on my Computer” is ticked

> Restart your browser

Page 65: ICTPRG405 Automate Processes - WordPress.comExpressing algorithms . Described below are two common ways to express the structure of an algorithm: 1 Pseudo code 2 Flowcharts . Pseudo

59 | P a g e I C T P R G 4 0 5 _ L G _ V 1

T A F E n o w

JavaScripts are commonly created in the <HEAD> section of a web page

The statement

document.write('Hello World');

is an instruction to write ‘Hello World’ in the current document.

<BODY onload="first()">

is an instruction to run the script first() when the page is loaded.

This web page can be used as a template to test scripts, by changing the text that occurs

between the <SCRIPT> and </SCRIPT>

E.g.

<html> <head> <title>My Template file</title> <script language="JavaScript"> function myfunction ( ) { // code goes here } </script> </head> ..... ..... <body onload="myfunction( )"> </body> </html>

Syntax

Syntax is loosely defined as the rules for how the statements fit together in a language.

Try entering ‘define:syntax’ into a search engine of your choice e.g. Google for the many

definitions you’ll find of what the term syntax means.

The syntax definition of a language provides answers to questions such as:

> Where is the end of this statement?

> How do I express an IF THEN ELSE construct?

Must be the same name

Page 66: ICTPRG405 Automate Processes - WordPress.comExpressing algorithms . Described below are two common ways to express the structure of an algorithm: 1 Pseudo code 2 Flowcharts . Pseudo

60 | P a g e I C T P R G 4 0 5 _ L G _ V 1 T A F E n o w

> What types of loops are there in this language?

> When do I need to use special characters like braces {}, brackets [ ], single quotes, double

quotes, colons, semi-colons, commas and so on?

> Can I use the word ‘input’ as a variable name?

The syntax of programming languages takes time and practise to learn. Documentation that

accompanies the particular program for a language defines the syntax of the language.

Unfortunately, there is no easy way to learn to program without having some concept of the

syntax of the language.

An easy way to learn the basic syntax of a language is to learn by example. The examples used

in this reading will only provide you with a starting point. You should also read the tutorials

and user guides for the different programming languages for a more complete introduction

to the language.

Reserved words

Programming languages have a set of words that are reserved for certain actions. Some

keywords common to many languages are: if, then, else, while, for, return. Since these words

have a special meaning to the language, we cannot use these words for our own purposes,

such as using them for the name of a variable.

Syntax errors

Syntax errors result from the incorrect construction or arrangement of code. They are

detected and reported by the interpreter when the code is executed. When the interpreter

finds a syntax error, it stops and outputs an error message.

In order that errors can be seen when they occur, make the following settings in your browser.

Choose Tools – Internet Options – Advanced

Page 67: ICTPRG405 Automate Processes - WordPress.comExpressing algorithms . Described below are two common ways to express the structure of an algorithm: 1 Pseudo code 2 Flowcharts . Pseudo

61 | P a g e I C T P R G 4 0 5 _ L G _ V 1

T A F E n o w

Table 35

Attribute Section Setting

Disable script debugging (Internet Explorer) Browsing ticked

Disable script debugging (Other) Browsing ticked

Display a notification about every script error Browsing ticked

Show friendly HTTP errors Browsing cleared

Note: With these settings, all script errors in all internet pages to which you browse will then

be displayed! You might want to turn these off when you are finished editing!

Page 68: ICTPRG405 Automate Processes - WordPress.comExpressing algorithms . Described below are two common ways to express the structure of an algorithm: 1 Pseudo code 2 Flowcharts . Pseudo

62 | P a g e I C T P R G 4 0 5 _ L G _ V 1 T A F E n o w

Viewing Script errors

Return to the Example1.htm script. Edit the file and delete the single quote (‘) after World as

follows:

document.write('Hello World);

save the file

open the script again

Internet Explorer

Click Show Details:

Page 69: ICTPRG405 Automate Processes - WordPress.comExpressing algorithms . Described below are two common ways to express the structure of an algorithm: 1 Pseudo code 2 Flowcharts . Pseudo

63 | P a g e I C T P R G 4 0 5 _ L G _ V 1

T A F E n o w

Important information is provided here:

> The line number of the error,

> The character position of the error,

> The name of the error

> The URL of the page which contained the error.

Mozilla Firefox

Open the error console (Tools – Web developer – Error console)

Google Chrome

Open the JavaScript console: Spanner Icon – Tools – JavaScript console

Page 70: ICTPRG405 Automate Processes - WordPress.comExpressing algorithms . Described below are two common ways to express the structure of an algorithm: 1 Pseudo code 2 Flowcharts . Pseudo

64 | P a g e I C T P R G 4 0 5 _ L G _ V 1 T A F E n o w

Safari

Open the error console: Develop menu - show error console

Example 2

This script occurs as Example2.htm in the Resources.zip

<!DOCTYPE html>

<html>

<head>

<title>My second script</title>

<script language="JavaScript">

function second() {

x = 2;

alert('The value of x is ' + x);

}

</script>

</head>

<body onload="second()">

</body>

</html>

Page 71: ICTPRG405 Automate Processes - WordPress.comExpressing algorithms . Described below are two common ways to express the structure of an algorithm: 1 Pseudo code 2 Flowcharts . Pseudo

65 | P a g e I C T P R G 4 0 5 _ L G _ V 1

T A F E n o w

Alerts are a good way of showing the value of variables created in a script.

Elements of syntax for JavaScript

In this section you’ll be introduced to some of the elements of syntax for JavaScript. For more

details you should consult the documentation for that language.

Operators

In programming languages, operators are the symbols that denote operations to be

performed on one or more values. The most commonly used types of operators include:

> Assignment (=)

> Arithmetic operators, such as addition.

> Comparison operators such as greater-than (>)

> Logical operators such as &&, %% and !

Assignment operator

We need to be able to tell the computer to store a value into a variable. To do this we

construct a statement called an assignment statement.

Statements are separated with semi-colons (;)

These are usually placed at the end of a line

For example, the JavaScript code below is an example of an assignment statement, which

stores the value 15 in the variable named ‘firstNumber’. The sign (=) is called the assignment

operator, because it assigns the value on its right-hand side to the variable on its left-hand

side.

firstNumber = 15;

Page 72: ICTPRG405 Automate Processes - WordPress.comExpressing algorithms . Described below are two common ways to express the structure of an algorithm: 1 Pseudo code 2 Flowcharts . Pseudo

66 | P a g e I C T P R G 4 0 5 _ L G _ V 1 T A F E n o w

Read “firstNumber becomes 15”

The variable called firstNumber would now hold the value 15 until we assign a new value to

the variable or our program exits.

Another example:

c = a + b;

Read “c becomes a plus b”

Arithmetic operators and expressions

Here is a simple example of addition in JavaScript:

c = a + 3;

Here, there are two operators: the addition (+) operator, and the assignment (=) operator. The

interpreter adds the value three to the value of a, and places the result into variable c.

Table 36 shows the arithmetic operators.

Table 36 Arithmetic operators

Operator Name Symbol Example Result

Addition + a = 1 + 2; a has value 3

Subtraction - a = 8 - 2; a has value 6

Multiplication * a = 4 * 5; a has value 20

Exponentiation or power ^ a = 2**3; a has value 8

Increment and decrement operators

Often in programming we want to simply add or subtract one. JavaScript provides a

shorthand way to do this using the increment or decrement operators.

So for example instead of:

a = a + 1;

you could simply write:

Page 73: ICTPRG405 Automate Processes - WordPress.comExpressing algorithms . Described below are two common ways to express the structure of an algorithm: 1 Pseudo code 2 Flowcharts . Pseudo

67 | P a g e I C T P R G 4 0 5 _ L G _ V 1

T A F E n o w

a++;

Or instead of:

a = a – 1;

you could write:

a - - ;

It is a good idea that, until you become proficient in programming, you use the long form. This

is more explicit, and reminds you that you are really assigning a new value to the variable.

Order of operations (operator precedence)

When creating mathematical expressions that use a mixture of mathematical operators, the

order in which the calculations are performed is determined by the precedence of the

operators used in the expression. This is the same as the order of operations in arithmetic.

The result of the example below is that the variable called ‘result’ will be assigned the value 7,

because the multiplication is performed before the addition.

result = 1 + 2 * 3; Result is 7

By default, the multiplication would be performed first, then the addition. This is because

multiplication has a higher order of precedence than addition, so it’s done before the

addition. To change the order of precedence, parenthesis () must be used. If you need the

addition done first, enclose the addition operation in parentheses like this:

total = (1 + 2) * 3;

In this case the value 9 is stored in the variable ‘total’.

Page 74: ICTPRG405 Automate Processes - WordPress.comExpressing algorithms . Described below are two common ways to express the structure of an algorithm: 1 Pseudo code 2 Flowcharts . Pseudo

68 | P a g e I C T P R G 4 0 5 _ L G _ V 1 T A F E n o w

Comparison operators

Comparison operators are used to compare two values and return a true or false result, as

shown in Table 37.

Table 37 Comparison operators in JavaScript

Operator Name Symbol Example Result of comparison

Greater-than > If a contains the value 3, a > 5 false

Less-than < If a contains the value 3, a < 5 true

Equal to == If a contains the value 3, a == 3 true

Not equal to != If a contains the value 3 a! = 2 true

Greater than or equal to >= If a contains the value 3, a >= 5 false

Less than or equal to <= If a contains the value 5, a <= 5 true

Comparison operators are usually used in conditions of IF statements or loops. For example,

suppose you need to add 10% to a price (say for tax) if the price is greater than $100. You

would do this using an 'if' statement:

If (price > 100) price = price * 1.1;

Page 75: ICTPRG405 Automate Processes - WordPress.comExpressing algorithms . Described below are two common ways to express the structure of an algorithm: 1 Pseudo code 2 Flowcharts . Pseudo

69 | P a g e I C T P R G 4 0 5 _ L G _ V 1

T A F E n o w

Logical operators

Often we need to combine expressions that have true or false values. This normally arises

when we need to combine expressions with comparison operators. For example, we may wish

to program something like the pseudo code below:

IF humidity > 50 AND temperature > 30 THEN

CALL start_air_conditioner

The JavaScript logical operators are AND, OR, and NOT, as shown in Table 38 below.

Table 38 Comparison operators in JavaScript

Operator Name

Symbol Example Result

AND True when BOTH

operands are true

&& If x contains the value 3, and y

contains the value 2

x < 5 and y > 3

false

OR True when EITHER

operand is true.

|| If x contains the value 3, and y

contains the value 2

x < 5 or y > 3

(because y is not

greater than 3)

NOT True when operand

is false

! If x contains 3

! (x == 3)

True

Additional information for operators for JavaScript can be found in the reference documents

for that program.

Syntax for structured programming constructs

You should have encountered the three basic structured programming constructs of

sequence, selection, and iteration. These are quite similar in most programming languages.

We will remind you briefly of the concepts before describing the syntax.

Page 76: ICTPRG405 Automate Processes - WordPress.comExpressing algorithms . Described below are two common ways to express the structure of an algorithm: 1 Pseudo code 2 Flowcharts . Pseudo

70 | P a g e I C T P R G 4 0 5 _ L G _ V 1 T A F E n o w

Sequence

A sequence is simply one or more statements that are to be executed in order, from top to

bottom. For example study this pseudo code sequence that swaps the content of variables x

and y:

SET temp = x

SET x = y

SET y = temp

Note that this sequence only works in the order specified—if you swap the order, you will not

get the desired result.

When coded into a programming language, a sequence of instruction is known as a block of

code. A block of code or statement block can contain one or many statements.

Block structure

These blocks can be included inside iteration and selection statements. In JavaScript, a set of

such statements are enclosed in braces { } Here is an example:

if (mark > 82)

{

document.write( 'Excellent result'); document.write('You have achieved a Distinction')

}

document.write('See you next semester');

The two document.write statements are indented the same amount and are part of the ‘if’

statement. These two statements will only be executed when the condition (mark > 82) is

true. The third document.write statement is not part of that block as it is not inside the braces.

This last document.write statement is at the same level as the ‘if’ statement itself, and will be

executed after the ‘if’ statement.

Page 77: ICTPRG405 Automate Processes - WordPress.comExpressing algorithms . Described below are two common ways to express the structure of an algorithm: 1 Pseudo code 2 Flowcharts . Pseudo

71 | P a g e I C T P R G 4 0 5 _ L G _ V 1

T A F E n o w

Notes:

> The last line of a block does not require a (;) – as there is no following line to be

separated!

> There are several ways of indenting code with delimited blocks. We will use the

commonest of these, called the ‘Kernighan and Ritchie’ style (after the designers of the C

programming language). See the article ‘Programming with style’ at:

http://www.riedquat.de/prog/style

Selection

Here is the pseudo code for the IF/ELSE statement:

IF test THEN

statement block

ELSE

statement block

ENDIF

Javascript uses the following syntax for IF/ELSE statements.

if ( test)

{

statement block

}

else

{

statement block

}

Note: the ELSE part is optional, so an IF without an ELSE is syntactically correct.

if ( test)

{

statement block

Page 78: ICTPRG405 Automate Processes - WordPress.comExpressing algorithms . Described below are two common ways to express the structure of an algorithm: 1 Pseudo code 2 Flowcharts . Pseudo

72 | P a g e I C T P R G 4 0 5 _ L G _ V 1 T A F E n o w

}

If however, the statement block contains only one statement the braces may be omitted.

if (mark > 82) document.write(‘A distinction’ );

For example, assuming that we have stored a test mark in a variable called ‘mark’ the code for

an IF/ELSE construct that displays PASS or FAIL could be:

if (mark >= 50)

document.write('PASS')

else

document.write ('FAIL')

When you need to do a series of mutually exclusive tests in pseudo code, you can string IF

statements together using ELSE IF. The syntax for JavaScript is shown below.

if (test)C:\Users\John\Desktop\ICA11 development\Diploma\ICAPRG405 Review\Unit Templates\compound.html - tok-suite {

statement block

}

else

if (test)

{

statement block

}

else

{

statement block

Alternatively, JavaScript has a Switch statement to perform the same function.

e.g.

Switch (number)

{

case “1” :

Page 79: ICTPRG405 Automate Processes - WordPress.comExpressing algorithms . Described below are two common ways to express the structure of an algorithm: 1 Pseudo code 2 Flowcharts . Pseudo

73 | P a g e I C T P R G 4 0 5 _ L G _ V 1

T A F E n o w

document.write (‘you pressed 1’);

break;

case “2”:

document.write (‘you pressed 2’);

break;

case “3”:

document.write (‘you pressed 3’);

break;

default :

document.write(“you did not press 1,2 or 3’);

}

The statements after the case are executed corresponding to the value of number. If none of

the cases hold the value of number the codes after the default: is executed.

Note the use of break - this sends execution to the line after the bracket closing the switch

statement.

Iteration

Let’s look at the syntax of the while loop:

while (expression)

{

statement1

statement2

statement3

}

User input

All scripting languages provide functions for accepting input from a user and placing it into

variables used in your script. One of these functions will accept input from the keyboard.

JavaScript provides several methods for accepting user input.

Page 80: ICTPRG405 Automate Processes - WordPress.comExpressing algorithms . Described below are two common ways to express the structure of an algorithm: 1 Pseudo code 2 Flowcharts . Pseudo

74 | P a g e I C T P R G 4 0 5 _ L G _ V 1 T A F E n o w

Prompt

Which = Prompt(‘Which currency?’,’dollar’);

The first input (Which Currency?) is the text which appears in the Prompt box

The second is the default entry, saving the user typing a response if they choose this entry.

The variable Which then holds the value entered by the user.

Confirm

This allows the user to give a yes/no response to a question

Ask = confirm(‘Are you ready?);

Clicking OK assigns Ask the value True, Cancel assigns Ask the value False.

Translating from pseudo code

Now let’s write some code based on simple algorithms to see how sequence, selection and

iteration can be expressed in a scripting language such as JavaScript.

Page 81: ICTPRG405 Automate Processes - WordPress.comExpressing algorithms . Described below are two common ways to express the structure of an algorithm: 1 Pseudo code 2 Flowcharts . Pseudo

75 | P a g e I C T P R G 4 0 5 _ L G _ V 1

T A F E n o w

Example 3: Simple sequence and arithmetic operators

Problem statement: With the two numbers, 10 and 15, perform the basic mathematical

operations of addition, subtraction, division and multiplication. Display the result of each

operation immediately after performing it.

Table 39 Pseudo code and Javascript code

Pseudo code Javascript code

SET num1 = 10

SET num2 = 15

SET result = num1 + num2

DISPLAY result

SET result = num1 — num2

DISPLAY result

SET result = num1 * num2

DISPLAY result

SET result = num1 / num2

DISPLAY result

num1 = 10;

num2 = 15;

result = num1 + num2;

document.write( 'Sum: ' + result + '<br />');

result = num1 - num2;

document.write( 'Difference: ' + result + '<br />');

result = num1 * num2;

document.write( 'Product: ' + result + '<br />');

result = num1 / num2;

document.write( 'Quotient: ' + result + '<br />');

Javascript output

Sum: 25

Difference: -5

Product: 150

Quotient: 0.6666666666666666

For the code line result = num1/ num2 JavaScript has performed division of the operands,

giving a decimal result.

Page 82: ICTPRG405 Automate Processes - WordPress.comExpressing algorithms . Described below are two common ways to express the structure of an algorithm: 1 Pseudo code 2 Flowcharts . Pseudo

76 | P a g e I C T P R G 4 0 5 _ L G _ V 1 T A F E n o w

Example 4: Selection

Problem statement: Create a program to display a student grade according to the following

criteria: A mark that is 50 or more will display a ‘Pass’ message. Any other mark will display a

‘Fail’ message. The mark will be input from the keyboard and will be a whole number in the

range 0 to 100 inclusive.

Pseudo code

READ mark

IF mark >= 50 THEN

DISPLAY Pass

ELSE

DISPLAY Fail

ENDIF

JavaScript code

A first draft of the JavaScript code might look like this:

userInput = prompt('Enter the student mark: ');

if (userInput >= 50)

alert( 'PASS')

else

alert( 'FAIL');

Note: The if part does not require a (;) if an else follows.

Try executing the above script. You will find that the code does not work correctly—it prints

‘PASS’ for marks below 50. So, what’s happening here?

The problem with the above script is that the IF test is comparing a string of ASCII characters

(userInput) with a number (50). This comparison does not yield the correct result as a

comparison of a string to a number is performed in terms of the ASCII character set. ASCII 50

in binary is 01100101 01100000, while 50 decimal in binary is 110010.

Page 83: ICTPRG405 Automate Processes - WordPress.comExpressing algorithms . Described below are two common ways to express the structure of an algorithm: 1 Pseudo code 2 Flowcharts . Pseudo

77 | P a g e I C T P R G 4 0 5 _ L G _ V 1

T A F E n o w

What we need to do is to convert the string ‘50’ to the number 50. Fortunately, JavaScript

provides a function parse_Int() to convert a string to an integer. So let’s try using it in our

script.

userInput = prompt('Enter the student mark: ');

mark = parseInt(userInput);

if (mark >= 50)

document.write ('PASS')

else

document.write ('FAIL');

LEARNING ACTIVITIES ACTIVITY 4

Try programming this problem:

Enter three numbers and determine which one is the largest

Example 5: Iteration

Problem statement: Create a program to accept marks from a user and display the original

mark and the student grade according to the following criteria. A mark that is 50 or more will

display a ‘Pass’ message. Any other mark will display a ‘Fail’ message. The mark will be input

from the keyboard and will be a whole number in the range 0 to 100 inclusive. The program is

to end when a negative mark is entered.

A loop is required in this case, as multiple marks can be entered.

Page 84: ICTPRG405 Automate Processes - WordPress.comExpressing algorithms . Described below are two common ways to express the structure of an algorithm: 1 Pseudo code 2 Flowcharts . Pseudo

78 | P a g e I C T P R G 4 0 5 _ L G _ V 1 T A F E n o w

Pseudo code

SET finished = FALSE

WHILE NOT finished DO

READ mark

IF mark < 0 THEN

SET finished = TRUE

ELSE

IF mark >= 50 THEN

DISPLAY 'PASS'

ELSE

DISPLAY 'FAIL'

ENDIF

ENDIF

ENDWHILE

DISPLAY 'all done'

JavaScript code

function allmarks()

{

finished = false;

while (!finished)

{

userInput = prompt('Enter the student mark: ','-1 to end');

mark = parseInt(userInput);

if (mark < 0) finished = true

else

Page 85: ICTPRG405 Automate Processes - WordPress.comExpressing algorithms . Described below are two common ways to express the structure of an algorithm: 1 Pseudo code 2 Flowcharts . Pseudo

79 | P a g e I C T P R G 4 0 5 _ L G _ V 1

T A F E n o w

if (mark >= 50) document.write( 'Mark entered: ' + mark + ' is a PASS <br/>')

else document.write( 'Mark entered: ' + mark + ' is a FAIL <br/>');

}

document.write('All done');

}

Best practice

Best practice in programming is essentially conforming to de-facto standards agreed upon by

members of the programming community. These standards involve issues such as code

layout and documentation styles that should be used but are not essential for writing scripts.

Indent your code consistently

Javascript is made easier to read if :

New levels of indent (3 characters) are used for each iteration and selection

Matching opening and closing braces are at the same level of indent

Naming variables

A good naming style for variables makes readable code. For example:

gstPayable = totalSale * gstTaxRate

balanceDue = totalSale—discount + gstPayable

describes the code better than the following does

x = xx * y

z = xx—yy + x

A few simple rules for variable names are to:

> choose meaningful names for your variables; this seemingly trivial exercise sometimes

requires some thought

> use all-capitals only for constants, for example ONE_DOZEN

> begin the name of a variable with a lowercase character, and begin any new words with

an uppercase character (this is the most popular convention for variables today) for

example, pricePerItem.

Page 86: ICTPRG405 Automate Processes - WordPress.comExpressing algorithms . Described below are two common ways to express the structure of an algorithm: 1 Pseudo code 2 Flowcharts . Pseudo

80 | P a g e I C T P R G 4 0 5 _ L G _ V 1 T A F E n o w

Comments

The comment character is the double forward slash symbol (//). It tells the interpreter to

ignore the text that follows, as the text is merely a comment or note to the script reader and is

not an instruction to execute. It allows you to explain what the code is supposed to do. Inline

comments are used at the end of a line of code, as follows.

Commenting example

finished = False // ensure loop entry initially

while (!finished)

{

userInput = prompt('Enter mark: ',0);

mark = int(userInput); // get mark as an integer

if (mark < 0) // user is finished

finished = True;

else // normal case

if (mark >= 50)

document.write( 'Mark entered: ' + mark, + 'is a PASS');

else

document.write( 'Mark entered: ' + mark, + 'is a FAIL');

}

document.write('All done');

Your comments should always address the logic of the code.

Page 87: ICTPRG405 Automate Processes - WordPress.comExpressing algorithms . Described below are two common ways to express the structure of an algorithm: 1 Pseudo code 2 Flowcharts . Pseudo

81 | P a g e I C T P R G 4 0 5 _ L G _ V 1

T A F E n o w

Block comments

Block comments appear at the start of a block of code. Their main purpose is to give a general

description of the processing being performed by the code that follows. They are often placed

at the top of a script to relate script usage, purpose, and revision history. Here is an example:

//-----------------------------------------------------------

// Purpose : Process student test marks

// Description : Accept marks from keyboard and display

// corresponding grade. Terminates when a

// negative number is entered.

// Author: W. Gates

// Date: 10 June 2006

// Version: 1.0.0

//-----------------------------------------------------------

The Document Object Model (DOM)

The objects in a document are accessed via JavaScript through a construct known as the

Document Object Model

A simple view of the document object model

Page 88: ICTPRG405 Automate Processes - WordPress.comExpressing algorithms . Described below are two common ways to express the structure of an algorithm: 1 Pseudo code 2 Flowcharts . Pseudo

82 | P a g e I C T P R G 4 0 5 _ L G _ V 1 T A F E n o w

Example 6

<html>

<head>

<title id="first">DOM example 1</title>

<script type="text/javascript" language="javascript">

function colourup()

{

textbox= document.form1.elements[0];

textbox.style.color ='yellow';

textbox.style.backgroundColor ='black';

}

</script

</head>

<body onload="colourup()">

<form name="form1" action="">

<input type="text" id="text1" value="alpha" />

</form>

</body>

</html>

In this example, an input box has its text and background colour changed by the action of the

function colourup( ).

The line

textbox= document.form1.elements[0];

searches the document for form1 and finds the first element (numbered from zero)

the next two lines change the styles of the text colour and background colour to yellow and

black respectively.

Page 89: ICTPRG405 Automate Processes - WordPress.comExpressing algorithms . Described below are two common ways to express the structure of an algorithm: 1 Pseudo code 2 Flowcharts . Pseudo

83 | P a g e I C T P R G 4 0 5 _ L G _ V 1

T A F E n o w

Example 7

<html>

<head>

<title id="first">DOM example 2</title>

<script type="text/javascript" language="javascript">

function colourup()

{

// get the value of the drop down

boxnumber= document.form1.elements[3].value;

textbox = document.form1.elements[boxnumber];

// set all boxes to black on white

for(i=0;i<3;i++)

{

document.form1.elements[i].style.backgroundColor = 'white';

document.form1.elements[i].style.color = 'black';

}

// now set the chosen one to yellow on black

textbox.style.color ='yellow';

textbox.style.backgroundColor ='black';

}

</script>

</head>

<body>

<form name="form1" action="">

1<input type="text" id="text1" value="alpha" />

2<input type="text" id="text2" value="beta" />

Page 90: ICTPRG405 Automate Processes - WordPress.comExpressing algorithms . Described below are two common ways to express the structure of an algorithm: 1 Pseudo code 2 Flowcharts . Pseudo

84 | P a g e I C T P R G 4 0 5 _ L G _ V 1 T A F E n o w

3<input type="text" id="text3" value="gamma" />

<select id="boxes" onchange="colourup()">

<option value="0">1</option>

<option value="1">2</option>

<option value="2">3</option>

</select>

</form>

</body>

</html>

This example creates 4 elements in a form – numbered 0 to 3

The three input boxes are elements 0, 1 & 2 and the dropdown box is element 3.

boxnumber = document.form1.elements[3].value;

is the value of the dropdown when it is changed.

textbox = document.form1.elements[boxnumber];

is the input box corresponding to the number chosen from the dropdown

Notice that the values displayed (1, 2,& 3) are different from the option values (0,1,2)

The for loop sets each of the input boxes to black text on white

Lastly, the lines

textbox.style.color ='yellow';

textbox.style.backgroundColor = 'black';

set the chosen textbox to yellow on black.

Page 91: ICTPRG405 Automate Processes - WordPress.comExpressing algorithms . Described below are two common ways to express the structure of an algorithm: 1 Pseudo code 2 Flowcharts . Pseudo

85 | P a g e I C T P R G 4 0 5 _ L G _ V 1

T A F E n o w

Example from Topic 2

This is the problem from Algorithm 2.3

Matraville College need an algorithm to find the average of five test results. The operator at

the keyboard will input the total marks possible for the test followed by the five test results.

The college would like to have displayed on the screen: the marks input, the percentage for

each test result and the average of the test results as a percentage.

Here is the final algorithm:

GET marksPoss

SET totalPercent = 0

FOR index = 0 TO 4

GET marks[index]

SET marksPer[index] = marks[index] / marksPoss * 100

SET totalPercent = totalPercent + marksPer[index]

DISPLAY marks[index]

DISPLAY marksPer[index]

ENDFOR

SET averagePercent = totalPercent / 5

DISPLAY averagePercent

JavaScript

function fiveMarks() {

marksPoss = prompt('Maximum mark: ');

mark = new Array(4);

markPer = new Array(4);

totalPercent = 0;

document.write('<table>');

document.write('<tr><td>Mark</td><td>Percentage</td>');

for(index=0;index<=4;index++){

mark[index] = prompt('Enter mark ' + (index + 1));

Page 92: ICTPRG405 Automate Processes - WordPress.comExpressing algorithms . Described below are two common ways to express the structure of an algorithm: 1 Pseudo code 2 Flowcharts . Pseudo

86 | P a g e I C T P R G 4 0 5 _ L G _ V 1 T A F E n o w

markPer[index] = mark[index] / marksPoss * 100;

document.write ('<tr><td>' +mark[index] +'</td><td>' + markPer[index] + '</td></tr>');

totalPercent = totalPercent + markPer[index];

}

document.write('</table>');

averagePercent = totalPercent / 5;

document.write ('Average percentage is ' + averagePercent);

}

The code need not reflect exactly the same logic –it may be necessary to include several lines

of code that correspond to one line of pseudo code.

Consider how you might change this to find the best mark as well.

Programming the HTML 5 canvas

HTML 5 is not yet W3C standard. As a result, not all browsers support the <canvas> element.

Use this code to test your browser

<!DOCTYPE html>

<html>

<head>

<title>Canvas test</title>

</head>

<body>

<canvas id="myCanvas" width="600" height="600"style="border:1px solid #FF0000;">

Canvas is not supported

</canvas>

</body>

</html>

Page 93: ICTPRG405 Automate Processes - WordPress.comExpressing algorithms . Described below are two common ways to express the structure of an algorithm: 1 Pseudo code 2 Flowcharts . Pseudo

87 | P a g e I C T P R G 4 0 5 _ L G _ V 1

T A F E n o w

If a red canvas border appears, your browser supports the HTML 5 canvas

Otherwise, the message canvas in not supported will be displayed.

Table 40 Drawing on the HTML 5 canvas

Action Function Example

Creates a context in which to

draw

getContext con= c.getContext(“2D”);

Sets the line width lineWidth con.lineWidth = 2;

Starts a draw path beginPath con.beginPath();

Sets the colour of lines strokeStyle con.strokeStyle = “Red”;

Moves to a given point moveTo con.moveTo(200,300);

Sets the size and font for text font con.font =’14pt Verdana’;

Draws filled text at the given

point

fiilText con.fillText(‘Name’,100,500);

Draws a line to a given point lineTo con.lineTo(500,250);

Sets the colour of a fill action fillstyle con.fillStyle = ‘black’;

Draws a filled rectangle at a

given point with given width

and height

fillRect con.fillRect(500,300,50,50)

Sets the type of line ends linecap con.linecap = ‘round’;

For a complete list of the functions for use with the HTML 5 canvas see,

https://simon.html5.org/dump/html5-canvas-cheat-sheet.html

Page 94: ICTPRG405 Automate Processes - WordPress.comExpressing algorithms . Described below are two common ways to express the structure of an algorithm: 1 Pseudo code 2 Flowcharts . Pseudo

88 | P a g e I C T P R G 4 0 5 _ L G _ V 1 T A F E n o w

Example 9

Draw this shape of the HTML 5 canvas

Setup the canvas

Draw the wall

Move to the roof

Draw the roof

Draw the door.

Webpage and JavaScript code

<!DOCTYPE html>

<html>

<head>

<title>Canvas test</title>

</head>

<body>

<canvas id="myCanvas" width="600" height="600"style="border:1px solid #FF0000;">

Canvas is not supported

</canvas>

<script type="text/javascript" language="javascript" >

c = document.getElementById("myCanvas");

con = c.getContext("2d");

con.strokeStyle = 'black';

// Draw the wall 70 pixels wide, 50 high at 300,300

con.fillStyle = 'blue';

con.fillRect(300, 300, 70, 50);

// move to the roof

con.moveTo(300, 300);

Page 95: ICTPRG405 Automate Processes - WordPress.comExpressing algorithms . Described below are two common ways to express the structure of an algorithm: 1 Pseudo code 2 Flowcharts . Pseudo

89 | P a g e I C T P R G 4 0 5 _ L G _ V 1

T A F E n o w

// Draw the roof

con.fillStyle = 'red';

con.lineTo(335, 300 - 35 * Math.sqrt(2));

con.lineTo(370, 300);

con.fill();

// Draw the door

con.fillStyle = 'yellow';

con.fillRect(330, 320, 10, 30);

con.stroke();

</script>

</body>

</html>

Notice in this example the code in run in the body of the webpage

LEARNING ACTIVITIES ACTIVITY 5

Try drawing some other simple shapes as well

Page 96: ICTPRG405 Automate Processes - WordPress.comExpressing algorithms . Described below are two common ways to express the structure of an algorithm: 1 Pseudo code 2 Flowcharts . Pseudo

90 | P a g e I C T P R G 4 0 5 _ L G _ V 1 T A F E n o w

Example 10

<!DOCTYPE html>

<html>

<head>

<meta charset="utf-8">

<meta http-equiv="X-UA-Compatible" content="IE=edge">

<title>Hello</title>

<script type="text/JavaScript" lang="JavaScript">

function drawOne(a,n)

{

// draws the rectangle for one of the values

// a is a counter for the column

// n is the value being graphed

con.fillStyle = 'blue';

con.fillRect(100 + 40 * a, 400, 20, -n);

// write the value below the column

con.strokeText(n, 100 + 40 * a, 440);

}

</script>

</head>

<body>

<h1>Show me the numbers</h1>

<canvas id="myCanvas" width="600" height="600"style="border:1px solid

#FF0000;">

Canvas is not supported

</canvas>

<script type="text/javascript" language="javascript" >

c = document.getElementById("myCanvas");

Page 97: ICTPRG405 Automate Processes - WordPress.comExpressing algorithms . Described below are two common ways to express the structure of an algorithm: 1 Pseudo code 2 Flowcharts . Pseudo

91 | P a g e I C T P R G 4 0 5 _ L G _ V 1

T A F E n o w

con = c.getContext("2d");

con.strokeStyle = 'black';

var scores = [75, 46, 32, 178, 95, 83];

// move to the bottom left

for(i=0;i< scores.length; i++)

{

drawOne( i, scores[i])

}

con.stroke();

</script>

</body>

</html>

This example uses the variable scores to draw a series of rectangles

Page 98: ICTPRG405 Automate Processes - WordPress.comExpressing algorithms . Described below are two common ways to express the structure of an algorithm: 1 Pseudo code 2 Flowcharts . Pseudo

92 | P a g e I C T P R G 4 0 5 _ L G _ V 1 T A F E n o w

Recursion

Resursion is the process of a function making a call to itself.

Here is a reucsive story.

“It was a dark and stormy night and the captain asked one of the crew to tell a story to while

away the hours. So he began:

“It was a dark and stormy night….”

This story will never end, so we don’t want a computer program to emulate it!

Recursive functions all have the same structure

function recursive ( parameter)

{

// some means of telling the rucursion to stop

// call the function again with a different paramter

recursive( parameter1)

Example

Print the first line of the story repeatedly, given a parameter to determine how many times

function story(n)

{

If (n ==0 ) return

else

{

Console.log “It was a dark and stormy night \n”;

story(n – 1);

}

}

Page 99: ICTPRG405 Automate Processes - WordPress.comExpressing algorithms . Described below are two common ways to express the structure of an algorithm: 1 Pseudo code 2 Flowcharts . Pseudo

93 | P a g e I C T P R G 4 0 5 _ L G _ V 1

T A F E n o w

Example 11

<!DOCTYPE html>

<html>

<head>

<meta charset="utf-8">

<meta http-equiv="X-UA-Compatible" content="IE=edge">

<title>Recursive story</title>

<script>

var div1;

function story(n)

{

if (n==0 ) return

else

{

div1= document.getElementById('line');

div1.innerHTML = div1.innerHTML + '<p>It was a dark and stormy night <\p>';

a = n - 1;

story(a);

}

}

</script>

</head>

<body onLoad="story(9);">

<h1>Story</h1>

<div id='line'></div>

</body>

</html>

Page 100: ICTPRG405 Automate Processes - WordPress.comExpressing algorithms . Described below are two common ways to express the structure of an algorithm: 1 Pseudo code 2 Flowcharts . Pseudo

94 | P a g e I C T P R G 4 0 5 _ L G _ V 1 T A F E n o w

In this example, the number passed to the story function determines whether another line is

to be printed or not.

At each call of the function either,

n = 0 and the story ends or

another line is added and the story( ) function is called again with a numer one less then the

previous call. Eventually, n become 0 and the story ends.

Example 12 Recursive boxes

<!DOCTYPE html>

<html>

<head>

<meta charset="utf-8">

<meta http-equiv="X-UA-Compatible" content="IE=edge">

<title>Recursive tree</title>

<script>

function box(list)

{

if (list.length == 0 ) return

else

{

first = list[0];

con.fillRect(20,position,first,first);

position = position + first + 10;

box(list.slice(1,list.length));

}

}

</script>

</head>

<body>

<h1>Boxes</h1>

Page 101: ICTPRG405 Automate Processes - WordPress.comExpressing algorithms . Described below are two common ways to express the structure of an algorithm: 1 Pseudo code 2 Flowcharts . Pseudo

95 | P a g e I C T P R G 4 0 5 _ L G _ V 1

T A F E n o w

<canvas id="myCanvas" width="600" height="600" style="border:1px solid #00FF00;">

Canvas is not supported

</canvas>

<script type="text/JavaScript" lang="JavaScript">

c = document.getElementById("myCanvas");

con = c.getContext("2d");

boxlist = [50, 25 , 75, 12 , 42, 6];

position = 10;

box(boxlist);

</script>

</body>

</html>

In this example, the boxlist contains an array of square sizes.

The function box is called with this array value.

The function is recursive.

If the array is empty, the function ends,

otheriwse,

the variable first is assigned the first value of the array.

A square is drawn using first as the size of the square.

Position is incread by 10, which ahas the efect of moving the next square 10 pixels further

down plus the size of the square just drawn.

The function is called again, using all but the first value.

box(list.slice(1,list.length));

this line passes the array from position 1 to the end, thus avoiding the first value.

Page 102: ICTPRG405 Automate Processes - WordPress.comExpressing algorithms . Described below are two common ways to express the structure of an algorithm: 1 Pseudo code 2 Flowcharts . Pseudo

96 | P a g e I C T P R G 4 0 5 _ L G _ V 1 T A F E n o w

SELF CHECK CHECK 3

I can now:

> edit JavaScript code

> create simple JavaScript functions

> provide solutions to simple problems

Page 103: ICTPRG405 Automate Processes - WordPress.comExpressing algorithms . Described below are two common ways to express the structure of an algorithm: 1 Pseudo code 2 Flowcharts . Pseudo

97 | P a g e I C T P R G 4 0 5 _ L G _ V 1

T A F E n o w

Topic 4 – Document script or code

Types of documentation

Creating good documentation to accompany your script is usually the final stage of script

development. It is a stage often ignored or poorly done. The material presented here will

introduce you to internal and external documentation that may accompany a script, to help

give you the skills to do it properly.

Software documentation can be categorised as either:

1 technical documentation

2 user documentation.

Page 104: ICTPRG405 Automate Processes - WordPress.comExpressing algorithms . Described below are two common ways to express the structure of an algorithm: 1 Pseudo code 2 Flowcharts . Pseudo

98 | P a g e I C T P R G 4 0 5 _ L G _ V 1 T A F E n o w

Scripts do not normally require extensive documentation. You will learn how to provide basic

technical documentation within the source code file itself, including self-documenting code,

and information embedded as comments. We will also look at providing basic user

documentation in a 'read-me' file to accompany the script you create.

Technical documentation

Technical documentation is targeted at the designers, writers and those maintaining

computer scripts. It typically consists of:

> problem and system description

> the algorithm itself

> the source code or program listing

> internal comments contained in the program listing

Problem and system description

Among a host of other documents, problem and system description may include documents

such as:

> functional specifications

> UML (unified modelling language) diagrams

> data flow diagrams

> decision tables

> decision trees

The algorithm itself

The algorithm itself is the original plan for the script and may be recorded in a separate

document and/or included in the source code as comments.

Hint: Write algorithms in pseudo code directly into a text editor. Once the algorithm is refined

and checked for errors, turn the original lines in the algorithm into comments. As each section

of the script is coded, the comments are a reminder of the algorithm. Later in the

development process, change the original comments into more appropriate comments where

necessary.

Page 105: ICTPRG405 Automate Processes - WordPress.comExpressing algorithms . Described below are two common ways to express the structure of an algorithm: 1 Pseudo code 2 Flowcharts . Pseudo

99 | P a g e I C T P R G 4 0 5 _ L G _ V 1

T A F E n o w

The source code

The source code is the actual text of the program that is interpreted or compiled. This is the

complete expression of what the program does, and the ultimate source of documentation

for other programmers.

You should always strive to make the meaning and intent of your code as clear as possible,

even without comments. Ideally, the code itself should be 'self-documenting', meaning that

another programmer can easily work out what the program is doing, and why.

A few of the things you can do to make you programs self-documenting are:

> Give variables the most meaningful and accurate name for their purpose.

> Similarly with functions, choose a name that describes clearly what the function does.

> Avoid complex or confusing code constructs. Some languages like C and PERL are

notorious for difficult syntax. You should always strive to find the clearest ways to express

yourself in code, as you do in English.

> Do not try to be too smart when programming. In other words, try to choose the clearest,

simplest way to do something rather than the smartest or 'coolest'. For example, do not

use obscure language features or complex data structures if this can be avoided.

> Indent your code properly. Most languages use delimiters (for example the braces { } to

indicate the nested structure of the code. In these languages, the compiler does not care

about indentation. Correct indentation must be maintained separately by the

programmer in order to make the code structure apparent to the reader. Unfortunately,

different programmers have different ideas about which indentation rules are best.

There are several excellent articles about self-documenting code on the Web. Search for the

term on Google (www.google.com), and read the first few articles.

Obfuscated code is the reverse of self-documenting code, where the programmer sets out to

make the program difficult to understand. To see some humorous examples, Obfuscated

Code

Page 106: ICTPRG405 Automate Processes - WordPress.comExpressing algorithms . Described below are two common ways to express the structure of an algorithm: 1 Pseudo code 2 Flowcharts . Pseudo

100 | P a g e I C T P R G 4 0 5 _ L G _ V 1 T A F E n o w

Comments

A comment is a piece of text in the source code that is meant for human readers. The compiler

or interpreter will ignore the comments.

In JavaScript, a comment is introduced using 2 forward-slash characters. (//) For example:

// count to three

for(i=1;i<=3;i++)

print i;

Comments can be also placed at the end of a line:

DOZEN = 12 // constant

Comments are used by code writers to explain the purpose and intentions of the code or

communicate that to others.

When code is changed or modified by a team of writers, code versions and records of changes

may become necessary. Code versions and records of changes are often required by

organisations when commissioning scripts; you may need to investigate the commenting

requirements for the code you develop.

Good commenting practice

Finding the right thing to say in a programming comment is not always easy. Here are a few

pointers:

> Not every line has to be commented. If you have done a good job with self-documenting

code, many lines will not require comments.

> Most variable definitions could benefit from a comment explaining how they will be

used.

> Do not just restate the code with equivalent comments. The following are not useful

comments, as they simply restate what the actual code is doing.

> avgMark = totalMarks / numMarks // calculate avgMark

> print 'Average mark:', avg_mark // Print avgMark

> Similarly, you don't usually need to explain the normal operation of simple programming

constructs such as loops.

> A single-line summary comment before each if statement or loop is often helpful.

> It is most important to comment special conditions, assumptions, or complex logic.

> While you are learning to program, it’s better to err on the side of too many comments.

Page 107: ICTPRG405 Automate Processes - WordPress.comExpressing algorithms . Described below are two common ways to express the structure of an algorithm: 1 Pseudo code 2 Flowcharts . Pseudo

101 | P a g e I C T P R G 4 0 5 _ L G _ V 1

T A F E n o w

> It is very useful to take some of your old code (from say six months ago) and quickly try to

understand it again. You will soon notice where you have not provided enough

comments.

Block comments

Block comments are comments that extend over multiple lines, forming a block. Block

comments are used to give a more extensive description of a section of code.

Block comments are typically used as prologs to modules (source code files), functions, and

classes. A prolog is documentation that is included before a significant section of code,

including, for example, the purpose of the code, the author, the dates created and modified,

the version number, expected inputs, a brief description of the processing required and the

outputs generated.

Block comments at the beginning of the script code can also be used to summarise code

modifications. The following is an example of this type of block comment.

//------------------------------------------------------------ // Filename : my_script.js // Purpose : validate the form data // // Description : Checks all the fields for emptiness, // determines if age is numeric. // Version : 1.1.0 // Created : 16 August 2008 // Author : John DeCoda //------------------------------------------------------------ // Modifications: //------------------------------------------------------------ // 23 June 2008 // Fred Smith—version changed from 1.0.1 to 1.1.0 // Replaced the code for the radio buttons with a dropdown // //------------------------------------------------------------

Some languages have beginning and ending delimiters for multi-line comments, for example:

/* This is a

multi-line comment

in Java

*/

Page 108: ICTPRG405 Automate Processes - WordPress.comExpressing algorithms . Described below are two common ways to express the structure of an algorithm: 1 Pseudo code 2 Flowcharts . Pseudo

102 | P a g e I C T P R G 4 0 5 _ L G _ V 1 T A F E n o w

JavaScript does not have a true multi-line comment like this, so you must begin each line of a

block comment with a new // character. Most uses of block comments are more useful as

documentation strings, as we will see in the next section.

Documentation strings

Comments are very useful for other programmers to understand your code. But to read the

comments, you must open the source code file itself and read each comment.

Often the comments (block comments especially) contain summary information that is very

useful to programmers as they work. For example, to use a function that appears in another

module, you need to know its exact name, what it does, how many parameters it takes, and

what it returns. Again, to find these details, you would need to open the file and check the

comment above that function.

Therefore, it is much better to have this summary information available online, so that the

programmer can browse through the available features of a software package. The current

trend is to automatically assemble the prolog information of functions, classes and modules

into convenient online documentation, normally formatted as HTML.

Sample input and output data

The test results recorded for your script are another form of technical documentation. The

recording of the input values and the resulting outputs may be thought of as documentation

on the behaviour of your script using certain input values.

User documentation

User documentation should be designed and written with specific goals in mind. The goals

inform the purpose, scope and content of the document, including the level of jargon used,

and even the grammar and layout.

To formulate these goals the following questions can be answered:

> What needs or requirements will this documentation meet?

> Who are the targeted users?

> What skills do these users have?

> What terminology are they familiar with?

Page 109: ICTPRG405 Automate Processes - WordPress.comExpressing algorithms . Described below are two common ways to express the structure of an algorithm: 1 Pseudo code 2 Flowcharts . Pseudo

103 | P a g e I C T P R G 4 0 5 _ L G _ V 1

T A F E n o w

User documentation may consist of read-me files, instructions and/or feedback generated by

your script, installation guides and how-to and FAQ files.

Note: With application programs or systems programs, the programmers and users are

usually distinctly different groups, each requiring separate types of documentation. Scripts,

however, are often written by people for their personal use, or for use by their colleagues. In

these situations, the user and technical documentation may be integrated in the script source

code prolog.

Read-me files

Script code that is distributed or made available for others to use is often accompanied by a

‘read-me’ file, which is typically a text file or HTML file.

The read-me file is aimed at the installers and users of the script. Its purpose depends on the

nature and complexity of the code being distributed. For instance, read-me files may contain:

> version and licence information

> system requirements

> installation and upgrade notes

> operating system information

> location and installation or access to documentation

> new features for upgraded software

> code corrections or ‘bug fixes’

> trouble-shooting advice.

For simple scripts, a read-me file would often contain a usage statement and may include

required inputs, and perhaps a description of the expected output.

Usage statements

It is also quite useful to include a usage statement in your script for when the user incorrectly

uses the script by typing invalid input or omitting input.

Rather than exiting the script without any messages explaining what occurred, you should

display a simple usage statement, and perhaps an example showing how the script is used.

Page 110: ICTPRG405 Automate Processes - WordPress.comExpressing algorithms . Described below are two common ways to express the structure of an algorithm: 1 Pseudo code 2 Flowcharts . Pseudo

104 | P a g e I C T P R G 4 0 5 _ L G _ V 1 T A F E n o w

JavaScript example of feedback to user

Usage: Specify the input box to validate.

Syntax: validate name

JavaScript code example

Usage: Specify the input box to validate.

Syntax: validate(inputbox)

if (inputbox) == ”” alert(‘no entry provided’);

Input prompts

When appropriate, users should be guided with meaningful dialogue in the form of

informative prompts for data entry requirements.

A prompt describing the type of data expected, or describing the data, is more useful than

one that does not.

Consider the following prompts:

Enter the filename (including extension) and press enter:

and

file? :

Although an experienced user may guess in the second example that ‘file’ would imply

including the file extension, for the sake of novice users it is better to be specific.

Progress messages

Progress messages are information messages that are generated by a script when important

steps in complex processing are complete. This is particularly useful for scripts that perform

complex operations that interact with other applications and/or the operating system, and for

scripts that may take some time to complete the required tasks. This can be done with alerts.

Page 111: ICTPRG405 Automate Processes - WordPress.comExpressing algorithms . Described below are two common ways to express the structure of an algorithm: 1 Pseudo code 2 Flowcharts . Pseudo

105 | P a g e I C T P R G 4 0 5 _ L G _ V 1

T A F E n o w

JavaScript example

// Provide progress info to user if sys.argv[1] == '/v'

If (errors ==0)

alert(‘ form completed sucessfully’);

// Code to submit form

Error messages

Error messages are generated by a script in the event of a problem that prevents the script

from performing or completing the required task(s). You should try to be as specific as

possible when writing error messages.

Installation guides

Installation guides are usually provided for more complex systems that rely on script code files

and/or data files being located in a specific folder structure. They may be in the format of

documents rather than text, as they may include screen shots or other graphical elements to

assist in guiding the installer through the installation process.

Some systems may also require registration with the operating system through the

creation/modification of registry entries in the Windows operating system and the

creation/modification of .ini and other configuration files.

How-to and FAQ files

How-to and FAQ (frequently asked questions) files are usually a short description of how to

accomplish a specific task. They are often provided when there are many scripts associated

with a scripted application, or a large number of switches or parameters associated with a

single script. They are typically aimed at non-experts and provide information to perform a

single function.

Page 112: ICTPRG405 Automate Processes - WordPress.comExpressing algorithms . Described below are two common ways to express the structure of an algorithm: 1 Pseudo code 2 Flowcharts . Pseudo

106 | P a g e I C T P R G 4 0 5 _ L G _ V 1 T A F E n o w

Worked Example

This is example 9 from the previous notes section

//-------------------------------------------------------------

// This code creates a small house image of the canvas

// Initialise the canvas

// A simple use of the canvas to create a small house image

// Author J.Chapman

// Date 3/9/2012

// Version 1.1

// Requires no inputs

// All functions use raw data

//---------------------------------------------------------

c = document.getElementById("myCanvas");

con = c.getContext("2d");

con.strokeStyle = 'black';

// Draw the wall 70 pixels wide, 50 high at 300,300

con.fillStyle = 'blue';

con.fillRect(300, 300, 70, 50);

// move to the roof

con.moveTo(300, 300);

// Draw the roof

con.fillStyle = 'red';

// Roof peak will be 35 * sqrt (2) above the wall

con.lineTo(335, 300 - 35 * Math.sqrt(2));

// join to the other corner of the wall

con.lineTo(370, 300);

con.fill();

con.fillStyle = 'yellow';

Page 113: ICTPRG405 Automate Processes - WordPress.comExpressing algorithms . Described below are two common ways to express the structure of an algorithm: 1 Pseudo code 2 Flowcharts . Pseudo

107 | P a g e I C T P R G 4 0 5 _ L G _ V 1

T A F E n o w

// Door is 10 x 30 so top left corner of the door is 330,320

con.fillRect(330, 320, 10, 30);

SELF CHECK CHECK 4

Check your understanding:

> I can document program code

> I can create ReadMe files

Page 114: ICTPRG405 Automate Processes - WordPress.comExpressing algorithms . Described below are two common ways to express the structure of an algorithm: 1 Pseudo code 2 Flowcharts . Pseudo

108 | P a g e I C T P R G 4 0 5 _ L G _ V 1 T A F E n o w

Answers to Activities Activity 1

Pick up fork

Pick up knife

Hold steak with fork tines

Draw knife across steak making a cut

Activity 2

Read number

IF (number is divisible by 4) THEN

PRINT “Divisible by 4”

END IF

IF (number is divisible by 2) THEN

PRINT “Divisible by 2”

ELSE

PRINT “Odd”

END IF

Page 115: ICTPRG405 Automate Processes - WordPress.comExpressing algorithms . Described below are two common ways to express the structure of an algorithm: 1 Pseudo code 2 Flowcharts . Pseudo

109 | P a g e I C T P R G 4 0 5 _ L G _ V 1

T A F E n o w

Activity 3

a)

FOR x = 24 to 68 step 6

Print x

NEXT

b)

x = 20

Found = false

WHILE not found

IF x is divisible by 6 then

Found = true

ELSE

Add 1 to x

END IF

END WHILE

WHILE x < 70

PRINT x

Add 6 to x

END WHILE