Doc-20230511-Wa0066 250815 213345
Doc-20230511-Wa0066 250815 213345
P per 2
Z in Merch nt
a
a
a
The use of algorithms
Consider what is meant by an algorithm. If you search for algorithm then you will nd
Zain Merchant
answers such as a process, or a set of rules, that are followed. This does not mean they
are limited to computers. You can nd algorithms in all areas of life. You will have
followed many of these without even considering that they are algorithms. For example,
in mathematics you will have followed a series of steps to solve a problem.
Algorithms can take many forms, and use a variety of words or structures.
Computers follow algorithms. Programs are written as a series of instructions that the
computer then follows. Algorithms for software might be millions of lines long, and they
have to make use of speci c instructions to tell the processor what to do.
A computer can only run machine code, that is binary. If you enter a command into the
computer, this has to be converted into binary for the processor to execute (run) it.
2
fi
fi
fi
Program development life cycle
When a person, or organisation, creates a new computer program they will use a
Zain Merchant
structured, organised plan of how to create the program. This is called the program
development life cycle.
There are several varieties of life cycle, including cyclic, spiral, waterfall and rapid
development. These all include the stages analysis, design, coding and testing.
An lysis
This rst stage involves looking at the problem and the system that is needed. The
problem is explored, and the requirements of the program are identi ed. Decomposition
is used to split the problem into subproblems. Subproblems allow the developers to
identify the requirements for each component part, and then tackle these separately in
the next stage. Once you have decomposed the problem, each of the subproblems can be
implemented as a subprogram.
Abstraction keeps the key elements required for the solution to the problem and discards
any unnecessary details and information that is not required. For example, a map only
shows what is required for traveling from one place to another. Di erent methods of
transport will require di erent types of map.
3
fi
a
ff
ff
fi
Design
Once the requirements have been identi ed, the program designers can begin planning
Zain Merchant
how the program will work in the design phase. This can include an overview of the
program using a structure diagram, and the designing of algorithms using owcharts and
pseudocode.
Coding
Once you have decomposed your problem into subproblems, and you have designed the
algorithms using owcharts and/or pseudocode then you can start writing the program in
your chosen programming language. This is often referred to as coding.
This will also include some iterative testing. This is testing that is carried out while the
program is being developed, for example, if you write the program code for one of the
subproblems, then you will test it with a range of di erent data to make sure it is fully
working before moving onto the next step.
Testing
When you have nished your program, you need to carry out testing to make sure it:
• fully works
4
fi
fl
fi
ff
fl
Structure diagram
A structure diagram is developed by decomposing a program into its subprograms. The
Zain Merchant
diagram has the name of the program at the top, and below this its subprograms. Each
subprogram can be split down further as well if required.
Ex mple 1
A calculator needs to allow the user to enter numbers and the symbol, calculate the result
and output this.
The name of the program is at the top. The boxes below are ready for subprograms
One way of splitting up a small program is to think of inputs, processes and outputs. A
calculator
has an input, processes and output, so these can be added to the diagram
5
a
The subprograms can then be split further. The calculator needs two numbers and a
Zain Merchant
The process. is dependent on the symbol entered. In this calculator, there is +, − , * and /.
Each of these could be given a separate box
6
Or the variable names from the input can be used
Zain Merchant
Both of these are valid. There are lots of ways you can decompose a problem, and
everyone could do it slightly di erently but the solution is still valid.
7
ff
This program was fairly small, so it has been split into very precise instructions that can
Zain Merchant
A computerised version of chess is being developed. Two players can enter their names
and then a new board will be displayed. The players take it in turns to select pieces to
move and the positions to move them to. The program will check that the moves are valid
and then move the pieces. It will remove any pieces that have been taken in each move,
and check if anyone has reached checkmate.
Ex mple 2
The name of the program is at the top
The program could be decomposed into inputs, processes and outputs, but this is a large
program so it can be split down by di erent functions instead. The rst part is that there
are two players who need entering, this is given the name ‘New players’. Then the game is
set up (‘New game’). The players can then move their pieces (‘Make move’). The program
will check if someone has checkmate (‘Check won’)
8
a
ff
fi
These can then be split further. They are each given their own sub-diagram here so that
Zain Merchant
they are easier to view
9
Checkpoint
1. Describe the process of decomposition.
2. A program asks the user to enter two numbers. The program then adds the numbers
together and outputs the total. Draw a structure diagram for the program.
Zain Merchant
3. A satellite navigation system needs to ask the user to input their destination. It then
nds the route to the destination and outputs the instructions to the user. Draw a
structure diagram for the system.
4. A login system asks the user to enter their username and password. It checks these are
valid and either outputs that they are correct, or incorrect and prompts to re-enter.
Draw a structure diagram for the system.
10
fi
11
Zain Merchant
Flowcharts
A owchart shows diagrammatically the steps required to complete a task and the order
Zain Merchant
that they are to be performed. These steps, together with the order, are called an
algorithm. Flowcharts are an e ective way to communicate how the algorithm that makes
up a system or sub-system works.
St rt/stop
Description Example
12
fl
fl
fl
a
ff
Flowcharts
Input
Description Example
Zain Merchant
A single input of a value with an identi er
for that value.
Output
Description Example
13
fi
fi
Process
Description Example
Zain Merchant
Decision
Description Example
= equal to
> greater than < less than
>= greater than <= less than.
= equal to
> greater than < less than
>= greater than <= less than.
Zain Merchant
15
fl
a
Ex mple 2
A owchart for a password validation program.
Zain Merchant
16
fl
a
Ex mple 3
Tickets are sold for a concert at $20 each, if 10 tickets are bought then the discount is
Zain Merchant
10%, if 20 tickets are bought the discount is 20%. No more than 25 tickets can be bought
in a single transaction.
This is owchart showing an algorithm to calculate the cost of buying a given number of
tickets:
17
a
fl
Checkpoint
1. Write the name of each owchart symbol in the shape.
Zain Merchant
• Start
• INPUT x
• INPUT y d IS x > y?
• x = x +y
• Stop
3. Draw a owchart to take three numbers as input, nd and output the largest number.
18
fl
fl
fl
fi
19
Zain Merchant
Pseudocode
Pseudocode refers to any code that is not written on a computer to run. There is no one
Zain Merchant
set pseudocode, because if there was then this would be code with a speci c language.
Instead it’s a term for any readable code-like statements that all programmers will
understand. This means that it uses keywords, and constructs such as IF statements,
WHILE loops, etc. These constructs occur in almost all languages, so any programmer
would be expected to read them and translate them into the actual programming
language they are using.
Example pseudocode:
INPUT Number1
IF Number1 < 10 THEN
OUTPUT "too small"
ELSE
OUTPUT "valid"
ENDIF
This uses the keywords INPUT, IF and OUTPUT. These can then be translated into
whatever language the programmer is using.
There are many di erent valid pseudocode formats. Some will always use capitals for the
commands, e.g. INPUT, IF, FOR. Some will use ← instead of an = for assignment. If you
write your pseudocode in almost perfect ‘code’, i.e. you actually write Python code,
because it is not to be run and you can have all sorts of syntax errors it is still
pseudocode. What is important is that the program is split into steps that can be easily
converted into a real program.
20
ff
fi
Testing
You will need to identify appropriate test data to use to test the program. There are four
Zain Merchant
types of test data:
• Boundary– data that is on the edge of being accepted and being rejected.
Example 1
A program allows the user to enter their age as a whole number between 10 and 100 years.
21
Example 2
Zain Merchant
22
Checkpoint
1. Identify three di erent types of test data.
2. Why can you have the same test data as normal and extreme types of test data?
Zain Merchant
3. What is the di erence between extreme and boundary test data?
Normal
Abnormal
Extreme
Boundary
23
ff
ff
Zain Merchant
24
Programming concepts
V ri bles nd const nts
What are variables and constants?
Zain Merchant
When you are writing a program, you will need to store data; whether this is data that has
been input, the result of calculations or any for any other reason. You can store data in
variables and constants.
A computer has memory, e.g. RAM. This is made of lots of spaces where you can put data.
Imagine this table is memory. Each of the boxes can store a piece of data.
In memory location 0 is the data 10. In memory location 1 is the data red.
25
a
a
a
a
Each variable and constant is one of these spaces in memory that is given an identi er (it
Zain Merchant
has a name). In this table the memory numbers have been replaced with their identi ers.
The memory space with the name number1 is storing the piece of data 10.
Variables and constants have one di erence. In a variable, you can change the data while
the program is running. For example, putting the number 30 into memory location
number1, the memory would then look like this:
26
ff
fi
fi
A constant cannot have its value changed while the program is running. When you
Zain Merchant
declare a constant you put a value into it and this cannot be changed.
Using variables
Putting data into a variable is done using an assignment statement. The left hand side of
the equals sign is the identi er. The right hand side of the equals sign is the value
Number ← 10
Colour ← "red"
Price ← 22.2
Number ← 10
Colour ← "red"
OUTPUT(Number)
OUTPUT("The colour is ", Colour)
Price ← Number * 2
27
fi
fi
Using constants
Zain Merchant
Before you use a constant in your program you need to give it a value. This is an
assignment statement the same as a variable. (No examples are given for Python as it
does not have in-built constants.)
28
D t types
Data in programs can be of di erent types. For example, it could be numeric or text. You
Zain Merchant
will need to tell your program what type of data you want it to store. Some programming
languages need you to declare what type of data your variable will store when you rst
use it.
STRING "123"
The data will always need to
be inside speech marks,
"help!"
either ' ' or " ".
-300
1.2
-20.49
TRUE
BOOLEAN Either true or false.
FALSE
CHAR ‘9’
The data will always need to
be inside speech marks,
‘?’
either '' or "".
29
a
a
ff
fi
Storing di erent data types
Zain Merchant
30
ff
Converting between d t types
You might need to turn one data type into another data type. This is not required as part
Zain Merchant
of the speci cation, but when you are programming in your chosen language you might
have to do it for your program to work. This is called casting. You can do this by using the
name of the data type you want the data to become.
Example 1
Example 2
31
fi
a
a
Checkpoint
1. Tick one or more boxes in each row to identify whether each statement refers to
variables and/or constants.
It is a memory location.
32
fi
Output
A program at some point will probably need to give information to the user. It does this
Zain Merchant
using output. When outputting strings (characters, letters, etc.).
Example 1
Example 2
If you want to output more than one piece of data then you can join them using a
concatenation symbol. Concatenation means join together, so it joins multiple pieces of
data together. This could be a comma (,), an ampersand (&) or a plus (+) depending on
your language. All are acceptable in pseudocode.
Example 1
Example 2
Example 3
33
Input
A program might need the user to enter (input) some data. To do this, the command
Zain Merchant
word INPUT is used. This cannot appear on its own, otherwise the data entered will
disappear into space. So you need to do something with it, for example, store it in a
variable.
Example 1
Example 2
34
Arithmetic oper tors
Operator Description Example
Zain Merchant
10+2 gives12
+ Adds two values together.
11.3 + 9 gives 20.3
10 - 2 gives 8
Subtracts the second value
-
from the rst.
11.3 - 9 gives 2.3
10 / 2 gives 5
Divides the rst number by
/
the second.
11.3 / 9 gives 1.256
2^3=8
^ Power of.
3^2=9
MOD has one special use in programming. It can be used to work out if a number is odd
or even. If you perform MOD 2 to a number and it returns 0 then it is even, if it returns 1
then it is odd.
35
fi
fi
fi
fi
a
Checkpoint
1. Calculate the result for each of these equations:
• DIV(9, 2)
•
Zain Merchant
DIV(17, 3)
• MOD(9, 2)
• MOD(17, 3)
36
Example 1
Zain Merchant
Taking two numbers as input and adding them together:
OUTPUT("Enter the rst number")
INPUT Num1
OUTPUT("Enter the second number")
INPUT Num2
Total ← Num1 + Num2
Example 2
Example 3
Example 4
Dividing 100 by 5:
Number1 ← 100
Number2 ← 5
Result ← Number1 / Number2
37
fi
Example 5
Zain Merchant
Example 6
Example 7
Total ← 1 + (2 * 3)
Total ← (1 + 2) * 3
The rst line will result in 7 (3 * 2 = 6 + 1 = 7). The second line will result in 9 (1 + 2 = 3 * 3 =
9).
38
fi
Sequence
Sequence is the rst of three constructs within programs. A sequence is a series of
Zain Merchant
statements that are executed (run) once, in the order they are written.
Example 1
OUTPUT("Enter a colour")
INPUT Colour
OUTPUT("Enter your name")
INPUT Name
OUTPUT(Name , " your favourite colour is " , Colour)
This is a sequence. It has 3 lines are executed once, and in the order they are written (line
1, then 2 then 3).
Example 2
X←1
Y←2
Z←3
Total ← X + Y + Z
OUTPUT("Enter the rst value")
INPUT Value1
39
fi
fi
Checkpoint
1. Give the result from the following calculations:
• 10 + 20
•
Zain Merchant
20 / 2
• 100 * 4
• 50 - 15
• 20 DIV 2
• 39 DIV 6
• 20 MOD 2
• 40 MOD 6
2. Write a program to take a number as input, multiply it by 2 and output the result.
3. Write a program to store the numbers 10 and 12 in constants, add them together and
then output the result.
4. Write a program to ask a user to enter their age and name, then output a message
that uses both values, e.g. Hello Suzie you are 15 year old.
40
41
Zain Merchant
Selection
Selection is the second of the three constructs. In selection a condition is checked and
Zain Merchant
this determines which, if any, code is run. There are two forms of selection, IF statements
and CASE statements.
Conditions need logical operators. These allow for comparisons to be made. Table
describes these di erent operators. Each statement using a logical operator results in
TRUE or FALSE.
Logical
Description Example
Operator
< Less than 10 < 10? would give FALSE. 10 is not less than 10.
Less than or
<= 10 <= 10? would give TRUE. 10 is less than or equal to 10.
equal to
11 <= 10? would give FALSE. 11 is not less than or equal to 10.
42
ff
Logical
Zain Merchant
Description Example
Operator
> Greater than 10 > 10? would give FALSE. 10 is not greater than 10.
43
IF st tements
The command IF is followed by a condition that is created using the logical operators.
Zain Merchant
IF has one comparison and the code inside the IF will only run if that condition is True. If
it is not true, the code in the IF statement will not run.
Example 1
This program will check the value in the variable num1 is equal to 10. If it is, it will output
the word True.
Num1 ← 10
IF Num1 = 10 THEN
OUTPUT("True")
ENDIF
Example 2
This program will check if the value input is greater than the one stored in the variable.
OUTPUT("Enter a number")
INPUT ValueInput
StoredValue ← 100
IF ValueInput > StoredValue THEN
OUTPUT("It is more than 100")
ENDIF
44
a
ELSE
This is added within an IF statement. If the IF statement’s condition is false then the ELSE
Zain Merchant
will
run. You can only ever have one ELSE in an IF statement. ELSE follows the structure:
IF comparison THEN
Statements that run if the comparison is true
ELSE
Statements that run if the comparison is false
ENDIF
Example 1
In this example if the two values are the same it outputs "That's correct". If they are not
the same then the ELSE runs, it will output "Incorrect".
Num ← 10
OUTPUT("Enter a number")
INPUT Guess
IF Num = Guess THEN
OUTPUT("That's correct")
ELSE
OUTPUT("Incorrect")
ENDIF
Example 2
In this example, it will output the smallest number, or one of the numbers if they are both
the same.
Value1 ← 10
Value2 ← 20
IF Value1 < Value2 THEN
OUTPUT(Value1)
ELSE
OUTPUT(Value2)
ENDIF
45
ELSEIF
This allows for a second condition to be used within the same IF statement. If the rst
Zain Merchant
Example 1
This will output which number is greater, or nothing will output if they are the same.
Num1 ← 10
Num2 ← 20
IF Num1 < Num2 THEN
OUTPUT(Num2)
ELSEIF Num2 < Num1 THEN
OUTPUT(Num1)
ENDIF
46
fi
Example 2
Zain Merchant
This uses ELSEIF and an ELSE to output the largest number.
IF Num1 > Num2 THEN
OUTPUT(Num1)
ELSEIF Num2 > Num1 THEN
OUTPUT(Num2)
ELSE
OUTPUT("They are the same")
ENDIF
Example 3
47
CASE st tements
A SELECT CASE statement allows the program to take one variable or value, and then
Zain Merchant
A case can have as many CASE statements as needed, but can only ever have a maximum
of one default (this runs if none of the comparisons are true).
Example 1
Using a SELECT CASE to output a grade for an in-lesson test. (No example is given for
Python as it does not have a CASE construct and no example is given for Java as it does
not support switch statements with comparisons, e.g. < or >.)
Score ← INPUT("Enter score")
CASE OF score:
>=80: OUTPUT ("A")
>=70: OUTPUT("B")
>=60: OUTPUT("C")
>=50: OUTPUT("D")
OTHERWISE OUTPUT("U")
ENDCASE
48
ff
a
Example 2
Zain Merchant
Output a message depending on which number is entered. (No example is given for
Python as it does not have a CASE construct.)
OUTPUT("Enter a number, 1 to 5")
INPUT Choice
CASE OF Choice:
1: OUTPUT("Menu option 1")
2: OUTPUT("Menu option 2")
3: OUTPUT("Menu option 3")
4: OUTPUT("Menu option 4")
5: OUTPUT("Menu option 5")
OTHERWISE OUTPUT("Invalid choice")
ENDCASE
49
Boole n oper tors
There are three Boolean operators that you can use to join conditions: the AND operator,
Zain Merchant
Boolean
Description Example
Operator
IF 1 = 1 AND 2 = 2
If both This will return TRUE. The left of the AND is true, and the
conditions
are true, the
right of the AND is true. IF 1 = 1 AND 1 > 2
result is true.
This will return FALSE. The left of AND is true, but the right
AND If one or
of AND is false.
both
conditions
IF 1 < -2 AND 0 < -1
are false, the
result is
false. This will return FALSE. Both comparisons are false, so the
result is false.
IF 1 = 1 OR 2 = 2
If one, or This will return TRUE. The left of the OR is true, and the
both,
conditions right of the OR is true.
are true, the
result is true. IF 1 = 1 OR 1 > 2
OR This will return TRUE. The left of OR is true, but the
If both
conditions right of OR is false.
are false, the IF 1 < -2 OR 0 < -1
result is
false. This will return FALSE. Both comparisons are false, so the
result is false.
50
a
a
Boolean
Zain Merchant
Description Example
Operator
IF NOT(1 = 1)
Reverse the The brackets equal to TRUE, 1 equals 1. The NOT makes
condition. If
the it FALSE, so it becomes 1 does not equal 1. IF NOT (End of
NOT condition is File)
True it
becomes This is used with le handing. End of File will return TRUE if
False. there is no data left in the le. The NOT turns this to false.
So while not at the end of the le.
51
fi
fi
fi
Example 1
Zain Merchant
This will output the rst message if both test marks are greater than or equal to 90. If only
one mark is greater than or equal to 90 then the second message will output.
OUTPUT("Enter the mark for test 1")
INPUT Mark1
OUTPUT("Enter the mark for test 2")
INPUT Mark2
IF Mark1 >= 90 AND Mark2 >= 90 THEN
OUTPUT("Well done you got top marks on both tests")
ELSEIF Mark1 >= 90 OR Mark2 >= 90 THEN
OUTPUT("Well done you got top marks on one of the tests")
ELSE
OUTPUT("You didn't quite get top marks on the tests, try
again next time")
ENDIF
Example 2
52
fi
Checkpoint
1. Describe what is meant by selection.
Zain Merchant
3. Write a program that takes two numbers as input and outputs the largest.
4. Write a program that outputs a question (e.g. a maths question), takes an answer from
a user and outputs if they are correct or not.
5. Ask the user to input a colour. The program should then output a di erent message if
the user enters the word "yellow", "green" or "blue". If neither of these are entered, the
program should output a di erent message. Use a CASE statement.
53
ff
ff
ff
Zain Merchant
54
Iteration
An iteration or loop is a programming construct where statements are run either a nite
Zain Merchant
number of times, until a condition is true or while a condition is true.
Count-controlled
This type of loop uses a counter to run a set number of times. The most common count-
controlled loop is the for loop. This has the structure:
FOR variable ← start value TO endvalue
Code that runs repeatedly
NEXT variable
The loop will run from the start value to the end value, increasing by 1 each time. If the
start value is 1 and the end value is 10, it will run 10 times (1, 2, 3, 4, 5, 6, 7, 8, 9 and 10).
Example 1
55
fi
Example 2
Zain Merchant
Example 3
You can change the amount that you increase the variable by each time you loop. This is
by using STEP. STEP 1 will increase the counter by 1 each time. STEP -1 will decrease the
counter by 1 each time. STEP 0.5 will increase the counter by 0.5 each time.
Example 1
Example 2
Output the numbers from 11 to 20, increasing by 0.5 each time. (No example is given for
Python as it does not support stepping in decimals.)
FOR Value ← 11 TO 20 STEP 0.5
OUTPUT(Value)
NEXT Value
56
fi
Pre-condition
A pre-condition loop tests the condition before starting the loop. This means that if the
Zain Merchant
condition is false, the code inside the loop will not run. It loops while the condition is
true. It stops looping when the condition is false.
Example 1
Example 2
57
Example 3
Zain Merchant
Asking the user to enter a number until they guess the stored number correctly:
Number ← 5
Guessed ← FALSE
WHILE Guessed = FALSE DO
OUTPUT("Guess the number")
INPUT Guess
IF Guess = Number THEN
Guessed ← TRUE
ENDIF
ENDWHILE
58
Post-condition loop
A post-condition loop runs the code inside the loop once, and then checks the condition
Zain Merchant
at the end of the loop. This means that the code will always run once.
In this case it continues until the Condition becomes True. It loops while the condition is
False.
Example 1
Looping until the user enters Yes. (No example is given for Python as it does not have an
in-built post-condition loop.)
REPEAT
OUTPUT("Do you want to stop?")
INPUT Answer
UNTIL Answer = "Yes"
Example 2
Outputting the numbers 1 to 10. (No example is given for Python as it does not have an in-
built
post-condition loop.)
Number ← 1
REPEAT
OUTPUT(Number)
Number ← Number + 1
UNTIL Number > 10
59
Example 3
Zain Merchant
Asking the user to enter a number until they guess the correct number.
NumberToGuess ← 15
REPEAT
OUTPUT("Guess the number")
INPUT Guess
UNTIL Guess = NumberToGuess
60
Checkpoint
1. Describe the di erence between a pre-condition and post-condition loop.
2. A program needs a loop that will run 50 times. Which type of loop would be most
appropriate?
Zain Merchant
3. Write a program to output the numbers 100 to 200.
4. Write a program to output the 5 times table (from 5 times 1, to 5 times 12).
5. Write a program to ask the user to enter a number continually, until they enter the
number 10, using a post-condition loop.
6. Write a program to output the word “Hello” until the user enters the word “stop”,
using a pre-condition loop.
61
ff
Zain Merchant
62
Totalling
Totalling is adding together a set of values. To write a program to total you need to:
Zain Merchant
• Initialise the total to 0.
Example 1
Asking the user to enter 10 numbers and totalling them:
Total ← 0
FOR Counter ← 0 TO 10
OUTPUT("Enter a number”)
Total ← Total + INPUT
NEXT Counter
OUTPUT("The total is " & Total)
Example 2
63
Counting
Counting is working out how many of something there are. For example how many
Zain Merchant
numbers were entered that were over 10. To write a program to count you need to:
Increment (add one to) the counter each time an item is entered, or found.
Example 1
Count how many numbers the user enters until they say to stop:
Count ← 0
Continue ← "Yes"
WHILE Continue = "Yes" DO
OUTPUT("Do you want to continue?")
INPUT Continue
Count ← Count + 1
ENDWHILE
OUTPUT("You continued " & Count - 1 & " times")
Example 2
Count how many numbers in an array of 100 elements are more than 50:
Count ← 0
FOR X ← 0 TO 99
IF ArrayData[X] > 50 THEN
Count ← Count + 1
ENDIF
NEXT X
64
Checkpoint
1. What are the two required elements for a totalling program.
Zain Merchant
3. Write a program to ask the user to input 100 numbers, total the values and output the
total.
4. Write a program to ask the user to input numbers. Count how many numbers are less
than 100, and how many are more than or equal to 100. Stop when the user enters the
number 0.
65
Zain Merchant
66
String manipulation
A string is a piece of text. This could be made up of characters, numbers and/or symbols.
Zain Merchant
There are lots of di erent string manipulators that you can use; these let you alter strings,
nd values in strings, etc. The two you need to know are length and substring.
Length
This command will return the number of characters in a string. It has the structure:
LENGTH(string).
Example 1
LENGTH("hi")
would return 2.
Example 2
LENGTH("0123")
would return 4.
Substring
This command will return some of the characters in the string. It has the structure:
Example 1
Using substring:
SUBSTRING("Hello", 0, 1)
This will start at character 0 and take 1 character. It will return "H".
67
fi
fi
ff
Example 2
Zain Merchant
Using substring:
SUBSTRING("Goodbye", 4, 3).
This will start at character 4 and take 3 characters. It will return "bye".
Example 3
Example 4
Example 5
Output each letter of a string one character at a time. Depending on your language, the
stopping condition might be the length, or the length −1 depending on whether the rst
character is 0 or 1.
OUTPUT("Enter a message")
INPUT StringInput
FOR Count ← 0 to LENGTH(StringInput) - 1
Character ← SUBSTRING(StringInput, Count, 1)
OUTPUT(Character)
NEXT Count
68
fi
fi
Example 6
Zain Merchant
Output the last 3 characters in a string:
OUTPUT("Enter a message")
INPUT StringInput
NewString ← SUBSTRING(StringInput, LENGTH(StringInput) - 3, 3)
OUTPUT(NewString)
Upper nd lower
The characters a–z can be converted into uppercase and the characters A–Z can be
converted into lowercase. This can be done to an individual character, or to an entire
string at the same time. If a character is already in upper case, trying to convert it to
upper case will not change it.
UPPER(string) LOWER(string)
Example 1
69
a
Nested statements
A nested statement is one or more selection and/or iteration statements inside another
Zain Merchant
The position of the start and end of these constructs are important. If, for example, a
loop starts inside an IF statement, the loop must also nish inside the same IF statement.
Example 1
Count how many numbers entered are more than 10, and how many are equal to 10:
MoreThan10 ← 0
EqualTo10 ← 0
FOR X ← 0 TO 99
OUTPUT("Enter a number")
INPUT Number
IF Number > 10 THEN
MoreThan10 ← MoreThan10 + 1
ELSEIF Number = 10 THEN
EqualTo10 ← EqualTo10 + 1
ENDIF
NEXT X
70
fi
Example 2
Zain Merchant
Loop counting how many values in an array are more than or equal to 100, and then stop
counting:
Number ← 0
Count ← 0
WHILE Number < 10 DO
DataInArray ← ArrayData[Count]
Count ← Count + 1
IF DataInArray >= 100 THEN
Number ← Number + 1
ENDIF
ENDWHILE
Example 3
This has a FOR loop inside an IF, and another IF inside the FOR loop.
71
Checkpoint
1. Give one example of a nested statement.
4. Write a program to take a string input from the user, count out how many numbers
are in the string and output the count.
72
73
Zain Merchant
Subroutines
A subroutine is a self-contained piece of code that has an identi er (name), and it can be
Zain Merchant
When you decompose a problem into sub-systems, each of the sub-systems can be
written as an individual subroutine. You can then call that subroutine when you need to
use it.
Subroutines are useful because they reduce code. You write the subroutine once, and
then you can call it as many times as you need to, instead of having to re-write it every
time. Each time you re- write it there is a chance of an error, so this reduces the chances
of this error.
There are two types of subroutine: procedures and functions. A function returns a value
to the program that called it. A procedure does not return a value.
Procedures and functions can both take one or more values as parameters. These are
values that are sent to the subroutine. Parameters will be introduced after the basics of
procedures and functions.
74
fi
Procedures
A procedure runs the code inside it, and does not return a value. The structure of a procedure is:
Zain Merchant
PROCEDURE identi er()
code to run inside the function
ENDPROCEDURE
Example 1
The main program can then call the procedure with the code:
Output1To10()
Example 2
A procedure to take two numbers from the user and multiply then together:
PROCEDURE Multiply()
OUTPUT("Enter a number")
INPUT Num1
OUTPUT("Enter a second number")
INPUT Num2
Total ← Num1 * Num2
ENDPROCEDURE
The procedure can be called in the main program with the code:
multiply()
75
fi
fi
Function
A function returns a value to the program that called it. This can be by either using the
Zain Merchant
RETURN command, or saving a value to the function’s identi er. Once a value is returned,
the function stops running, so it cannot have any code after otherwise this will not run.
When the function is called it returns a value, so something needs to happen with this
value. It could be output, e.g.
OUTPUT(function identi er)
Example 1
Write a function to ask the user to enter two values, add them together and return the
value:
FUNCTION Multiply()
OUTPUT("Enter a number")
INPUT Num1
OUTPUT("Enter another number")
INPUT Num2
RETURN Num1 * Num2
ENDFUNCTION
76
fi
fi
fi
fi
fi
Example 2
Zain Merchant
Write a function to total all the values in an array with 50 elements and then return the
total:
FUNCTION TotalValues()
Total ← 0
FOR X ← 0 TO 49
Total ← Total + Array[X]
NEXT X
RETURN Total
ENDFUNCTION
Scope
The scope of a variable is the areas within a program that it can be accessed. There are
two scopes: global and local.
If you declare a variable (or constant, or array) as global then it means it can be accessed
by any part of the program. That includes the main program and any subroutines. In
most languages this means declaring it at the top of the program.
77
Example 1
Zain Merchant
Declaring a global variable, then outputting its value twice. Once in the main program,
and once in a procedure call call.
GLOBAL Data
PROCEDURE OutputData()
OUTPUT(Data)
ENDPROCEDURE
//main program
Data ← 1
OUTPUT(Data)
OutputData()
If you declare a variable (or constant, or array) as local, then it can only be accessed in
the part of the code where it is declared. If you declare it rst in a subroutine, then it can
only be accessed within that subroutine. If you declare it in the main program, it can only
be accessed in the main program.
Example 2
Creating a local variable to the main program and outputting it twice. Once in the main
program, and once from a subroutine where it is sent as a parameter.
PROCEDURE OutputData(DataParameter)
OUTPUT(DataParameter)
ENDPROCEDURE
Data ← 1
OUTPUT(DataParameter)
OutputData(Data)
78
fi
P r m ters
A parameter is a value that is sent from the main program to the subroutine (procedure or
Zain Merchant
function). Parameters are declared inside the brackets after the subroutines name, e.g.
PROCEDURE identi er(parameter1, parameter2 ...) ENDPROCEDURE
or
FUNCTION identi er(parameter1, parameter2 ...) ENDFUNCTION
If a subroutine is declared with parameters, then it must be called with the same number
of parameters. For example:
PROCEDURE Total(Num1, Num2)
ENDPROCEDURE
This has two parameters. When the procedure is called it must have 2 numbers sent to it.
This could be numbers, e.g.
Total(1,2)
or variables. e.g.
Total(Number1, Number2)
Example 1
A function takes two numbers, divides them and returns the result:
FUNCTION Division(First, Second)
RETURN First / Second
ENDFUNCTION
The main program sends 10 and 2, then outputs the return value.
OUTPUT(Division(10, 2))
79
a
a
a
fi
fi
Checkpoint
1. What is the di erence between a function and a procedure?
Num1 ← Num1 * 2
Num2 ← Num2 + Num1
RETURN(Num1 + Num2)
ENDFUNCTION
4. Write a program statement to call the following function with the parameter 100 and
output the return value.
FUNCTION FindValue(Number)
Number ← Number + INPUT
RETURN Number
ENDFUNCTION
5. Write a procedure to take three numbers as parameters and output the largest.
6. Write a function that takes two strings as parameters. It takes the rst 3 characters of
each string and combines them, returning the resulting string.
80
ff
fi
81
Zain Merchant
Library routines
A program library is a set of subroutines that are pre-written and that can be called within
Zain Merchant
a program.
In some programming languages the operators for MOD and DIV are library functions. In
other programming languages they are just operators. For example, 2 MOD 4 is the same
as MOD(2, 4).
Two other library routines that you need to know are ROUND and RANDOM.
ROUND
This will take a real number (decimal) and limit how many numbers there are after the
decimal point.
For example ROUND(10.123, 1) will take the number 10.123 and only leave 1 number after the
decimal point, returning 10.1.
ROUND(4.8293, 2)
82
RANDOM
This will generate a random number between two values that it takes as parameters. For
Zain Merchant
example,
RANDOM(10, 20)
83
Maintainable programs
When you write a program there are several things to take into consideration to make it a
Zain Merchant
maintainable program. This is so that when you come back to it in a week, or a year, you
can still understand what all of the code does. It might be you are writing a program that
someone else needs to understand, so you need to make it understandable to someone
who does not know what the program does.
The identi ers for subroutines are usually descriptions of their function. For example, a
procedure to output the numbers 1 to 10 could be called Function1, but then there is no
indication of what it does. Instead, it could be called Output1To10.
Comments
A comment is a description of a line of code, or section of code. To write a comment you
use a special character or characters, for example, //. This tells the program not to
execute the text after this symbol.
You do not need to comment every line of code, for example, the statement Count = 0
does not need commenting, it is clear that it is storing 0 in the variable count.
Example 1
84
a
fi
fi
f
fi
Example 2
Zain Merchant
OUTPUT("Enter a number")
INPUT Num1
OUTPUT("Enter a number")
INPUT Num2
// nd and output the largest number
IF Num1 > Num2 THEN
OUTPUT(Num1)
ELSE
OUTPUT(Num2)
ENDIF
85
fi
Checkpoint
1. Explain how subroutines help make a program maintainable.
86
87
Zain Merchant
Arrays
An array is a data structure. It allows you store multiple pieces of data in one structure
Zain Merchant
with one identi er. In an array, each data item must be of the same data type. If it stores
integers, then all values must be integers. If it stores strings, then all values must be
strings.
1-dimension l rr ys
A 1-dimensional array has just one row of data. The best way to visualise an array is with a
table:
Index 0 1 2 3 4
Data 10 5 90 26 87
This array has 5 spaces. Each space has an index. In this array the rst data item is in
position 0, the data value is 10. In the second array space (index 1), the number 5 is stored.
Arrays can be 0-indexed or 1-indexed. This depends on the programming language that
you use. Some arrays start with 0 as the rst space. Some arrays start with 1 as the rst
space.
Arrays use brackets after the identi er to indicate the index you want to access. For
example, Array[0] is accessing the rst element in the array named Array. MyData[3] is
accessing the fourth element in the array named MyData.
You need to know the array identi er and the position where you want to store the data.
Example 1
Store the colour "red" in the rst position of the array named Colour:
Colour[0] ← "red"
88
fi
fi
a
fi
fi
fi
a
fi
a
fi
fi
Example 2
Zain Merchant
Store the colour "yellow" in the second position of the array named Colour:
Colour[1] ← "yellow"
Example 3
Store the number 20 in the sixth position of the array named Numbers:
Numbers[5] ← 20
To access data in an array you need to know the identi er and the position of the data
you want. This will be a value, so you need to do something with this value, e.g. store it in
a variable.
Example 1
Example 2
Example 3
89
fi
fi
Using variables as indices
Zain Merchant
Example
Ask the user which array element to output from the array colours:
OUTPUT("Enter the array element you want to output")
INPUT ToOutput
OUTPUT(Colours[ToOutput])
If you have a set of values in an array you can use iteration to loop through each of the
elements in turn. For example, you might want to output all of the values one at a time.
You could add together all of the values in an array and output the total. You might want
to take 10 values in from the user and store each one in the array.
These are all best done using a count-controlled loop. This is because you usually know
how many values you want to enter, or how many values there are in the array that you
want to work through.
Example 1
90
Example 2
Zain Merchant
Ask the user to input 20 numbers and store each in the array Numbers:
FOR counter ← 0 TO 19
OUTPUT("Enter a number")
INPUT Numbers[Counter]
NEXT counter
Example 3
Searching the values in the array values that has 50 values, for the data input by the user:
ValueToFind ← INPUT("Enter the value to nd")
FOR Count ← 0 TO 49
IF Values[Counter] = ValueToFind THEN
OUTPUT("Found it")
ENDIF
NEXT Count
91
fi
2-dimension l rr ys
A 2-dimensional array is best viewed as a table with rows and columns.
Zain Merchant
index 0 1 2 3 4
0 10 5 90 26 87
1 3 15 74 62 5
2 7 10 85 4 24
In a 2-dimensional array there are two indices. For example, from the table:
Position[0, 0] is 10.
Position[0, 2] is 7.
Position[4, 2] is 24.
You need to know which position, i.e. both indices, the across and the down.
Example 1
Example 2
92
fi
a
a
a
Getting data out of an array
Zain Merchant
You need to know both indices to access the data.
Example 1
Output the data in the array ArrayData, element 5 across and 1 down:
OUTPUT(ArrayData[4, 1])
Example 2
Access the data in the array colours, in the rst element across and the third down:
ColourAccessed ← Colours[0, 2]
Each index can be stored in a variable in the same way as they can be in a 1D array.
Example 1
Example 2
93
fi
Using iteration to read and write
Zain Merchant
Due to the two dimensions, you need two nested loops to read through all the data
elements. If you think about the table again, one loop goes through the columns and one
loop goes through the rows.
The rst loop will check row 1. The column will change from 0, 1, 2, 3, 4. The row will stay
the same at 0.
index 0 1 2 3 4
0 10 5 90 26 87
1 3 15 74 62 5
2 7 10 85 4 24
The rst loop will check row 2. The column will change from 0, 1, 2, 3, 4. The row will stay
the same at 1.
It is best to use count controlled loops to go through the array. It has the structure:
FOR row ← rst index to last index
FOR column ← rst index to last index
Code to run
NEXT row
NEXT count
Example 1
DataArray has 10 elements by 3 elements. Output all of the elements in the array:
FOR Row ← 0 TO 2
FOR Column ← 0 TO 9
OUTPUT(DataArray[Column, Row])
NEXT Row
NEXT Count
94
fi
fi
fi
fi
Example 2
Zain Merchant
Search a 2-dimensional array, with 50 elements by 100 elements, for the value input by the
user:
OUTPUT("Enter a number to search for")
INPUT SearchValue
FOR Row ← 0 TO 49
FOR Column ← 0 TO 99
IF DataArray[Row, Column] = SearchValue THEN
OUTPUT("Found it at " & Column & " " & Row)
ENDIF
NEXT Column
NEXT Row
Example 3
Find and output the total of all elements in the each of the rst dimensions, in an array of
10 elements by 15 elements:
FOR Row ← 0 TO 9
Total ← 0
FOR Column ← 0 TO 14
Total ← Total + TheArray[Row, Column]
NEXT Column
OUTPUT("Index " & Row & " has the total " & Total)
NEXT Row
95
fi
Example 2
Zain Merchant
A procedure takes 2 values and outputs all the numbers between the rst number to the
second:
PROCEDURE OutputNumbers(Num1, Num2)
FOR Count ← Num1 TO Num2
OUTPUT Count
NEXT Count
ENDPROCEDURE
96
fi
Checkpoint
1. Explain the di erence between a variable and an array.
MyData[1] ← 4
MyData[2] ← “7"
MyData[3] ← “9"
3. Write a program to read 10 numbers from the user into a 1-dimensional array named
MyNumbers.
4. Write a program to add together all 100 elements in a 1-dimensional array named
MyNumbers.
97
ff
98
Zain Merchant
File handling
If you have data in a program, when you stop or close a program all of that data is lost. If
Zain Merchant
you need to save data to use again later then you need to save it externally into a text le.
The storage and access of data in a le is called le handling.
• Open the le using its lename (the lename will be a string value).
• Read the data value, and do something with it (e.g. output it, store it in a variable).
Example 1
99
a
fi
fi
fi
fi
fi
fi
fi
fi
fi
fi
fi
fi
a
fi
f
fi
fi
fi
Example 2
Zain Merchant
Read and output the number stored in the le myNumber.txt by storing the lename in a
variable:
Filename ← "myNumber.txt"
OPEN Filename
TheFileData ← READ(Filename)
CLOSE(Filename)
OUTPUT(TheFileData)
Writing to ile
The speci cation states that you will only need to write a single item of data or a line of
text. This means you will be overwriting any data that is already in the le, you do not
need to worry about appending (to add onto the end) to data that already exists, or
writing multiple values to the same le.
• Open the le using its lename (the lename will be a string value).
100
fi
fi
fi
fi
fi
fi
a
f
fi
fi
fi
fi
fi
You can use the pseudocode commands:
Zain Merchant
OPEN lename
WRITE data
CLOSE lename
Example 1
Example 2
Write the number 100 to the le myData.txt storing the lename in a variable:
Filename ← "myData.txt"
OPEN Filename
WRITE 100
CLOSE Filename
101
fi
fi
fi
fi
fi
Checkpoint
1. Why do some programs need to store data in les?
2. What are the three stages that need to be followed to write data to a le?
Zain Merchant
3. Write a program to read in a value from the le dataStore.txt and output it.
4. Write a program to ask the user to input a lename, then store the word "house" in the
le.
102
fi
fi
fi
fi
fi
Zain Merchant
103
Common algorithms
A search algorithm checks a set of data to identify whether a speci c value exists in the
Zain Merchant
data, or not. One example of this is a linear search.
A sorting algorithm takes a set of data and rearranges it to be in a speci c order, e.g. in
ascending alphabetical order. One example of this is a bubble sort.
Line r se rch
In a program you might need to look for a speci c value in a set of data. A linear search
will check each item one at a time, starting with the rst item and continuing until it either
nds the item, or it checks the last value.
Example 1
5 3 9 4 2 1 8
Compare the rst number (5) with the search value (4). They are not the same.
Compare the second number (3) with 4. They are not the same.
Compare the third number (9) with 4. They are not the same.
Compare the fourth number(4) with 4. They are the same. It has been found.
104
fi
a
fi
a
fi
fi
fi
fi
Example 2
Zain Merchant
Compare the "a" with "#". They are not the same. Compare the "v" with "#". They are not
the same. Compare the "!" with "#". They are not the same. There are no more values, so
"#" is not found.
Example 3
The array dataArray stores a set of data under one identi er. Each element in the array
has an index.
Index 0 1 2 3
Data 1 5 6 8
105
fi
This can now be written as an algorithm:
Zain Merchant
FOR ArrayIndex = 0 to LENGTH(Array) -1 //loop through each
element
//check if the current index is the data searched for
IF DataArray[ArrayIndex] = SearchValue THEN
//if it is, output the index where it is found
OUTPUT "Found at " & ArrayIndex
ELSE
//if it not found, increment arrayIndex to check the
next value
ArrayIndex ← ArrayIndex + 1
ENDIF
NEXT ArrayIndex
This algorithm is ine cient because if it nds the search value then it still continues searching.
This is useful if you want to know whether the search value appears more than once.
You can make the algorithm more e cient by stopping as soon as the value is found, for
example:
Found ← FALSE
ArrayIndex ← 0
//run while the value is not found, and you have not checked
//all elements
WHILE Found = FALSE AND ArrayIndex < LENGTH(Array) DO
//check if the current index is the data searched for
IF DataArray[ArrayIndex] = SearchValue THEN
//if it is output where it was found
OUTPUT "Found at " & ArrayIndex
//set found to be true to stop the while loop running
//again
Found ← TRUE
ELSE
//if it is not found, increment ArrayIndex to the next
value
ArrayIndex ← ArrayIndex + 1
ENDIF
ENDWHILE
106
ffi
ffi
fi
Bubble sort
When writing a program you may need to sort a set of data into a speci c order, for
Zain Merchant
A bubble sort takes the rst 2 values; value 1 and 2, and compares them. If they are the
wrong way around it swaps them. It then puts these back and takes values 2 and 3 and
compares them. If they are the wrong way around it swaps them. This repeats until it has
worked all the way through the list once. It then starts again with the rst two values.
It is called a bubble sort because it acts like a bubble moving across all the elements to
the end, then starting from the beginning.
1. The algorithm has been through the entire list, the number of elements in the list −1.
So if there are 10 elements, the algorithm runs 9 times. If there are 100 elements, the
algorithm runs 99 times. If there are XElements, the algorithm runs XElements - 1
times. This is the easiest way to program it, but it is not e cient. All elements might
be in the correct order to begin with, but it is still going to run through the same
number of times.
2. Either the algorithm has run through the list XElements - 1 times, or it has run through
the list, checking all of the elements, and it has not made any changes.
107
fi
ffi
fi
fi
A bubble sort can be written as a pseudocode algorithm. There are di erent versions of
Zain Merchant
the algorithm. Here are two di erent versions.
Version 1
108
ff
ff
Version 2
Zain Merchant
Stopping when there are no changes or when it has run array length − 1 times.
NumberPasses ← 0
//continue until one pass has no changes (changes = false)
//or it has looped array length - 1 times
WHILE Changes = FALSE or NumberPasses <= LENGTH(DataArray) - 1
DO
//reset changes each time a new pass starts
Changes ← FALSE
//loop through each element in the array
//check if the data is in the correct order
FOR Index ← 0 to LENGTH(DataArray) - 1
IF DataArray[Index] > DataArray[Index + 1] THEN
//if not swap the items
Temp ← DataArray[Index]
DataArray[Index] ← DataArray[Index + 1]
DataArray[Index + 1] ← Temp
Changes ← TRUE
ENDIF
NEXT Index
ENDWHILE
109
Checkpoint
1. Perform a linear search for the number 6 in the following data: 10 5 6 8 1 2
2. Perform a linear search for the letter “f” in the following data: bulpfagh
Zain Merchant
3. Perform a bubble sort to put the following data into ascending numerical order:
1562901
4. Perform a bubble sort to put the following data into descending numerical order: 60 2
40 52 3 5
5. Explain the di erence in e ciency between the two di erent bubble sort algorithms.
110
ff
ffi
ff
111
Zain Merchant
Tot lling
Totalling is adding a group of values together to give a total.
Zain Merchant
For example, a person buys items at a supermarket. The items cost: $0.50, $1.00, $1.00,
$15.50, $21.30 The total is 0.5 + 1 + 1 + 15.5 + 21.3 = $39.30 To do this in a program you need
to:
Add the value to the current contents of the total, e.g. Total ← Total + Value.
Example 1
Example 2
112
a
Counting
Counting is working out how many of something there are. For example, counting how
Zain Merchant
many ngers you have or counting how many items you bought when you went shopping.
Example 1
113
fi
Example 2
Zain Merchant
Count how many numbers in an array are below 10, and how many are more than 20:
CountBelow10 ← 0 //initialise both counters to 0
CountAbove20 ← 0
FOR X ← 0 to LENGTH(NumberArray) //loop through each array element
//if the number is less than 10
IF NumberArray[x] < 10 THEN
CountBelow10 ← CountBelow10 + 1 //increment the counter
//if the number is greater than 20
ELSEIF NumberArray[x] > 20 THEN
CountAbove20 ← CountAbove20 + 1 //increment the counter
ENDIF
NEXT X
114
Finding the minimum
The minimum value is the smallest value within a set. For example, the marks for a class
Zain Merchant
are entered and the lowest mark is the minimum.
initialise a minimum variable to be a large value, beyond those that will be entered, e.g.
Minimum ← 9999.
Compare each value to the minimum variable, e.g. IF Number < Minimum.
If it is, it replaces the minimum value, e.g. minimum ← number. This means the new value
is the minimum, so the next time a value is compared, it is checking it with the new
minimum value.
Example 1
115
Example 2
Zain Merchant
• Initialise a maximum variable to be a small value, beyond those that will be entered, e.g.
Maximum ← -9999.
• Compare each value to the maximum variable, e.g. IF Number > Maximum.
• If it is, it replaces the maximum value, e.g. Maximum ← Number. This means the new
value is the maximum, so the next time a value is compared,it is checking it with the
new maximum value.
116
a
Example 1
Zain Merchant
Find the largest number input by a user:
Maximum ← -9999 //initialise maximum to small value
Number ← 1
WHILE Number >= 1 DO //loop until the user enters 0
Number = INPUT("Enter a number or 0 to stop")
IF Number > Maximum THEN // check if the number entered is
larger than //the current maximum
Maximum ← Number //if true then make maximum because
the number
ENDIF
ENDWHILE
Example 2
117
Finding the ver ge
The average here is referring to the mean. This is the total of all the values added
Zain Merchant
the average = (1 + 3 + 5 + 8 + 4 + 4 + 6 + 9) / 8 = 40 / 8 = 5
To do this in a program you need to use the count and total from earlier in this section.
The average is then calculated with the formulae Total / Count.
Example 1
Example 2
118
a
a
Checkpoint
1. Explain the di erence between totalling and counting.
2. A program allows numbers to be entered between 20 and 200, and nds the smallest
and largest entered. Identify appropriate values to initialise the variables Smallest and
Zain Merchant
Largest.
3. Write an algorithm to input 40 numbers and output the total and average.
4. Write an algorithm to input 100 numbers and output the smallest and largest.
119
ff
fi
Zain Merchant
120
Validation on input
Validation is the checking of data that is input to make sure it is reasonable, and/or within
Zain Merchant
set bounds. For example, making sure that a number is entered for an age or limiting the
range of numbers that can be entered.
R nge check
A range check assesses whether data is within one or two bounds. For example, an age
must be between 0 and 100. A date must be before today’s date.
Range checks can be programmed using selection to produce an error, or within a loop
that keeps asking you enter a value until it is valid.
Example 1
Using selection:
This algorithm will check whether a number is higher than 1 and less than 10.
Number ← INPUT("Enter a number between 1 and 10")
IF Number < 1 OR Number > 10 THEN
OUTPUT("Invalid")
ELSE
OUTPUT("Valid")
ENDIF
121
a
ff
Example 2
Zain Merchant
Using a loop:
This algorithm will check if a number is higher than 1 and less than 10. It will continually
ask for a value to be input until the number is valid.
Number ← INPUT("Enter a number between 1 and 10")
WHILE Number < 1 OR Number > 10 DO
OUTPUT("Invalid please try again")
Number ← INPUT()
ENDWHILE
Length check
A length check will check the number of characters that are present. This could in a
string, for example, the length of “hello world” is 11, the space is also a character. It could
be in a variable, for example, in this example, 8 will be output:
TheData ← "123 ABC!"
OUTPUT(LENGTH(TheData))
The length of a piece of data can be found using a variety of commands depending on
the language you are using. The following are all valid and there are many more:
LENGTH(theData)
122
Example 1
Zain Merchant
Using selection:
This algorithm will check if the data input has 10 or less characters to be invalid,
otherwise (10 or more) it is valid.
Data ← INPUT()
IF LENGTH(Data) < 10 THEN
OUTPUT("Invalid")
ELSE
OUTPUT("Valid")
ENDIF
Example 2
Using iteration:
This algorithm will also check the length but will continually ask for this to be input until
it is 10 or more characters long.
Data ← Input()
WHILE LENGTH(Data) < 10 DO
OUTPUT("Invalid, please try again")
Data ← INPUT()
ENDWHILE
123
Type check
Data can be in di erent forms, including an integer (whole number), real (decimal
Zain Merchant
number), string (any characters), Boolean (true or false). There are two ways of writing a
type check:
1. Use a function such as .GetDataType() to return the data type, that you can then
compare to the one you want.
2. Use a function such as .IsInteger() to return True if it is an integer and False otherwise.
Example 1
Using selection:
This algorithm will check if the data entered is an integer value to be valid.
INPUT Data
//check if the data entered is an Integer
IF Data.GetDataType() <> Integer THEN //if it is not an integer
OUTPUT ("Invalid")
ENDIF
Example 2
Using iteration:
This algorithm will continually ask for the data to be input until it is a string value.
INPUT Data
//loop while the data entered is not a string
WHILE Data.IsString = FALSE DO
OUTPUT("Invalid please try again")
INPUT Data
ENDWHILE
124
ff
Presence check
A presence check makes sure that some data has been entered. Programming languages
Zain Merchant
can make use of the value null, or for a string value an empty string represented by "".
Example 1
Using selection:
This algorithm outputs Invalid if there is no data entered.
INPUT Data
IF Data = NULL THEN //check if the data entered is null
OUTPUT("Invalid")
ENDIF
Example 2
Using iteration:
This algorithm continually takes an input while there is no data entered.
INPUT Data
WHILE Data = "" DO //loop while there is nothing in data
OUTPUT("Invalid please try again")
INPUT Data
ENDWHILE
125
Form t check
Some data may need to be entered in a speci c way, for example, a date must be: _ _ / _ _ /
Zain Merchant
_ _ _ _, where each space is a number – a format check makes sure the data is entered this
way. An ID number may need to be 1 number followed by 3 characters.
Example 1
Using selection:
126
a
fi
fi
Example 2
Zain Merchant
Using a loop:
This algorithm checks whether an input is in the format two numbers, /, two numbers, /,
four numbers.
INPUT Date
//loop while the data is not in the correct format
WHILE (SUBSTRING(Date, 0, 2).IsNumeric = FALSE OR //2 numbers
SUBSTRING(Date, 2, 1) <> "/" OR // 1st slash
SUBSTRING(Date, 3, 2).IsNumeric = FALSE OR //2 numbers
SUBSTRING(Date, 5, 1) <> "/" OR //2nd slash
SUBSTRING(Date, 6, 4).IsNumeric = FALSE) DO // 4 numbers, year
OUTPUT("Invalid")
INPUT Date
ENDWHILE
OUTPUT("Valid")
127
Check digit
A check digit is calculated from a set of numbers, and is input with the numbers. When the
Zain Merchant
data has been input, the calculation is performed on the data again and the result is
compared with the nal number (the check digit).
Example
This algorithm calculates the check digit using the method 5 digit number input. 9999, 4
digits used to calculate 5th check digit, and compares it to the input value.
INPUT Code
//extract 1st digit
Digit1 ← Code DIV 1000
Code ← Code - (1000 * Digit1)
//extract 2nd digit
digit2 ← Code DIV 100
Code ← Code - (100 * Digit1)
//extract 3rd digit
Digit3 ← Code DIV 10
Code ← Code - (10 * Digit1)
//extract 4th digit
Digit4 ← DIV(Code, 1)
CheckDigit ← Code
//calculate check digit from data entered
//multiply by position and add together
Total ← (Digit1 * 4) + (Digit2 * 3) + (Digit2 * 2) + Digit3
NewCheckDigit ← MOD(Total, 11) // nd Mod 11 of total
NewCheckDigit ← 11 - NewCheckDigit //subtract result from
newCheckDigit
//check if the calculated check digit is the same as the last
digit in the //code
IF NewCheckDigit = CheckDigit THEN
OUTPUT("Correct data entry")
ELSE
OUTPUT("Incorrect data entry")
ENDIF
128
fi
fi
Veri ication of data
When entering data from another source, for example, a paper copy, it is important to
Zain Merchant
make sure you have entered exactly what was written originally. This is called veri cation,
a check that you have copied the data accurately.
There is a di erence between entering data accurately, and entering the correct data.
Veri cation only checks you have copied it accurately, the actual data may still be
incorrect if the original was incorrect.
Two forms of veri cation are a visual check and double entry.
A visual check is where you compare the data entered to the original. For example,
reading each line from a paper copy and checking it is identical on the computer.
A double entry check is where the same data is entered twice, usually by di erent people.
The computer will then check whether there are any di erences in what they each
entered.
129
fi
ff
f
fi
ff
ff
fi
Checkpoint
1. What is validation?
6. Write a validation routine to input a word and check that it is more than 10 characters
long.
7. Write a validation routine to input a number and check that it is an integer value.
130
fi
131
Zain Merchant
Trace tables
A trace table is a structure to help you follow an algorithm, for example, to nd an error,
Zain Merchant
Each statement in an algorithm is run manually, and the values that are written to
variables are written in the table in the order the changes are made.
Each column in the table is designated to one variable. There can also be a column for
any outputs to be written in. User prompts are also entered in the trace table, these can
be entered in a separate column or as an output (because they will be output). For
example, x = input(“Enter a number”), the text “Enter a number” is a user prompt and will
need to be added to the trace table.
For example, trace the following algorithm with the input values 1 and 3.
INPUT Number1
INPUT Number2
IF Number1 > Number2 THEN
OUTPUT(Number1)
ELSE
OUTPUT(Number2)
ENDIF
132
a
fi
a
ff
fi
There are two variables and there is an output (each variable has a column, and the
Zain Merchant
output has a column).
You then complete this table by reading through the algorithm one line at a time. It is
important not to jump ahead and guess what the algorithm will do. Read one line and
perform that action.
1 3
133
Run the IF statement
Zain Merchant
1 3 3
For example: trace the following algorithm with the input values 4, 3, 2, 1, 0.
01 Count←0
02 InputValue ← 1
03 Total←0
04 WHILE InputValue > 0 DO
05 INPUT InputValue
06 Total ← Total + InputValue
07 Count ← Count + 1
08 ENDWHILE
09 OUTPUT "The total is ", Total
10 OUTPUT "There were ", Count, " Numbers"
134
a
a
Start by creating the trace table with each of the variables and the output. There are 3
Zain Merchant
variables in this algorithm:
1. Run the rst 3 lines of code. These are the initialisations, lines 01, 02 and 03.
01 Count←0
02 InputValue ← 1
03 Total←0
0 1 0
LOOP is 1 so this is TRUE meaning that the code inside the loop is run
0 1 0
4
135
fi
fi
3. Run lines 06 and 07.
Zain Merchant
0 1 0
1 4 4
Line 08:
08 ENDWHILE
InputValue is 4, so while 4 > 0 is TRUE to run line 05 with the second input value of 3.
05 INPUT InputValue
0 1 0
1 4 4
136
5. Lines 06 and 07 run.
Zain Merchant
06 Total←Total+ InputValue Total←4+3
07 Count←Count+1 Count←1+1
0 1 0
1 4 4
2 3 7
0 1 0
1 4 4
2 3 7
3 2 9
137
7. Line 08 again returns to line 04. WHILE 2 > 0 is TRUE. Run lines 05, 06 and 07.
Zain Merchant
0 1 0
1 4 4
2 3 7
3 2 9
4 1 10
Line 08 returns to line 04 again. WHILE 1 > 0 is TRUE. Run lines 05, 06 and 07.
05 INPUT InputValue InputValue ← 0
06 Total ← Total + InputValue Total←10+1
07 Count ← Count + 1 Count←4+1
0 1 0
1 4 4
2 3 7
3 2 9
4 1 10
138
9. Line 08 returns to line 04 again. WHILE 0 > 0 is FALSE this time, so the loop does not
Zain Merchant
run.
0 1 0
1 4 4
2 3 7
3 2 9
4 1 10 The total is 10
There were 5
numbers
139
Finding the purpose of an algorithm
A trace table can help you work out the purpose of an algorithm. By following an
Zain Merchant
algorithm step- by-step you can see what happens to the values, what changes are made,
and when these are made. From this you can determine the purpose of the algorithm.
1 . First test the algorithm with a set of data that you come up with (if they are not
provided for you). For example, test this algorithm using 1, 2 then 3.
2 . Create a trace table by following the algorithm with the data input.
1 2 3 3
140
a
a
a
3. Repeat the process with a di erent set of data, for example, this time using 10, 5, 1.
Zain Merchant
4. Complete the trace table.
10 5 1 10
16
Keep on repeating this process until you can identify the pattern.
In this case it is outputting the largest number input and then outputting the total of the 3
numbers input.
141
ff
Describing n lgorithm
When you are describing an algorithm you need to do more than repeat the line of code
Zain Merchant
using English statements. For example, in the following code, for line 02 don’t just say, ‘it
is a for loop from y is 0 to x.’ This is stating what each part of the code is, but it does not
describe the algorithm.
01 INPUT X
02 FOR Y ← 0 TO X 03 OUTPUT Y
04 NEXT Y
You can do a trace table to help you work out the purpose of the algorithm before
describing it if that helps you. This algorithm has three parts: line 01, line 02 and line 03.
These are summarised below:
• Loops from 0 to the number that has been input. (line 02)
From this you can develop a description of the algorithm, for example:
The algorithm takes a number from the user, and then outputs all of the numbers from 0 to the
number input.
142
a
a
Finding errors in a program and
correcting the errors
To nd an error in an algorithm you need to know the purpose of the algorithm. You can
Zain Merchant
then test the algorithm with di erent data, completing trace tables if needed, to nd out
what the algorithm actually does. Once you know the di erence between what it does
and should do, you can start to identify the errors and the changes you need to make.
Using a trace table will allow you to follow each step in the algorithm and by comparing
this to the intended outcome you can nd where it goes wrong, and then work out how
to correct it.
For example, this program should take 5 numbers as input and output the total of all the
numbers.
01 Total←1
02 Quantity ← 1
03 WHILE Quantity < 5 DO
04 INPUT Number
05 Total ← Number
06 Quantity ← Quantity + 1
07 ENDWHILE
08 OUTPUT(Total)
First dry run the algorithm. If not provided, you will need to identify some test data to
use. This algorithm should take 5 numbers as input, so you could use 1, 2, 3, 4, 5.
Then work out what the result of the algorithm should be. It outputs the total, so it
should output: 1 + 2 + 3 + 4 + 5 = 15
Now draw a trace table for the algorithm (revisit the section on trace tables if needed)
and then run each step of the algorithm, writing the values in the table.
143
fi
a
a
a
ff
fi
f
ff
a
fi
a
Total Quantity Number Output
Zain Merchant
1 1
1 2 1
2 3 2
3 4 3
4 5 4
2 Total starts with 1 but this will add another 1 to the total, so it should be 0.
1 The total should not be overwritten. Line 05 overwrites the total. This should be Total
← Total + Number.
2 The total should not start at 1, it should be 0. Line 01 writes 1 to total. This line should
be Total ← 0.
3 Only 4 numbers are input, it should be 5. There are two ways this can be changed, both
are valid. Either Line 02 can be Quantity ← 0 or line 03 can be WHILE Quantity < 6.
144
fi
Finding errors by re ding the code
You may not always need to use a trace table, or you may not want to. There are many
Zain Merchant
di erent ways of nding the errors. In this example you will look for each of the
requirements in the algorithm to determine whether it has been met.
The following algorithm should take 3 numbers as input, and output the largest value and
the average value.
01 Total←0
02 Largest ← 999
03 FORX←0TO2
04 INPUT Data
05 IF Data < 999 THEN
06 Large ← Data
07 ENDIF
08 Total ← Total + Data
09 NEXT X
10 OUTPUT Largest
11 Average ← Total / 3
12 OUTPUT Average
Re-read the description: take 3 numbers as input, and output the largest value and the
average value.
145
ff
fi
a
The two outputs need to be calculated before being output, so they can be added to the
Zain Merchant
requirements:
The for loop goes from 0 to 2, so it will run 0, 1, 2 = 3 times. Inside the loop it inputs a
value each time. This is correct.
A. Initialise a largest variable with a low number. This is not met. Line 02 largest is set to
999 but this should be a very small value, e.g. Largest ← -1
B. It should check if the data input is larger than the data in largest. This is not met. Line
05 checks if data is less than 999. It should be larger. IF Data > Largest THEN
C. Line 06 replaces the value in Large with data, but the identi er is incorrect, the
variable is named largest. Largest ← Data
146
fi
fi
fi
The third requirement:
Zain Merchant
Output the largest value.
Line 10 outputs the largest value, this is correct.
The fourth requirement:
Calculate the average value.
The average is calculated by totalling the inputs and then dividing by the number of
inputs. Line 08 totals the data entered, but it uses the wrong identi er, it should be data
not DATA.
Total ← Total + Data
In this case the errors and corrections have been identi ed along the way. You can also
combine this with using test data to check both the original algorithm and to check that
your corrections are accurate.
147
fi
fi
fi