Chapter 7
Chapter 7
• 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.10: The New players subprogram Output An output of text in speech marks,
and/or the identifier of a value
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:
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.
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.
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.
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
0 1 0 5 0 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