0% found this document useful (0 votes)
42 views14 pages

Chapter 7

Uploaded by

DM Coll
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
42 views14 pages

Chapter 7

Uploaded by

DM Coll
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 14

Chapter 7

Algorithm design and Figure 7.1: A person reading programming statements

problem solving Discussion questions


1 What are the key features of an event driven language?
2 Why do you think there is a need for different types of programming
language? Can you think of any types of problem that lend
themselves to one type of language?
IN THIS CHAPTER YOU WILL:

• learn about the use of, and stages in, the program development life
cycle
• use decomposition to split a system into sub-systems 7.1 Program development life cycle
• create structure diagrams, flowcharts and pseudocode algorithms When a person, or organisation, creates a new computer program they will use
• explain how a bubble sort and linear search works a structured, organised plan of how to create the program. This is called the
program development life cycle.
• describe and produce algorithms that include finding the maximum,
minimum and average values There are several varieties of life cycle, including cyclic, spiral, waterfall and
rapid development. These all include the stages analysis, design, coding and
• understand the need for validation and verification and write programs testing.
that use both
• identify appropriate test data for an algorithm
• complete a trace table for an algorithm 7.2 Analysis
• learn how to check a program for errors and amend the program
This first stage involves looking at the problem and the system that is needed.
• learn how to explain the purpose of an algorithm. The problem is explored, and the requirements of the program are identified.
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
GETTING STARTED the problem, each of the subproblems can be implemented as a subprogram.
Set up an obstacle course using chairs and other objects. Write down a
set of instructions to guide a friend through the obstacle course, for
example, stating how many steps to take, which way to turn, etc.
Give the instructions to a friend and ask them to follow the instructions
7.3 Design
safely (e.g. stop if they are about to hit something). Amend the Once the requirements have been identified, the program designers can begin
instructions until your friend can successfully get through the obstacle planning how the program will work in the design phase. This can include an
course. overview of the program using a structure diagram, and the designing of
algorithms using flowcharts and pseudocode.

Structure diagram
THE USE OF ALGORITHMS A structure diagram is developed by decomposing a program into its
subprograms. The diagram has the name of the program at the top, and below
Consider what is meant by an algorithm. If you search for algorithm then this its subprograms. Each subprogram can be split down further as well if
you will find answers such as a process, or a set of rules, that are required.
followed. This does not mean they are limited to computers. You can find
algorithms in all areas of life. You will have followed many of these without Example 1
even considering that they are algorithms. For example, in mathematics A calculator needs to allow the user to enter numbers and the symbol,
you will have followed a series of steps to solve a problem. calculate the result and output this.
Algorithms can take many forms, and use a variety of words or structures. The name of the program is at the top. The boxes below are ready for
Computers follow algorithms. Programs are written as a series of subprograms (Figure 7.2).
instructions that the computer then follows. Algorithms for software might
be millions of lines long, and they have to make use of specific
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.
Different programming languages have different focuses. Some different Figure 7.2: A structure diagram for a calculator
types are shown:
Declarative 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
This declares rules and you can ask it questions and it will give an answer added to the diagram (Figure 7.3).
based upon the rules. For example, here are some facts:
person(ali) Ali is a person.
person(jennifer) Jennifer is a person.
person(tyler) Tyler is a person.
friend(jennifer, tyler) Jennifer is friends with Tyler is a
person. Figure 7.3: Input, process and output are added to the calculator structure
friend(tyler, ali) Tyler is friends with Ali. diagram

From this you could ask who Jennifer is friends with, and it will return The subprograms can then be split further. The calculator needs two numbers
Tyler. and a symbol to be entered (e.g. 2 + 3). Add these boxes below input (Figure
Object-oriented 7.4).
This allows the user to create objects that have features (attributes) and
processes (methods). For example, you could have a car as an object. Its
features are colour, engine size, number of doors. Its processes are move
forward, move backwards, turn.
Event driven
Some programs use buttons, text boxes and other items that the user can
interact with. An event driven language has code that is only run when
one of these items is clicked, or changed. The code is not run from start to
finish, each item has its own code.
Figure 7.4: Expanding the input subprograms
Procedural
This has statements that are run in the order that they are written. It
makes use of subroutines (procedures and functions) that can be called
from other parts of the program. This is the type of language that you are
most likely to start learning to program with.
Questions
Both of these are valid. There are lots of ways you can decompose a problem,
1 Describe the process of decomposition.
and everyone could do it slightly differently but the solution is still valid.
Finally, the output needs identifying (Figure 7.7): 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.
3 A satellite navigation system needs to ask the user to input their
destination. It then finds 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.
Figure 7.7: A finished structure diagram for the calculator
Flowcharts
This program was fairly small, so it has been split into very precise instructions
that can then be programmed. The next example is a larger problem. A flowchart is a diagrammatic representation of an algorithm. Figure 7.14
shows some of the set of standard symbols.
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.
Example 2 Figure 7.14: Flowchart symbols
The name of the program is at the top (Figure 7.8).
A flowchart shows each step of a process, in the order that each step is
performed. Each shape has one statement within it, for example, input number,
or add 1 to x. The shapes are joined with arrows to show the direction of flow
and the content inside each box can be written as words, or as pseudocode
statements. Table 7.1 shows examples of how the flowchart symbols are used.

Figure 7.8: A structure diagram for a chess program Shape Description Examples
Start/stop A flowchart begins with a Start box,
The program could be decomposed into inputs, processes and outputs, but with one arrow from it.
this is a large program so it can be split down by different functions instead.
A flowchart ends with a Stop box, with
The first part is that there are two players who need entering, this is given the
one arrow going into it.
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’) (Figure 7.9):

Figure 7.15:
Start/Stop

Figure 7.9: Subprograms for the chess program


Input A single input of a value with an
identifier for that value.
These can then be split further. They are each given their own sub-diagram One arrow should go into the box, and
here so that they are easier to view (Figures 7.10–13): one arrow should come out.

Figure 7.16: Input

Figure 7.10: The New players subprogram Output An output of text in speech marks,
and/or the identifier of a value

Figure 7.11: The New game subprogram

Figure 7.17: Output

Process An action that is being performed,


Figure 7.12: The Make move subprogram usually a mathematical calculation.
One arrow goes into the box, and one
arrow comes out of the box.

Figure 7.18: Process


Figure 7.13: The Check won subprogram

ACTIVITY 7.1 Decision A question with two outcomes, yes or


no (or true or false). The question is a
 Can you split any of these subprograms down further? In ‘Check won’ comparison from:
(Figure 7.13) what should happen if the result is checkmate? Should there = equal to
be an output? What if there is check but not checkmate? Should this be
> greater than
output?
< less than
Peer Assessment >= greater than
Compare your subsystems with a friend. Did you have the same <= less than.
answers? If so, are they both valid structure diagrams even though they
You can have more than one
are different?
condition by including AND or OR.
See Chapter 8, Section 6 for the use
Once you have decomposed your program into subprograms, you will need to of these operators. Figure 7.19: Decision
design an algorithm for each part. This could be the level 1 (the first row below
One arrow goes into the box. Two
the top box) like in the calculator example. It could be for a lower level, like in
arrows come out, one labelled yes (or
the game of chess. Each box should become an individual algorithm. When
true) and the other no (or false).
you write your program, each of these individual algorithms might be a
separate function or procedure (see Chapter 8, Section 12). Together, these
individual algorithms should come together to create the whole system. Table 7.1: Flowchart symbol examples
It is important that all arrows are complete, i.e. all boxes lead somewhere else
so that you cannot get stuck in the flowchart with nowhere to go. 7.4 Pseudocode
Example 1 Pseudocode refers to any code that is not written on a computer to run. There
is no one set pseudocode, because if there was then this would be code with a
Figure 7.20 shows a flowchart for a calculator. specific 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. Here the pseudocode
program is converted into Python, VB.NET and Java.
Python
number1 = input()
if number < 10:
print("too small")
else:
print("valid")
VB.NET
number1 = console.readline()
if number < 10 then
console.writeline("too small")
else
Figure 7.20: A flowchart for a calculator console.writeline("valid")
endif
Example 2 Java
Figure 7.21 shows a flowchart for a password validation program. number = Integer.parseInt(scanner.nextLine());
if (number < 10){
System.out.println("too small");
}else{
System.out.println("valid");
}
There are many different 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.
Table 7.2 shows some examples of valid and invalid pseudocode.

Valid pseudocode Invalid pseudocode


INPUT Value Input the value X
FOR X = 0 to 9
OUTPUT Loop 10 times
Value + X In each loop output the loop
NEXT X number added to the input value
Figure 7.21: A flowchart for a password validation program
num1 = input input = num1
ACTIVITY 7.2 num2 = input input = num2
Flowcharts can be used for more than writing programs. Work in pairs to if num1 > num2 if num1 is greater than num2 then
produce a flowchart for making a cup of tea, or coffee, or another drink. then output num1
print(num1) if num1 is not greater than num2
then output num2
Questions else

5 Write the name of each flowchart symbol in the shape.


print(num2)
Endif
a
Table 7.2: Valid/invalid pseudocode examples
b
TIP

c The syllabus includes information about the pseudocode conventions that


will appear within examinations. The pseudocode conventions in this book
don’t always exactly follow the conventions you will see in your exams, but
they are still valid. Remember that your syntax doesn’t have to be perfect –
d it is your logic that is important.

6 Draw the flowchart symbol for each statement:


a Start
b INPUT x
c INPUT y
d IS x > y?
e x=x+y
f Stop
7 Draw a flowchart to take three numbers as input, find and output the
largest number.
PROGRAMMING TASK 7.1 7.6 Testing
When you have finished your program, you need to carry out testing to make
A computer game stores a number for the user to guess. The user has up sure it:
to 10 attempts to guess the number. After each turn the program outputs
whether the number they guessed is smaller, larger, or equal to the • fully works
number they are trying to guess. If they have 10 guesses without getting it • does not crash
correct, tell them what the answer is. If they get it correct, output the
• meets all requirements.
number of attempts it took them.
You will need to identify appropriate test data to use to test the program. There
Getting started
are four types of test data:
1 Play the game with a partner. Discuss the different steps that you
• Normal – data that the program should accept.
follow. Use this to Identify the inputs, processes and outputs required
by this problem. • Abnormal– data that the program should not accept.
2 Recap the different components of a structure diagram and the • Extreme– data that is at the edge of what is allowed.
purpose of decomposition. • Boundary– data that is on the edge of being accepted and being rejected.
3 Read an algorithm you have previously written that makes use of:
Example 1
input, output, selection and loops. Revisit the steps you identified in
Task 1, which of the four areas is needed in each part. A program allows the user to enter their age as a whole number between 10
and 100 years.
Practice Test data type Example data
1 Decompose the system into its subsystems by creating a structure Normal Any number between 10 and 100 inclusive,
diagram.
e.g. 10, 20, 50, 100, etc.
2 Draw a flowchart for the game.
3 Convert your flowchart into pseudocode. Abnormal Any data that is not a number between 10 and 100,
e.g. 9, −1, 101, 200, “age”, “30”, 12.2.

Challenge Extreme The largest number accepted – 100.


1 Is your code efficient? Are there any variables that are used that don’t The smallest number accepted – 10.
need to be? Can you reduce the number of lines of code?
Boundary Either side of the largest bound – 100 and 101.
2 Amend your program so that each time it runs, a random number is
generated for the user to guess. Either side of the smallest bound – 9 and 10.

Example 2
REFLECTION A user needs to enter a password at least 8 characters long.
After completing Programming Task 7.1: Test data type Example data
How did you approach the programming task? Did you skip the getting Normal Any set of 8 or more characters, but they must be text (have
started or did you jump straight to the practice? speech marks),
Did that approach work? Will you consider the getting started next time? e.g. "abcdefgh" "12fghj567812".
Did you tackle the challenge yourself?
Abnormal Any set of characters with 7 or less characters,
If not, would you revisit this when you are feeling more confident in this
e.g. "1234567", "seven".
topic?
Extreme Any with 8 characters only,
e.g. "12345678", "ajrkdhJK".
ACTIVITY 7.3
Boundary Either side of the 8 character bound, 7 characters or 8
Find an example of a flowchart and turn it into a pseudocode algorithm. characters,
e.g. "1234567", "12345678", "abcdefg", "iJHFD7hJ",

Questions
ACTIVITY 7.4
8 Describe the purpose of pseudocode.
9 Tick one box in each row to identify if the statements are appropriate In pairs find a computer game to play. Anything as simple as a puzzle
pseudocode statements, or not. game, to a full 3D adventure game. Discuss how this game might have
been tested. What data would be used as inputs?
Statement Valid Invalid
x = x + 1
INPUT z Questions
IF y < 6 THEN 12 Identify three different types of test data.
add 3 to the value entered 13 Why can you have the same test data as normal and extreme types of
test data?
store the value entered in
the variable newValue 14 What is the difference between extreme and boundary test data?
15 A program asks the user to input a number between 1 and 10 (inclusive).
value1 = INPUT("Enter a
number") Identify test data for each of the test data types in the table:

IF number is more than 10 Test type Test data


WHILE number1 <> 0 Normal
Abnormal
10 Write a pseudocode algorithm to:
Extreme
• take three values as input
Boundary
• multiply the numbers together
• output the result.
11 Write a pseudocode algorithm to:
• take 10 numbers as input (using a loop)
• add together the values
• output the total with an appropriate message.

7.5 Coding
Once you have decomposed your problem into subproblems, and you have
designed the algorithms using flowcharts 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 different
data to make sure it is fully working before moving onto the next step.
This algorithm is inefficient because if it finds the search value then it still
7.7 Common algorithms continues searching. This is useful if you want to know whether the search
A search algorithm checks a set of data to identify whether a specific value value appears more than once.
exists in the data, or not. One example of this is a linear search. You can make the algorithm more efficient by stopping as soon as the value is
A sorting algorithm takes a set of data and rearranges it to be in a specific found, for example:
order, e.g. in ascending alphabetical order. One example of this is a bubble Found ← FALSE
sort.
ArrayIndex ← 0
//run while the value is not found, and you
COMPUTER SCIENCE IN CONTEXT have not checked
Sorting data and searching for data are activities that a very large //all elements
proportion of programs will use at some point. For example, outputting a WHILE Found = FALSE AND ArrayIndex <
list of data may need sorting into order. A user may enter a username and LENGTH(Array) DO
the program needs to search for this in the set of valid usernames. //check if the current index is the data
There are many different searching and sorting algorithms, each one has searched for
its benefits and drawbacks depending on the problem. This could be the IF DataArray[ArrayIndex] = SearchValue THEN
number of data items it has to sort through, or whether the data is already //if it is output where it was found
in order to search for a value. It is up to the programmer to identify the OUTPUT "Found at " & ArrayIndex
algorithm that is most appropriate for their program to make sure it is as //set found to be true to stop the while
efficient as possible (both in the time it takes to run, and the amount of loop running
memory it needs to perform this task).
//again
Found ← TRUE
ELSE
Linear search //if it is not found, increment ArrayIndex
In a program you might need to look for a specific value in a set of data. A to the next value
linear search will check each item one at a time, starting with the first item and ArrayIndex ← ArrayIndex + 1
continuing until it either finds the item, or it checks the last value.
ENDIF
ACTIVITY 7.5
ENDWHILE

Get a set of playing cards. Select 10 random cards and place them face TIP
down on the table in a row. Perform a linear search to see if the Ace of
Different programming languages use different characters to indicate the
Spades is in the set.
start of a comment (there is no closing character). For example, #, //, /* and
1 Turn over the first card.  '. You have to use one of these characters when writing pseudocode, but
2 Is it the Ace of Spades? any one of these is acceptable.

3 If it is, then stop searching, you’ve found it.


4 If it isn’t, turn over the next card. Repeat from 2. Bubble sort
When writing a program you may need to sort a set of data into a specific
order, for example, ascending numerical order or descending alphabetical
order.
One method of sorting data is using a bubble sort.
A bubble sort takes the first 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 first 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.
Example 1
There are two ways to tell the algorithm when to stop.
Search this set of data for the number 4.
1 The algorithm has been through the entire list, the number of elements in
5 3 9 4 2 1 8 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,
Compare the first number (5) with the search value (4). They are not the same. the algorithm runs XElements - 1 times. This is the easiest way to
Compare the second number (3) with 4. They are not the same. program it, but it is not efficient. All elements might be in the correct order
to begin with, but it is still going to run through the same number of times.
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. 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
Example 2 any changes.
Search this set of data for the character "#".
ACTIVITY 7.6
"a" "v" "!"
Get a set of playing cards. Select 10 random cards and place them face
Compare the "a" with "#". They are not the same. down on the table in a row. Perform a bubble sort to put the cards in
Compare the "v" with "#". They are not the same. ascending numerical order.
Compare the "!" with "#". They are not the same. 1 Turn over the first two cards.
There are no more values, so "#" is not found. 2 If the 1st is larger than the 2nd, swap them. Otherwise, do nothing.
Example 3 3 Turn the cards back over.
Searching an array (Chapter 8, Section 15 on arrays). 4 Turn over the 2nd and 3rd cards.
The array dataArray stores a set of data under one identifier. Each 5 Repeat step 2.
element in the array has an index. 6 Repeat turning over the cards and swapping until you have been
through all 10 cards once.
Index 0 1 2 3
7 Did you make any swaps? If so, start again from step 1. If not, stop
Data 1 5 6 8
because the cards should be in order.
Search the array for the number 6
Is DataArray[0] = 6? No, DataArray[0] = 1
A bubble sort can be written as a pseudocode algorithm. There are different
Is DataArray[1] = 6? No, DataArray[1] = 5 versions of the algorithm. Here are two different versions.
Is DataArray[2] = 6? Yes, DataArray[2] = 6
Version 1
6 was found in index 2.
Stopping only when it has run array length −1 times.
This can now be written as an algorithm:
//loop array length - 1 number of times
FOR ArrayIndex = 0 to LENGTH(Array) -1 //loop FOR NumberPasses ← 0 to LENGTH(DataArray) - 1
through each element //loop through each element in the array
//check if the current index is the data FOR Index ← 0 to LENGTH(DataArray) - 1
searched for //check if the data is in the correct
IF DataArray[ArrayIndex] = SearchValue THEN order
//if it is, output the index where it is IF DataArray[Index] > DataArray[Index + 1]
found THEN
OUTPUT "Found at " & ArrayIndex //if not swap the items
ELSE Temp ← DataArray[Index]
//if it not found, increment arrayIndex to DataArray[Index] ← DataArray[Index + 1]
check the next value
DataArray[Index + 1] ← Temp
ArrayIndex ← ArrayIndex + 1 ENDIF
ENDIF NEXT Index
NEXT ArrayIndex NEXT NumberPasses
Version 2
Should it stop?
Stopping when there are no changes or when it has run array length − 1 times.
Compare to the two criteria:
NumberPasses ← 0 a you have passed through all numbers 3 times [True, 3 passes have
//continue until one pass has no changes been made so stop].
(changes = false)
Questions
//or it has looped array length - 1 times
WHILE Changes = FALSE or NumberPasses <= 1 How many swaps were made in this bubble sort?
LENGTH(DataArray) - 1 DO 2 Why did it stop after 3 passes?
//reset changes each time a new pass starts 3 How would you change this process to put the data into descending
Changes ← FALSE numerical order?
//loop through each element in the array
//check if the data is in the correct order
FOR Index ← 0 to LENGTH(DataArray) - 1 SKILLS FOCUS 7.2
IF DataArray[Index] > DataArray[Index + 1] BUBBLE SORT WITH CHARACTERS INTO DESCENDING ORDER
THEN
//if not swap the items Put the characters "z" "c" "f" "a" "h" into descending alphabetical order.
Temp ← DataArray[Index] First identify the data and method. This is string data, and into descending
DataArray[Index] ← DataArray[Index + 1] alphabetical order.
DataArray[Index + 1] ← Temp There are five characters, so keep on sorting until either:
Changes ← TRUE a you have passed through all characters 4 times
ENDIF or
NEXT Index
b you have passed through all the numbers once without making any
ENDWHILE changes.
SKILLS FOCUS 7.1 Draw a table with the given characters:

BUBBLE SORT OF NUMERICAL DATA z c f a h

When you are performing a bubble sort, first identify the order required, e.g. Pass 1. Work through each of the data items once. If the pair is in the
ascending or descending. Then identify the data item being sorted, e.g. is it incorrect order, swap them.
a number, a letter, a set of words, etc.
z c f a h
For example: sort the numbers 6 2 5 1 into ascending numerical order.
z f c a h
There are 4 numbers that need sorted into ascending numerical order. This
z f c h a
means you keep on sorting until either:
a you have passed through all numbers 3 times Should it stop? It has not run 4 times. It has made changes. Repeat.
or Pass 2.
b you have passed through all the numbers once without making any z f c h a
changes. z f h c a
To help guide your working it’s often useful to draw a table for each of the
items. Should it stop? It has not run 4 times, and it made a change. Repeat.

Draw a table with the four values: Pass 3.

6 2 5 1 z f h c a
z h f c a
Pass 1. Work through the data items, comparing each pair in turn. If the data
is in the wrong order, swap them. Should it stop? It has not run 4 times. It has made 1 change. Repeat.
Data Instructions Pass 4.
6 2 5 1 z f h c a
6 2 5 1 Compare the first two values. Should it stop? It has run 4 times – stop.
2 6 5 1 They are in the wrong order so swap them. Questions
2 6 5 1 Compare values 2 and 3. 1 How many comparisons were made that did not result in swaps?
2 5 6 1 They are in the wrong order so swap them. 2 How would you change this algorithm to work with strings instead of
2 5 6 1 Compare values 3 and 4. multiple characters, e.g. 'zoo' 'farm' 'cat' 'horse' 'animal'?
2 5 1 6 They are in the wrong order so swap them.
PROGRAMMING TASK 7.2
Now you have completed 1 pass, check if it should stop!
Compare to the two criteria: A program asks the user to enter a set of 20 numbers. The user can then
enter a number for the program to search for in the set of data. The
a you have passed through all numbers 3 times [False, only 1 pass has
program will output if it is found, or not. The program should then put the
been made]
data into ascending order and output the newly arranged data.
or
Getting started
b you have passed through all the numbers once without making any
1 Practise the linear search process using a set of cards. Lay them out
changes [False, there has been at least one change].
and search them in turn to identify if a specific one is present.
Pass 2. Work through the data items, comparing each pair in turn. If the data
2 Practise the bubble sort process using a set of cards. Lay them out
is in the wrong order swap them.
and put them into the correct order following the bubble sort
Data Instructions instructions.
2 5 1 6 3 Recap the programming skills; input, output, selection and iteration.
Focus on how to loop 20 times to enter 20 numbers.
2 5 1 6 Compare the first two values.
4 Read the linear search and bubble sort algorithms with a partner.
2 5 1 6 They are in the correct order. Compare values 2 and 3.
Follow each instruction in the algorithm.
2 1 5 6 They are in the wrong order. Swap them.
2 1 5 6 Compare values 3 and 4. They are in the correct order. Practice
Should it stop? 1 Identify the inputs, processes and outputs for the problem.
Compare to the two criteria: 2 Create a structure diagram for the problem.
a you have passed through all numbers 3 times [False, only 2 passes 3 Write a pseudocode algorithm to take in the set of 20 numbers from
have been made] the user.
or 4 Amend the algorithm to allow the user to input a number to search for,
and then the code to perform a linear search on the data and output
b you have passed through all the numbers once without making any the result.
changes [False, there has been at least one change].
5 Amend the program to perform a bubble sort on the data, and output
Pass 3. Work through the data items, comparing each pair in turn. If the data the arranged program.
is in the wrong order swap them.
Data Instructions Challenge
2 1 5 6 1 Move the linear search into its own subroutine (procedure or function)
2 1 5 6 Compare the first two values. so it can be called from anywhere in the main program.
1 2 5 6 They are in the wrong order. Swap them. 2 Move the bubble sort into its own subroutine and call it from the
program.
1 2 5 6 Compare values 2 and 3.
1 2 5 6 They are in the correct order. Compare values 3 and 4.
1 2 5 6 They are in the correct order.
Questions
Example 2
16 Perform a linear search for the number 6 in the following data:
10 5 Count how many numbers in an array are below 10, and how many are more
than 20:
17 Perform a linear search for the letter “f” in the following data:
b u l p f a g h CountBelow10 ← 0 //initialise both counters to
18 Perform a bubble sort to put the following data into ascending numerical 0
order: CountAbove20 ← 0
1 5 FOR X ← 0 to LENGTH(NumberArray) //loop through
19 Perform a bubble sort to put the following data into descending numerical each array element
order: //if the number is less than 10
60 2 IF NumberArray[x] < 10 THEN
20 Explain the difference in efficiency between the two different bubble sort CountBelow10 ← CountBelow10 + 1
algorithms. //increment the counter
//if the number is greater than 20
Totalling ELSEIF NumberArray[x] > 20 THEN
CountAbove20 ← CountAbove20 + 1
Totalling is adding a group of values together to give a total.
//increment the counter
For example, a person buys items at a supermarket. The items cost: $0.50, ENDIF
$1.00, $1.00, $15.50, $21.30 The total is 0.5 + 1 + 1 + 15.5 + 21.3 = $39.30
NEXT X
To do this in a program you need to:
• Initialise a variable to store the total, e.g. Total ← 0. PROGRAMMING TASK 7.4
• Add the value to the current contents of the total, e.g. Total ← Total A program needs to ask the user to input the weight of parcels being
+ Value. posted. It needs to count how many parcels are less than 1 kg, how many
are between 1 kg and 2 kg, and how many are above 2 kg.
Example 1
Getting started
Totalling the 10 values input by the user:
1 Recap how to count in an algorithm. What are the different pieces of
Total ← 0 //Initialise the total variable to 0 code you need? For example, initialise the count to start at 0.
FOR X ← 0 TO 9
2 You will need to use selection to compare the inputs with the weights.
Total ← Total + INPUT("Enter a value") //Add Recap the use of selection and the format, including the differences
the input to the total between the operators >, >=, < and <=.
NEXT X
OUTPUT Total Practice
Example 2 1 Draw a structure diagram for the problem.
Totalling the values in an array named dataArray: 2 Write an algorithm to read in the weights of the parcels until the user
has finished.
TotalValue ← 0 //Initialise the total variable
to 0 3 Amend the algorithm to count and output how many parcels are
FOR Count ← 0 TO LENGTH(DataArray) - 1 below 1 kg.
TotalValue ← TotalValue + DataArray[Count] 4 Amend the algorithm to also count and output how many parcels are
//Add the input to the total between 1 and 2 kg.
NEXT Count 5 Amend the algorithm to also count and output how many parcels are
OUTPUT Total more than 2 kg.

PROGRAMMING TASK 7.3


Challenge
A program is needed to ask the user to input the price of products they The user would like to enter the limits that they are counting themselves
have bought. Calculate and output the total cost they spent. when the program starts. For example, counting how many parcels are
Getting started less than 1.5 kg instead of 1 kg. Amend the program to make this change.

1 What are the steps required to find the total? For example, initialising
the total to 0 will be the first step. Finding the minimum
2 You will need to work out how to continue asking for the price of
The minimum value is the smallest value within a set. For example, the marks
products until they do not have any more. Have a look at some of the
for a class are entered and the lowest mark is the minimum.
previous algorithms in this chapter that perform similar actions to this.
What did they use? How did they limit the number that could be To do this in a program you need to:
entered? • initialise a minimum variable to be a large value, beyond those that will be
entered, e.g. Minimum ← 9999.
Practice
• Compare each value to the minimum variable, e.g. IF Number <
1 Create a structure diagram for the problem. Minimum.
2 Write an algorithm to ask users to repeatedly input the price of
• If it is, it replaces the minimum value, e.g. minimum ← number.
products they have bought until there are no more to enter.
This means the new value is the minimum, so the next time a value is
3 Amend the algorithm to total the cost of all the products and output compared, it is checking it with the new minimum value.
this at the end of the algorithm.
Example 1
Find the smallest number input by a user:
Challenge
1 Amend the algorithm to also count how many items they entered. You
Minimum ← 9999 //initialise minimum to large
can look ahead to the next section or work out how to count them value
yourself. Number ← 1
2 Now you have the total and the quantity, amend your program to work
WHILE Number >= 1 DO //loop until the user
out the average cost. enters 0
Number ← INPUT("Enter a number or 0 to
stop")
Counting IF Number < Minimum THEN // check if the
Counting is working out how many of something there are. For example,
number entered is smaller than //the current
counting how many fingers you have or counting how many items you bought minimum
when you went shopping. Minimum ← Number //if true then make
To do this in a program you need to: minimum because the number
ENDIF
• Initialise a variable to start the count, e.g. CountItems ← 0. ENDWHILE
• Add 1 to the count variable each time, e.g. Count ← Count + 1.
Example 2
Example 1 Find the smallest number in an array of data:
Count the number of items the user enters:
Minimum ← 999999
Count ← 0 //initialise the count variable FOR X ← 0 TO LENGTH(NumberArray)
Number ← 0 IF NumberArray[X] < minimum THEN
WHILE Number <> -1 DO // loop until the user Minimum ← NumberArray[X]
enters -2 ENDIF
Number ← INPUT("Enter a number. Enter -1 to NEXT X
stop")
Count ← Count + 1 //add 1 to count each time
a number is input
ENDWHILE
Finding the maximum PROGRAMMING TASK 7.5
The maximum value is the largest value within a set. For example, the marks A teacher needs a system to calculate the lowest, highest and average
for a class are entered and the highest mark is the maximum. mark their 30 students got in a test out of 100.
To do this in a program you need to: Getting started
• Initialise a maximum variable to be a small value, beyond those that will be 1 Identify the code required to work out the minimum and maximum
entered, e.g. Maximum ← -9999. values in a set of data.
• Compare each value to the maximum variable, e.g. IF Number > 2 Recap how to calculate an average of a set of numbers.
Maximum. 3 30 numbers will need entering. Recap how to loop 30 times.
• 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 Practice
compared,it is checking it with the new maximum value.
1 Write an algorithm to allow the teacher to enter the marks for all 30
Example 1 students.
Find the largest number input by a user: 2 Amend the program to calculate and output the smallest (minimum)
mark.
Maximum ← -9999 //initialise maximum to small
value 3 Amend the program to calculate and output the largest (maximum)
mark.
Number ← 1
WHILE Number >= 1 DO //loop until the user 4 Amend the program to calculate and output the average mark.
enters 0
Number = INPUT("Enter a number or 0 to Challenge
stop")
Extend the program to count how many got below the average, and how
IF Number > Maximum THEN // check if the many got above the average number of marks.
number entered is larger than //the current
maximum Extend the program to work out how many students got each level. 80 or
more = distinction. 60 or more = merit. 40 or more = pass. Below 40 = fail.
Maximum ← Number //if true then make
maximum because the number
ENDIF Questions
ENDWHILE 21 Explain the difference between totalling and counting.
Example 2 22 A program allows numbers to be entered between 20 and 200, and finds
Find the largest number in an array of data: the smallest and largest entered. Identify appropriate values to initialise
the variables Smallest and Largest.
Maximum ← -1 // initialise the maximum value to
a small number 23 Write an algorithm to input 40 numbers and output the total and average.
FOR X ← 0 TO LENGTH(NumberArray) 24 Write an algorithm to input 100 numbers and output the smallest and
//check if the number entered is larger than largest.
the current maximum
Validation on input
IF NumberArray[X] > Maximum THEN
Maximum ← NumberArray[X] //if true store Validation is the checking of data that is input to make sure it is reasonable,
the value in maximum and/or within set bounds. For example, making sure that a number is entered
for an age or limiting the range of numbers that can be entered.
ENDIF
NEXT X
ACTIVITY 7.7
Finding the average
Have you ever entered data to be told that it is invalid? What were you
The average here is referring to the mean. This is the total of all the values trying to enter, and why was it incorrect? Visit some websites that need
added together, then divided by how many numbers there are. you to enter some data (but stay safe and make sure it is not personal
For example, if the data is 1, 3, 5, 8, 4, 2, 6, 9 , data). What restrictions do they have? Are there some spaces that you
need to enter data in? Do some of them give you a set structure to fill in,
the average = (1 + 3 + 5 + 8 + 4 + 4 + 6 + 9) / 8 = 40 / 8 = 5 for example, a date as _ _ / _ _ / _ _ _ _?
To do this in a program you need to use the count and total from earlier in this Are these all controlled with validation rules?
section. The average is then calculated with the formulae Total / Count.
There are different types of validation.
Example 1
Find the average of the numbers input by a user: Range check
Count ← 0 //initialise the count to 0 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
Total ← 0 //initialise the total to 0 date.
Number ← 1
Range checks can be programmed using selection to produce an error, or
WHILE Number >= 1 DO //loop until the user within a loop that keeps asking you enter a value until it is valid.
enters 0
Number ← INPUT("Enter a number or 0 to Example 1
stop") Using selection:
Total ← Total + Number //add the number This algorithm will check whether a number is higher than 1 and less than 10.
entered to the total
Number ← INPUT("Enter a number between 1 and
Count ← Count + 1 //add 1 to the count
10")
ENDWHILE
IF Number < 1 OR Number > 10 THEN
Example 2 OUTPUT("Invalid")
Find the average of the numbers in an array of data: ELSE
OUTPUT("Valid")
Count ← 0 //initialise the count to 0
ENDIF
Total ← 0 //initialise the total to 0
FOR X ← 0 TO LENGTH(NumberArray) Example 2
Total ← Total + NumberArray[X] //add value Using a loop:
to total This algorithm will check if a number is higher than 1 and less than 10. It will
Count ← Count + 1 //add 1 to count continually ask for a value to be input until the number is valid.
NEXT X 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 Format check
A length check will check the number of characters that are present. This Some data may need to be entered in a specific way, for example, a date must
could in a string, for example, the length of “hello world” is 11, the space is also be: _ _ / _ _ / _ _ _ _, where each space is a number – a format check makes
a character. It could be in a variable, for example, in this example, 8 will be sure the data is entered this way. An ID number may need to be 1 number
output: followed by 3 characters.
TheData ← "123 ABC!" Example 1
OUTPUT(LENGTH(TheData)) Using selection:
The length of a piece of data can be found using a variety of commands An ID number entered needs to be 1 number followed by 2 characters. This
depending on the language you are using. The following are all valid and there algorithm checks the characters and outputs whether it meets the required
are many more: format.
theData.length() INPUT IdNumber
LENGTH(theData) //check if the first character is a number, and
LEN(theData) characters 2 //and 3 are strings
theData.len IF(SUBSTRING(IdNumber, 0, 1).IsNumeric = TRUE
A length check can be programmed using selection or iteration. AND
Example 1
SUBSTRING(IsNumber, 1, 2) = TRUE) THEN
OUTPUT("Valid")
Using selection: ELSE
This algorithm will check if the data input has 10 or less characters to be OUTPUT("Invalid")
invalid, otherwise (10 or more) it is valid. ENDIF
Data ← INPUT()
IF LENGTH(Data) < 10 THEN Note that SUBSTRING(String, X, Y) starts at character x in the
OUTPUT("Invalid") string, and returns y number of characters.
ELSE Example 2
OUTPUT("Valid") Using a loop:
ENDIF
This algorithm checks whether an input is in the format two numbers, /, two
Example 2 numbers, /, four numbers.
Using iteration: INPUT Date
This algorithm will also check the length but will continually ask for this to be //loop while the data is not in the correct
input until it is 10 or more characters long. format
WHILE (SUBSTRING(Date, 0, 2).IsNumeric = FALSE
Data ← Input() OR //2 numbers
WHILE LENGTH(Data) < 10 DO
SUBSTRING(Date, 2, 1) <> "/" OR // 1st slash
OUTPUT("Invalid, please try again")
SUBSTRING(Date, 3, 2).IsNumeric = FALSE OR
Data ← INPUT() //2 numbers
ENDWHILE
SUBSTRING(Date, 5, 1) <> "/" OR //2nd slash
Type check SUBSTRING(Date, 6, 4).IsNumeric = FALSE)
Data can be in different forms, including an integer (whole number), real DO // 4 numbers, year
(decimal number), string (any characters), Boolean (true or false). There are OUTPUT("Invalid")
two ways of writing a type check: INPUT Date
1 Use a function such as .GetDataType() to return the data type, that ENDWHILE
you can then compare to the one you want. OUTPUT("Valid")
2 Use a function such as .IsInteger() to return True if it is an integer Check digit
and False otherwise. A check digit is calculated from a set of numbers, and is input with the
Example 1 numbers. When the data has been input, the calculation is performed on the
data again and the result is compared with the final number (the check digit).
Using selection:
Example
This algorithm will check if the data entered is an integer value to be valid.
This algorithm calculates the check digit using the method 5 digit number input.
INPUT Data 9999, 4 digits used to calculate 5th check digit, and compares it to the input
//check if the data entered is an Integer value.
IF Data.GetDataType() <> Integer THEN //if it
is not an integer INPUT Code
OUTPUT ("Invalid") //extract 1st digit
ENDIF Digit1 ← Code DIV 1000
Code ← Code - (1000 * Digit1)
Example 2 //extract 2nd digit
Using iteration: digit2 ← Code DIV 100
This algorithm will continually ask for the data to be input until it is a string Code ← Code - (100 * Digit1)
value. //extract 3rd digit
INPUT Data Digit3 ← Code DIV 10
//loop while the data entered is not a string Code ← Code - (10 * Digit1)
WHILE Data.IsString = FALSE DO //extract 4th digit
OUTPUT("Invalid please try again") Digit4 ← DIV(Code, 1)
INPUT Data CheckDigit ← Code
ENDWHILE //calculate check digit from data entered
//multiply by position and add together
Presence check
Total ← (Digit1 * 4) + (Digit2 * 3) + (Digit2 *
A presence check makes sure that some data has been entered. 2) + Digit3
Programming languages can make use of the value null, or for a string NewCheckDigit ← MOD(Total, 11) //find Mod 11 of
value an empty string represented by "". total
Example 1 NewCheckDigit ← 11 - NewCheckDigit //subtract
Using selection: result from newCheckDigit
//check if the calculated check digit is the
This algorithm outputs Invalid if there is no data entered.
same as the last digit in the //code
INPUT Data IF NewCheckDigit = CheckDigit THEN
IF Data = NULL THEN //check if the data entered OUTPUT("Correct data entry")
is null ELSE
OUTPUT("Invalid") OUTPUT("Incorrect data entry")
ENDIF 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
You can find out more about check digits in Chapter 2. 7.8 Trace tables
Verification of data A trace table is a structure to help you follow an algorithm, for example, to find
an error, or to work out what the algorithm does.
When entering data from another source, for example, a paper copy, it is
important to make sure you have entered exactly what was written originally. Each statement in an algorithm is run manually, and the values that are written
This is called verification, a check that you have copied the data accurately. to variables are written in the table in the order the changes are made.
There is a difference between entering data accurately, and entering the Each column in the table is designated to one variable. There can also be a
correct data. Verification only checks you have copied it accurately, the actual column for any outputs to be written in. User prompts are also entered in the
data may still be incorrect if the original was incorrect. 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
Two forms of verification are a visual check and double entry.
text “Enter a number” is a user prompt and will need to be added to the trace
A visual check is where you compare the data entered to the original. For table.
example, reading each line from a paper copy and checking it is identical on
Specific inputs can be given to test different parts of the algorithm.
the computer.
A double entry check is where the same data is entered twice, usually by SKILLS FOCUS 7.3
different people. The computer will then check whether there are any
differences in what they each entered. TRACE TABLE WITH SELECTION
To create a trace table you need to identify all of the variables in an
COMPUTER SCIENCE IN CONTEXT algorithm. Each variable should have its own column in the trace table.
There should also be an output column if the program will output any data or
Have you ever had to enter data into a program twice? You have most strings.
likely done this when entering your email address, or a password. Think
about why it was important that your email and password were entered For example, trace the following algorithm with the input values 1 and 3.
accurately. What could have happened if they were not? INPUT Number1
INPUT Number2
IF Number1 > Number2 THEN
PROGRAMMING TASK 7.6 OUTPUT(Number1)
ELSE
A user needs to enter a series of data that each require validation. The
table shows the data and the requirements: OUTPUT(Number2)
ENDIF
Data Validation requirements
There are two variables and there is an output (each variable has a column,
Username Minimum length of 5 characters. and the output has a column).
Date of birth In the format NN/NN/NNNN, e.g. 01/01/2020.
number1 number2 OUTPUT
Type of character Limited to: "Elf", "Fairy", "Gnome", "Magician".
Starting strength A number between 1 and 5 inclusive.
Starting health 10 minus the starting strength input.
You then complete this table by reading through the algorithm one line at a
Getting started time. It is important not to jump ahead and guess what the algorithm will do.
For each of the validation requirements, decide on which type of validation Read one line and perform that action.
you are going to use. Try and choose a different one for each value. Run line 1 of the code (input values 1, 3):
Recap the algorithms for each type, write an example beside each of the INPUT Number1
ones you have chosen. INPUT Number2
IF Number1 > Number2 THEN
Practice OUTPUT(Number1)
1 Write an algorithm to take as input the five values. ELSE
2 Amend the program to include the validation for each item of data.
OUTPUT(Number2)
ENDIF
3 Amend your program to output, for each data item, whether their data
is valid or invalid.

Challenge
Run line 2 of the code (input values 1, 3):
Extend the program to repeatedly ask for each item of data until they
enter one that is valid. Then the next piece of data should be input. INPUT Number1
Could any of the items of data have more than one validation rule used?
INPUT Number2
Find at least one piece of data that can have two types of validation and IF Number1 > Number2 THEN
implement it in your program. OUTPUT(Number1)
ELSE
OUTPUT(Number2)
ACTIVITY 7.8 ENDIF
Work in pairs to identify how many times you have come across validation
or verification in a program or website. Compare your answers with
another pair. How common are validation and verification? Are there any
methods not identified here, for example, what is two-step verification?

Questions
25 What is validation?
26 Give three examples of validation checks.
27 What is the purpose of verification?
28 Identify which validation rule this algorithm uses:
INPUT Num
IF Num > 0 AND Num < 100 THEN
ACTIVITY 7.9
OUTPUT "Valid"
ELSE Run the algorithm in Skills Focus 7.3 with the following input data:
OUTPUT "Invalid"
a 10, 2
ENDIF
b 9, 9
29 Identify which validation rule this algorithm uses: c 20, 30
REPEAT
INPUT Value
Peer Assessment
UNTIL Value <> NULL AND Value <> ""
Compare your answers from running the algorithm with the different
30 Write a validation routine to input a word and check that it is more than values with a partner. Did you get the same result? If not, work out which
10 characters long. is correct by running the algorithms again.
31 Write a validation routine to input a number and check that it is an integer
value.
SKILLS FOCUS 7.4
7 Line 08 again returns to line 04. WHILE 2 > 0 is TRUE. Run lines 05,
TRACE TABLE WITH LOOPS 06 and 07.
When you are following an algorithm that includes a loop (iteration), some of
the code will be repeated. To follow the code run one line at a time as 05 INPUT InputValue InputValue ← 1
before, and when you get to the end of the loop, go back to the start of the 06 Total ← Total + Total ← 9 + 1
loop. InputValue
For example: trace the following algorithm with the input values 4, 3, 2, 1, 0. 07 Count ← Count + 1 Count ← 3 + 1
01 Count ← 0
count inputValue total OUTPUT
02 InputValue ← 1
0 1 0
03 Total ← 0
04 WHILE InputValue > 0 DO 1 4 4
05 INPUT InputValue 2 3 7
06 Total ← Total + InputValue 3 2 9
07 Count ← Count + 1
4 1 10
08 ENDWHILE
09 OUTPUT "The total is ", Total 8 Line 08 returns to line 04 again. WHILE 1 > 0 is TRUE. Run lines 05,
10 OUTPUT "There were ", Count, " Numbers" 06 and 07.
Start by creating the trace table with each of the variables and the output.
There are 3 variables in this algorithm: 05 INPUT InputValue InputValue ← 0
06 Total ← Total + Total ← 10 + 1
Count InputValue Total OUTPUT InputValue
07 Count ← Count + 1 Count ← 4 + 1

count inputValue total OUTPUT


1 Run the first 3 lines of code. These are the initialisations, lines 01, 02
and 03. 0 1 0
01 Count ← 0 1 4 4
02 InputValue ← 1 2 3 7
03 Total ← 0 3 2 9
Count InputValue Total OUTPUT 4 1 10

0 1 0 5 0 10

9 Line 08 returns to line 04 again. WHILE 0 > 0 is FALSE this time, so


the loop does not run.
2 Run line 04.
04 WHILE InputValue > 0 DO Jump to line 09 run line 09 and 10.

LOOP is 1 so this is TRUE meaning that the code inside the loop is run 09 OUTPUT "The total is ", Total
10 OUTPUT "There were ", Count, " numbers"
Run line 05 with the first input value of 4.
05 INPUT InputValue

3 Run lines 06 and 07.


Questions
06 Total ← Total + Total ← 0 + 4 1 What do you record in a trace table?
InputValue 2 When do you change the value in a column?
07 Count ← Count + 1 Count ← 0 + 1

count inputValue total OUTPUT ACTIVITY 7.10


0 1 0 Trace the algorithm in Skills Focus 7.4 with the following inputs:
1 4 4 a 1,
4 Line 08: b 1, −1, 2
08 ENDWHILE c 10, 20, 30, −5
sends you back to line 04.
Self Assessment
04 WHILE InputValue > 0 DO
Trace the algorithms a second time and see whether you got the same
InputValue is 4, so while 4 > 0 is TRUE to run line 05 with the result. If not, where did you go wrong?
second input value of 3.
05 INPUT InputValue

count inputValue total OUTPUT


0 1 0
1 4 4
3

5 Lines 06 and 07 run.

06 Total ← Total + Total ← 4 + 3


InputValue
07 Count ← Count + 1 Count ← 1 + 1

count inputValue total OUTPUT


0 1 0
1 4 4
2 3 7

6 Line 08 ENDWHILE returns to line 04.


04 WHILE InputValue > 0 DO WHILE 3 > 0 is
TRUE. Run lines 05, 06 and 07.

05 INPUT InputValue InputValue ← 2


06 Total ← Total + Total ← 7 + 2
InputValue
07 Count ← Count + 1 Count ← 2 + 1

count inputValue total OUTPUT


0 1 0
1 4 4
2 3 7
3 2 9
SKILLS FOCUS 7.6
7.9 Finding the purpose of an algorithm
A trace table can help you work out the purpose of an algorithm. By following DESCRIBING AN ALGORITHM
an algorithm step-by-step you can see what happens to the values, what When you are describing an algorithm you need to do more than repeat the
changes are made, and when these are made. From this you can determine line of code using English statements. For example, in the following code,
the purpose of the algorithm. 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.
SKILLS FOCUS 7.5 01 INPUT X
FINDING THE PURPOSE WITH A TRACE TABLE 02 FOR Y ← 0 TO X
03 OUTPUT Y
Describe the processes in this algorithm and state its purpose.
04 NEXT Y
INPUT Value1 You can do a trace table to help you work out the purpose of the algorithm
INPUT Value2 before describing it if that helps you. This algorithm has three parts: line 01,
INPUT Value3 line 02 and line 03. These are summarised below:
IF Value1 > Value2 AND Value1 > Value3 THEN • Takes a number as input. (line 01)
OUTPUT(Value1)
ELSEIF Value2 > Value1 AND Value2 > Value3 • Loops from 0 to the number that has been input. (line 02)
THEN • Outputs the values from 0 to the number. (line 03)
OUTPUT(Value2) From this you can develop a description of the algorithm, for example:
ELSE
The algorithm takes a number from the user, and then outputs all of the
OUTPUT(Value3) numbers from 0 to the number input.
ENDIF
Questions
OUTPUT(Value1 + Value2 + Value3)
1 What methods can you use to work out the purpose of an 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 2 Why should your description explain more than what each part of the
then 3. code does?
2 Create a trace table by following the algorithm with the data input. 3 Describe the purpose of this algorithm:
01 X ← -1
Value1 Value2 Value3 OUTPUT 02 Count ← 0
1 2 3 3 03 WHILE Count < 10 DO
6 04 INPUT Y
05 IF Y > X THEN
3 Repeat the process with a different set of data, for example, this time 06 X = Y
using 07 ENDIF
10, 5, 1. 08 Count ← Count + 1
4 Complete the trace table. 09ENDWHILE
10 OUTPUT(X)
Value1 Value2 Value3 OUTPUT
10 5 1 10
16
7.10 Finding errors in a program and correcting the
errors
Keep on repeating this process until you can identify the pattern. To find an error in an algorithm you need to know the purpose of the algorithm.
In this case it is outputting the largest number input and then outputting the You can then test the algorithm with different data, completing trace tables if
total of needed, to find out what the algorithm actually does. Once you know the
the 3 numbers input. difference between what it does and should do, you can start to identify the
errors and the changes you need to make.
Questions
1 Two sets of data were used to run this algorithm. If you had to choose
COMPUTER SCIENCE IN CONTEXT
a third set what would you choose?
2 How do you know when to stop testing the algorithm with different Computer programmers will come across errors all the time. These could
data? be ones that they have made, or that they are testing or fixing for other
people. There are lots of ways that they can find the errors, but many of
3 Describe the processes in this algorithm and state its purpose using a
them will use the two methods used here; using a trace table, and dry
trace table. running by reading the code. There are other options often available to
Quantity ← 0 them as well, for example, features within the Integrated Development
Total ← 0 Environment (IDE) that they use to write the program. These features
Value ← 0 allow the programmer to see the values of variables and the outputs at
Small ← 999 each stage, without having to trace them manually.
WHILE Quantity < 5 DO
INPUT Value SKILLS FOCUS 7.7
IF Value >= 10 AND Value <= 100 THEN
Quantity ← Quantity + 1 USING A TRACE TABLE TO FIND ERRORS IN A PROGRAM
Total ← Total + Value Using a trace table will allow you to follow each step in the algorithm and by
IF Value < Small THEN comparing this to the intended outcome you can find where it goes wrong,
Small ← Value and then work out how to correct it.
ENDIF For example, this program should take 5 numbers as input and output the
ENDIF total of all the numbers.
ENDWHILE 01 Total ← 1
OUTPUT("small = ", Small) 02 Quantity ← 1
OUTPUT(Total / Quantity) 03 WHILE Quantity < 5 DO 
 04 INPUT Number
tip
05 Total ← Number
Copy the trace table and test the algorithm in Q3 with some sample data, 06 Quantity ← Quantity + 1
e.g. 1, 100, 50, 10, 33, 3, 42. 07 ENDWHILE
08 OUTPUT(Total)
quantity Total value small OUTPUT 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.
Total Quantity Number OUTPUT
The third requirement:
1 1
Output the largest value.
1 2 1
Line 10 outputs the largest value, this is correct.
2 3 2
The fourth requirement:
3 4 3
Calculate the average value.
4 5 4
The average is calculated by totalling the inputs and then dividing by the
number of inputs.
Now look at the results and where it has gone wrong: Line 08 totals the data entered, but it uses the wrong identifier, it should be
data not DATA.
1 The total is overwritten each time, it should be added to.
2 Total starts with 1 but this will add another 1 to the total, so it should be Total ← Total + Data
0. Line 11 works out the average correctly.
3 Only four numbers can be input, it should be five. The fifth requirement:
Let’s take each of the problems one at a time to solve them. Output the average value.
1 The total should not be overwritten. Line 05 overwrites the total. This Line 12 outputs the average correctly.
should be Total ← Total + Number.
In this case the errors and corrections have been identified along the way.
2 The total should not start at 1, it should be 0. Line 01 writes 1 to total. You can also combine this with using test data to check both the original
This line should be Total ← 0. algorithm and to check that your corrections are accurate.
3 Only 4 numbers are input, it should be 5. There are two ways this can Questions
be changed, both are valid. Either Line 02 can be Quantity ← 0 1 Complete the trace table for the following algorithm with the input data:
or line 03 can be WHILE Quantity < 6. 20 50 60 25 35.
Total ← 0
Average ← 0
SKILLS FOCUS 7.8
Counter ← 0
FINDING ERRORS BY READING THE CODE WHILE Counter <= 5 DO
You may not always need to use a trace table, or you may not want to. INPUT Mark
There are many different ways of finding the errors. In this example you will Total ← Total + Mark
look for each of the requirements in the algorithm to determine whether it Counter ← Counter + 1
has been met. ENDWHILE
The following algorithm should take 3 numbers as input, and output the Average ← Total / Counter
largest value and the average value. OUTPUT "The total is ", Total
01 Total ← 0 OUTPUT "The average is ", Average
02 Largest ← 999 Total Average Counter Mark OUTPUT
03 FOR X ← 0 TO 2
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 2 a Complete the trace table for the following algorithm using the input
value and the average value. data: 7.
This can be split into three sections: INPUT Number
WHILE Number >= 0 DO
1 Take 3 numbers as input.
OUTPUT Number
2 Output the largest value. Number ← Number - 1
3 Output the average value. ENDWHILE
The two outputs need to be calculated before being output, so they can be
added to the requirements: Number OUTPUT
1 Take 3 numbers as input.
2 Calculate the largest value.
3 Output the largest value.
4 Calculate the average value.
5 Output the average value.
Now check the first requirement:
Does it take 3 numbers as input?
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.
b State the purpose of the algorithm.
The second requirement:
3 Explain the purpose of the following algorithm:
Calculate the largest value.
Valid ← 0
To find the largest it needs to: Invalid ← 0
a Initialise a largest variable with a low number. Continue ← "Y"
This is not met. Line 02 largest is set to 999 but this should be a very WHILE Continue = "Y" DO
small value, e.g. INPUT Value
IF Value >= 10 AND Value <= 20 THEN
Largest ← -1
Valid ← Valid + 1
b It should check if the data input is larger than the data in largest. ELSE
This is not met. Line 05 checks if data is less than 999. It should be Invalid ← Invalid + 1
larger. ENDIF
IF Data > Largest THEN OUTPUT "Continue?"
INPUT continue
c Line 06 replaces the value in Large with data, but the identifier is
ENDWHILE
incorrect, the variable is named largest.
OUTPUT "valid = ", Valid
Largest ← Data
OUTPUT "invalid = ", Invalid
SUMMARY Blue White Yellow Continue Colour Quantity OUTPUT

Programs are developed by following a program development life cycle.


The program development life cycle is made up of; analysis, design,
coding and testing.
In the analysis stage the problem is identified and decomposed.
In the design stage the algorithms are planned.
In the coding stage the program is written.
In the testing stage the program is tested.
Decomposition is the splitting of a system into sub-systems.
Decomposition can be shown using a structure diagram.
Algorithms can be planned using flowcharts and pseudocode.
[5]
A linear search checks each item of data in turn.
A bubble sort compares the items in pairs repeatedly. 6 Show the stages of a linear search, when looking for the number 100
Totalling is adding together the values. in the following data:

Counting is adding 1 to the count for each item. 10 20 [3]


To find the minimum value, a variable needs to be initialised with a large
value. 7 Show the stages of a bubble sort to put the following data into
ascending alphabetical order:
To find the maximum value, a variable needs to be initialised with a small
value. apple pear banana pineapple orange peach [5]
Validation is checking data entered is reasonable and within bounds.
Validation checks include; range check, length check, type check, 8 The following algorithm should:
presence check, format check and check digit. • Ask the user to input a number 20 times.
Verification checks that data has been input accurately. • Count and output how many numbers are less than 10, equal to
Verification checks include visual check and double entry check. 10, and more than 10.
Four types of test data are normal, abnormal, extreme and boundary. • Calculate and output the average number entered.
A trace table is used to dry run an algorithm. It can be used to find the 01 TotalLess ← 0
purpose of an algorithm and to find errors in the algorithm. 02 Equal ← 0
03 TotalMore ← 0
04 Total ← 0
05 FOR X ← 0 TO 20
EXAM-STYLE QUESTIONS 06 INPUT Number
07 IF Number <= 10 THEN
1 Define the term algorithm. 08 TotalLess ← TotalLess + 1
[1] 09 ELSEIF Number <> 10 THEN
2 One stage of the program development life cycle is the 10 Equal ← Equal + 1
analysis. Identify and describe two other stages. 11 ELSE
[4]
12 TotalMore ← TotalMore + 1
3 Describe the purpose of decomposition. [2] 13 ENDIF
4 A computer game allows a user to load a saved game or to 14 Total ← Total + Number
start a new game. The game then loads the puzzle for that 15 NEXT X
level. The user controls a character by using the arrow keys 16 OUTPUT "Total less = ", TotalLess
on the keyboard. The left arrow moves the character left, the 17 OUTPUT "Total equal = ", Equal
up makes the character jump, right moves the character right, 18 OUTPUT "Total more = ", TotalMore
down makes the character lie down.
19 OUTPUT "Average = ", Total / 20
a Draw a structure diagram for the game. [4]
b Write an algorithm using a flowchart to represent the input The algorithm has four errors in it.
of a key from a user, and then move the character. [6]
Identify the line number of each error and write the corrected
c When the user starts a new game, they have to input a
line for each. [4]
name that is made of at least 8 letters. This is validated
using a length check.
i Identify one other appropriate validation routine that
could be used to validate the name. [1]
ii Write, using pseudocode, the length check validation
for the name. [4] SELF-EVALUATION CHECKLIST
[Total: 15]
After studying this chapter, think about how confident you are with the
5 Complete the trace table for the following algorithm, with the input different topics. This will help you to see any gaps in your knowledge and
data: help you to learn more effectively.
You might find it helpful to rate how confident you are for each of these
blue 5 Y blue 1 Y yellow 3 Y white 5 x statements when you are revising. You should revisit any topics that you
rated ‘Needs more work’ or ‘Getting there’.
Blue ← 10
I can… See Needs Getting Confident
White ← 5 topic more there to move
Yellow ← 2 work on
Continue ← "Y" identify the stages in the program 7.1
WHILE Continue = "Y" DO development life cycle.
INPUT Colour
use decomposition to split a system 7.2
INPUT Quantity into sub-systems.
IF Colour = "Blue" AND Quantity <=
Blue THEN create structure diagrams, flowcharts 7.3
and pseudocode algorithms.
Blue ← Blue - Quantity
OUTPUT "Blue left = ", Blue explain how a bubble sort and linear 7.7
search works.
ELSEIF Colour = "White" AND Quantity
<= White describe and produce algorithms that 7.7
White ← White - Quantity include finding the maximum, minimum
and average values.
OUTPUT "White left = ", White
ELSEIF Colour = "Yellow" AND Quantity understand the need for validation and 7.7
<= Yellow verification and write programs that
make use of each.
OUTPUT "Yellow left = ", Yellow
ELSE identify appropriate test data for an 7.6
OUTPUT "Try again" algorithm.
ENDIF complete a trace table for an algorithm. 7.8
OUTPUT "Continue?" check a program for errors and amend 7.10
INPUT Continue the program.
ENDWHILE explain the purpose of an algorithm. 7.9

You might also like