You are on page 1of 170

Student book answers

1.1 ........................................................................................................................................... 3
End of topic questions ..................................................................................................... 3
Exam practice questions ................................................................................................. 6
1.2 ........................................................................................................................................... 7
End of topic questions ..................................................................................................... 7
Exam practice questions ................................................................................................. 9
1.3 ........................................................................................................................................... 9
End of topic questions ..................................................................................................... 9
1.4 ......................................................................................................................................... 14
End of topic questions ................................................................................................... 14
Exam practice questions ............................................................................................... 16
1.5 ......................................................................................................................................... 16
End of topic questions ................................................................................................... 16
Exam practice questions ............................................................................................... 17
1.6 ......................................................................................................................................... 18
End of topic questions ................................................................................................... 18
Exam practice questions ............................................................................................... 21
2.1 ......................................................................................................................................... 21
End of topic questions ................................................................................................... 21
Exam practice questions ............................................................................................... 30
2.2 ......................................................................................................................................... 36
End of topic questions ................................................................................................... 36
2.3 ......................................................................................................................................... 38
End of topic questions ................................................................................................... 38
Exam practice questions ............................................................................................... 67
2.4 ......................................................................................................................................... 68
End of topic questions ................................................................................................... 68
Exam practice questions ............................................................................................... 84
2.5 ......................................................................................................................................... 90
End of topic questions ................................................................................................... 90
Exam practice questions ............................................................................................... 94
2.6 ......................................................................................................................................... 95
End of topic questions ................................................................................................... 95
Exam practice questions ............................................................................................. 102
2.7 ....................................................................................................................................... 106
End of topic questions ................................................................................................. 106
Exam practice questions ............................................................................................. 111
3.1 ....................................................................................................................................... 112
End of topic questions ................................................................................................. 112
Exam practice questions ............................................................................................. 114
4.1 ....................................................................................................................................... 117
End of topic questions ................................................................................................. 117
Exam practice questions ............................................................................................. 118
4.2 ....................................................................................................................................... 118
End of topic questions ................................................................................................. 118
AQA Computing A2 Teacher Notes Nelson Thornes Ltd 2009

Exam practice questions ............................................................................................. 120


5.1 ....................................................................................................................................... 121
End of topic questions ................................................................................................. 121
Exam practice questions ............................................................................................. 122
5.2 ....................................................................................................................................... 122
End of topic questions ................................................................................................. 122
Exam practice questions ............................................................................................. 122
5.3 ....................................................................................................................................... 122
End of topic questions ................................................................................................. 122
Exam practice questions ............................................................................................. 124
6.1 ....................................................................................................................................... 137
End of topic questions ................................................................................................. 137
Exam practice questions ............................................................................................. 139
6.2 ....................................................................................................................................... 142
End of topic questions ................................................................................................. 142
Exam practice questions ............................................................................................. 146
6.3 ....................................................................................................................................... 148
End of topic questions ................................................................................................. 148
Exam practice questions ............................................................................................. 150
6.4 ....................................................................................................................................... 150
End of topic questions ................................................................................................. 150
Exam practice questions ............................................................................................. 152
7.1 ....................................................................................................................................... 154
End of topic questions ................................................................................................. 154
Exam practice questions ............................................................................................. 158
7.2 ....................................................................................................................................... 159
End of topic questions ................................................................................................. 159
7.3 ....................................................................................................................................... 160
Exam practice questions ............................................................................................. 160
7.4 ....................................................................................................................................... 166
Exam practice questions ............................................................................................. 166
7.6 ....................................................................................................................................... 168
End of topic questions ................................................................................................. 168

AQA Computing A2 Teacher Notes Nelson Thornes Ltd 2009

1.1
End of topic questions
1 Information hiding means hiding design details behind a standard interface.
2 An interface is a device or combination of devices such as a keyboard/VDU situated between the
user and the internal operation of a machine and through which the user interacts with the machine.
3 Possible answers are:
a) By hiding the complexities of the machine behind a well-designed interface users are able to
learn how to use a machine with the minimum of training.
b) The operator of a machine does not need to know how the operation of the machine is achieved
only how to control it.
c) The internal components of the machine may be replaced by similarly functioning components
but designed in a different way, e.g. using a different technology, without the experience of the
user changing or the user needing to be re-trained.
4 In order to make the manufacturing, and maintenance of a car manageable, a car is divided into
parts with particular interfaces hiding design decisions. Some car parts or components are listed
below:
Engine
Gearbox
Transmission (transfers power from engine to wheels)
Lights
Pedals
This division into separate components or modules allows the car manufacturer to offer different
options. For example, a particular model may be offered with different capacities of engine, 1.8
litres, 2.5 litres, 3 litres. All three engines fit the same transmission, the same engine mounts, and
the same controls. This is possible because all three engines provide the same interface to the other
parts/modules that they connect to. The same applies for maintenance. An engine may be replaced
relatively easily because it is designed to fit the engine mounts, transmission system and so on.
5 A well-designed computer program has a solution in which the source code has been decomposed
into modules using the principle of information hiding. When a programmer is working on one
module he or she does not need to know the detail contained in other modules, only what other
modules can do for the programmer. Also changes are much easier to make with this approach
because the changes typically are local to a module rather than global changes across all modules.
6 a) Different objects can have identical interfaces
b) Sharing a common interface among many different objects means that users of the objects do not
need to be re-trained when changing from using one object to using another
c) To use a module or object a user needs to have no knowledge of the modules or objects
internal design
d) The internal design can be kept secret
e) Allows flexibility, one module may be replaced by another module with an identical interface
but a different internal design or manner in which the modules function is carried out
f) Changes are made easier because changes are local to modules
7 Abstraction means omitting unnecessary details or, as a skill, it means drawing out the essence of a
problem, solving it and then seeing what other problems can be solved using the same techniques.
8 Any suitable example, e.g. sketching a map to give someone directions. You might base your sketch
on an ordnance survey map. You pick and add four or five major labelled landmarks to your sketch
AQA Computing A2 Teacher Notes Nelson Thornes Ltd 2009

and link these by lines representing the route. You have left out all the unnecessary detail on the
ordnance survey map in order to convey the essentials of the route in your sketch.

ConvertTemperature

9
F GetF

Write('Input F: ')

Display(C)

ConvertFtoC(F)

ConvertFtoC (F - 32)* 5/9

Writeln('Celsius = ', C)

Readln(FTemp)
GetF FTemp

F GetF
C ConvertFtoC(F)
Display(C)

10 There are several ways of classifying plants. One way to classify plants is according to the way a
plant absorbs water. Plants are either vascular or non-vascular. Vascular plants have tube-like
structures that transport water from the roots to the stem to the leaves. Non-vascular plants absorb
water only through their surfaces.

Vascular

Nonvascular

Angiosperms

Seeds on cones

Parallelveins
Branching
Parallel
Branching
veins
network
of veins
network
of veins
Monocots

Seeds in
flowers

11 Each person can shake hands with 0 to n 1 other people. This creates n 1 possible holes. It is not
possible for both the '0' and the 'n 1' hole to be empty because when one person shakes hands with
everybody, it's not possible to have another person who shakes hands with nobody; likewise, when
one person shakes hands with no one there cannot be a person who shakes hands with everybody.
This leaves n people to be placed in at most n 1 non-empty holes, guaranteeing duplication.

AQA Computing A2 Teacher Notes Nelson Thornes Ltd 2009

12 Assume that in a box there are 10 black socks and 12 blue socks and you need to get one pair of
socks of the same colour. Supposing you can take socks out of the box only once and only without
looking, how many socks do you have to pull out together? Use the Pigeonhole principle.
The correct answer is three. To have at least one pair of the same colour (m = 2 holes, one
per colour), using one pigeonhole per colour, you need only three socks (n = 3 objects). In
this example, if the first and second sock drawn are not of the same colour, the very next
sock drawn would complete at least one same-colour pair. (m =.
13

Guyana
Venezuela
Suriname
French

Columbia

Guyana

Brazil
Peru
Ecuador
Bolivia

Paraguay

Uruguay

Chile

Argentina

AQA Computing A2 Teacher Notes Nelson Thornes Ltd 2009

14

(a)
B
A

C
E
D

(b) 3

Exam practice questions


Question Number
1

Answer

Marks

Information hiding means hiding design details behind a


standard interface.

In software development, a programmer can use a


library module without needing an intimate knowledge
of the modules design. Information hiding usually
means that a software module is self-contained,
otherwise its design would have to be revealed. This
allows the internal design of a module to be changed
whilst isolating users from these changes, i.e. the
software that uses the module should still work and
probably better than before because of the internal
changes to the module. Also, changes are much easier to
make with this approach because the changes typically are
local to a module rather than global changes across all
modules. If a whole software project is divided into
modules using the principle of information hiding then it is
possible for different programmers to work on different
modules at the same time so that the project can be
completed more quickly. Information hiding also creates
designs that can be kept secret more easily. From a users
point of view, information hiding means that when the
internal design of a module changes the user doesnt have to
be retrained. Outwardly the module should still appear the
same.
The principle of information hiding allows the division of
any piece of equipment, software or hardware, into separate
parts. For example, a car is a complex piece of equipment.
In order to make the design, manufacturing, and

AQA Computing A2 Teacher Notes Nelson Thornes Ltd 2009

maintenance of a car manageable, a car is divided into parts


with particular interfaces hiding design decisions. This
division into separate components or modules allows the car
manufacturer to offer different options. For example, a
particular model may be offered with different capacities of
engine, 1.8 litres, 2.5 litres, 3 litres. All three engines fit the
same transmission, the same engine mounts, and the same
controls. This is possible because all three engines provide
the same interface to the other parts/modules that they
connect to.
Question Number

Answer

Marks

2a

Abstraction by generalisation proceeds from a detailed


picture of specific instances to a less detailed picture of
classes to which the instances belong or are examples of.
This is an example of classification-type generalisation.
Another type of generalisation is of the decomposition-type.
In this type, the abstraction proceeds in the direction of
more and more detail as in top-down program development.

2b

Abstraction by representation is applied to problem solving.


Details are removed until it becomes possible to represent
the problem in a way that is possible to solve.

5 Question
Number

6 Answer

7 Marks

3a

B
A
C
3b

2 tables

D
2

1.2
End of topic questions
1 Algorithms are considered to be procedural solutions to problems and problem solving is a human
activity. Designing algorithms is a problem solving activity that can be useful regardless of whether a
computer is involved. Computer programs would not exist without algorithms. Therefore, a study of
algorithms is considered to be a cornerstone of computer science. There may be more than one
algorithm for solving a particular problem and algorithms for solving a particular problem may do so
with dramatically different speeds and also with different memory requirements.

AQA Computing A2 Teacher Notes Nelson Thornes Ltd 2009

2 a) Twice as long
b) Eight times as long
c) 2n times as long
3 Using a standard unit of time measurement, such as a second, to estimate the running time of a
program implementing the algorithm, would not be sensible. The estimate would be dependent on the
speed of the computer, the quality of the program implementing the algorithm and the compiler used in
generating the machine code.
4 Compute the number of times the basic operation is executed on inputs of size n. The basic
operation is the operation in the algorithm contributing the most to the total running time.
5 a) The computational complexity of an algorithm measures how economical the algorithm is with
time and space.
b) Computational complexity of a problem is taken to be the worst-case complexity of the most
efficient algorithm, which solves the problem.
6 a) Time-complexity of an algorithm indicates how fast an algorithm runs.
b) Space-efficiency of an algorithm indicates how much memory an algorithm needs.
7 Input size is number of elements in the array, i.e. n. The innermost loop contains a single operation,
the comparison of two elements. Consider this as the algorithms basic operation. In the worst-case
scenario, the input is an array for which the number of element comparisons is the largest amongst
all arrays of size n. There are two cases for this worst case scenario:
a) arrays with no equal elements
b) arrays in which the last two elements are the only pairs of equal elements.
For such inputs, one comparison is made for each repetition of the innermost loop, i.e. for each
value of the loops variable j between limits i + 1 and n. This is repeated for each value of the outer
loop, i.e. for each value of the loops variable i between its limits 1 and n - 1. Consider the case
when n = 6.

Element
no.
1
2
3
4
5

No. of
comparisons
5
4
3
2
1

Element in first column compared with


elements
2, 3, 4, 5, 6
3, 4, 5, 6
4, 5, 6
5, 6
6

In general, the number of comparisons becomes 1 + 2 + 3 + 4 + 5 + + n


n-1)n
This has the sum
2
n2
b) For large values of n this becomes

as (n - 1)n = n2 - n and for large n, n2 dominates.

8 Asymptotic behaviour of a function is the behaviour of the function for very large values of n.
9 Given a function g(n) then big O of g, represents the class of functions that grow no faster than the
function g.
10
f = O(log2 n)
f = O(n)
f = O(nlog2 n )
f = O(n2)
f = O(n3)

AQA Computing A2 Teacher Notes Nelson Thornes Ltd 2009

f = O(2n)
f = O(n!)
11 (a)Exponential growth exhibits growth rates that vary according to the form kn, e.g. 2n where k = 2
and n = 1, 2, 3, etc.
(b) Polynomial growth exhibits growth rates that vary according to the form nk, e.g. n3 where k = 3
and n = 1, 2, 3, 4, etc.
(c) An exponential time algorithm is one whose execution time grows exponentially with input size.
(d) A polynomial time algorithm is one whose execution time grows as a polynomial of input size.
(e) A linear time algorithm is a polynomial time algorithm that executes in O(n) time.

Exam practice questions


Question 1 Specimen Paper COMP 3 Q1
Question number

Answer

Marks

1a

1. A
2. C
3. B

1b

Start at first item; and examine each succeeding item in turn;


Until item is found; or the end of the list reached;
A algorithm
max 3
O(n) as up to n items searched;
All items may be searched;
max 1

1c

For each succeeding pair of items;


if they are out of sequence they are swapped;
the process is repeated;
up to n-1 times; or until no more swaps are made;
max 3
All n items are compared up to n-1 times;
1

1.3
End of topic questions
1 A finite state machine (FSM) consists of a set of input symbols (input symbol alphabet) and if it
produces output, a set of output symbols (output symbol alphabet), a finite set of states and a
transition function that maps a state-symbol pair (current state and input symbol) to a state (next
state) and possibly generates an output (output symbol) depending on the type of FSM.
2 000100

AQA Computing A2 Teacher Notes Nelson Thornes Ltd 2009

3 00000000, S0
4

5 Mealy machine: an FSM that determines its outputs from the present state and from the inputs.
Moore machine: an FSM that determines its outputs from the present state only.
6

7
=0
=1
=1
= 0c1
8 One-bit binary adder
9 An FSM without output is known as a finite state automaton (FSA) or finite automaton, plural finite
state automata. FSA are restricted to decision problems, i.e. problems that are solved by answering
YES or NO. Therefore, FSA do not write anything at all whilst processing input whereas an FSM
with output does.

AQA Computing A2 Teacher Notes Nelson Thornes Ltd 2009

10

10

No
Yes
No
Yes
No

AQA Computing A2 Teacher Notes Nelson Thornes Ltd 2009

11

AQA Computing A2 Teacher Notes Nelson Thornes Ltd 2009

12

AQA Computing A2 Teacher Notes Nelson Thornes Ltd 2009

13

11 An FSA is deterministic if every state has exactly one transition or edge leaving it for each of the
symbols in the alphabet. As there is exactly one edge for each symbol, an input word will cause the
exact same behaviour every time a deterministic finite automaton is run on the word. A finite
automaton can be non-deterministic if it does not have exactly one edge for each symbol of the
alphabet. A state can have no edges for a symbol or it can have multiple edges for each symbol of
the alphabet.
12 On reaching the end of the input if the FSA is in an accepting state then the FSA outputs a YES
response.
13 aa|b(a|b)*

1.4
End of topic questions
1

11111

AQA Computing A2 Teacher Notes Nelson Thornes Ltd 2009

14

2 a)

b)

3 Adds 1 to the number on the tape


4 A Turing machine (TM) is a finite state machine that controls one or more tapes, where at least one
tape is of unbounded length (i.e. infinitely long).
5 Principle of universality: a universal machine is a machine capable of simulating any other
machine.
6 A universal Turing machine, U, is an interpreter that reads the description <M> of any arbitrary
Turing machine M and faithfully executes operations on data D precisely as M does. For single-tape
Turing machines, imagine that <M> is written at the beginning of the tape, followed by D.
7 Coffee maker
8 A consequence of a universal Turing machine is that programs and data are really the same thing.
A program is just a sequence of symbols that looks like any other piece of input but when fed to a
universal machine this input wakes up and begins to compute. A computer downloads Java applets,
e-mail viruses as data but can then proceed to execute them as programs.
9 A microprocessor is a universal machine. An embedded computer with a microprocessor at its core
can be programmed to perform as a microcontroller by choosing the right set of program
instructions. The program or programs are changed when a different functionality is required.
10 A task is computable if and only if it can be computed by a Turing machine.

AQA Computing A2 Teacher Notes Nelson Thornes Ltd 2009

15

Exam practice questions


Question 1 Specimen Paper COMP3 Q6
Question Answer
Number

Marks

1a

(i)
1 mark for correctly positioned arrow, ignore data on tape

(ii) 1

1b

2 marks for correct tape symbols, 1 mark for correct position of arrow

1c

3 + 1 or the successor to 3

1.5
End of topic questions
1
a) The answer is not decidable
b) Undecidable or noncomputable
2
1024
1048576
1073741824
1099511627776
1125899906842624
1152921504606847000
1.329227995784916 10+36
3
a)
24 = 16
210 = 1024
18446744073709552000
1.33 1050
b) Intractable
4
a) Tractable means that a problem has a reasonable (polynomial) time solution as the size of the
input increases.
b) Intractable means that no reasonable (polynomial) time solution has yet been found.

AQA Computing A2 Teacher Notes Nelson Thornes Ltd 2009

16

c)
first option = 10.24 and second option = 11
first option = 10485.76 and second option = 21
first option = 45035996273704.96 and second option = 53
5 15 days
6 NP-type problem
7 No

Exam practice questions


Question number

Answer

Marks

1a

Lets call the liars group A and the truth tellers group B. If
the native belongs to B, then since this native tells the truth
he/she contradicts themself by saying that they did not say
they were a truth teller when asked if they were a truth
teller. Therefore the native belongs to the liars group.

1b

The problem posed in part (a) belongs to the family of logic


problems known as decision problems.

1c

First is from the liars group. If the first is from the truth
tellers group then the statement would be a contradiction.
If the first is from the liars group then he has lied and so
both are not from the liars group. Therefore, the second
must be from the truth tellers group.
The second from the truth tellers group.

1. No, there is only one haircutter and he cuts the hair of


everyone on the island who does not cut their own hair.
If the haircutter cut their hair then this would contradict
the statement in the previous sentence. Therefore, the
haircutter does not cut his own hair. So, the haircutters
hair must be cut by someone else. However, everyone
who cuts anothers hair is called a haircutter but the
island has only one haircutter. Therefore, the question
cannot be answered.
2. This type of problem is undecidable.

16

210

264

Intractable

The planks would take up a large amount of space and it


would take a long time to place all the planks in the squares
on the sand.

Answer

Marks

1d

1e

Question number

AQA Computing A2 Teacher Notes Nelson Thornes Ltd 2009

17

2a

Intractable means that no reasonable (polynomial) time


solution has yet been found. Processing will take an
unreasonable amount of time even for quite small data sets.

2b

For a class of intractable problems it is possible to guess a


solution and check the solution in polynomial time, i.e. a
reasonable amount of time. School timetabling is one of
these problems. They are known as non-deterministic
polynomial type problems or NP-type problems.

Question number

Answer

Marks

The halting problem is the problem of determining without


executing a program whether it will halt on a given input. It
relates to answering the question of whether or not it is
possible to write a program that can, in general, test any
other program supplied with its input and determine, without
executing the program under test, if it will halt on this input.
The answer to this question is no.

1.6
End of topic questions
1
a) A valid string consists of one or more as or one or more cs followed by two bs[ll]
b) aaccbb, cacccbb
2 (a|c)a*c*bb
3
a) (0|1)*
b) 1+
c) 10*
d) (110|011)(0|1)*
e) (0|1)+0
f) 11(0|1)*11
4 x*y*z*
5 beean
6 bead
7 10101
8 01296-433006 or 01793 234589
9 www.([_a-zA-Z\d\-]+(\.[_a-zA-Z\d\-]+)+)
10 li(c|s)en(c|s)e

AQA Computing A2 Teacher Notes Nelson Thornes Ltd 2009

18

11 Roman Numerals

12

Identifier

Letter

Digit

AQA Computing A2 Teacher Notes Nelson Thornes Ltd 2009

19

13 UserID

Digit

Digit

A..Z

A..Z

Pa

Ph
14
a)
b)
c)
d)
e)
f)

xy+
xy+2/
xy+x4-/
xy
xy+2
xy+xy-/

a)
b)
c)
d)
e)

x*y
(x + y) * 6
(x + y) / (x - y)
(2 * x + 3 * y) /8
((x +y) 2) * (6 - x)

15

AQA Computing A2 Teacher Notes Nelson Thornes Ltd 2009

20

Exam practice questions


Question 1 Specimen Paper COMP3 CPT4 Q7
Question
Answer
number

Marks

1a

1b

5 6 2 ;*; +;
No Brackets;
Easy to Compute;

2
1

Question 2 - KB
Question number

Answer

Marks

2a

Yes

2b

No

2c

Yes

2.1
End of topic questions
Q1 This is to produce a table as Table 01 in the book.
Q2 & Q3 are just using the code in the book and running it.
Q4 & Q5 Library unit
Unit Unit2;
Interface
Type TClock = Class
Private
Hours: Integer;
Minutes: Integer;
Public
Function GetHours: Integer;
Function GetMinutes: Integer;

AQA Computing A2 Teacher Notes Nelson Thornes Ltd 2009

21

Procedure SetTime(h, m : Integer);


Procedure IncrementTime ; Virtual;
End;
Type TAlarmClock = Class (TClock)
Private
AlarmHours: Integer;
AlarmMinutes: Integer;
Public
Function GetAlarmHours: Integer;
Function GetAlarmMinutes: Integer;
Procedure SetAlarmTime(h, m : Integer);
End;
Type TWatch = Class (TClock)
Private
DayOfWeek: Integer;
DayNumber: Integer;
Public
Function GetDayNumber: Integer;
Function GetDayName: String;
Procedure SetDayOfWeek(d : Integer);
Procedure SetDayNumber(d : Integer);
Procedure IncrementTime; Override;
End;
Implementation
Uses SysUtils;
Function TClock.GetHours: Integer;
Begin
GetHours := Hours;
End;
Function TClock.GetMinutes: Integer;
Begin
GetMinutes := Minutes;
End;
Procedure TClock.SetTime (h, m : Integer);
Begin
Hours := h;
Minutes := m;
End;
Procedure TClock.IncrementTime;
Begin
Minutes := Minutes + 1;
Sleep(600); // wait one minute
If Minutes = 60
Then
Begin
Hours := Hours + 1;
Minutes := 0;
If Hours = 24 Then Hours := 0;
End;
End;
Procedure TWatch.IncrementTime;
Begin
Inherited IncrementTime;

AQA Computing A2 Teacher Notes Nelson Thornes Ltd 2009

22

If Hours = 24
Then
Begin
Hours := 0;
DayNumber :=
If DayNumber
DayOfWeek :=
If DayOfWeek
End;
End;

DayNumber + 1;
> 31 Then Daynumber := 1;
DayOfWeek + 1;
> 7 Then DayOfWeek := 1;

Function TWatch.GetDayNumber: Integer;


Begin
GetDayNumber := DayNumber;
End;
Function
Begin
Case
1:
2:
3:
4:
5:
6:
7:
End;
End;

TWatch.GetDayName: String;
DayOfWeek Of
GetDayName :=
GetDayName :=
GetDayName :=
GetDayName :=
GetDayName :=
GetDayName :=
GetDayName :=

'Sun';
'Mon';
'Tue';
'Wed';
'Thu';
'Fri';
'Sat';

Procedure TWatch.SetDayOfWeek (d : Integer);


Begin
DayOfWeek := d;
End;
Procedure TWatch.SetDayNumber(d: Integer);
Begin
DayNumber := d;
End;
Function TAlarmClock.GetAlarmHours: Integer;
Begin
GetAlarmHours := AlarmHours;
End;
Function TAlarmClock.GetAlarmMinutes: Integer;
Begin
GetAlarmMinutes := AlarmMinutes;
End;
Procedure TAlarmClock.SetAlarmTime (h, m : Integer);
Begin
AlarmHours := h;
AlarmMinutes := m;
End;
End.

AQA Computing A2 Teacher Notes Nelson Thornes Ltd 2009

23

Q4)
Program AlarmClockExample;
{$APPTYPE CONSOLE}
Uses
SysUtils,
Unit2 in 'Unit2.pas';
Var AlarmClock: TAlarmClock;
Begin
AlarmClock := TAlarmClock.Create;
AlarmClock.SetTime(15,10);
AlarmClock.SetAlarmTime(15,15);
Repeat
AlarmClock.IncrementTime;
writeln(AlarmClock.GetHours,':',AlarmClock.GetMinutes);
Until (AlarmClock.GetAlarmHours = AlarmClock.GetHours)
And (AlarmClock.GetAlarmMinutes = AlarmClock.GetMinutes);
Writeln('Wake up');;
AlarmClock.Free;
ReadLn;
End.

Q5)
Program WatchExample;
{$APPTYPE CONSOLE}
uses
SysUtils,
Unit2 in 'Unit2.pas';
Var Watch: TWatch;
Begin
Watch := TWatch.Create;
Watch.SetTime(23,50); // give a start time
Watch.SetDayNumber(15); // give a start date
Watch.SetDayOfWeek(7); // give a day of the week
Repeat
Watch.IncrementTime;
// display the time and date
write(Watch.GetHours:2,':',Watch.GetMinutes:2);
WriteLn(' ',Watch.GetDayName,' ', Watch.GetDayNumber);
Until False;
Watch.Free;
ReadLn;
End.

AQA Computing A2 Teacher Notes Nelson Thornes Ltd 2009

24

Q6 & Q7
Class definition code:
Unit ClassDefs;
Interface
Uses Classes, StdCtrls;
Type TClock = Class (TLabel)
Private
Hours: Integer;
Minutes: Integer;
Seconds: Integer; // only required for Exercise 2
Function IntToStrF (i: Integer): String;
Public
Constructor Create (AOwner:TComponent); Override;
Procedure IncrementTime;
Procedure DisplayTime;
End;
Implementation
Uses SysUtils, StrUtils;
Constructor TClock.Create (AOwner: TComponent);
Begin
Inherited Create(AOwner);
Top := 20;
Left := 20;
Hours := 0;
Minutes := 0;
Seconds := 0; // only required for Exercise 2
Caption := '00:00:00';
End;
Procedure TClock.IncrementTime;
Begin
Seconds := Seconds + 1; // only required for Exercise 2
If Seconds = 60
// only required for Exercise 2
Then
Begin
Minutes := Minutes + 1;
Seconds := 0;
// only required for Exercise 2
If Minutes = 60
Then
Begin
Hours := Hours + 1;
Minutes := 0;
If Hours = 24
Then Hours := 0;
End;
End;
End;
Function TClock.IntToStrF (i: Integer): String;
Var StringI: String[2];
Begin
StringI := IntToStr(i);
If Length(StringI)=1
Then IntToStrF := '0' + StringI

AQA Computing A2 Teacher Notes Nelson Thornes Ltd 2009

25

Else IntToStrF := StringI;


End;
Procedure TClock.DisplayTime;
Var StrMinutes, StrHours, StrSeconds : String[2];
Begin
StrMinutes := IntToStrF(Minutes);
StrHours := IntToStrF(Hours);
StrSeconds := IntToStrF(Seconds);
// only required for Exercise 2
Caption := StrHours + ':' + StrMinutes + ':' + StrSeconds;
End;
End.
Code for the form:
Unit ClockForm;
Interface
Uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls,
Forms,
Dialogs, ClassDefs, ExtCtrls;
Type
TForm1 = Class(TForm)
tmrClockTick: TTimer;
Procedure FormCreate(Sender: TObject);
Procedure tmrClockTickTimer(Sender: TObject);
Private
{ Private declarations }
Public
Clock : TClock;
End;
Var
Form1: TForm1;
Implementation
{$R *.dfm}
Procedure TForm1.FormCreate(Sender: TObject);
Begin
Clock := TClock.Create(Self);
Clock.Parent := Self;
tmrClockTick.Enabled := True;
tmrClockTick.Interval := 1000; // tick every second
End;
Procedure TForm1.tmrClockTickTimer(Sender: TObject);
Begin
Clock.IncrementTime;
Clock.DisplayTime;
End;
End.

AQA Computing A2 Teacher Notes Nelson Thornes Ltd 2009

26

Q8)
Unit ClassDefs;
Interface
Uses Classes, StdCtrls;
Type TClock = Class (TLabel)
Private
Hours: Integer;
Minutes: Integer;
Function IntToStrF (i: Integer): String;
Public
Constructor Create (AOwner:TComponent); Override;
Procedure IncrementTime;
Procedure DisplayTime;
Function GetHours: Integer;
Function GetMinutes: Integer;
Procedure SetTime(h, m : Integer);
End;
Type TAlarmClock = Class (TClock)
Private
AlarmHours: Integer;
AlarmMinutes: Integer;
Public
Function GetAlarmHours: Integer;
Function GetAlarmMinutes: Integer;
Procedure SetAlarmTime(h, m : Integer);
Procedure Ring;
End;
Implementation
Uses SysUtils, StrUtils;
Constructor TClock.Create (AOwner: TComponent);
Begin
Inherited Create(AOwner);
Top := 20;
Left := 20;
SetTime(0,0);
End;
Procedure TClock.SetTime(h: Integer; m: Integer);
Begin
Hours := h;
Minutes := m;
End;
Function TClock.GetHours: Integer;
Begin
GetHours := Hours;
End;
Function TClock.GetMinutes: Integer;
Begin
GetMinutes := Minutes;
End;

AQA Computing A2 Teacher Notes Nelson Thornes Ltd 2009

27

Procedure TClock.IncrementTime;
Begin
Minutes := Minutes + 1;
If Minutes = 60
Then
Begin
Hours := Hours + 1;
Minutes := 0;
If Hours = 24
Then Hours := 0;
End;
End;
Function TClock.IntToStrF (i: Integer): String;
Var StringI: String[2];
Begin
StringI := IntToStr(i);
If Length(StringI)=1
Then IntToStrF := '0' + StringI
Else IntToStrF := StringI;
End;
Procedure TClock.DisplayTime;
Var StrMinutes, StrHours : String[2];
Begin
StrMinutes := IntToStrF(Minutes);
StrHours := IntToStrF(Hours);
Caption := StrHours + ':' + StrMinutes;
End;
Function TAlarmClock.GetAlarmHours: Integer;
Begin
GetAlarmHours := AlarmHours;
End;
Function TAlarmClock.GetAlarmMinutes: Integer;
Begin
GetAlarmMinutes := AlarmMinutes;
End;
Procedure TAlarmClock.SetAlarmTime (h, m : Integer);
Begin
AlarmHours := h;
AlarmMinutes := m;
End;
Procedure TAlarmClock.Ring;
Begin
If (AlarmHours=Hours) And (AlarmMinutes=Minutes)
Then
Caption := 'Wake Up' // this can be elaborated on!!!
End;
End.
Unit ClockForm;
Interface

AQA Computing A2 Teacher Notes Nelson Thornes Ltd 2009

28

Uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls,
Forms,
Dialogs, ClassDefs, ExtCtrls, StdCtrls;
Type
TForm1 = Class(TForm)
tmrClockTick: TTimer;
btnSetAlarm: TButton;
procedure FormCreate(Sender: TObject);
procedure tmrClockTickTimer(Sender: TObject);
procedure btnSetAlarmClick(Sender: TObject);
Private
{ Private declarations }
Public
AlarmClock : TAlarmClock;
End;
Var
Form1: TForm1;
Implementation
{$R *.dfm}
Procedure TForm1.btnSetAlarmClick(Sender: TObject);
Begin
AlarmClock.SetTime(15,10);
// this can made interactive by copying
AlarmClock.SetAlarmTime(15,15); // values from textboxes
tmrClockTick.Enabled := True;
End;
Procedure TForm1.FormCreate(Sender: TObject);
Begin
AlarmClock := TAlarmClock.Create(Self);
AlarmClock.Parent := Self;
tmrClockTick.Enabled := False;
tmrClockTick.Interval := 600; // tick every minute
End;
Procedure TForm1.tmrClockTickTimer(Sender: TObject);
Begin
AlarmClock.IncrementTime;
AlarmClock.DisplayTime;
AlarmClock.Ring;
End;
End.

AQA Computing A2 Teacher Notes Nelson Thornes Ltd 2009

29

Inheritance diagram of the shapes classes

TShape

TRectangle

TEllipse

Exam practice questions


Question 1 June 2008 CPT4 Q6
Question
number

Answer

1a

1b

Marks
2

Insert a SetColour procedure; A Function


into the Public section;
R make Colour Public

AQA Computing A2 Teacher Notes Nelson Thornes Ltd 2009

30

1c

Yacht = Class/sub-class (Boat)


(Public)
Procedure SetBoatDetails (Override)
Function GetMasts
Function GetEngine
Private
Masts: Interger
Engine: Boolean
End
A Procedure SetMasts and Procedure SetEngine/Procedure
AddnewYacht/SetYachtsDetails instead of Procedure SetBoatDetails
Mast and Engine must be private
P1 if extra functions/variables are included
R any diagrams
I any parameters to methods

1
1
1
1
1
1

Question 2 January 2008 CPT4 Q4


Question
number

Answer

2a

Marks

1 mark for correct boxes


1 mark for correct lines
1 mark for correct line endings
2b
4

1 mark for Loan=Class + Public + Private + End


1 mark for CreateLoan + DeleteLoan + GetLoanDetails
1 mark for Person + BookLoaned
1 mark for DateOfLoan + ReturnDate

AQA Computing A2 Teacher Notes Nelson Thornes Ltd 2009

31

A any reasonable names for operations and data items


2c

Add a new data item ShortLoan; of type Boolean; A loanlength;


integer;
A loantype; string;
Modify the code for the operations.

Max 2

Question
Number

Answer

Marks

3a

mouse click// mouse movement// keyboard operation// any interrupt;

3b

event-driven programs service an event and wait for another;


non event-driven programs run to completion/ are sequential;

3c

contains its own data/fields/variables/properties;


contains its own
operations/methods/functions/procedures/behaviours/code;
responds to messages;
A Based on a Class definition

Max 2

3d

frame/form/window/button/check box/radio button/menu/text box;


A any sensible widget
R Plurals

Question 4 January 2007 CPT4 Q8

Question
number

Answer

4a

Marks
2

1 mark for all three classes in appropriate single enclosures.


1 mark for correct independent arrows in correct directions.
4b

(Insert) a SetColour Procedure; A Function


into the Public section;

AQA Computing A2 Teacher Notes Nelson Thornes Ltd 2009

32

R make Colour Public

4c

Van = Class/ subclass (Vehicle), i.e. Clearly identify Van as a (sub)


class of vehicle (1 mark)
(Public)
Procedure SetVehicleDetails (Override) condone if not included
Function GetCapacity
Function GetTailLift
(penalise extra functions/procedures once.)
Private
Capacity : Integer/real/fixed/float
TailLift : Boolean
(penalise once if not private and once if extra variables listed.)
End

AQA Computing A2 Teacher Notes Nelson Thornes Ltd 2009

Max 6

1 mark
1 mark
1 mark

1 mark
1 mark

33

A Procedure SetCapacity and Procedure SetTailLift/


Procedure AddNewVan
instead of Procedure SetVehicleDetails
OR
Public class/subclass Van extends/inherits Vehicle (1 mark)

mark
public void SetVehicleDetails
public int GetCapacity

public boolean/int GetTailLift

mark

private int Capacity

private boolean/int TailLift

mark

1
mark

A public void SetCapacity and public void SetTailLift//


public void AddNewVan instead of public void

1
mark

SetVehicleDetails

R any diagrams

mark

I any parameters to methods

6
marks
(10)
Question 5 January 2006 CPT4 Q6
Question
number

Answer

Marks

5a

a class has properties/fields/attributes/characteristics and


methods/procedures/functions
of the parent class it is derived from
// a subclass/derived class inherits all the
properties/fields/attributes/characteristics and
methods/procedures/functions from a super-class/base-class/parent
class;

1 mark

AQA Computing A2 Teacher Notes Nelson Thornes Ltd 2009

34

5b

StockItem (=) Class // Class (=) StockItem; (A Object instead of Class)


Public (procedure DisplayDetails) (virtual)(virtual;abstract)
(procedure) SetLoan (virtual)(virtual;abstract)
Private; A protected
Title: String
OnLoan: Boolean
DateAcquired: String/DateTime/
End
Book = Class (StockItem) // Class Book extends/derives from
StockItem
// Book Sub-class: StockItem; A without keyword Class

1 mark
1 mark

1 mark for keywords Class and StockItem


1 mark for keyword Public and correct methods
A text instead of string
1 mark for correct data fields Date & data types
dont allow the other fields

1 mark
1 mark

If candidate declared
Private
getters and
setters for the base
Author: String
class fields then
ISBN: String
dont have to have
Public
DisplayDetails as a
(Procedure) DisplayDetails (override) base class method.
End
CD = Class (StockItem) // Class CD extends/derives from StockItem //
CD Subclass: StockItem;
Private
Artist: String
PlayingTime: Integer/Real/Time/DateTime
Public
(Procedure) DisplayDetails (override)
End

1 mark
1 mark

No marks for a diagrammatic answer. I method parameters


Java version:
Public Class StockItem
{
Private String title;
Private boolean onLoan;
Private String dateAquired;

AQA Computing A2 Teacher Notes Nelson Thornes Ltd 2009

1 mark

35

Public void displayDetails ();


Public void setLoan ();
}
Public Class Book extends StockItem
{
Private string author;
Private string isbn;
Public void displayDetails ();
}
Public Class CD extends StockItem
{
Private string artist;
Private integer playingTime;
Public void displayDetails();
}

Total (max 7)

2.2
End of topic questions
2

Product := 1;
For i := 1 To n
Do Product := i * Product;
Factorial := Product;

3
Call number

Call number 1

Output

Comment

Procedure call completed

4
Call number 2

4
3

Call number 3

3
2

Call number 4

2
1

Return to previous call


Continue call 3

Procedure call completed


Return to previous call

AQA Computing A2 Teacher Notes Nelson Thornes Ltd 2009

36

Continue call 2

Procedure call completed


Return to previous call

Continue call 1

Procedure call completed

Call number

Output

Comment

Call number 1

4
Call number 2

4
3

Call number 3

3
2

Call number 4

2
1

Procedure call completed


Return to previous call

Continue call 3

Procedure call completed


Return to previous call

Continue call 2

Procedure call completed


Return to previous call

Continue call 1

Procedure call completed

5
Function Fibonacci(n: Integer): Integer;
Begin
If n=0
Then Fibonacci := 0
Else
If n=1
Then Fibonacci := 1
Else Fibonacci := Fibonacci(n-1) + Fibonacci(n-2);
End;

6
Function Power(a, n: Integer): Integer;
Begin
If n=0
Then Power := 1
Else Power := a * Power(a, n-1);
End;

7 2n-1
8 A solution using iteration is: on odd-numbered moves, move the smallest disk clockwise. On evennumbered moves, make the single other move which is possible.
9 Requires student to test the code in the book using 3 disks and 3 pegs as per images.

AQA Computing A2 Teacher Notes Nelson Thornes Ltd 2009

37

2.3
End of topic questions
Exercise 1
Program Project1;
{$APPTYPE CONSOLE}
Uses
SysUtils;
Const MaxListSize=30;
Var
ExitChosen: Boolean = False;
MenuItem: Char;
NameList: Array[1..MaxListSize] Of String;
NumberOfFriendsStored: Integer = 0;
Function ListEmpty: Boolean;
Begin
ListEmpty := NumberOfFriendsStored=0;
End;
Function ListFull: Boolean;
Begin
ListFull := NumberOfFriendsStored=MaxListSize;
End;
Procedure GetMenuChoice(Var Choice: Char);
Begin
WriteLn;
WriteLn('Menu');
WriteLn;
WriteLn('1) Add a name to the list');
WriteLn('2) Show number of names in the list');
WriteLn('3) Show list of names');
WriteLn('4) Exit Program');
WriteLn;
Write('Enter your choice number: ');
ReadLn(Choice);
End;
Procedure AddNameToList;
Var NewName: String; Finish: Boolean;
Begin
Finish := False;
If ListFull
Then WriteLn('Can''t add any more names')
Else

AQA Computing A2 Teacher Notes Nelson Thornes Ltd 2009

38

Begin
Repeat
Write('Enter Name to be added to list (to finish type
XXX): ');
ReadLn(NewName);
If NewName = 'XXX'
Then
Finish := True
Else
Begin
NumberOfFriendsStored := NumberOfFriendsStored + 1;
NameList[NumberOfFriendsStored] := NewName;
End;
Until Finish Or ListFull;
If ListFull
Then WriteLn('Can''t add any more names');
End;
End;
Procedure PrintListOfNames;
Var i: Integer;
Begin
If Not ListEmpty
Then
For i := 1 To NumberOfFriendsStored
Do WriteLn(NameList[i]);
End;
Procedure OutputNumberOfNamesInList;
Begin
WriteLn('There are ', NumberOfFriendsStored, ' Names in the
list');
End;
Begin
AddNametoList;
Repeat
GetMenuChoice(MenuItem);
Case MenuItem Of
'1': AddNameToList;
'2': OutputNumberOfNamesInList;
'3': PrintListOfNames;
'4': ExitChosen := True;
Else WriteLn('Invalid menu choice. Try again');
End;
Until ExitChosen;
End.

Exercise 2
Program Project1;

AQA Computing A2 Teacher Notes Nelson Thornes Ltd 2009

39

{$APPTYPE CONSOLE}
Uses
SysUtils;
Const MaxListSize=30;
Var
ExitChosen: Boolean = False;
MenuItem: Char;
NameList: Array[1..MaxListSize] Of String;
NumberOfFriendsStored: Integer = 0;
Function ListEmpty: Boolean;
Begin
ListEmpty := NumberOfFriendsStored=0;
End;
Function ListFull: Boolean;
Begin
ListFull := NumberOfFriendsStored=MaxListSize;
End;
Procedure GetMenuChoice(Var Choice: Char);
Begin
WriteLn;
WriteLn('Menu');
WriteLn;
WriteLn('1) Add a name to the list');
WriteLn('2) Show number of names in the list');
WriteLn('3) Show list of names');
WriteLn('4) Find a name');
WriteLn('5) Delete a name');
WriteLn('6) Exit Program');
WriteLn;
Write('Enter your choice number: ');
ReadLn(Choice);
End;
Procedure AddNameToList;
Var NewName: String; Finish: Boolean;
Begin
Finish := False;
If ListFull
Then WriteLn('Can''t add any more names')
Else
Begin
Repeat
Write('Enter Name to be added to list (to finish type
XXX): ');
ReadLn(NewName);
If NewName = 'XXX'

AQA Computing A2 Teacher Notes Nelson Thornes Ltd 2009

40

Then
Finish := True
Else
Begin
NumberOfFriendsStored := NumberOfFriendsStored + 1;
NameList[NumberOfFriendsStored] := NewName;
End;
Until Finish Or ListFull;
If ListFull
Then WriteLn('Can''t add any more names');
End;
End;
Procedure PrintListOfNames;
Var i: Integer;
Begin
If Not ListEmpty
Then
For i := 1 To NumberOfFriendsStored
Do WriteLn(NameList[i]);
End;
Procedure OutputNumberOfNamesInList;
Begin
WriteLn('There are ', NumberOfFriendsStored, ' Names in the
list');
End;
Procedure SearchFor(N: String; Var Pos: Integer);
Var Found, NotInList: Boolean;
Begin
Found := False;
NotInList := False;
Pos := 1;
Repeat
If NameList[Pos] = N
Then Found := True
Else Pos := Pos + 1;
If Pos > NumberOfFriendsStored
Then NotInList := True;
Until Found Or NotInList;
If NotInList
Then Pos := 0;
End;
Procedure Delete(Pos: Integer);
Begin
While Pos < NumberOfFriendsStored
Do
Begin
NameList[Pos] := NameList[Pos+1];

AQA Computing A2 Teacher Notes Nelson Thornes Ltd 2009

41

Pos := Pos + 1;
End;
NameList[Pos] := ''; // clear space
NumberOfFriendsStored := NumberOfFriendsStored - 1;
End;
Procedure FindName;
Var Name: String; Position: Integer;
Begin
Write('Please enter the name you wish to find: ');
ReadLn(Name);
SearchFor(Name, Position);
If Position=0
Then WriteLn('Sorry, the name is not in the list')
Else WriteLn(Name, ' is name number ', Position, ' in the
list');
End;
Procedure DeleteName;
Var Name: String; Position: Integer;
Begin
Write('Please enter the name you wish to delete: ');
ReadLn(Name);
SearchFor(Name, Position);
If Position=0
Then WriteLn('Sorry, the name is not in the list')
Else Delete(Position);
End;
Begin
AddNametoList;
Repeat
GetMenuChoice(MenuItem);
Case MenuItem Of
'1': AddNameToList;
'2': OutputNumberOfNamesInList;
'3': PrintListOfNames;
'4': FindName;
'5': DeleteName;
'6': ExitChosen := True;
Else WriteLn('Invalid menu choice. Try again');
End;
Until ExitChosen;
End.

AQA Computing A2 Teacher Notes Nelson Thornes Ltd 2009

42

Exercise 3
Program Project1;
{$APPTYPE CONSOLE}
Uses
SysUtils;
Const MaxListSize=30;
Type TFriend = Record
Name: String;
Replied: Boolean;
ComingToParty: Boolean;
End;
Var
ExitChosen: Boolean = False;
MenuItem: Char;
NameList: Array[1..MaxListSize] Of TFriend;
NumberOfFriendsStored: Integer = 0;
Function ListEmpty: Boolean;
Begin
ListEmpty := NumberOfFriendsStored=0;
End;
Function ListFull: Boolean;
Begin
ListFull := NumberOfFriendsStored=MaxListSize;
End;
Procedure GetMenuChoice(Var Choice: Char);
Begin
WriteLn;
WriteLn('Menu');
WriteLn;
WriteLn('1) Add a name to the list');
WriteLn('2) Show number of names in the list');
WriteLn('3) Print list of names');
WriteLn('4) Find a name');
WriteLn('5) Delete a name');
WriteLn('6) Print list of all those definitely coming to the
party');
WriteLn('7) Print list of all those who have not replied yet');
WriteLn('8) Exit Program');
WriteLn;
Write('Enter your choice number: ');
ReadLn(Choice);
End;

AQA Computing A2 Teacher Notes Nelson Thornes Ltd 2009

43

Procedure AddNameToList;
Var NewName: String; Finish: Boolean;
Begin
Finish := False;
If ListFull
Then WriteLn('Can''t add any more names')
Else
Begin
Repeat
Write('Enter Name to be added to list (to finish type
XXX): ');
ReadLn(NewName);
If NewName = 'XXX'
Then
Finish := True
Else
Begin
NumberOfFriendsStored := NumberOfFriendsStored + 1;
NameList[NumberOfFriendsStored].Name := NewName;
NameList[NumberOfFriendsStored].Replied := False;
NameList[NumberOfFriendsStored].ComingToParty :=
False;
End;
Until Finish Or ListFull;
If ListFull
Then WriteLn('Can''t add any more names');
End;
End;
Procedure PrintListOfNames;
Var i: Integer;
Begin
If Not ListEmpty
Then
For i := 1 To NumberOfFriendsStored
Do WriteLn(NameList[i].Name);
End;
Procedure OutputNumberOfNamesInList;
Begin
WriteLn('There are ', NumberOfFriendsStored, ' Names in the
list');
End;
Procedure SearchFor(N: String; Var Pos: Integer);
Var Found, NotInList: Boolean;
Begin
Found := False;
NotInList := False;
Pos := 1;
Repeat

AQA Computing A2 Teacher Notes Nelson Thornes Ltd 2009

44

If NameList[Pos].Name = N
Then Found := True
Else Pos := Pos + 1;
If Pos > NumberOfFriendsStored
Then NotInList := True;
Until Found Or NotInList;
If NotInList
Then Pos := 0;
End;
Procedure Delete(Pos: Integer);
Begin
While Pos < NumberOfFriendsStored
Do
Begin
NameList[Pos] := NameList[Pos+1];
Pos := Pos + 1;
End;
NameList[Pos].Name := ''; // clear space
NumberOfFriendsStored := NumberOfFriendsStored - 1;
End;
Procedure FindName;
Var Name: String; Position: Integer; Answer: Char;
Begin
Write('Please enter the name you wish to find: ');
ReadLn(Name);
SearchFor(Name, Position);
If Position=0
Then WriteLn('Sorry, the name is not in the list')
Else
Begin
Repeat
Write('Has ', Name, ' replied to the invite? (y/n) ');
ReadLn(Answer);
Until ((Answer = 'y') Or (Answer = 'n'));
If Answer='y'
Then
Begin
NameList[Position].Replied := True;
Repeat
Write('Is ', Name, ' coming to the party? (y/n) ');
ReadLn(Answer);
Until ((Answer = 'y') Or (Answer = 'n'));
If Answer='y'
Then NameList[Position].ComingToParty := True;
End;
End;
End;
Procedure DeleteName;

AQA Computing A2 Teacher Notes Nelson Thornes Ltd 2009

45

Var Name: String; Position: Integer;


Begin
Write('Please enter the name you wish to delete: ');
ReadLn(Name);
SearchFor(Name, Position);
If Position=0
Then WriteLn('Sorry, the name is not in the list')
Else Delete(Position);
End;
Procedure AttendanceList;
Var i: Integer;
Begin
WriteLn;
WriteLn('The following are definitely coming to the party:');
WriteLn('=================================================');
WriteLn;
For i := 1 To NumberOfFriendsStored
Do
If NameList[i].ComingToParty
Then WriteLn(NameList[i].Name);
End;
Procedure NoReplyList;
Var i: Integer;
Begin
WriteLn;
WriteLn('The following have not replied yet:');
WriteLn('===================================');
WriteLn;
For i := 1 To NumberOfFriendsStored
Do
If Not NameList[i].Replied
Then WriteLn(NameList[i].Name);
End;

Begin
AddNametoList;
Repeat
GetMenuChoice(MenuItem);
Case MenuItem Of
'1': AddNameToList;
'2': OutputNumberOfNamesInList;
'3': PrintListOfNames;
'4': FindName;
'5': DeleteName;
'6': AttendanceList;
'7': NoReplyList;
'8': ExitChosen := True;
Else WriteLn('Invalid menu choice. Try again');

AQA Computing A2 Teacher Notes Nelson Thornes Ltd 2009

46

End;
Until ExitChosen;
End.

AQA Computing A2 Teacher Notes Nelson Thornes Ltd 2009

47

Exercise 4
Program Project1;
{$APPTYPE CONSOLE}
Uses
SysUtils;
Const MaxListSize = 6;
Type TNode = Record
Data: String;
Pointer: Integer;
End;
Var
Node: Array[1..MaxListSize] Of TNode;
Start: Integer = 0; // list empty
NextFree: Integer;
MenuItem: Char;
ExitChosen: Boolean = False;
Procedure InitialiseList;
Var i: Integer;
Begin
NextFree := 1;
For i := 1 To MaxListSize - 1
Do
Node[i].Pointer := i+ 1;
Node[MaxListSize].Pointer := 0;
End;
Function ListFull: Boolean;
Begin
ListFull := NextFree=0;
End;
Function ListEmpty: Boolean;
Begin
ListEmpty := Start=0;
End;
Procedure GetMenuChoice(Var Choice: Char);
Begin
WriteLn;
WriteLn('Menu');
WriteLn;
WriteLn('1) Add a name to the list');
WriteLn('2) Show list of names');
WriteLn('3) Delete a name');

AQA Computing A2 Teacher Notes Nelson Thornes Ltd 2009

48

WriteLn('4) Exit Program');


WriteLn;
Write('Enter your choice number: ');
ReadLn(Choice);
End;
Procedure AddNodeToFrontOfList(Name: String);
Var Temp: Integer;
Begin
Node[NextFree].Data := Name;
Temp := NextFree;
NextFree := Node[NextFree].Pointer;
Node[Temp].Pointer := Start;
Start := Temp;
End;
Procedure AddNodeIntoList(Name: String; ThisNode: Integer);
// the new node is to be inserted after ThisNode
Var Temp: Integer;
Begin
Node[NextFree].Data := Name;
Temp := NextFree;
NextFree := Node[NextFree].Pointer;
Node[Temp].Pointer := Node[ThisNode].Pointer;
Node[ThisNode].Pointer := Temp;
End;
Procedure DeleteHeadOfList;
Var Temp: Integer;
Begin
Temp := Start;
Start := Node[Start].Pointer;
Node[Temp].Pointer := NextFree;
NextFree := Temp;
End;
Procedure DeleteNodeWithinList(PreviousNode, ThisNode: Integer);
// ThisNode is the node to be deleted)
Var Temp: Integer;
Begin
Temp := NextFree;
NextFree := Node[PreviousNode].Pointer;
Node[PreviousNode].Pointer := Node[ThisNode].Pointer;
Node[ThisNode].Pointer := Temp;
End;
Procedure OutputListElements;
Var ThisNode: Integer;
Begin
If ListEmpty
Then WriteLn('List is empty')

AQA Computing A2 Teacher Notes Nelson Thornes Ltd 2009

49

Else
Begin
ThisNode := Start;
Repeat
WriteLn(Node[ThisNode].Data);
ThisNode := Node[ThisNode].Pointer;
Until ThisNode = 0;
End;
End;
Function InsertionPoint(N: String): Integer;
Var ThisNode, NextNode: Integer;
Begin
ThisNode := 0;
// start at the beginning of the list
NextNode := Start;
While NextNode > 0
// not end of list
Do
Begin
ThisNode := NextNode;
NextNode := Node[NextNode].Pointer;
// follow the
pointer
End;
InsertionPoint := ThisNode;
End;
Procedure SearchFor(N: String; Var This, Previous: Integer);
Begin
This:= Start;
Previous:= 0;
While (This > 0) And (Node[This].Data <> N)
Do
Begin
Previous := This;
This := Node[This].Pointer;
End;
If Node[This].Data <> N
Then This := 0;
// name not found
End;
Procedure AddNameToList;
Var Finish: Boolean; NewName: String; Position: Integer;
Begin
Finish := False;
If ListFull
Then WriteLn('Can''t add any more names')
Else
Begin
Repeat
Write('Enter Name to be added to list (to finish type
XXX): ');
ReadLn(NewName);

AQA Computing A2 Teacher Notes Nelson Thornes Ltd 2009

50

If NewName = 'XXX'
Then
Finish := True
Else
Begin
If ListEmpty
Then AddNodeToFrontOfList(NewName)
Else
Begin
Position := InsertionPoint(NewName);
If Position = 0
Then AddNodeToFrontOfList(NewName)
Else AddNodeIntoList(NewName, Position);
End;
End;
Until Finish Or ListFull;
If ListFull
Then WriteLn('Can''t add any more names');
End;
End;
Procedure DeleteName;
Var Name: String; ThisNode, PreviousNode: Integer;
Begin
If ListEmpty
Then WriteLn('There are no names in the list')
Else
Begin
Write('Please enter the name you wish to delete: ');
ReadLn(Name);
SearchFor(Name, ThisNode, PreviousNode);
If ThisNode=0
Then WriteLn('Sorry, the name is not in the list')
Else
If ThisNode = Start
Then DeleteHeadOFList
Else DeleteNodeWithinList(PreviousNode, ThisNode);
End;
End;
Procedure ShowArray;
// this is just to check the linked list is built up correctly
Var i: Integer;
Begin
WriteLn('Start: ', Start);
WriteLn('NextFree: ',NextFree);
For i := 1 To MaxListSize
Do WriteLn('[',i,']', Node[i].Data ,'->',Node[i].Pointer);
End;
Begin

AQA Computing A2 Teacher Notes Nelson Thornes Ltd 2009

51

InitialiseList;
Repeat
GetMenuChoice(MenuItem);
Case MenuItem Of
'1': AddNameToList;
'2': OutputListElements;
'3': DeleteName;
'4': ExitChosen := True;
'6': ShowArray; // for testing purposes
Else WriteLn('Invalid menu choice. Try again');
End;
Until ExitChosen;
End.

AQA Computing A2 Teacher Notes Nelson Thornes Ltd 2009

52

Exercise 5

Program Project2;
{$APPTYPE CONSOLE}
Uses
SysUtils;
Type
TNodePtr = ^TNode;
TNode = Record
Data : String;
Ptr : TNodePtr;
End;
Var
Start : TNodePtr;
MenuItem: Char;
ExitChosen: Boolean = False;
Procedure InitList (Var List: TNodePtr);
Begin
List := Nil;
End;
Procedure GetMenuChoice(Var Choice: Char);
Begin
WriteLn;
WriteLn('Menu');
WriteLn;
WriteLn('1) Add a name to the list');
WriteLn('2) Show list of names');
WriteLn('3) Delete a name');
WriteLn('4) Exit Program');
WriteLn;
Write('Enter your choice number: ');
ReadLn(Choice);
End;

Procedure AddItem (Var List: TNodePtr; NewItem: String);


Var NewNode, ThisNode, NextNode: TNodePtr;
Begin
New (NewNode);
NewNode^.Data := NewItem;
NewNode^.Ptr := Nil;
If List = Nil
Then List := NewNode
Else
Begin
NextNode := List;
While NextNode <> Nil
Do

AQA Computing A2 Teacher Notes Nelson Thornes Ltd 2009

53

Begin
ThisNode := NextNode;
NextNode := NextNode^.Ptr;
End;
ThisNode^.Ptr := NewNode;
End;
End;
Procedure DeleteItem (Var List: TNodePtr; WantedData: String);
Var ThisNode, PreviousNode: TNodePtr;
Begin
If List <> Nil
Then
Begin
ThisNode := List;
If List^.Data = WantedData
// is it the first node ?
Then List := List^.Ptr
Else
Begin
While ThisNode^.Data <> WantedData
Do
Begin
PreviousNode := ThisNode;
ThisNode := ThisNode^.Ptr
End;
PreviousNode^.Ptr := ThisNode^.Ptr;
End;
Dispose (ThisNode);
End
Else WriteLn('List empty');
End;
Procedure PrintList (List : TNodePtr);
Var ThisNode : TNodePtr;
Begin
If List <> Nil
Then
Begin
ThisNode := List;
Repeat
WriteLn (ThisNode^.Data);
ThisNode := ThisNode^.Ptr;
Until ThisNode = Nil;
End;
End;
Function GetName: String;
Var Name: String;
Begin
Write('Enter a name: ');
ReadLn(Name);

AQA Computing A2 Teacher Notes Nelson Thornes Ltd 2009

54

GetName := Name;
End;
Begin
InitList(Start);
Repeat
GetMenuChoice(MenuItem);
Case MenuItem Of
'1': AddItem(Start,GetName);
'2': PrintList(Start);
'3': DeleteItem(Start,GetName);
'4': ExitChosen := True;
Else WriteLn('Invalid menu choice. Try again');
End;
Until ExitChosen;
End.

AQA Computing A2 Teacher Notes Nelson Thornes Ltd 2009

55

Exercise 6
Program Project2;
{$APPTYPE CONSOLE}
Uses
SysUtils;
Type
TNodePtr = ^TNode;
TNode = Record
Data : String;
Ptr : TNodePtr;
End;
Var
Start : TNodePtr;
MenuItem: Char;
ExitChosen: Boolean = False;
Procedure InitList (Var List: TNodePtr);
Begin
List := Nil;
End;
Procedure GetMenuChoice(Var Choice: Char);
Begin
WriteLn;
WriteLn('Menu');
WriteLn;
WriteLn('1) Add a name to the list');
WriteLn('2) Show list of names');
WriteLn('3) Delete a name');
WriteLn('4) Exit Program');
WriteLn;
Write('Enter your choice number: ');
ReadLn(Choice);
End;

Procedure AddItem (Var List: TNodePtr; NewItem: String);


Var NewNode, ThisNode, NextNode: TNodePtr;
Begin
New (NewNode);
NewNode^.Data := NewItem;
NewNode^.Ptr := Nil;
If List = Nil
Then List := NewNode
Else
Begin
NextNode := List;
While NextNode <> Nil

AQA Computing A2 Teacher Notes Nelson Thornes Ltd 2009

56

Do
Begin
ThisNode := NextNode;
NextNode := NextNode^.Ptr;
End;
ThisNode^.Ptr := NewNode;
End;
End;
Procedure DeleteItem (Var List: TNodePtr; WantedData: String);
Var ThisNode, PreviousNode: TNodePtr; Found: Boolean;
Begin
If List = Nil
Then
WriteLn('List empty')
Else
Begin
ThisNode := List;
If List^.Data = WantedData
// is it the first node ?
Then
Begin
List := List^.Ptr;
// Then adjust front pointer
Dispose (ThisNode);
End
Else
Begin
Found:= False;
While (ThisNode^.Ptr <> Nil) And Not Found
Do
Begin
PreviousNode := ThisNode;
ThisNode := ThisNode^.Ptr;
Found := ThisNode^.Data = WantedData;
End;
If Found
Then
Begin
PreviousNode^.Ptr := ThisNode^.Ptr;
Dispose (ThisNode);
End
Else WriteLn('Name not in list');
End;
End;
End;
Procedure PrintList (List : TNodePtr);
Var ThisNode : TNodePtr;
Begin
If List <> Nil
Then
Begin

AQA Computing A2 Teacher Notes Nelson Thornes Ltd 2009

57

ThisNode := List;
Repeat
WriteLn (ThisNode^.Data);
ThisNode := ThisNode^.Ptr;
Until ThisNode = Nil;
End;
End;
Function GetName: String;
Var Name: String;
Begin
Write('Enter a name: ');
ReadLn(Name);
GetName := Name;
End;
Begin
InitList(Start);
Repeat
GetMenuChoice(MenuItem);
Case MenuItem Of
'1': AddItem(Start,GetName);
'2': PrintList(Start);
'3': DeleteItem(Start,GetName);
'4': ExitChosen := True;
Else WriteLn('Invalid menu choice. Try again');
End;
Until ExitChosen;
End.

AQA Computing A2 Teacher Notes Nelson Thornes Ltd 2009

58

Exercises 7, 8
Program Project2;
{$APPTYPE CONSOLE}
Uses
SysUtils;
Type
TNodePtr = ^TNode;
TNode = Record
Data : String;
Ptr : TNodePtr;
End;
Var
Start : TNodePtr;
MenuItem: Char;
ExitChosen: Boolean = False;
Procedure InitList (Var List: TNodePtr);
Begin
List := Nil;
End;
Procedure GetMenuChoice(Var Choice: Char);
Begin
WriteLn;
WriteLn('Menu');
WriteLn;
WriteLn('1) Add a name to the list');
WriteLn('2) Show list of names');
WriteLn('3) Find a name');
WriteLn('4) Delete a name');
WriteLn('5) Exit Program');
WriteLn;
Write('Enter your choice number: ');
ReadLn(Choice);
End;

Procedure AddItem (Var List: TNodePtr; NewItem: String);


Var NewNode, ThisNode, NextNode: TNodePtr;
Begin
New (NewNode);
NewNode^.Data := NewItem;
NewNode^.Ptr := Nil;
If List = Nil
Then List := NewNode
Else
Begin
NextNode := List;
While NextNode <> Nil

AQA Computing A2 Teacher Notes Nelson Thornes Ltd 2009

59

Do
Begin
ThisNode := NextNode;
NextNode := NextNode^.Ptr;
End;
ThisNode^.Ptr := NewNode;
End;
End;
Procedure SearchFor(N:String; List: TNodePtr; Var This, Previous:
TNodePtr);
Var Found: Boolean;
Begin
This := List;
Previous := Nil;
Found:= False;
While (This^.Ptr <> Nil) And Not Found
Do
Begin
Previous := This;
This := This^.Ptr;
Found := This^.Data = N;
End;
If Not Found
Then This := Nil;
End;
Procedure DeleteItem (Var List: TNodePtr; WantedData: String);
Var ThisNode, PreviousNode: TNodePtr; Found: Boolean;
Begin
If List = Nil
Then
WriteLn('List empty')
Else
Begin
ThisNode := List;
If List^.Data = WantedData
// is it the first node ?
Then
Begin
List := List^.Ptr;
// Then adjust front pointer
Dispose (ThisNode);
End
Else
Begin
SearchFor(WantedData, List, ThisNode, PreviousNode);
If ThisNode = Nil
Then WriteLn('Name not in list')
Else
Begin
PreviousNode^.Ptr := ThisNode^.Ptr;
Dispose (ThisNode);

AQA Computing A2 Teacher Notes Nelson Thornes Ltd 2009

60

End;
End;
End;
End;
Procedure PrintList (List : TNodePtr);
Var ThisNode : TNodePtr;
Begin
If List = Nil
Then
WriteLn('List empty')
Else
Begin
ThisNode := List;
Repeat
WriteLn (ThisNode^.Data);
ThisNode := ThisNode^.Ptr;
Until ThisNode = Nil;
End;
End;
Function GetName: String;
Var Name: String;
Begin
Write('Enter a name: ');
ReadLn(Name);
GetName := Name;
End;
Procedure FindName(List: TNodePtr; Name: String);
Var ThisNode, PreviousNode: TNodePtr;
Begin
If List = Nil
Then WriteLn('No names in list')
Else
Begin
SearchFor(Name, List, ThisNode, PreviousNode);
If ThisNode = Nil
Then WriteLn('Sorry, the name does not exist in the
list');
End;
End;
Begin
InitList(Start);
Repeat
GetMenuChoice(MenuItem);
Case MenuItem Of
'1': AddItem(Start,GetName);
'2': PrintList(Start);
'3': FindName(Start, GetName);

AQA Computing A2 Teacher Notes Nelson Thornes Ltd 2009

61

'4': DeleteItem(Start,GetName);
'5': ExitChosen := True;
Else WriteLn('Invalid menu choice. Try again');
End;
Until ExitChosen;

End.

AQA Computing A2 Teacher Notes Nelson Thornes Ltd 2009

62

Exercise 9
Program Project2;
{$APPTYPE CONSOLE}
Uses
SysUtils;
Type
TNodePtr = ^TNode;
TNode = Record
Data : String;
Ptr : TNodePtr;
End;
Var
Start : TNodePtr;
MenuItem: Char;
ExitChosen: Boolean = False;
Procedure InitList (Var List: TNodePtr);
Begin
List := Nil;
End;
Procedure GetMenuChoice(Var Choice: Char);
Begin
WriteLn;
WriteLn('Menu');
WriteLn;
WriteLn('1) Add a name to the list');
WriteLn('2) Show list of names');
WriteLn('3) Find a name');
WriteLn('4) Delete a name');
WriteLn('5) Exit Program');
WriteLn;
Write('Enter your choice number: ');
ReadLn(Choice);
End;
Function InsertionPoint(List: TNodePtr; NewItem: String): TNodePtr;
Var This, Next: TNodePtr;
Begin
This := Nil;
Next := List;
While (Next <> Nil) And (Next^.Data < NewItem)
Do
Begin
This := Next;
Next := Next^.Ptr;
End;
InsertionPoint := This
End;

AQA Computing A2 Teacher Notes Nelson Thornes Ltd 2009

63

Procedure AddItem (Var List: TNodePtr; NewItem: String);


Var NewNode, ThisNode, NextNode: TNodePtr;
Begin
New (NewNode);
NewNode^.Data := NewItem;
NewNode^.Ptr := Nil;
If List = Nil
Then List := NewNode
Else
Begin
ThisNode := InsertionPoint(List, NewItem);
If ThisNode = Nil
Then
Begin
NewNode^.Ptr := List;
List := NewNode;
End
Else
Begin
NewNode^.Ptr := ThisNode^.Ptr;
ThisNode^.Ptr := NewNode;
End;
End;
End;
Procedure SearchFor(N:String; List: TNodePtr; Var This, Previous:
TNodePtr);
Var Found: Boolean;
Begin
This := List;
Previous := Nil;
Found:= False;
While (This^.Ptr <> Nil) And Not Found
Do
Begin
Previous := This;
This := This^.Ptr;
Found := This^.Data = N;
End;
If Not Found
Then This := Nil;
End;
Procedure DeleteItem (Var List: TNodePtr; WantedData: String);
Var ThisNode, PreviousNode: TNodePtr; Found: Boolean;
Begin
If List = Nil
Then
WriteLn('List empty')
Else

AQA Computing A2 Teacher Notes Nelson Thornes Ltd 2009

64

Begin
ThisNode := List;
If List^.Data = WantedData
// is it the first node ?
Then
Begin
List := List^.Ptr;
// Then adjust front pointer
Dispose (ThisNode);
End
Else
Begin
SearchFor(WantedData, List, ThisNode, PreviousNode);
If ThisNode = Nil
Then WriteLn('Name not in list')
Else
Begin
PreviousNode^.Ptr := ThisNode^.Ptr;
Dispose (ThisNode);
End;
End;
End;
End;
Procedure PrintList (List : TNodePtr);
Var ThisNode : TNodePtr;
Begin
If List = Nil
Then
WriteLn('List empty')
Else
Begin
ThisNode := List;
Repeat
WriteLn (ThisNode^.Data);
ThisNode := ThisNode^.Ptr;
Until ThisNode = Nil;
End;
End;
Function GetName: String;
Var Name: String;
Begin
Write('Enter a name: ');
ReadLn(Name);
GetName := Name;
End;
Procedure FindName(List: TNodePtr; Name: String);
Var ThisNode, PreviousNode: TNodePtr;
Begin
If List = Nil
Then WriteLn('No names in list')

AQA Computing A2 Teacher Notes Nelson Thornes Ltd 2009

65

Else
Begin
SearchFor(Name, List, ThisNode, PreviousNode);
If ThisNode = Nil
Then WriteLn('Sorry, the name does not exist in the
list');
End;
End;
Begin
InitList(Start);
Repeat
GetMenuChoice(MenuItem);
Case MenuItem Of
'1': AddItem(Start,GetName);
'2': PrintList(Start);
'3': FindName(Start, GetName);
'4': DeleteItem(Start,GetName);
'5': ExitChosen := True;
Else WriteLn('Invalid menu choice. Try again');
End;
Until ExitChosen;
End.

AQA Computing A2 Teacher Notes Nelson Thornes Ltd 2009

66

Exam practice questions


Question 1 January 2003 CPT4 Q1
Question Answer
number
1 a) i)

Data must be given in correct order


1
pheasant
2
teal
3
widgeon
START
4
partridge
5
woodpigeon

Marks

2
3
5
1
0

End Pointer can be blank


1 for correct START and END pointers;
1 for correctly numbered nodes and correct pointers (need all birds)
ii)

1
pheasant
7
2
teal
3
3
widgeon
5
4
partridge
1
5
woodpigeon
0
START
6
grouse
4
7
snipe
2
//correctly amended diagram
1 for grouse and snipe physically at end;
1 for correct pointers (if not as ms then clear and logical);

b)

The amount of memory taken up can vary;


//The size/length of the structure/linked list can vary;
At run time;

c)

A heap/stack/a pool of available locations;


A pointer holds the address of the allocated block/next available location;

AQA Computing A2 Teacher Notes Nelson Thornes Ltd 2009

1
Max 2
1
1

67

2.4
End of topic questions
1a)

1b)

AQA Computing A2 Teacher Notes Nelson Thornes Ltd 2009

68

2
Stack
Index
TopOfStackPointer

Data

6
5
4
3

Cup

Saucer

Plate

3
Program StackExampleUsingLinearList;
{$APPTYPE CONSOLE}
Uses
SysUtils;
Const MaxStackSize=6;
Var
ExitChosen: Boolean;
MenuItem: Char;
Stack: Array[1..MaxStackSize] Of String;
TopOfStackPointer: Integer = 0;
Function StackEmpty: Boolean;
Begin
StackEmpty := TopOfStackPointer=0;
End;
Function StackFull: Boolean;
Begin
StackFull := TopOfStackPointer=MaxStackSize;
End;
Procedure GetMenuChoice(Var Choice: Char);
Begin
WriteLn;
WriteLn('Menu');
WriteLn;
WriteLn('1) Add an item to the stack');
WriteLn('2) Remove an item from the stack');
WriteLn('3) Show contents of stack');
WriteLn('4) Exit Program');
WriteLn;
Write('Enter your choice number: ');
ReadLn(Choice);
AQA Computing A2 Teacher Notes Nelson Thornes Ltd 2009

69

End;
Procedure AddItemToStack;
Begin
If StackFull
Then WriteLn('Can''t add to a full stack')
Else
Begin
TopOfStackPointer := TopOfStackPointer + 1;
Write('Enter item to be added to stack: ');
ReadLn(Stack[TopOfStackPointer]);
End;
End;
Procedure RemoveItemFromStack;
Begin
If StackEmpty
Then WriteLn('Can''t take anything from an empty stack')
Else
Begin
WriteLn('Item popped off stack: ', Stack[TopOfStackPointer]);
TopOfStackPointer := TopOfStackPointer - 1;
End;
End;
Procedure ShowContentsOfStack;
Var Pointer: Integer;
Begin
Pointer := MaxStackSize; // output stack with bottom of stack
last
While TopOfStackPointer < Pointer
Do
Begin
WriteLn(Pointer);
Pointer := Pointer 1;
End;
While Pointer > 0
Do
Begin
WriteLn(Pointer,' ',Stack[Pointer]);
Pointer := Pointer 1;
End;
End;
Begin
ExitChosen := False;
Repeat
GetMenuChoice(MenuItem);
Case MenuItem Of
'1': AddItemToStack;
AQA Computing A2 Teacher Notes Nelson Thornes Ltd 2009

70

'2':
'3':
'4':
Else
End;
Until
End.

RemoveItemFromStack;
ShowContentsOfStack;
ExitChosen := True;
WriteLn('Invalid menu choice. Try again');
ExitChosen;

4
Program LinkedListStackExample;
{$APPTYPE CONSOLE}
Uses
SysUtils;
Const MaxStackSize=6;
Type TNode = Record
Data: String;
Pointer: Integer;
End;
Var
ExitChosen: Boolean;
MenuItem: Char;
Stack: Array[1..MaxStackSize] Of TNode;
FreePtr: Integer;
TopOfStackPointer: Integer = 0;
Procedure InitialiseStack;
Var i: Integer;
Begin
FreePtr := 1;
For i := 1 To MaxStackSize 1
Do
Stack[i].Pointer := i + 1;
Stack[MaxStackSize].Pointer := 0;
End;
Function StackEmpty: Boolean;
Begin
StackEmpty := TopOfStackPointer=0;
End;
Function StackFull: Boolean;
Begin
StackFull := FreePtr=0;
End;
AQA Computing A2 Teacher Notes Nelson Thornes Ltd 2009

71

Procedure GetMenuChoice(Var Choice: Char);


Begin
WriteLn;
WriteLn('Menu');
WriteLn;
WriteLn('1) Add an item to the stack');
WriteLn('2) Remove an item from the stack');
WriteLn('3) Show contents of stack');
WriteLn('4) Exit Program');
WriteLn;
Write('Enter your choice number: ');
ReadLn(Choice);
End;
Procedure AddItemToStack;
Var Temp: Integer;
Begin
If StackFull
Then WriteLn('Can''t add to a full stack')
Else
Begin
Temp := TopOfStackPointer;
TopOfStackPointer := FreePtr;
FreePtr := Stack[FreePtr].Pointer;
Write('Enter item to be added to stack: ');
ReadLn(Stack[TopOfStackPointer].Data);
Stack[TopOfStackPointer].Pointer := Temp;
End;
End;
Procedure RemoveItemFromStack;
Var Temp: Integer;
Begin
If StackEmpty
Then WriteLn('Can''t take anything from an empty stack')
Else
Begin
Temp := TopOfStackPointer;
WriteLn('Item popped: ', Stack[TopOfStackPointer].Data);
TopOfStackPointer := Stack[TopOfStackPointer].Pointer;
Stack[Temp].Pointer := FreePtr;
FreePtr := Temp;
End;
End;
Procedure ShowContentsOfStack;
Var ThisNode: Integer;
Begin
If StackEmpty
AQA Computing A2 Teacher Notes Nelson Thornes Ltd 2009

72

Then WriteLn('empty stack')


Else
Begin
ThisNode := TopOfStackPointer;
Repeat
WriteLn(Stack[ThisNode].Data);
ThisNode := Stack[ThisNode].Pointer;
Until ThisNode=0; // end of linked list reached
End;
End;
Begin
ExitChosen := False;
InitialiseStack;
Repeat
GetMenuChoice(MenuItem);
Case MenuItem Of
'1': AddItemToStack;
'2': RemoveItemFromStack;
'3': ShowContentsOfStack;
'4': ExitChosen := True;
Else WriteLn('Invalid menu choice. Try again');
End;
Until ExitChosen;
End.

5
Program StackExampleUsingHeap;
{$APPTYPE CONSOLE}
Uses
SysUtils;
Type
TNodePtr = ^TNode;
TNode = Record
Data : String;
Ptr : TNodePtr;
End;
Var
TopOfStack : TNodePtr;
ExitChosen: Boolean;
MenuItem: Char;
Procedure InitStack (Var Stack: TNodePtr);
Begin
Stack := Nil;
End;
Procedure AddItemToStack (Var Stack: TNodePtr);
AQA Computing A2 Teacher Notes Nelson Thornes Ltd 2009

73

Var NewNode: TNodePtr; NewItem: String;


Begin
Write('Enter item to be added to stack: ');
ReadLn(NewItem);
New (NewNode);
NewNode^.Data := NewItem;
NewNode^.Ptr := Nil;
If Stack = Nil
Then
Stack := NewNode
Else
Begin
NewNode^.Ptr := Stack;
Stack := NewNode;
End;
End;
Procedure RemoveItemFromStack (Var Stack: TNodePtr);
Var ThisNode: TNodePtr;
Begin
If Stack <> Nil
Then
Begin
WriteLn('Popped Data: ', Stack.Data);
ThisNode := Stack;
Stack := Stack^.Ptr;
Dispose (ThisNode);
End
Else WriteLn('Stack Empty');
End;
Procedure ShowContentsOfStack (Stack : TNodePtr);
Var ThisNode : TNodePtr;
Begin
If Stack <> Nil
Then
Begin
ThisNode := Stack;
Repeat
WriteLn (ThisNode^.Data);
ThisNode := ThisNode^.Ptr;
Until ThisNode = Nil;
End
Else WriteLn('Stack Empty');
End;
Procedure GetMenuChoice(Var Choice: Char);
Begin
WriteLn;
AQA Computing A2 Teacher Notes Nelson Thornes Ltd 2009

74

WriteLn('Menu');
WriteLn;
WriteLn('1) Add an item to the stack');
WriteLn('2) Remove an item from the stack');
WriteLn('3) Show contents of stack');
WriteLn('4) Exit Program');
WriteLn;
Write('Enter your choice number: ');
ReadLn(Choice);
End;
Begin
InitStack (TopOfStack);
ExitChosen := False;
Repeat
GetMenuChoice(MenuItem);
Case MenuItem Of
'1': AddItemToStack(TopOfStack);
'2': RemoveItemFromStack(TopOfStack);
'3': ShowContentsOfStack(TopOfStack);
'4': ExitChosen := True;
Else WriteLn('Invalid menu choice. Try again');
End;
Until ExitChosen;
Readln;
End.

6
Program StackExampleOOP;
{$APPTYPE CONSOLE}
Uses
SysUtils, StackClass in 'StackClass.pas';
Var
MenuItem: Char;
Stack : TStack;
ExitChosen: Boolean;
NewItem: String;
Procedure GetMenuChoice(Var Choice: Char);
Begin
WriteLn;
WriteLn('Menu');
WriteLn;
WriteLn('1) Add an item to the stack');
WriteLn('2) Remove an item from the stack');
AQA Computing A2 Teacher Notes Nelson Thornes Ltd 2009

75

WriteLn('3) Show contents of stack');


WriteLn('4) Exit Program');
WriteLn;
Write('Enter your choice number: ');
ReadLn(Choice);
End;
Begin
Stack := TStack.Create;
Repeat
GetMenuChoice(MenuItem);
Case MenuItem Of
'1': Begin
Write('Enter item to be added to stack: ');
ReadLn(NewItem);
Stack.Push(NewItem);
End;
'2': WriteLn('Item popped: ',Stack.Pop);
'3': Stack.PrintStack;
'4': ExitChosen := True;
Else WriteLn('Invalid menu choice. Try again');
End;
Until ExitChosen;
End.

7a)
Queue
Index
FrontPointer

BackPointer

Data

Jones

Smith

Peters

Franklin

Taylor

6
b)
Queue
Index
FrontPointer

Data

1
2

AQA Computing A2 Teacher Notes Nelson Thornes Ltd 2009

76

BackPointer

Peters

Franklin

Taylor

c)
Queue
Index
FrontPointer

BackPointer

Data

Peters

Franklin

Taylor

8
Program LinearQueue;
{$APPTYPE CONSOLE}
uses
SysUtils;
Const MaxQueueSize=6;
Var
ExitChosen: Boolean;
MenuItem: Char;
Queue: Array[1..MaxQueueSize] Of String;
BackPointer: Integer = 0;
Function QueueEmpty: Boolean;
Begin
QueueEmpty := BackPointer=0;
End;
Function QueueFull: Boolean;
Begin
QueueFull := BackPointer=MaxQueueSize;
End;
Procedure GetMenuChoice(Var Choice: Char);
Begin
WriteLn;
AQA Computing A2 Teacher Notes Nelson Thornes Ltd 2009

77

WriteLn('Menu');
WriteLn;
WriteLn('1) Add an item to the queue');
WriteLn('2) Remove an item from the queue');
WriteLn('3) Show contents of queue');
WriteLn('4) Exit Program');
WriteLn;
Write('Enter your choice number: ');
ReadLn(Choice);
End;
Procedure AddItemToQueue;
Begin
If QueueFull
Then WriteLn('Can''t add to a full queue')
Else
Begin
BackPointer := BackPointer + 1;
Write('Enter item to be added to queue: ');
ReadLn(Queue[BackPointer]);
End;
End;
Procedure ShuffleQueue(Ptr: Integer);
Var i: Integer;
Begin
For i := 2 To Ptr
Do Queue[i-1] := Queue[i];
Queue[Ptr]:=''; // clear the space
End;
Procedure RemoveItemFromQueue;
Begin
If QueueEmpty
Then WriteLn('Can''t take anything from an empty queue')
Else
Begin
WriteLn('Item taken from queue: ', Queue[1]);
If BackPointer > 1
Then ShuffleQueue(BackPointer);
BackPointer := BackPointer - 1;
End;
End;
Procedure ShowContentsOfQueue;
Var Pointer: Integer;
Begin
For Pointer := 1 To MaxQueueSize
Do WriteLn(Pointer, Queue[Pointer]);
End;
AQA Computing A2 Teacher Notes Nelson Thornes Ltd 2009

78

Begin
ExitChosen := False;
Repeat
GetMenuChoice(MenuItem);
Case MenuItem Of
'1': AddItemToQueue;
'2': RemoveItemFromQueue;
'3': ShowContentsOfQueue;
'4': ExitChosen := True;
Else WriteLn('Invalid menu choice. Try again');
End;
Until ExitChosen;
End.
9
Program CircularQueueExample;
{$APPTYPE CONSOLE}
uses
SysUtils;
Const MaxQueueSize=6;
Var
ExitChosen: Boolean;
MenuItem: Char;
Queue: Array[1..MaxQueueSize] Of String;
BackPointer: Integer = 0;
FrontPointer: Integer = 0;
NumberOfItemsInQueue: Integer = 0;
Function QueueEmpty: Boolean;
Begin
QueueEmpty := NumberOfItemsInQueue=0;
End;
Function QueueFull: Boolean;
Begin
QueueFull := NumberOfItemsInQueue=MaxQueueSize;
End;
Procedure GetMenuChoice(Var Choice: Char);
Begin
WriteLn;
WriteLn('Menu');
WriteLn;
WriteLn('1) Add an item to the queue');
WriteLn('2) Remove an item from the queue');
WriteLn('3) Show contents of queue');
WriteLn('4) Exit Program');
WriteLn;
AQA Computing A2 Teacher Notes Nelson Thornes Ltd 2009

79

Write('Enter your choice number: ');


ReadLn(Choice);
End;
Procedure IncrementPointer(Var Ptr: Integer);
Begin
Ptr := Ptr MOD MaxQueueSize + 1;
End;
Procedure AddItemToQueue;
Begin
If QueueFull
Then WriteLn('Can''t add to a full queue')
Else
Begin
If QueueEmpty
Then FrontPointer := 1;
IncrementPointer(BackPointer);
Write('Enter item to be added to queue: ');
ReadLn(Queue[BackPointer]);
NumberOfItemsInQueue := NumberOfItemsInQueue + 1;
End;
End;
Procedure RemoveItemFromQueue;
Begin
If QueueEmpty
Then WriteLn('Can''t take anything from an empty queue')
Else
Begin
WriteLn('Item taken from queue: ', Queue[FrontPointer]);
Queue[FrontPointer] := ''; // clear space
NumberOfItemsInQueue := NumberOfItemsInQueue - 1;
If NumberOfItemsInQueue = 0
Then
Begin
FrontPointer := 0;
BackPointer := 0;
End
Else
IncrementPointer(FrontPointer);
End;
End;
Procedure ShowContentsOfQueue;
Var Pointer: Integer;
Begin
For Pointer := 1 To MaxQueueSize
Do
Begin
AQA Computing A2 Teacher Notes Nelson Thornes Ltd 2009

80

Write(Pointer, Queue[Pointer]);
If Pointer = FrontPointer
Then Write('<-- Front');
If Pointer = BackPointer
Then Write('<-- Back');
WriteLn;
End;
End;
Begin
ExitChosen := False;
Repeat
GetMenuChoice(MenuItem);
Case MenuItem Of
'1': AddItemToQueue;
'2': RemoveItemFromQueue;
'3': ShowContentsOfQueue;
'4': ExitChosen := True;
Else WriteLn('Invalid menu choice. Try again');
End;
Until ExitChosen;
End.

10
Program QueueExampleUsingHeap;
{$APPTYPE CONSOLE}
Uses
SysUtils;
Type
TNodePtr = ^TNode;
TNode = Record
Data : String;
Ptr : TNodePtr;
End;
Var
FrontPointer : TNodePtr;
BackPointer : TNodePtr;
ExitChosen: Boolean;
MenuItem: Char;
Procedure InitQueue;
Begin
FrontPointer := Nil;
BackPointer := Nil;
End;
Procedure AddItemToQueue;
Var NewNode: TNodePtr; NewItem: String;
AQA Computing A2 Teacher Notes Nelson Thornes Ltd 2009

81

Begin
Write('Enter item to be added to Queue: ');
ReadLn(NewItem);
New (NewNode);
NewNode^.Data := NewItem;
NewNode^.Ptr := Nil;
If BackPointer = Nil
Then
Begin
FrontPointer := NewNode;
BackPointer := NewNode;
End
Else
Begin
BackPointer^.Ptr := NewNode;
BackPointer := NewNode;
End;
End;
Procedure RemoveItemFromQueue;
Var ThisNode: TNodePtr;
Begin
If FrontPointer <> Nil
Then
Begin
WriteLn('Popped Data: ', FrontPointer.Data);
ThisNode := FrontPointer;
Frontpointer := FrontPointer^.Ptr;
Dispose (ThisNode);
IF FrontPointer = Nil
Then BackPointer := Nil;
End
Else WriteLn('Queue Empty');
End;
Procedure ShowContentsOfQueue;
Var ThisNode : TNodePtr;
Begin
If FrontPointer <> Nil
Then
Begin
ThisNode := FrontPointer;
Repeat
WriteLn (ThisNode^.Data);
ThisNode := ThisNode^.Ptr;
Until ThisNode = Nil;
End
Else WriteLn('Queue Empty');
AQA Computing A2 Teacher Notes Nelson Thornes Ltd 2009

82

End;
Procedure GetMenuChoice(Var Choice: Char);
Begin
WriteLn;
WriteLn('Menu');
WriteLn;
WriteLn('1) Add an item to the Queue');
WriteLn('2) Remove an item from the Queue');
WriteLn('3) Show contents of Queue');
WriteLn('4) Exit Program');
WriteLn;
Write('Enter your choice number: ');
ReadLn(Choice);
End;
Begin
InitQueue;
ExitChosen := False;
Repeat
GetMenuChoice(MenuItem);
Case MenuItem Of
'1': AddItemToQueue;
'2': RemoveItemFromQueue;
'3': ShowContentsOfQueue;
'4': ExitChosen := True;
Else WriteLn('Invalid menu choice. Try again');
End;
Until ExitChosen;
Readln;
End.

11
Program OOPQueueExample;
{$APPTYPE CONSOLE}
Uses
SysUtils,
QueueClass In 'QueueClass.pas';
Var
Queue: TQueue;
MenuItem: Char;
ExitChosen: Boolean;
NewItem: String;
Procedure GetMenuChoice(Var Choice: Char);
Begin
WriteLn;
WriteLn('Menu');
AQA Computing A2 Teacher Notes Nelson Thornes Ltd 2009

83

WriteLn;
WriteLn('1) Add an item to the queue');
WriteLn('2) Remove an item from the queue');
WriteLn('3) Show contents of queue');
WriteLn('4) Exit Program');
WriteLn;
Write('Enter your choice number: ');
ReadLn(Choice);
End;
Begin
Queue := TQueue.Create;
Repeat
GetMenuChoice(MenuItem);
Case MenuItem Of
'1': Begin
Write('Enter item to be added to queue: ');
ReadLn(NewItem);
Queue.Add(NewItem);
End;
'2':
'3':
'4':
Else
End;
Until
End.

WriteLn('Item popped: ',Queue.Remove);


Queue.PrintQueue;
ExitChosen := True;
WriteLn('Invalid menu choice. Try again');
ExitChosen;

Exam practice questions


Question 1 May 2007 CPT1 Q5
Question Answer
number
1a

Last (item) in, is the first (item) out/first (item) in is the last (item) out;
R. LIFO / FILO

AQA Computing A2 Teacher Notes Nelson Thornes Ltd 2009

Marks
1

84

1b

i)

All items in the correct locations

ii)

1
Correct three items // ft from an incorrect (i) including 605 as the first
location used;
A. .R. and .Y. entries indicated in some way as . deleted.
iii)

Correct list of five items // ft from an incorrect (i) + a correct ft (ii) including
605 as
the first location used;
1c

i) Queue ; A. First In . First Out FIFO / LILO


ii) Items are removed/popped from the stack (one at a time) (and items are
then added to the queue);
iii) Items leave the queue on a .first in-first out. basis; A. from the front of
the queue
iv) .Y., .R., .E., .V., .A. on the queue;
.Y., .R., .E., .V., .A. on the final stack;
A. using 701 for the first queue location

AQA Computing A2 Teacher Notes Nelson Thornes Ltd 2009

1
1
1
2

85

Question 2 January 2007 CPT1 Q4


Question Answer
number

Marks

2a

Next item to be added is at position/location/address (Tail + 1);


Position/location/address Tail is the last item in the queue; R. .points to the
end of the queue.

Max 1

2b

Cat // item at position Head;

2c

Snake + Eel + Shark at positions 3,4,5;


Tail points to 5;
Head points to 2;
I. Dog and Cat crossed through
2d

Tail will eventually reach position 99 (A. 100);


Head will eventually reach 99 (A. 100);
Memory/queue will become full;
Space is not re-useable

Question 3 June 2005 CPT1 Q7


Question Answer
Number
3a

Max 2

Marks

First In First Out; or by description

Last In First Out; or by description

2
2

3b

3c

1
1
1

Reverse the contents of a queue/list;

Push all contents of queue/list onto stack then pop them off into a new
queue/list;
Procedure/function calls;

AQA Computing A2 Teacher Notes Nelson Thornes Ltd 2009

86

Local variables;
Parameters;
Return address;
Volatile environment; A register contents
State 1 Describe 1
3d

List of elements inserted into tree;

to allow rapid/fast searching of the data;


to output sorted/ordered data;
Question 4 January 2004 CPT1 Q8
Question Answer
number
4
Last In First Out;

Marks
1

4b) i)

4b) ii)

4b) iii)

4b) iv)

4c)

To reverse elements/pass parameters/store volatile environment;


A store return address

AQA Computing A2 Teacher Notes Nelson Thornes Ltd 2009

87

Question 5 June 2008 CPT4 Q2


Question Answer
number
5a) i)
Empty entries waste memory // Maximum size // fixed size;
5a) ii)
Memory used by pointers//takes more time to add/delete notes//indirect
access takes more time; R programming difficulties
5b)
Place next item in first location/location 0/location 1//Implement a
circular array/queue//allow wraparound;
5c)
IsFull/IsQueueFull;
Question 6 January 2007 CPT4 Q6
Question Answer
number
6a

Marks
1
1
1
1

Marks
3

6b

AddItem//Add;

6c

i) Full/FullQueue;

1
1

ii) No memory used for pointers;


I Faster
R Easier to program
iii) Size is limited by array size;
memory wasted when not full;
Question 7 January 2006 CPT4 Q2
Question Answer
number
i) Empty entries waste space // Maximum/fixed/static size
7a)
A stack may overflow

ii) Space used by pointers // more complex to program


7b)

i) The size of the stack/amount of data is known/limited/predictable


Memory saved since no pointers (if not given in a (ii))
R easier to program
ii) The size of the stack is unknown//
The stack is volatile/number of items fluctuates widely;

AQA Computing A2 Teacher Notes Nelson Thornes Ltd 2009

Marks
1
1
1
1

88

Question 8 June 2002 CPT4 Q5


Question
Answer
number

Marks
4

8a)

2
8b)

8c)

In a linear queue data is static, so queue moves through storage/


In a FIFO structure storage locations are only used once;
In a circular queue, the locations will be re-used;
Thus a circular queue has a more efficient use of memory;

1
1
1

1 mark for each of 2 points

AQA Computing A2 Teacher Notes Nelson Thornes Ltd 2009

89

2.5
End of topic questions
1 The number of actors that the actor at the vertex has starred with in movies.
2

3 A graph is a diagram consisting of circles called vertices, joined by lines called edges or arcs.
Each edge joins exactly two vertices.

AQA Computing A2 Teacher Notes Nelson Thornes Ltd 2009

90

5a)

b) Three cages: one for A, one for D and one for B, C and E
6a)
Vertex 1

b)

Vertex

Adjacent vertices

2, 3, 5

1, 4, 5

1, 4, 5

2, 3, 5

1, 2, 3, 4

AQA Computing A2 Teacher Notes Nelson Thornes Ltd 2009

91

7a)
Vertex

Vertex

Adjacent vertices

2, 3

1, 2, 4

Vertex

20

81

30

-3

54

Vertex

Adjacent
Vertices

20

81

2, 3

30

1, 2, 4

b)

8a)

b)

AQA Computing A2 Teacher Notes Nelson Thornes Ltd 2009

54

92

9a) When many vertex pairs are connected by edges, then the adjacency matrix is best because
it doesn't waste much space, and it indicates whether an edge exists with one access (rather than
following a list).
b)
When the graph is sparse, that is, not many of its vertex pairs have edges between them, the
adjacency list is best.
10

11

Imagine a graph of four vertices connected by four edges to create a cycle as follows:

If one edge is removed then the graph becomes a tree a tree is a connected graph with no cycles.
Generalising, a tree of n vertices must have n1 edges.
12 A tree is a connected undirected graph with no cycles. A rooted tree is a tree in which one
vertex has been designated as the root and every edge is directed away from the root.
13 Vertices visited in the following order EGFDABC

AQA Computing A2 Teacher Notes Nelson Thornes Ltd 2009

93

Exam practice questions


Question 1 Specimen Paper COMP 3 Q3
Question
Answer
number

Marks

1a

Max 3

or

1b

i) Max size only limited by memory;


Only uses memory it requires;
ii) No pointers required;

AQA Computing A2 Teacher Notes Nelson Thornes Ltd 2009

max 1
1
94

i) Adjacency matrix;

1c

1
2

ii) Faster to insert/delete; fixed size;

2.6
End of topic questions
1 Dry-run of iterative algorithm searching for Davidson
ItemSought First
Last
Midpoint List[Midpoint]
Davidson

15

King

Farmer

Bond

Clark

ItemFound

SearchFailed

False

False

True

2 Dry-run of recursive algorithm searching for Davidson


Cal
l

ItemSough
t

Firs
t

Las
t

Midpoin
t

List[Midpoint
]

ItemFoun
d

SearchFaile
d

Davidson

15

King

False

False

Davidson

Farmer

False

False

Davidson

Bond

False

False

Clark

False

True

4
Davidson
3
3
3
Four calls are made before the search fails.
3a)

Program Project1;
{$APPTYPE CONSOLE}
Uses
SysUtils;
Const Max = 13;
Var NameToFind: String;
Var NumberOfIterations: Integer = 0;
Var NumberOfProcedureCalls: Integer = 0;
Var SortedList: Array[0..Max] Of String = ('Alan', 'Ben',
'Chris', 'David', 'Eve', 'Fred', 'Greg', 'Heidi',
'Ida', 'Jude', 'Karl', 'Les', 'Mike', 'Noel');
// could read a text file of many names into an array to test
instead
Procedure BinarySearch1 (Var List: Array Of String; First, Last:
Integer; ItemSought: String);
Var ItemFound, SearchFailed: Boolean; MidPoint: Integer;
Begin
AQA Computing A2 Teacher Notes Nelson Thornes Ltd 2009

95

ItemFound := False;
SearchFailed := False;
Repeat
NumberOfIterations := NumberOfIterations + 1; // for stats
only
Midpoint := (First + Last) DIV 2; // integer part of division
If List[Midpoint] = ItemSought
Then ItemFound := True
Else
If First >= Last
Then SearchFailed := True
Else
If List[Midpoint] > ItemSought
Then Last := Midpoint 1
Else First := Midpoint + 1
Until ItemFound Or SearchFailed;
If SearchFailed
Then WriteLn('No such name')
Else WriteLn('Name found at position ',MidPoint);
End;

c) The iterative program uses less memory as it does not have the procedure call overheads.
Each procedure call saves return address, parameters and local variables on the stack (in
main memory).
4
First Last

CurrentPointer

CurrentValue

72

28

45

Pointer

List
[1]

[2]

[3]

[4]

[5]

[6]

87

72

28

45

59

36

1
0

87

87

28

45

59

36

72

87

28

45

59

36

72

87

28

45

59

36

72

87

87

45

59

36

1
0

72

72

87

45

59

36

28

72

87

45

59

36

28

72

87

45

59

36

28

72

87

87

59

36

2
1

28

72

72

87

59

36

28

45

72

87

59

36

AQA Computing A2 Teacher Notes Nelson Thornes Ltd 2009

96

59

36

28

45

72

87

59

36

28

45

72

87

87

36

3
2

28

45

72

72

87

36

28

45

59

72

87

36

28

45

59

72

87

36

28

45

59

72

87

87

28

45

59

72

72

87

28

45

59

59

72

87

2
1

28

45

45

59

72

87

28

36

45

59

72

87

5a) & b) Answer to insertion sort:


Program Project1;
{$APPTYPE CONSOLE}
Uses
SysUtils;
Const Max = 7;
Type TList = Array[1..Max] Of Integer;
Var UnsortedList: TList ;
Procedure OutputList(List:TList; First, Last: Integer);
Var i: Integer;
Begin
Write('(');
For i := First To Last1
Do Write(List[i], ' ,');
WriteLn(List[Last],')');
End;
Procedure Sort (List: TList; First, Last: Integer);
Var CurrentPointer, Pointer: Integer; CurrentValue: Integer;
Begin
For CurrentPointer := First + 1 To Last
Do
Begin
CurrentValue := List[CurrentPointer];
Pointer := CurrentPointer 1;
Write(First:6, Last:6, CurrentPointer:6, CurrentValue:6,
Pointer:6);
OutputList(List, First, Last);
While (List[Pointer] > CurrentValue) AND (Pointer > 0)
Do
AQA Computing A2 Teacher Notes Nelson Thornes Ltd 2009

97

Begin
List[Pointer+1] := List[Pointer];
Pointer := Pointer 1;
Write(First:6, Last:6, CurrentPointer:6, CurrentValue:6,
Pointer:6);
OutputList(List, First, Last);
End;
List[Pointer+1] := CurrentValue;
Write(First:6, Last:6, CurrentPointer:6, CurrentValue:6,
Pointer:6);
OutputList(List, First, Last);
End;
End;
Begin
UnsortedList[1]:=56;
UnsortedList[2]:=23;
UnsortedList[3]:=67;
UnsortedList[4]:=12;
UnsortedList[5]:=45;
UnsortedList[6]:=99;
UnsortedList[7]:=17;
OutputList(UnsortedList,1,Max);
Sort(UnsortedList,1,Max);
ReadLn;
End.

6 Bubble sort program


Program Project1;
{$APPTYPE CONSOLE}
Uses
SysUtils;
Const Max = 7;
Type TList = Array[1..Max] Of Integer;
Var UnsortedList: TList;
Procedure OutputList(List:TList; NumberOfItems: Integer);
Var i: Integer;
Begin
Write('(');
For i := 1 To NumberOfItems-1
Do Write(List[i], ' ,');
WriteLn(List[NumberOfItems],')');
End;
Procedure BubbleSort(List: TList; NumberOfItems: Integer);
Var NoMoreSwaps: Boolean; Temp, Element: Integer;
Begin
Repeat
AQA Computing A2 Teacher Notes Nelson Thornes Ltd 2009

98

NoMoreSwaps := True;
For Element := 1 To NumberOfItems 1
Do
If List[Element] > List[Element+1]
Then
Begin
NoMoreSwaps := False;
Temp := List[Element];
List[Element] := List[Element + 1];
List[Element + 1] := Temp;
OutputList(List,NumberOfItems);
End;
Until NoMoreSwaps;
End;
Begin
UnsortedList[1]:=56;
UnsortedList[2]:=23;
UnsortedList[3]:=67;
UnsortedList[4]:=12;
UnsortedList[5]:=45;
UnsortedList[6]:=99;
UnsortedList[7]:=17;
OutputList(UnsortedList,Max);
BubbleSort(UnsortedList,Max);
ReadLn;
End.

The bubble sort program does 11 swaps of elements using the given test data. Each
swap consists of 3 assignments. This means that 33 assignments are required.
The insertion sort program uses 22 assignments for the same test data.
i) using the list: 12, 23, 45, 56, 67, 99, 17
The insertion sort uses 17 assignments.
The bubble sort uses 15 assignments.
ii) using the list: 99, 67, 56, 45, 23, 17, 12
The insertion sort uses 66 assignments.
The bubble sort uses 66 assignments.
8
Program Project1;
{$APPTYPE CONSOLE}
Uses
SysUtils;
Const Max = 7;
Type TList = Array[0..Max] Of Integer;
Var UnsortedList: TList ;
AQA Computing A2 Teacher Notes Nelson Thornes Ltd 2009

99

Procedure OutputList(List:TList; First, Last: Integer);


Var i: Integer;
Begin
Write('(');
For i := First To Last-1
Do Write(List[i], ' ,');
WriteLn(List[Last],')');
End;
Procedure Swap(Var A, B : Integer);
Var Temp: Integer;
Begin
Temp := A;
A := B;
B := Temp;
End;
Procedure QuickSort (Var List: TList; First, Last:Integer);
Var PivotValue, LeftPointer, RightPointer, Pivot: Integer;
Begin
If First < Last
{if there are elements in the list}
Then
Begin
PivotValue := List[First];
LeftPointer := First + 1;
RightPointer := Last;
Pivot := 0;
While LeftPointer <= RightPointer
Do
Begin
While (List[LeftPointer] < PivotValue) And (LeftPointer
<= RightPointer)
Do
Begin
LeftPointer := LeftPointer + 1;
End;
While (List[RightPointer] > PivotValue) And (LeftPointer
<= RightPointer)
Do
Begin
RightPointer := RightPointer 1;
End;
If LeftPointer < RightPointer
Then
Swap (List[LeftPointer], List[RightPointer]);
End;
Pivot := RightPointer;
Swap (List[First], List[Pivot]);
QuickSort (List, First, Pivot 1);
QuickSort (List, Pivot + 1, Last);
AQA Computing A2 Teacher Notes Nelson Thornes Ltd 2009

100

End;
End;
Begin
UnsortedList[1]:=56;
UnsortedList[2]:=23;
UnsortedList[3]:=67;
UnsortedList[4]:=12;
UnsortedList[5]:=45;
UnsortedList[6]:=99;
UnsortedList[7]:=17;
OutputList(UnsortedList,1,7);
QuickSort(UnsortedList,1,7);
OutputList(UnsortedList,1,7);
ReadLn;
End.

Quick sort questions


1
List

Comment

First Last Pivot Left


Right
Pivot
value pointer pointer

[1] [2] [3]

[4] [5]

[6] [7]

56

45

12

56

23

67

12

45

99

17

Swap left &


right

56

23

17

12

45

99

67

Swap right &


pivot

45

23

17

12

56

99

67

45

23

17

12

12

23

17

45

12

23

17

12

23

17

No value
larger than
pivot value

No value
smaller than
pivot value

Last < First


return from
call
23

23

17

17

23

AQA Computing A2 Teacher Notes Nelson Thornes Ltd 2009

No value
larger than
pivot value

Last = First
101

Return from
call
4

Last < First


return from
call

Last < First


return from
call

99

99

67

67

99

No value
larger than
pivot value

Last = First
return from
call

Last < First


return from
call

Exam practice questions


Question 1 Jan 2007 CPT4 Q7
Question
Answer
number
1a)

Marks
8

1 mark for first row (12, 1, 9)


2 marks for second row (1 mark for each 5)
2 marks for third row (3 and 3)
2 marks for fourth row (1 mark for Lower = 4, 1 mark for upper = 4)
AQA Computing A2 Teacher Notes Nelson Thornes Ltd 2009

102

1 mark for correct return value


1b)

Find the position of 12/ a number in the array// search for 12/ a number in the
array;

AQA Computing A2 Teacher Notes Nelson Thornes Ltd 2009

103

Question 2 June 2006 CPT4 Q5


Question Answer
number
271;
2a)
The required item might be the 271st one/last one/ not be present//
Every item accessed;
2b)

9;

Each comparison halves the number of items to be accessed//


271 lies between 28 and 29

Marks
1
1
1
1

2c)

5
1
1

1 mark for Count1


1 mark for Count2
1 mark for Temp
(ii) (Bubble) sort the items into ascending order;
(ii) Reduce the number of tests each pass// stop when no swaps occur during
a pass//
Add a flag NoSwaps to indicate when no swaps occur// change loop control
to Repeat until no swaps// sort variable sized array;

AQA Computing A2 Teacher Notes Nelson Thornes Ltd 2009

104

Question 3 June 2004 CPT4 Q8


Question Answer
number
3a)
A procedure/routine which calls itself//is defined in terms of itself; R reentrant;
A function instead of procedure R program
iteration Talked Out (no mark)

Marks
1

3b) i)

Accept True in row 3


Marks in each row all three/two parts correct
Accept empty cell to mean: same as in previous row.
Stop marking when logic goes wrong
3b) ii)

Binary search;;
Search;
R any other type of search

Question 4 January 2003 CPT4 Q3


Question Answer
number
4a) i)
8

2
Marks
1

4a) ii)

Each time a comparison is made in a binary search the number of items


to be searched/list is halved;
//137 lies between 27 and 28
Could have (ii) even if (i) incorrect

1
1

4b) i)

137

4b) ii)

In a linear search of 137 items, the required item might be the 137th
one;
need a termination - must explain why 137 is the maximum
Question 5 June 2002 CPT4 Q4
Question Answer
number
5a)
1, 17, 9, 21, 15, 23;

Marks
2

(2 if all right, 1 if 4 of 6)
If > misinterpreted, follow through for 1 mark
AQA Computing A2 Teacher Notes Nelson Thornes Ltd 2009

105

5b)

A bubble sort

5c)

To detect when all the numbers have been sorted


Efficiency (to stop procedure repeating unnecessarily);
R to detect when numbers have switched

2.7
End of topic questions
1a

entities: lorry, queue, loading bay


Attributes of lorry: waiting, being unloaded
Attributes of queue: lorries in queue, queue empty
Attributes of loading bay: loading bay free, loading bay in use

states: no lorry waiting, no lorry being unloaded


no lorry waiting, lorry being unloaded
lorries waiting in queue, lorry being unloaded
possible events: a lorry arrives, a lorry leaves the loading bay
possible activities: unloading a lorry, inter-arrival time of lorries

c
Lorries
Queuing

Lorries
Arriving

Lorry
Being Unloaded

Loading Bay
Free

d possible variables: arrival times of lorries, loading times of lorries, number of loading
bays
2
Master
clock
(hours)
05:00
06:00

Lorries
arriving

Lorries being
unloaded

Lorries in
queue

Lorry hours
in queue

Loading bay
status

Lorry1

Lorry1

0
0

0
0

Free
In use

AQA Computing A2 Teacher Notes Nelson Thornes Ltd 2009

106

07:00
08:00
09:00
10:00
11:00
12:00
13:00
14:00
15:00
16:00
17:00
18:00
19:00
20:00

Lorry2
Lorry3
Lorry4
Lorry5

Lorry1
Lorry1
Lorry2
Lorry2
Lorry2
Lorry3
Lorry3
Lorry3
Lorry4
Lorry4
Lorry4
Lorry5
Lorry5
Lorry5

0
1
0
1
1
1
1
2
1
1
1
0
0
0

AQA Computing A2 Teacher Notes Nelson Thornes Ltd 2009

0
1
1
2
3
4
5
7
8
9
10
10
10
10

In use
In use
In use
In use
In use
In use
In use
In use
In use
In use
In use
In use
In use
In use

107

3
Master
clock
(hours
)
05:00
06:00
07:00
08:00
09:00
10:00
11:00
12:00
13:00
14:00
15:00
16:00

Lorries Lorries
arriving being
unloaded
in Bay 1
Lorry1
Lorry1
Lorry1
Lorry2
Lorry1
Lorry3
Lorry4
Lorry5

Lorry3
Lorry3
Lorry3
Lorry5
Lorry5
Lorry5

Lorries
being
unloaded
in Bay 2

Lorry2
Lorry2
Lorry2
Lorry4
Lorry4
Lorry4

Lorries Loading
in
bay
queue
hours
free
0
2
0
3
0
4
0
4
0
5
0
5
0
6
0
6
0
7
0
7
0
8
0
9

Loading
Bay 1
status

Loading
bay 2
status

Free
In use
In use
In use
Free
In use
In use
In use
Free
In use
In use
In use

Free
Free
Free
In use
In use
In use
Free
In use
In use
In use
Free
Free

4a

entities: passenger, queue, check-in desk


Attributes for passenger: waiting, checking in
Attributes for queue: passengers in queue, queue empty
Attributes for check-in desk: in use, free

states: no passenger waiting, check-in desk free


no passenger waiting, passenger checking in
passengers waiting, passenger checking in
events: passenger arrives, passenger finishes checking in
activities: checking in a passenger, inter-arrival time of passengers

c
Master
clock
(minutes)
1
2
3
4
5
6
7
8
9

Passenger
arriving

Passenger
checking in

Passengers
in queue (25
at start)

Passenger26

Passenger1
Passenger1
Passenger2
Passenger2
Passenger3
Passenger3
Passenger4
Passenger4
Passenger5

24
24
23
23
23
23
22
22
21

AQA Computing A2 Teacher Notes Nelson Thornes Ltd 2009

Passenger
minutes in queue
(from check-in
desk opening)
24
48
71
94
117
140
162
184
205

Check-in
desk
status
In use
In use
In use
In use
In use
In use
In use
In use
In use
108

10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52

Passenger27

Passenger28

Passenger29

Passenger30

Passenger31

Passenger32

Passenger33

Passenger34

Passenger35

Passenger36

Passenger37

Passenger38

Passenger5
Passenger6
Passenger6
Passenger7
Passenger7
Passenger8
Passenger8
Passenger9
Passenger9
Passenger10
Passenger10
Passenger11
Passenger11
Passenger12
Passenger12
Passenger13
Passenger13
Passenger14
Passenger14
Passenger15
Passenger15
Passenger16
Passenger16
Passenger17
Passenger17
Passenger18
Passenger18
Passenger19
Passenger19
Passenger20
Passenger20
Passenger21
Passenger21
Passenger22
Passenger22
Passenger23
Passenger23
Passenger24
Passenger24
Passenger25
Passenger25
Passenger26
Passenger26

22
21
21
20
20
20
20
19
19
18
19
18
18
17
17
17
17
16
16
15
16
15
15
15
15
14
15
14
14
14
14
13
14
13
13
13
13
12
13
12
12
12
12

AQA Computing A2 Teacher Notes Nelson Thornes Ltd 2009

227
248
269
289
309
329
349
368
387
405
424
442
460
477
494
511
528
544
560
575
591
606
621
636
651
665
680
694
708
722
736
749
763
776
789
802
815
827
840
852
864
876
888

In use
In use
In use
In use
In use
In use
In use
In use
In use
In use
In use
In use
In use
In use
In use
In use
In use
In use
In use
In use
In use
In use
In use
In use
In use
In use
In use
In use
In use
In use
In use
In use
In use
In use
In use
In use
In use
In use
In use
In use
In use
In use
In use
109

53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
6

Passenger39

Passenger40

Passenger41

Passenger42

Passenger43

Passenger44

Passenger45

Passenger46

Passenger47

Passenger27
Passenger27
Passenger28
Passenger28
Passenger29
Passenger29
Passenger30
Passenger30
Passenger31
Passenger31
Passenger32
Passenger32
Passenger33
Passenger33
Passenger34
Passenger34
Passenger35
Passenger35
Passenger36
Passenger36
Passenger37
Passenger37
Passenger38
Passenger38
Passenger39
Passenger39
Passenger40
Passenger40
Passenger41
Passenger41
Passenger42
Passenger42
Passenger43
Passenger43
Passenger44
Passenger44
Passenger45
Passenger45

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

899
911
922
933
944
955
965
976
986
996
1005
1014
1023
1032
1040
1048
1055
1063
1070
1077
1083
1089
1095
1101
1106
1111
1115
1120
1124
1128
1131
1134
1137
1140
1142
1144
1145
1147

In use
In use
In use
In use
In use
In use
In use
In use
In use
In use
In use
In use
In use
In use
In use
In use
In use
In use
In use
In use
In use
In use
In use
In use
In use
In use
In use
In use
In use
In use
In use
In use
In use
In use
In use
In use
In use
In use

passengers are still waiting to check in half an hour before take off.
If the check-in process takes longer, there would be even more passengers not
checked in.
Queues would be even longer if more passengers arrive during the peak half-hour.

AQA Computing A2 Teacher Notes Nelson Thornes Ltd 2009

110

A second check-in desk would then become necessary.

Exam practice questions


Question Answer
number
A computer model is used to manipulate variables and observe results.
1a
We may consider simulation because experimenting with the real
1b
system might cause unknown irremovable effects, or because we can
experiment with a model more cheaply and at a time of our choosing.
Possible examples include queuing for service, traffic flow,
1c
population growth.

Marks

Question Answer
number
The entities are: ship, queue, berth.
2a
The attributes for ship are: waiting, being unloaded.
The attributes for berth are: berth free, berth in use.
The attributes for queue are: ships in queue, queue empty.
Possible states are:
2b
no ship waiting in queue, berth free
no ship waiting in queue, ship being unloaded in berth
ships waiting in queue, ship being unloaded in berth.

Marks

1
1

Possible events are:


a ship arrives
a ship leaves the berth.
Possible activities are:
the unloading of a ship
the inter-arrival time of ships.
2c
Ships
Arriving

Ships
Queuing

Ship
Being Unloaded

Berth
Free

AQA Computing A2 Teacher Notes Nelson Thornes Ltd 2009

111

2d
Master
clock
(hours)
1
2
3
4
5
6
7
8
9
10

Ship
arriving

Ship being
unloaded

Ships in Ship hours Berth


queue
in queue
status

Ship1

Ship1
Ship1
Ship1
Ship2
Ship2
Ship2
Ship3
Ship3
Ship3

0
0
0
1
0
1
1
1
1
2

Ship2
Ship3
Ship4
Ship5

0
1
1
2
3
4
5
7

Free
In use
In use
In use
In use
In use
In use
In use
In use
In use

Possible variables: ship arrival times, unloading times, number of


berths, maximum space for ships queuing.

2e

3.1
End of topic questions
Mantissa

Exponent

m x 2e

Denary

0.1011 10010

0001102=610

0.101110012 x 26 = 101110.012

46.25

1.0101 01000

0001002=410

-0.1010112 x 24 = -01010.112

-10.75

0.1100 00000

1111112=-110

0.112 x 2-1 = 0.0112

0.375

Qu.
1

d
2

1.0100 00000

1111012=-310

-3

-0.112 x 2 = -0.000112
5

-0.09375

1.10100 01000

101002=2010

1.10100012 x 2 = 110100.012

52.25

1.01100 00000

011112=1510

1.0112 x 20 = 1.0112

1.375

1.01010 00000

011102=1410

1.01012 x 2-1 = 0.101012

0.65625

-1.10001 11010

101102=2210

-1.1000111012 x 27 = -11000111.012

-199.25

-1.01100 00000

011012=1310

-1.0112 x 2-2 = -0.010112

-0.34375

0.00000 00000

111112 special case infinity

0.00000 00000

000002 special case zero

AQA Computing A2 Teacher Notes Nelson Thornes Ltd 2009

112

h
3

-0.00000 00000

111112 special case infinity

Mantissa

Exponent

5.5

0.10112 x 23

0.1011 00000

000011

0.375

0.112 x 2-1

0.1100 00000

111111

-9.75

1.0110012 x 24

1.0110 01000

000100

-0.1875

1.012 x 2-2

1.0100 00000

111110

b
5.5
0.375
-9.75
-0.1875

1.0112 x 22
1.12 x 2

-2
3

-1.001112 x 2
-3

-1.12 x 2

Sign

Exponent

Mantissa

10001

01 1000 0000

01101

10 0000 0000

10010

00 1110 0000

01100

10 0000 0000

4 Precision means the maximum number of significant digits we can represent. Precision is
important with floating point numbers because there are an infinite number of values between
any two given real numbers. These have to be mapped to a finite number of representations
(bit patterns). Therefore some values will be approximated.
5 36.1 is between 1.0010000011 x 25 and 1.0010000100 x 25
1.0010000011 x 25 = 36.09375
1.0010000100 x 25 = 36.125
Rounding to the nearest value, means 36.1 is represented by 1.0010000011 x 25
This introduces an absolute error or 0.00625 or a relative error of 0.000173
6 1.0110000000 x 212 x 27 = 1.0110000000 x 219
The largest possible value in the exponent field in minifloat format is 111102 = 30. As the
exponent is stored in excess-15 mode, the largest exponent possible is 15. Therefore the
result of this calculation will cause the exponent field to contain 11111 and set the mantissa to
0 (this means +).
7 1.0110000000 x 2-9 x 27 = 1.0110000000 x 2-16
The smallest possible value in the exponent field in minifloat format is 000002 = 0. As the
exponent is stored in excess-15 mode, the smallest exponent possible is -15. Therefore the
result of this calculation will cause the exponent field to contain 0 and set the mantissa to 0
(this means 0).
8
1.10100 000002 x 212=
1101000000000.02
+ 1.01000 000002 x 2-7 =
+ 000000000000.0000001012
1101000000000.0000001012
=
1.1010000000000000001012 x 212
However, there are only 11 bits for the mantissa, so the result is 1.10100000002 x 212
Note that the effect of adding a very small number to a large number does not change the
result.

AQA Computing A2 Teacher Notes Nelson Thornes Ltd 2009

113

Exam practice questions


Question 1 January 2008 CPT4 Q1
Question
Answer
Number
1a
BF2

Marks
1

1b

-;1038

1c

+;191;.125; A 1/8

2
(1 mark
for sign, 1
mark for
value)
3

1d

-;2;.03125; A 1/32

(If incorrect part marks as follows


1 mark for complemented mantissa 01000001
1 mark for moving binary point 2 places)
1e

To maximise precision in a given number of bits;


A to maximise accuracy in a given number of bits
To minimise rounding errors;
To allow a wider range of values to be stored;

Question 2 June 2005 CPT4 Q2


Question
Answer
Number
2a
140 1/4 ;; one mark for correct integer part,

Max 2

Marks
2

140.25;; one mark for correct fractional part

AQA Computing A2 Teacher Notes Nelson Thornes Ltd 2009

114

2b

i) -14.5;;; give 2 marks for 14.5


partial marks for workings if result incorrect:
1 mark for negative number;
1 mark for x24 (accept 16 instead of 24);
A showing that binary point moves 4 places right;
ii)leftmost 2 digits/bits are different;
a significant bit is stored after the binary point;
bit after point different from bit before point;
(negative number) starts with 10. (positive number starts with 01)..;
A the first bit after the sign bit is a .0.;
A The second bit is a .0.;
A an answer that clearly implies a .0. follows the .1.
iii) to maximise accuracy/precision for a given number of bits
// to minimise rounding errors;
A more accurate/precise for a given number of bits;
a given number can only be expressed in one way in a given number
of bits
// a given number can only be expressed in one way in a given format;
to simplify arithmetic/logical operations;
I range

Question 3 January 2005 CPT4 Q7


Question
Answer
number
3a)
BE4; must be capital letters

max 1

Marks
1

b)

190.25 / 190 1/4 ;; one mark for correct integer part,


one mark for correct fractional part
one mark for correct working
(e.g. correct place values)

c)

-1052;; 1 mark for workings if result incorrect


1 mark for sign, 1 mark for 1052

d) i)

-8.25 / -81/4;;; partial marks for workings if result incorrect


1 mark for sign, 1 mark for moving binary point 4 places or showing
24

ii)

starts with 1 0
the first 2 binary digits are different;
a significant bit is stored after the (implied) binary point;
bit after (implied) binary point different from bit before binary point;
A all leading 1.s have been removed // there are no leading 1.s;
R there are no leading zeros

Question 4 June 2004 CPT4 Q4(b)


Question
Answer
AQA Computing A2 Teacher Notes Nelson Thornes Ltd 2009

Marks
115

number
4a) i)

(if the answer is wrong give:


moving e places to right / exponent processing 2e or equivalent: 1
mark
correctly identifying negative number: 1 mark
follow through if binary representation wrong
ii)

To maximise precision in a given number of bits // to minimise


rounding errors

// to have just one representation of the decimal number // to simplify


arithmetic operations: 1 mark
A to maximise accuracy in a given number of bits;

Question 5 June 2003 CPT4 Q4


Question
Answer
number
5a) i)
positive
ii)
< 2-2
5b)
Correct answer 194.5

Marks
1
1
2
1

or 194

working
If wrong answer, method marks as follows:
exponent 28 [clearly defined]
application of shift / *28 from correct start point
correct interpretation of bits

1 mark
1 mark
1 mark

(Basically here, if it is a little inaccurate, give 2 marks, if quite


inaccurate but slightly correct, give 1 mark.)
c) i)

Processing fixed point numbers is quicker than floating point / less


processing is required;
More accurate / greater precision;

AQA Computing A2 Teacher Notes Nelson Thornes Ltd 2009

116

ii)

Where the possible range of numbers to be stored is limited / small;


Where number is of a set format / processing integers /
Working with currency;
Where maximum precision is required

4.1
End of topic questions
1
2

System programs and application programs.


Hide the complexities of the hardware from the user.
Manage the hardware resources in order to provide for an orderly and controlled allocation of
the processors, memories and I/O devices among the various programs competing for them,
manage the storage of data.
Processors
a) Storage
b) Input/output devices

c) Data
4 Processor scheduling
a) Memory management
b) I/O management
c) File management
5 Virtual machine: this is the apparent machine that the operating system presents to the user,
achieved by hiding the complexities of the hardware behind layers of operating system
software.
6 Application program interface: this is a layer of software that allows application programs to
call on the services of the operating system.
7 A standard application program interface (API) allows a software developer to write an
application on one computer and have a high degree of confidence that it will run on another
computer of the same type, even if the specifications of the latter are different. The program
should continue to run when hardware upgrades and updates occur because the operating
system, not the application, manages the hardware and the distribution of its resources.
8 Command Line and Graphical user interface.
Some embedded systems require no operating system because they function as very simple
controllers. Others such as mobile phones do require an operating system. However, a mobile
phone operating system has to manage a different set of resources. The resources include the
keypad, the screen, the address book, the phone dialler, the battery and the network connection.
Operating systems for general purpose computers have to manage resources such as printers, hard
drives, DVD R/W drives, high resolution flat screen visual display units, mouse and standard
QWERTY keyboard.
AQA Computing A2 Teacher Notes Nelson Thornes Ltd 2009

117

Exam practice questions


Question 1 January 2003 CPT2 Q5
Question number
Answer

Marks

1a)

OS hides complexities of hardware from the user;

1b)

Any three @ 1 each


Processor(s)/cpu(s);
Memory/IAS/Main memory;
Disk (space)/backing store; A Hard disk/drive //Floppy
disk (drive)//Secondary storage
I/O devices//peripherals; R examples
File space; A files R data
R programs

Max 3

4.2
End of topic questions
1a) Interactive operating system: An operating system in which the user and the computer are in
direct two-way communication.
1b) Real time operating system: inputs are processed in a timely manner so that the output can
affect the source of the inputs.
1c) Network operating system: in this system, a layer of software, added to the operating system
of a computer connected to the network, intercepts commands that reference resources
elsewhere on network, e.g. File server and then redirects the request to the remote resource in
a manner completely transparent to the user.
2 Both the airline reservation system and the system to land an aircraft:
have to support application programs which are non-sequential in nature, i.e. programs which
do not have a START- PROCESS - END structure;
have to deal with a number of events which happen in parallel and at unpredictable moments
in time;
have to carry out processing and produce a response within a specified interval of time.
In the case of the airline reservation system Airline reservation system - up to a 1000
messages per second can arrive from any one of 11000-12000 terminals, situated all over the
world. The response time must be less than 3 seconds.
In the case of the aircraft landing system - up to 1000 signals per second can arrive from
sensors attached to the system being controlled. The response time must be less than one
thousandth of a second.
a) C: - local hard drive; D: - DVD R/W drive; E: - flash memory drive; N: - network drive
b) Network operating system
AQA Computing A2 Teacher Notes Nelson Thornes Ltd 2009

118

c) Washing machine; microwave oven; central heating controller


d) Cable TV set-top box; broadband router; computer network firewall
The mobile phone operating system will be different from that of a desktop computer because
the kind of resources available to a mobile phone is different. In particular, the energy, the
physical context and the mobility of the user, and the limited amount of some resources such
as memory or CPU. An operating system for a mobile phone needs to manage a limited
amount of energy from the battery, a limited amount of memory and a processor of limited
capability. It needs to manage a network connection in a fairly autonomous way that
continually sends a message packet to base stations so that mobile phone location can be
identified. It needs to manage a keyboard that supports predictive text, a physically small
display, an address book, a phone dialler and a battery of limited power. It needs to meet real
time constraints because, for example, multimedia applications need to run. It needs to take
into account the instability of mobile phone networks (bandwidth, connection, etc).
The O.S. for a smartphone needs to be more powerful than that of an ordinary mobile phone
because the smartphone offers advanced capabilities with PC-functionality beyond a typical
mobile phone. The operating system must support advanced features like e-mail and Internet
capabilities and/or a full keyboard. The OS must have the capability to allow a user to install
new applications on the smartphone.
The operating system must take on the tasks of the BIOS in a PC and has to be designed to
run on processors with low clock frequency and a main memory of limited capacity. The
operating system must use various techniques to save energy and must cater for short reaction
times. The operating system must support character input via a stylus and touch sensitive
screen and should support high-resolution colour rendition with resolutions of approximately
640x480 pixels.
An embedded computer system is a dedicated computer system with a limited or non-existent
user interface and designed to operate completely or largely autonomously from within other
machinery, e.g. a motorcar. An embedded computer system in a motorcar could be set up to
manage the engine of the car carrying out a range of tasks one of which is controlling the
ignition of the gases in the cylinders.
The embedded computer O.S. must manage multiple tasks that need to meet specific time
constraints. In the simplest system, a low-level piece of code switches between tasks or
threads based on a timer (connected to an interrupt). Operating systems for embedded
systems are designed to work with the constraints of limited memory size and limited
processor performance. In portable embedded system the operating system must also take
account of limited battery life.
The O.S. on which embedded systems rely has had to become more sophisticated as
the hardware of embedded systems has become more complex with every
generation, and more features have been added. The role of an O.S. is to manage the
resources and to hide the complexities of the hardware. In the case of embedded
computer systems, it required to hide the complexities from the application
programs so making it possible to create new applications without consuming an
excessive amount of development time. With more tasks to manage and subject to
strict timing constraints a greater reliance on getting this support from the O.S. has
become necessary. This in turn requires greater sophistication in the O.S.

AQA Computing A2 Teacher Notes Nelson Thornes Ltd 2009

119

Exam practice questions


Question 1 - KB
Question Number

Answer

Marks

An embedded computer systems operating system has a


limited number of resources to manage unlike a desktop
operating system, most notably a limited or non-existent
user-interface and does not have to support the execution of
a large number of different applications. On the contrary the
embedded systems operating system has to support the
execution of a limited number of applications.

Question Number

Answer

Marks

A server operating system is an operating system optimised


to provide one or more specialised services to networked
clients such as file storage, domain control, running
applications. They are optimised for the service that they
carry out. This leads to a near optimum performance that
would not be achieved if a server were carrying out a large
amount of general-purpose processing.

Question Number

Answer

Marks

1 - It has one set of tasks to perform; 2 - Very


straightforward input to expect (a numbered keypad and a
few pre-set buttons); 3 - Simple, never-changing hardware to
control.

Answer
Any three from:
1) They have to support application programs which are nonsequential in nature, i.e. programs which do not have a
START- PROCESS - END structure;
2) They have to deal with a number of events which happen
in parallel and at unpredictable moments in time;
3) They have to carry out processing and produce a response
within a specified interval of time;
4) Some systems are safety-critical meaning they must be
fail-safe and guarantee a response within a specified time
interval.

Marks

Question 2 - KB

Question 3 - KB

Question 4 - KB
Question Number
4

AQA Computing A2 Teacher Notes Nelson Thornes Ltd 2009

120

5.1
End of topic questions
1

Blind Person

Guide Dog

provided with

Guide Dog

allocated to

Blind Person

Person

keeps

Car

registered to

Car

Person

BookTitle

Borrower

makes

has

borrows

Loan

BookCopy

of

AQA Computing A2 Teacher Notes Nelson Thornes Ltd 2009

121

Exam practice questions


Please see the Teacher Notes for Section 5.3: SQL for all of the answer to the
Examination-style questions.

5.2
End of topic questions
1 Course (CourseCode, CourseName)
Student (StudentID, StudentName, StudentAddress, StudentDateOfBirth)
CourseSet (CourseCode, SetNo, TeacherInitials)
Enrolment (StudentID, CourseCode, SetNo)
2 Borrower (BorrowerID, BorrowerName, BorrowerAddress)
BookTitle (ISBN, Title, Author)
BookCopy (AccessionNumber, ISBN)
Loan (BorrowerID, AccessionNumber, LoanDate)

Exam practice questions


Please see the Teacher Notes for Section 5.3: SQL for all of the answer to the
Examination-style questions.

5.3
End of topic questions
1a)
CREATE DATABASE CourseEnrolment
CREATE TABLE Course
(
CourseCode VARCHAR(5),
CourseName VARCHAR(20),
PRIMARY KEY (CourseCode)
);
CREATE TABLE Student
(
StudentID VARCHAR(10),
StudentName VARCHAR(25),
StudentAddress VARCHAR(50),
StudentDateOfBirth Date,
PRIMARY KEY (StudentID)
);
CREATE TABLE CourseSet
(
CourseCode VARCHAR(5),
AQA Computing A2 Teacher Notes Nelson Thornes Ltd 2009

122

SetNo INT,
TeacherInitials VARCHAR(3),
PRIMARY KEY (CourseCode, SetNo)
FOREIGN KEY (CourseCode) REFERENCES Course (CourseCode)
);
CREATE TABLE Enrolment
(
StudentID VARCHAR(10),
CourseCode VARCHAR(5),
SetNo INT,
PRIMARY KEY (StudentID, CourseCode),
FOREIGN KEY (StudentID) REFERENCES Student (StudentID),
FOREIGN KEY (CourseCode, SetNo) REFERENCES CourseSet (CourseCode,
SetNo)
);
1 b) SELECT * FROM Course

1 c) SELECT CourseCode, CourseName, StudentID, StudentName


FROM Enrolment, Student, Course
WHERE Enrolment.CourseCode = Course.CourseCode
AND Enrolment.StudentID = Student.StudentID
ORDER BY CourseCode

2a)
CREATE DATABASE BookLoanSystem
CREATE TABLE Borrower
(
BorrowerID VARCHAR(5),
BorrowerName VARCHAR(20),
BorrowerAddress VARCHAR(50),
PRIMARY KEY (BorrowerID)
);
CREATE TABLE BookCopy
(
AccessionNumber INT,
ISBN VARCHAR(13),
PRIMARY KEY (AccessionNumber),
Foreign Key (ISBN) REFERENCES BookTitle(ISBN)
);
CREATE TABLE BookTitle
(
ISBN VARCHAR(13),
Title VARCHAR(30),
Author VARCHAR(25),
PRIMARY KEY (ISBN)
);
CREATE TABLE Loan
(
BorrowerID VARCHAR(5),
AccessionNumber INT,
LoanDate Date,
PRIMARY KEY (AccessionNumber, LoanDate),
Foreign Key (BorrowerID) REFERENCES Borrower(BorrowerID),
Foreign Key (AccessionNumber) REFERENCES BookCopy(AccessionNumber)
AQA Computing A2 Teacher Notes Nelson Thornes Ltd 2009

123

);

2 b)
SELECT BorrowerID, BorrowerName
FROM Borrower, Loan
WHERE Borrower.BorrowerID = Loan.BorrowerID

2 c)
SELECT BorrowerID, BorrowerName
COUNT(Loan.AccessionNumber) AS BookCount
FROM Borrower, Loan
WHERE Borrower.BorrowerID = Loan.BorrowerID
Group By BorrowerID

Exam practice questions


Question 1 June 2007 CPT5 Q5
Question Answer
number
1a

i) Recipe table; A Figure 2;


ii) Why: contains multiple values in Ingredients field/attribute/column;
// data in Ingredients column not atomic // repeating groups.

1b

i) fully normalised:
every attribute is dependent on the key, the whole key and nothing but the
key;
OR (tables contain no repeating groups of attributes,) no partial
dependencies;
no non-key dependencies; A rely on instead of depend on;
OR if (and only if) every determinant in the relation is a candidate key.
ii) Why: to aid consistency of data // to avoid potential data inconsistency
problems;
// to eliminate data inconsistency // to minimise data duplication;
// to eliminate data redundancy; A reduce instead of eliminate;
R saving space.

Marks
1
1

1
1c

i) Recipe (RecipeID, Dish, PrepTime, CookTime, NoOfServings,


CookInstructions);
ii) FoodItem (FoodItemID, FoodItemName, PackSize, Price);
iii) RecipeIngredient(FoodItemID, RecipeID, Quantity).

1
1
4

(1 mark for each correct field, 1 mark for correct primary key.
AQA Computing A2 Teacher Notes Nelson Thornes Ltd 2009

124

Take off 1 mark for every extra field included.)


1d

SELECT FoodItemName, Quantity, PackSize, Price


FROM FoodItem, RecipeId = RecipeIngredient, Recipe
WHERE (Recipe.RecipeId = RecipeIngreident.RecipeId)
AND (RecipedIngredient.FoodItemId = FoodItem.FoodItemId)
AND (Recipe.Dish = Feat Salad)
ORDER BY FoodItemName

1
1
1
1
1
1
Max 5

field names F/T P1 for fieldname.tablename


P1 tbl prefix
A ORDER BY FoodItemName
A Dish instead of Recipe.Dish
A feta salad instead of Feta Salad A #feta salad# instead of Feta
Salad

AQA Computing A2 Teacher Notes Nelson Thornes Ltd 2009

125

Question 2 January 2007 CPT5 Q3


Question Answer
number

Marks

2a

Copyright, Designs and Patents Act (1998); if other laws included T.O.

2b

Boxes for correct entities: SoftwareLicence SoftwareInstallation (1 mark)


Correct degree of relationship: 1 to many (1 mark)
Suitable name for relationship: (1 mark)

2c

Any sensible field length accepted except for SoftwareID, ComputerID,


StaffID
i) SoftwareID VARCHAR(10) PRIMARY KEY (NOT NULL)
// SoftwareID VARCHAR(10)
PRIMARY KEY(SoftwareID);

SoftwareName VARCHAR(30)
Version VARCHAR(10)
Supplier VARCHAR(20)
DatePurchased DATE
ExpiryDate/DateValidTo DATE
NoOfLicences INT

(1 mark for any 3 attributes correct


P1 if extra symbols used.
Ignore spaces and case in attribute
names.)

(A char/string/text/alphanumeric
Instead of VARCHAR
A Date/Time instead of Date
A Integer instead of INT
BOD any attributes which are
clearly more than 1 word.)

ii )
SoftwareID VARCHAR(10)
ComputerID VARCHAR(6)
DateInstalled DATE
(1 mark for any 2 attributes correct.)
StaffID VARCHAR(3)
PRIMARY KEY (SoftwareID, ComputerID)
(If not DDL, give 1
FOREIGN KEY (SoftwareID)
mark if composite
REFERENCES Software Licence(SoftwareID)
key identified.)
I NOT NULL

AQA Computing A2 Teacher Notes Nelson Thornes Ltd 2009

126

2d

4
SELECT ComputerID, SoftwareName, Version; Extra attributes: T.O.
FROM SoftwareLicence, SoftwareInstallation;
WHERE SoftwareLicence.SoftwareID=SoftwareInstallation.SoftwareID;
ORDER BY ComputerID;
A ASC or DESC

Accept (instead of FROM WHERE):


FROM SoftwareLicence INNER JOIN
SoftwareInstallation ON
SoftwareLicence.SoftwareID =
SoftwareInstallation.SoftwareID

P1 for other spurious


punctuation inc.
semicolons

A LEFT JOIN

Table names prefixed with tbl, P1


If table name and attribute transposed, P1

Question 3 June 2006 CPT 5 Q5


Question Answer
number
3a

Marks

i)

R one to many relationship


ii)
Entity-Relationship Diagram; A E-R diagram; A E-R D R E-A-R diagram

AQA Computing A2 Teacher Notes Nelson Thornes Ltd 2009

127

3b

3c

AQA Computing A2 Teacher Notes Nelson Thornes Ltd 2009

128

F/T with attribute names


P1 for tbl prefix
P1 if table name after attribute name
I extra punctuation

AQA Computing A2 Teacher Notes Nelson Thornes Ltd 2009

129

Question 4 January 2005 CPT5 Q9


Question Answer

Marks

number

4a

I Minor spelling
i)
1

ii)

1
iii)
1

AQA Computing A2 Teacher Notes Nelson Thornes Ltd 2009

130

4b

Penalise table name. field name in reverse order once


R Quotes and additional constructs
I Table names unless in wrong order or wrongly expressed
i)
Select FirstName, Surname
From Student
ii)

1
I table name
unless incorrect

Select Student.FirstName, Student.Surname


MarkAwarded.Mark;
From Student, MarkAwareded;
Where MarkAwarded.LifecyclePhaseID = 1;

And Student.StudentID =
MarkAwarded.StudentID ;
Order By Student Surname;
Order By Student.Surname Asc
A Ascending
Asc/Ascending must be in correct position
A OrderBy

Question 5 June 2004 CPT5 Q9


Question Answer
number
5a

Marks

(NB Take note of labelling inside boxes because candidates positioning of


labels may be opposite to that shown below.)
Alternative symbols:

AQA Computing A2 Teacher Notes Nelson Thornes Ltd 2009

131

Accept minor misspelling or spaces


between parts of
entity name.
A. plural names
I. Box outlines

i)

1
ii)

iii)

iv)

5b

(R. Tbl in front of table name penalise once.)

Select Swimmer.Surname is
Select Surname
OK
From Swimmer
I. Brackets surrounding
Where SwimmerNo = 6;
attributes
R. Extra attributes, tables,
criteria
AQA Computing A2 Teacher Notes Nelson Thornes Ltd 2009
I. Quotes around value 6
I. ;
i)

132

3
ii)
Select SwimmerNo
From GalaRaceSwimmer
Where (RaceNo = 5); And (GalaNo = 2);
Order By TimeRecordedForRace;

A. Asc or Ascending in correct


place i.e. after
TimeRecordedForRace
R. Asc/Ascending in any other
position and/or with other words

iii)
Select Swimmer.Surname
From Swimmer, GalaRace;
Where (GalaNo = 4);
And (GalaRace.SwimmerNoOfWinner
= Swimmer.SwimmerNo);

Select Surname
From Swimmer
Where SwimmerNo In;
(Select SwimmerNoOfWinner
From GalaRace;
Where GalaNo = 4);
R. = in place of In
I. Brackets

I. Brackets surrounding
attributes, table names in
front of attributes unless
incorrect
A. Criteria without
brackets
R. Extra attributes,
tables, criteria in this
solution but be careful
because candidates may
give an alternative
involving extra
attributes, tables, criteria
that will work
I. Quotes around value 5
and value 2

A. Select
Swimmer.Surname,
GalaRace.RaceNo From
Or
A. Select Surname, RaceNo
From
Brackets may be omitted.
A. GalaRace.GalaNo = 4
And SwimmerNoOfWinner
= SwimmerNo is OK
Total 11

AQA Computing A2 Teacher Notes Nelson Thornes Ltd 2009

133

Question 6 June 2003 CPT5 Q8


Question Answer
number
6a

Marks

i)

1
ii)

L other entities
6b

i)
Select Book.Title
From Book
Where BookISBN = 1-57820-082-2;

A. Title
;

A. ISBN = 1-57820082-2

Any extra attributes lose mark where extra attributes


used
R. 1-57820-082-2 Need quotes
A. 1-57820-082-2
R. TblBook penalise once
R. Title.Book, wrong order
ii)
Dont need Book in Select
Select Book.AuthorName, Book.ISBN
From Book, BookCopy
Where (Book.ISBN = BookCopy.ISBN)
And )BookCopy.AccessionNumber = 1234)

Penalise TblBook/TblBookCopy
once
R. quotes on 1234
Any extra attributes lose mark
where extra attributes used
Brackets non-essential. May see
conditions interchanged, this is OK.
AQA Computing A2 Teacher Notes Nelson Thornes Ltd 2009

;
;
;
;

A. BoodCopy.ISBN in place
of BOOK.ISBN
A. AccessionNumber in
place of
BookCopy.AccessionNumbe
r
134

A. In for =
C

Mail-merge//Mail-merging

1
Total 9

Question 7 January 2003 CPT5 Q8


Question Answer
number
7a

Marks
3

(NB: dont allow relationship between Ward and PatientMedicalCondition.)

AQA Computing A2 Teacher Notes Nelson Thornes Ltd 2009

135

7b

(For each extra attribute lose one mark.)


i)
Ward(WardName, NurseInCharge, NoOfBeds)

A. NumberOBeds, NameOfNurseInCharge,
NurseInChargeName
R. WardId, Name, NurseName, NameOfNurse, BedNo,
BedNumber, NumOfBeds
ii)
Patient(PatientNo, Surname, Forename, Address, DOB, Gender, WardName)

A. PatientId, PatientNumber, PatientSurname, PatientForename,


PatientAddress, DateOfBirth, PatientDateOfBirth,
PatientGender, Sex, PatientSex
iii)
MedicalConditionID(MedicalConditionNumber, Name,
RecommendedStandardTreatment)

A. MedicalConditionId, MedicalConditionNumber,
MedicalconditionName, ConditionName, StandardTreatment,
Treatment, RecommendedTreatment
R. ConditionNumber, ConditionID
iv)
PatientMedicalCondition(PatientNo. MedicalConditionNo)

A. Attributes rejected in (ii) and (iii) for PatientNo and


MedicalConditionNo
R. If attributes used are not consistent with (ii) and (iii)
7c

(Accept tbl in front of table name.)


Select Patient.Forename, Patient.Surname, PatientMedicalCondition,
MedicalConditionNo
From Patient, PatientMedicalCondition
Where Patient.WardName = Victoria
And Patient.PatientNo = PatientMedicalCondition.PatientNo

A. Forename, Surname, MedicalConditionNo, WardName


Total 12
AQA Computing A2 Teacher Notes Nelson Thornes Ltd 2009

136

6.1
End of topic questions
1
2

4
5

In serial data transmission, single bits are sent one after another along a single wire
In parallel data transmission, bits are sent down several wires simultaneously.
a) The transmission of data between computer and printer is controlled by the printer via the
Ready/Busy wire. If the printer is ready to receive, the Ready/Busy wire is set by the
printer at 5 volts, otherwise it is set to 0 volts. The computer reads the state of Ready/Busy
wire. If set to Busy, the computer does not send data. If the signal on this wire is set to
Ready, the computer places signals representing the data onto the data wires.
b) A short while afterwards, the computer sets the voltage on the Strobe wire to 5 volts. The
printer detects this strobe signal voltage and starts to read the data on the data wires at the
same time it sets the Ready/Busy wire status to busy. When the printer is finished reading
data, it sets the Ready/Busy wire back to Ready.
c) Serial data transmission is used for long-distance communication. The need for only one
signal pathway each way is the main reason for this use. This makes it easy to regenerate
the signal, which can reduce significantly in strength over long distances. It makes it easier
to route through telecommunication switches when routing the signal. It also saves on the
cost of cabling.
d) Parallel data transmission is used over short distances because it is difficult to keep the
voltages on the eight wires in-line with each other (the problem is known as skew)
beyond a certain distance. This can lead to the voltage on each wire being read incorrectly.
It is also expensive to run eight or more wires over long distances especially if the signals
on the wires need to be switched onto a different path, for example, in digital switching
centres such as telephone exchanges. Therefore, parallel communication has been restricted
to computer to printer connections and computer buses.
The Baud rate is the rate at which signals on a wire /line may change. One baud is one
signal change per second. The bit rate is the number of bits transmitted per second. The bit
rate can be greater than the baud rate if each signal can code more than one bit. For
example, if each signal contains 2 bits and the baud rate is 100 baud (100 signals sent per
second) then the bit rate is 2 100 bits/s.
The greater the bandwidth of the transmission system, the higher is the bit rate that can be
transmitted over that system
Latency refers to the time delay that can occur between the moment something is initiated
and the moment its first effect begins. In a wide area network involving satellites,
significant time delay occurs because of the physical distance between the ground stations
involved and the geostationary satellite. Requesting and receiving a web page can involve a
considerable time delay even though the bit rate of the uplink and downlink to the satellite
is high, that is, the bandwidth is large. With a round trip distance in excess of 143,200
kilometres, speed of microwaves 3 108 metres/second, the propagation time delay is
approximately 0.4 seconds.
In asynchronous serial data transmission, the arrival of data cannot be predicted by the
receiver, instead a start bit is used to signal the arrival of data and to synchronise the
transmitter and receiver temporarily.
a) The arrival of data at the receiver is signalled by a special bit called a start bit.

AQA Computing A2 Teacher Notes Nelson Thornes Ltd 2009

137

b) The data bits are sent immediately following the start bit, then a parity bit if the data bits
are protected by a parity bit and finally, the transmitter attaches a stop bit. Thus, the start
bit and the stop bit frame a transmission of a few data bits encoding a single character, for
example, the character A. The time interval for the stop bit allows the receiver to deal
with the received bits, that is, transfer these into the RAM of the computer.
A communication protocol is a set of pre-agreed signals, codes and rules to be used for data
and information exchange between computers or a computer and a peripheral device such
as a printer that ensure that the communication is successful.
The handshaking protocol in serial data transmission involves exchange of the following
signals between sender and receiver, for example, between computer and a printer.
Assuming that the printer is present and switched on, the handshaking protocol for
computer serial port to serial port of a printer is as follows:
Computer

Are you ready?

Printer

Clear to send pin 8 on printer

Computer

Yes, I am

Printer

Request to send pin 7 on computer

Printer
Printer
Printer

Start bit

Printer

Clear to send pin 8 on printer

Computer
Computer
Computer
Computer

Here it is
Busy
Thats it
I am ready again

Clear to send pin 8 on printer


Stop bit

The sending device, the computer, enquires whether the receiving device is ready to
receive. The sending device waits for a response that indicates that the receiving device, the
printer, is ready to receive. On receipt of this signal, the sending device coordinates the
sending of the data and informs that receiver that it is sending the data. The sender then
waits for the receiver to become ready to receive more data.
The parity bit is an extra bit added to each 7 or 8 data bits that are transmitted. This parity
bit is calculated from the 7 or 8 data bits and is either a 1 or a 0 depending on whether even
parity or odd parity is chosen.
Even parity:
The parity bit is set to either 1 or 0 so that the number of 1s across data bits and parity bit is
an even number.

AQA Computing A2 Teacher Notes Nelson Thornes Ltd 2009

138

Data Bits
Parity Bit
e.g.
Odd parity:
1
1of 1s across
0
0 bits
1 and 1parity0bit is
The parity bit is set to either 1 or 00so that 0the number
data
an odd number.
e.g.
Data Bits
Parity Bit
1

10 The sending computer generates the correct parity bit and attaches it to the end of the data bits
as they are transmitted. The receiving computer regenerates a parity bit from the received data
bits, which it checks against the received parity bit. If the two are different, an error during
transmission has occurred.
11 Baseband mode of operation dedicates the whole bandwidth of the transmission medium to
one data channel at a time (a single channel system).
12 Broadband mode of operation employs the bandwidth of the transmission medium to carry
several data streams at the same time (a multi-channel system).
a) Baseband tends to be used over short distances such as found in local area networks
where high performance can be achieved with this approach at low cost.
b) Broadband is used for long distance communication because long-distance
communications media are expensive to install and maintain. It would be wasteful if each
media path could support only a single data stream

Exam practice questions


Question 1 June 2005 CPT1 Q5
Question Answer
number
1a
Name: Start bit;
Purpose: Synchronise receiver;
Name: Parity bit;
Purpose: Perform parity check// check for errors in transmission;
A Prevent errors
Name: Stop bit;
Purpose: Allow start bit to be recognised// Allow receiver to process
received bits;
A Indicates end of data
the number of signal/voltage changes per second;
1b

Marks
2
2
2

A rate at which signals are sent; A rate at which voltage changes;

number of bits per second/unit of time;


R the rate at which bits are sent (question paraphrased)
Range of frequencies a channel can handle;
A maximum line speed; A maximum transmission speed

1
AQA Computing A2 Teacher Notes Nelson Thornes Ltd 2009

139

1c

A signal can contain one or more bits;


Bit rate can be higher than baud rate;
bit rate = baud rate * number of bits per signal change

Question 2 January 2008 CPT1 Q6

Question Answer
number
2a

Bits are sent along a single wire/line; bits are sent one after
another;

Marks
Max 1

R Bits of (the) data


2b

i Data bit;

Max 2

Parity (bit);
Signal to start data transfer/strobe;

Max 1

Signal ready to receive data/busy;


Signal to acknowledge data transfer/Complete;
Out of paper/ink/error ;
On-line/off-line;
Handshaking//control signal/status signal (BUT only if not by
exampleabove);
Ground;ii Transmission over long distances;
When a high data transfer rate is required;
A No driver is available
2c

Data is transmitted intermittently (rather than as a steady stream);

Sender and receiver are only synchronised when data is being


sent //start bitsynchronises the receiver;
R Description only of start and stop bits
Question 3 January 2002 CPT1 Q8
Question Answer
number
3a
Several bits are transmitted simultaneously/at the same time; down
several wires; 1
A several bits of data; R data
R down two wires A diagram A a byte/word at a time;
AQA Computing A2 Teacher Notes Nelson Thornes Ltd 2009

Marks
1

140

3b

Exchange of signals between devices/devices communicating with each


other;
To establish their readiness to send or receive data a method of ensuring
that both the sender and receiver are ready before transmission begins;

Question 4 June 2002 CPT5 Q4


Question Answer
number
4a) i)
Baseband: Single/data signal sent at a time Or single
message/packet/frame sent at a time Or uses single channel Or one
transmission at a time
A Single stream of data;
Over full bandwidth (of the cable) Or occupying full bandwidth (of the
cable)
Or signal uses all available frequencies;
(ignore any additional references which are bits, 0/1 in any part of the
above)
R Single bits sent at a time
R Only works over short distances
4a) ii)
Broadband: Several/data signals sent simultaneously Or several
messages/packets/frames simultaneously Or more than one signal
occupies bandwidth;
Each at a different frequency or in a different channel Or in a different
time slot;
Or
Multiple channels used;
Each at a different frequency Or in a different time slot;
Or signal (or equivalent) uses only one frequency Or signal (or
equivalent) uses only part of the bandwidth;;
R Fast connection
R Video, sound and text.
R ADSL, cable examples, etc
4b) i)
Two reasons:

Marks
4

Max 2

Wide area networks expensive to install;


Wide area networks expensive to maintain;
Wide area networks involve long distances;
Can allow multiple data stream to keep costs down;
Many channels needed to cope with high volume of traffic
Or enables more users to use network without experiencing congestion;
R Faster
AQA Computing A2 Teacher Notes Nelson Thornes Ltd 2009

141

R Can work over longer distances


R More than one user will want to use it simultaneously
R Cheaper, more efficient
Question 5 June 2002 CPT1 Q9
Question Answer
number
5a
bits transferred simultaneously I concurrently;
bits sent down many wires at the same time;
A a clear diagram;

Marks
R data R bytes
A bits of data

5b) i)

data get skewed; timing of bits becomes different / out of line;


A over longer distances the data may not be correct;
A too expensive because of amount of wires/cables/lines;
R signal decays R corrupted data

5b) ii)

use serial transmission

Max 1

6.2
End of topic questions
1

2
3

a) Local Area Network or LAN consists of linked computers in close proximity.


b) A standalone computer is a computer that is not networked. It therefore requires its own
peripherals, such as printer and application software, to be installed locally.
c) A wide area network is a set of links that connect together geographically remote
computers.
The term topology, in the context of networking, refers to the shape, configuration or
structure of the inter-connections connecting devices to the network.
An internet is a collection of local area networks and computers that are inter-connected by a
wide area network

AQA Computing A2 Teacher Notes Nelson Thornes Ltd 2009

142

A computer communicates on the network through a network interface card or network


adapter. A network adapter plugs into the motherboard of a computer and into a network
cable. Network adapters perform all the functions required to communicate on a network.
They convert data from the form stored in the computer to the form transmitted or received
on the cable.
In the Ethernet protocol, each network card is assigned a unique address called its MAC
address. MAC is an acronym for Media Access Control. A MAC address is a 48-bit address,
for example 00-02-22-C9-54-13, expressed in hexadecimal and separated into six bytes. Part
of the MAC address identifies the manufacturer. Each network card manufacturer has been
allocated a block of MAC addresses to assign to their cards.
The collision problem occurs in bus networks when two computers transmit onto the bus at
the same time. The pulses of voltages from each will eventually collide resulting in higher
voltage swings. A computer attempting to read these pulses will fail to do so correctly.
When this happens, a collision is said to have occurred and the bus becomes unusable for
the duration of the transmissions from both computers.
Coaxial cable bus networks are segmented so as to reduce collisions and therefore improve
the performance of the network. A network segment in Ethernet is a run of Ethernet cable,
for example coaxial cable, to which is attached a number of workstations. Non-switched
Ethernet bus networks, for example coaxial cable, are often split into smaller sections, called
segments, in order to improve their performance. Performance in a non-switched Ethernet
network can drop significantly as more stations are added to it. This is because in Ethernet,
the cable along which data travels is shared by all stations connected to it. If lots of stations
have data to transmit, the network gets congested, and many collisions occur. Segmentation
is one solution to congestion on an Ethernet network.
The central switch in a switched Ethernet local area network ensures that collisions cannot
occur by forming a temporary unshared connection between sender and receiver. Frames
sent by other computers arrive on dedicated cables and are queued until an unshared
temporary connection can be made for these. The switch is thus making and breaking
temporary connections between each sender and receiver at high speed. As there is never
more than one frame travelling along each connection, collisions cannot occur.

AQA Computing A2 Teacher Notes Nelson Thornes Ltd 2009

143

9
10
11

In a thin-client network, all processing takes place in a central server, the clients are dumb
terminals with little or no processing power or local hard disk storage.
A thick- or rich-client network is one in which the applications are run in the client
workstations. Therefore, client workstations must have local processing power.
Bus and star topologies appear very similar in the way that they are physically wired using
the current switch-based hardware. Even thin client systems, which can be considered to
resemble a traditional star network, use an Ethernet bus switch to connect a central server to
nodes. In a traditional star topology network, each link from node to central computer is an
independent link. Each link is therefore secure from eavesdropping by other nodes. If a link
to a node goes down, the other links and nodes are unaffected. However, if the central
computer goes down, then the whole network will fail. In a true star-based network, the
speed of each link to the central computer should remain high because the links are not
shared. Traffic between nodes in a switched-based bus network will not be adversely
affected if a node goes down unless, of course, the traffic involves the broken node or the
node is a domain server that validates users when they attempt to log in. Neither will
unplugging a network cable in a switched-based bus network affect the rest of the network.
In a coaxial cable bus network, a break in the cable stops the whole network from working.
All connected nodes are able to read the frames travelling on the coaxial cable bus network.
Therefore, coaxial cable bus networks are not secure against eavesdropping. The frames in a
coaxial cable Ethernet bus networks can collide when multiple nodes send at the same time.
This results in the network showing a noticeable slowing of performance. Although
collisions between frames in switch-based Ethernet bus networks cannot occur, performance
can be affected when traffic volumes are high because the buffers in the switches suffer
overflow. A wireless network is a broadcast network and so is less secure than a cabled
switch-based Ethernet network unless wireless encryption is enabled. With a wireless-based
network without encryption, it is possible to eavesdrop on traffic intended for other
computers. A wireless network can also suffer congestion because the channels are shared.
a) A peer-to-peer network (P2P) is one that has no dedicated servers. All computers are
equal and therefore known as peers.
b) A server is a computer that provides shared resources to network users.
c) A client is a computer that uses the services provided by a server.
d) In server-based networking resource security, administration and other functions are
provided by dedicated servers.
e) In Web 2.0, software becomes a service that is accessed over the internet.
f) Web services are self-contained, modular applications that can be described, published,
located, and invoked over a network, generally, the web.
g) Software as a Service (SaaS, typically pronounced 'sass') is a model of software
deployment where an application is hosted as a service provided to customers across the
internet.
h) In web services architecture, all components in the system are services.
i) Ajax is a web technology that allows only the part of a web page that needs updating to
be fetched from the web server.
j) A wireless network refers to any type of local area network in which the nodes
(computers or computing devices, often portable devices) are not connected by wires but
instead use radio waves to transmit data back and forth between the computers.

AQA Computing A2 Teacher Notes Nelson Thornes Ltd 2009

144

12

13

14
15

k) Wi-Fi is the trademark for various IEEE 802.11 technologies that support wireless
networking of home and business networks.
l) Bluetooth is a wireless protocol for exchanging data over short distances from fixed and
mobile devices.
Googles search engine is an example of Web 2.0. Google began its life as a native web
application that has never been sold or packaged for its customers. Instead, the web
application, Googles search engine, is delivered as a service, with customers paying,
directly or indirectly, for the use of that service. None of the trappings of the old software
industry are present. There are no scheduled software releases, just continuous improvement.
There is no licensing or sale, just usage. There is no porting to different platforms so that
customers can run the software on their own equipment, just a massively scalable collection
of commodity PCs running open-source operating systems plus Google-written applications
and utilities that no one outside the company ever gets to see. Googles data centres where it
all happens are closely guarded and visitors are not welcome. The software never needs to
be distributed but only performed. Google's service is not a server though it is delivered by
a massive collection of internet servers. Neither is it a browser, though it is experienced by
the user within the browser. Nor does its flagship search service even host the content that it
enables users to find. This content is located on the web in the web pages. Googles software
finds the links in these web pages and using a very clever algorithm arrives at a page rank
index for pages on the web.
A router is a device that receives packets or datagrams from one host (computer) or router
and uses the destination IP address that they contain to pass on the packets, correctly
formatted, to another host (computer) or router.
A gateway is a device used to connect networks using different protocols so that information
can be passed from one system to another successfully
When a computer, X, in the English local area network (LAN) wishes to send to a computer,
Y, in the Australian LAN, it knows immediately that Y is on a different network. It therefore
sends to the inward facing port of the gateway that it is directly connected to. This gateway
then reforms the frame so that it is compatible with the internet and sends this frame on port
B to the internet. The internet is a collection of routers. The public IP address of Ys LAN is
used by the routers to route the wide area network frame to the other side of the world.
When the frame eventually arrives at the outward facing port of the gateway for the
Australian LAN, this gateway reforms the frame before sending it into the LAN via the
inward facing port. Both gateways have two network cards, one for the outward facing port
and one for the inward facing port.

First Hop

AQA Computing A2 Teacher Notes Nelson Thornes Ltd 2009

145

Second Hop

Third Hop

Exam practice questions


Question 1 June 2002 CPT5 Q4 b) ii) and iii)
Question
Answer
number
1a
First mark: (More packet) collisions take place; Stations attempting to send at
the same time; Each station broadcasts to every other one; Some stations may
be attempting to broadcast at the same time;
Second mark: Packets need to be sent again;
Station has to retransmit (after a random delay);
1b
First mark: Exclusive bus connection (made temporarily between sender and
receiver)
Or data transfers take place in turns
Or switch connects just sender and receiver
Or collision domain limited to two stations
Or switch splits bus LAN into several smaller segments
Or switch allocates a time slot to each transmission
Or each host/computer/station/workstation/node has its own link on which
one packet at most can travel
Or switch allows a dedicated connection/pathway to be set up when a
computer wishes to send information to another
Or switch separates work stations (in different segments) and only passes
packets between segments when necessary
Or switch (ports) act as bridges which segment network;
Second mark: therefore collisions cannot occur (between two stations) Or
collisions reduced

AQA Computing A2 Teacher Notes Nelson Thornes Ltd 2009

Marks
Max 2

146

Question 2 January 2005 CPT5 Q10


Question
Answer
number
2a
A set of rules/procedures

Marks
1

2b

Bus; R Ethernet on its own

2c

Twisted pair//coaxial (cable)//optical fibre//fibre optic;

2d

Need first octet or first and second octet or first, second and third octet to be
identical. Also must have four octets.
For example:
192.168.0.1
192.168.0.2
One mark for four octets;
One mark for same LAN;

2e

(Use candidates example from D)


i 192.168.0;
ii 1 or 2;

2f

a (unique) address/identifier assigned to network card // (unique) hardware


address/identifier;

2g

Any two tasks @ one each


Allocation of port numbers;
Routing a packet/frame/segment to correct application/service;
Splitting messages/data into packets // Disassembling messages //
Assembling packets;
Adding TCP headers // Adding sequence nos;
Error handling // sets parity bits;
Checking that transmission successful;
Resending transmission if necessary;
A Sets packet size

2h

Any one of the following applications for one mark;


Telnet;
Internet browser;
http (client) // web server;
email;
FTP;
TFTP;
SMTP;

AQA Computing A2 Teacher Notes Nelson Thornes Ltd 2009

147

R Non-networked applications such as word processor


2i

Internet registry // Internet registrar;


A I.P. registry/registrar

Question 3 2010 Specimen question paper COMP3 Q5


Question
Answer
number
3a
A 192.71.0.1; A any valid number instead of 1

Marks
3

B 192.71.0.2; A any valid number instead of 2


C 192.71.1.1; A any valid number instead of 1

6.3
End of topic questions
1

The common gateway interface or CGI: this is a gateway between the web server and a
web-server extension that tells the server how to send information to a web-server
extension, and what the server should do after receiving information from a web-server
extension.

A web-server extension: this is a program written in native code, that is, an executable or
a script that is interpreted by an interpreter running on the web server that extends the
functionality of the web server and allows it to generate content at the time of the HTTP
request.
The common gateway interface or CGI is a gateway between the web server and a webserver extension. The CGI specification tells the server how to send information to a
web-server extension, and what the server should do after receiving information from a
web server extension. In its simplest form, the gateway consists of two objects, the
request object and the response object. An HTTP request sent by a web browser such as
Get / is placed in the request object in the gateway. The web-server extension accesses
the request object and processes its contents before formulating a response, which is
placed in the response object in the gateway. The web server then accesses the response
object to pass its contents back to the web browser.
Get /webpage.asp?myname=fred&age=6
When the post method is used by the browser or an HTTP application then the data, for
example myname=fred&age=6, is passed in the message body while when the Get
method is used the data is passed with the command in the address bar of the browser as
shown in the answer to question 4.
Dynamic web page content means content that is generated at the time of receipt of the
web browser request.
A script is executed on the server to determine the parts of the web page that are
dynamically created at the time of receipt of the request.
www.educational-computing.co.uk?surname=bond&age=6

4
5

6
7
8

AQA Computing A2 Teacher Notes Nelson Thornes Ltd 2009

148

9 Perl, php, VBScript


10 Internet service providers (ISPs) are able to read an interpreted server-side script because
it is high level and therefore can monitor scripts and prevent scripts that could be
harmful from executing. This is not the case with server-side executables which are
compiled code presented in low-level form, making it difficult for ISPs to understand
whether the executable could be harmful.
11

12
Create a connection
Select a database
Perform a database query
Use returned data, if any
Close connection
13 Delphi, php, VBScript

AQA Computing A2 Teacher Notes Nelson Thornes Ltd 2009

149

Exam practice questions


Question 1 January 2003 CPT5 Q7b(i) and (ii)
Question number
Answer
1b) i)
A Fred;
1b) ii)

Marks

B James;

1
1

A Fred;
B James;

1
1

6.4
End of topic questions
1
Virus
Name

When

Type of
attack

Type of damage

Number of
computers affected

Melissa
virus

1999

Macro
virus

A document was created with the virus


in it and anyone who opened it would
catch the virus. The virus would then
send itself by email to the first 50
people in the persons address book.
This made the virus replicate at a fast
rate

Thousands of
computers
worldwide. Melissa
shut down internet
mail systems that got
clogged with infected
emails
The creator of this
virus was jailed in
2002

2005

Crossscripting
virus

a malicious website could load another MySpace and Yahoo


website into another frame or window,
sites affected
then use Javascript to read/write data on
the other website

2000

worm

flooded the internet with emails with


the subject, ILOVEYOU. The body of
the deceptive email read, "Kindly check
the attached love letter coming from
me." When opened, the e-mail wreaked
havoc on computers, replicating it
automatically, sending copies to
everyone in the users address book,
and damaging computer files, such as
MP3s.

Love Bug

AQA Computing A2 Teacher Notes Nelson Thornes Ltd 2009

affected 80 percent
of businesses in
Australia and the
United States

150

Code Red

2001

worm

operated in three stages scanning,


flooding and sleeping. During the
scanning phase, the worm searched for
vulnerable computers and ran damaging
computer code on them. Next, in the
flooding phase, the worm sent bogus
data packets to the White House
website. The White House, however,
changed their websites IP address and
was therefore able to avoid the attack.

Blaster

2003

worm

wreaked havoc on Microsoft XP,


Windows NT 4.0 and Windows Server
2003 users. The worm spread quickly,
checking for vulnerable computers and
then sending itself to those machines.
The worm was intended to attack
Microsofts update website. Some users
found that their computers were
sluggish, but otherwise may have been
unaware that they had been infected.

2 Here is what one bank says:


- Well NEVER send you time sensitive emails to confirm or change your security
details, account numbers, card numbers, PINs or expiry dates.
- Well NEVER ask you to input ALL of your security when logging onto internet
banking.
- Well NEVER send you an email containing a link to a log in page.
You probably get mountains of email every day. The chances are a fair bit of its
unsolicited but comes with halfway plausible return addresses.
More and more of these emails contain attachments carrying viruses, worms, or
Trojan horses which will harm your system if they go undetected.
Were also seeing a lot more phishing emails. This is where a mail is sent from a
third party, saying they are from your bank, asking you to click on a link to
confirm/update your security information. The page you get directed to usually looks
exactly like the banks page and when you enter your account and security
information, you may get forwarded to the real login page, or have to click another
link to login to your account.
What really happens is you actually send your account and security details to
someone who wants to get away with your money.
Some junk email uses social engineering to tell you about a contest youve won, or
details of a product you might fancy. Pretty obviously, the sender wants you to
interact with the email in a way thats financially beneficial to them.
Our emails never ask for personal details. The only time well need those is when
youre securely logged on to our banking or enrolment.
AQA Computing A2 Teacher Notes Nelson Thornes Ltd 2009

151

But if you do get mail asking for personal information its best to delete it right
away. There could be a dodgy dealer on the other end.
Please DONT respond to any such email. Remember - we would never ask a
customer to re-register their security details. And well never ask for your security
details until youre safely logged into your account on our website.
The best advice we can give for emails youre unsure of is, dont open them. If you
use an email program like Outlook, Eudora or Notes, its a good idea to turn off your
Preview Pane too. Finally, if you receive an attachment you werent expecting, or
you dont know whom its from, dont open them. If you havent received an email
virus or worm yet, you will. Sorry, but its only a matter of time.
Every time you receive a message with an attachment, test it with these criteria.

The Know test: Is the email from someone that you know?
The Received test: Have you received email from this sender before?
The Expect test: Were you expecting email with an attachment from this sender?
The Sense test: Does email from the sender make sense? For example, would the sender - lets
say your mother - send you an email message with the Subject line, "Here you go, ;o)"
containing a message with the attachment AnnaKournikova.jpg.vbs? A message like that
probably doesnt make sense. In fact, its an instance of the Anna Kournikova worm and
reading it can damage your system.
The Virus test: Does this email contain a virus? To determine this, you need to install and use
an anti-virus program. Alternatively, use an email service that checks viruses for you.
Some email systems provide additional benefits at no extra cost. Hotmail uses the McAfee scan to look for
viruses in your email attachments before they send you it. If the email looks like it contains a virus you will
be given a warning before you open it.

3 Strong passwords use combinations of uppercase and lowercase letters, numbers, and
punctuation, they arent usually found in any dictionary. For example using river
would be a weak password, whereas r!V3r_78 would be much stronger.

Exam practice questions


Question 1 January 2007 CPT5 Q5
Question
Answer
Number
1a
If you send the key with the message, anyone can decrypt the message

1b
1c

Marks

key would need to be sent by means other than email, otherwise anyone could
intercept the key and use it do decrypt the message;

Jill.s public key;


Jill.s private key;

1
1

the message data is hashed into a message digest; the message digest is
encrypted; with the sender.s private key;

Jills software decrypts the signature; using Jacks public key; contained in
AQA Computing A2 Teacher Notes Nelson Thornes Ltd 2009

152

digital certificate sent with message; to verify Jack.s public key; decrypt digital
certificate using Certificate Authority.s (trusted third party.s) public key; Jills
software then hashes the document data into a message digest; If recalculated
message digest is the same as the original message digest (decrypted
signature); then Jill knows that the signed data has not been changed;
Max 4
I decryption of message
Question 2 January 2006 CPT5 Q7
Question
Answer
Number
2a
converting/transforming from plain text into ciphertext/secret code;

Marks
max 1

A scrambled; A transposition / conversion / coding


the sender processes the message prior to transmission so that if it is
accidentally or
deliberately intercepted while it is being transferred it will be incomprehensible
to
the intercepting party;
Data coded so that unauthorised users can.t read or access the data;
2b

b) i) Bs public key;
ii) Bs private key;

1
1

2c

i) a hashing function is applied to the text of the message;


the result/message digest is encrypted;
using Bs private key;
A the data generated is added to the end of the message;
A message/date stamp is used to produce digital signature;
ii) A uses Certificate Authoritys public key;
to verify Bs public key;
digital signature is decrypted;
using Bs public key;
the hashing function is applied to the text of the message;
the result of the hashing function is compared with the digital signature;
if they are the same the message is authentic;

max 3

Question 3 January 2003 CPT5 Q5


Question
Answer
number
3a
E-mail may pass through many computers/servers if it travels over a
network, each computer can make a copy/can be accessed;
When a message arrives at its destination, it waits until the intended
recipient picks it up. During this time the message is vulnerable to being
read or copied by the computers operator;
Electronic eavesdropping of telephone wires and local area networks is
AQA Computing A2 Teacher Notes Nelson Thornes Ltd 2009

max 4

Marks

153

possible;
With e-mail alterations lave no trace (no physical damage) wheras with
paper alterations leave a physical mark;
Max 1
3b)

i)

E-mail encrypted using public key;


Recipients private key used to decrypt e-mail;

ii)

E-mail encrypted by sender using private key;


Recipient decrypts e-mail using senders public key;

7.1
End of topic questions
1 The Humber Bridge solved the problem for commuters of getting from Hull to Grimsby across
the Humber River, thus reducing the distance that they had to travel considerably.
2 Any three from:
a) The solution must cope with a volume of traffic crossing the bridge per hour up to
b) The solution must cover a distance across water of
c) The solution must be capable of supporting a total weight of
d) The solution must connect to the existing road network in the area.
3 a) a ferry between the south and north shores and vice versa
b) a hovercraft between the south and north shores and vice versa
c) a bridge between the south and north shores and vice versa
4 because the requirements were not precise enough for the bridge designers to work with.
5 problem definition
feasibility study
analysis
high-level design
low-level design
implementation and testing
maintenance
6a) What is the proposed system to do?
What are the problems with the current way of doing things?
What data/information is recorded in the current system?
How much data is recorded at present?
What data/information is to be recorded in the proposed system?
How much data will the proposed system record?
How frequently will the data need to be updated?
Will new records need to be added or old ones deleted?
AQA Computing A2 Teacher Notes Nelson Thornes Ltd 2009

154

How often? Will the changes come in batches, or in ones and twos?
How important is the data/information that is recorded?
What processes or functions are performed by the current system?
What processes or functions are to be performed by the new system?
When should these be done and where?
What special algorithms do these processes use, e.g. calculation of compound
interest? Which processes should be executed manually?
What are the inputs to the current system and what inputs will be required for the
proposed system? Ask to see any input documents that are used in the current
system.
What are the outputs from the current system and what outputs will be required
from the proposed system? Establish if hard copy output is required.
How often will outputs be required? Ask to see some output from the current
system.
What computing resources does the end user possess?
Is the end user prepared to purchase software/hardware resources?
Is security an issue?
Should there be limited access to some or all parts of the proposed system?
How are exceptions and errors handled in the current system?
What errors and exceptions should be reported in the proposed system?
How should they be reported? Should anything else be done?
Are there any constraints on hardware, software, data, methods of working, cost,
time, and so on?
Does the user have a particular solution in mind?
Do you have some suggestions to make to the user?
b) renewal subscription letters
reminder letters
membership lists
members record
membership categories list and fees
payment records
c) Interviewing staff facts can be gathered directly from the people who have
direct experience of the present system. Full and detailed answers can be obtained
by pursuing particular lines of questioning.
Examining existing paperwork, documentation, records and procedure manuals
for the current system can be used to identify the data that is used in the current
system, the information that is produced by the current system and the procedures
that are carried out.
Using a questionnaire to survey opinions of staff enables the same set of questions
to be asked to many people. A carefully designed questionnaire can be a very quick
and cheap way to obtain specific answers to specific questions from a large number
of people.
AQA Computing A2 Teacher Notes Nelson Thornes Ltd 2009

155

Observation of operation of the current system enables current methods of


working to be examined and necessary exceptions to the normal pattern of
working to be noted.
A prototype is an early or trial working version of the proposed system developed to test
possible solutions.
Prototyping is used to (any three):

clarify requirements

perform risk analysis

find a solution to a particular problem

check whether a solution can handle the workload

test a solution within the proposed environment.

Through a process of refinement to progress, in conjunction with users, to a final working


system. This process is called evolutionary, iterative development:

9
10
11

12

to discover errors in design

to discover problems.

Once one phase is complete, it is not revisited. The customer doesnt get to see the
developing product. Therefore, it is more difficult to discover, and expensive to fix, errors
in a previous stage. For example, analysis can be incomplete or wrong in places because
there is little opportunity to evaluate the consequences of the analysis and also as the
project progresses, requirements may change. The customer doesnt get to see the product
until it is ready for delivery. The communication path between the customer and the
developers is very long, that is, indirect, because developers talk to analysts who talk to
customers. This means that there is greater potential for the developer to misinterpret the
customers requirements. There is no opportunity for the customer to correct the
developers error. The waterfall model communicates by written documents forwards
through the cycle but no analyst can express the requirements that they know about 100 per
cent completely and correctly through writing. Customers express themselves in everyday
English whereas developers use technical language. The lack of interaction between
customer and developer in the waterfall model may result in a gulf appearing between the
developer and the customer which may result in imperfect communication and a product
that is far removed from what the customer wanted.
In this model, water is allowed to flow up hill, that is, the analysis, design and
implementation phases can be revisited, which is not the case with the waterfall model.
The spiral model is more appropriate because you are not yet a professional software
developer and you will be working on your own.
Volumetrics refers to measuring/assessing the volume of data that a system will be required
to process and store. Analysis needs to provide developers with volumetric information in
order for the developers to make appropriate design decisions.
It is important that the set of objectives is agreed with the end user(s)/customer. However, it
is very easy for the analyst and the end user(s) to overlook something important that should
be included. A list is not always the best way of visualising what it is that needs to be done.
Analysis must also try to represent what needs to be done pictorially. One way that this can
be done is using a data flow diagram.

AQA Computing A2 Teacher Notes Nelson Thornes Ltd 2009

156

Context diagram
Level 1 DFD
Level 2 DFD
13 Business algorithms are algorithms supplied by the end user. These are algorithms used by
the existing system or would be used if a system existed. An example is an algorithm for
calculating interest on an investment, for example, if a customer invests 100 how much
interest would be earned in the first year of the investment and in subsequent years?
14 At least 10:
Bubble sort
Insertion sort
Shell sort
Merge sort
Heap sort
Quick sort
Bucket sort
Radix sort
Distribution sort
Shuffle sort
15 a) specification
b) design
c) specification
d) design
e) specification
16
association, aggregation (composition/containment), inheritance.
Inheritance class diagram shows the relationship between two object types in
which one object type is a kind of the other object type, for example, a car is a
kind of vehicle.
Aggregation or composition or containment class diagram shows the relationship
between two object types in which one object type has a component which is of
the other object type, for example, a car has an engine or contains an engine.
Association class diagram shows the relationship when it is not inheritance and it
is not aggregation, for example, a snake uses the ground to get from A to B. The
relationship is just an association because a snake is not a kind of ground and a
snake does not contain ground. It is, in fact, a uses relationship.
17 Analyst doesnt fully understand the problem to be solved and therefore does not provide a
clear statement of the problem to be solved. Consequently, a different problem is solved.
Analyst fails to obtain a complete picture of the customers needs/requirements.
Analyst fails to specify in the clearest terms the customers requirements to the
customer so customer agrees to the development of a solution that is not exactly
what they want.

AQA Computing A2 Teacher Notes Nelson Thornes Ltd 2009

157

Analyst fails to communicate to the developer precisely what the system must do
and therefore the developer develops a solution which doesnt match the
customers expectations.

Exam practice questions


Question
number
1

2a
2b

Answer

Problem definition, feasibility study, analysis, design,


implementation, testing, maintenance.
Any three from: Interview, survey, observation, examination
of the paperwork.
1. Interviewing
Interviewing is useful because facts can be
gathered directly from the people who have
direct experience of the present system. Full
and detailed answers can be obtained by
pursuing particular lines of questioning

Marks
3

3
3

2. Examination of existing paperwork


Examination of the existing paper work,
documentation, records and procedure
manuals can be used to identify the data that
is used in the current system, the information
that is produced by the current system and
the procedures that are carried out.
3. Survey
Questionnaires enable the same set of questions to
be asked to many people. A carefully designed
questionnaire can be a very quick and cheap way to
obtain specific answers to specific questions from a
large number of people.
4. Observation
Observation of the current practice enables current
methods of working to be examined and necessary
exceptions to the normal pattern of working to be noted.
3a

Specification

3b

Design

3c

Design

3d

Specification

AQA Computing A2 Teacher Notes Nelson Thornes Ltd 2009

158

7.2
End of topic questions
1

AQA Computing A2 Teacher Notes Nelson Thornes Ltd 2009

159

7.3
Exam practice questions
Question 1 June 2008 CPT5 Q1e
StartDateTime

EndDateTime

Mileage

OverdueHours

Normal

Erroneous

Boundary

01/12/07 06:00

01/12/07
15:30

15

16/12/07 18:00

12/12/07
09:00

237

04/12/07 23:00

04/12/07
08:30

03/12/07 08:00

03/12/07
09:00

01/12/07 06:00

01/12/07
15:30

1.5

01/12/07 06:00

01/12/07
15:30

-2

04/12/07 08:30

05/12/07
23:00

57

01/12/07 06:00

01/12/07
15:30

15

1
1

Question 2 January 2008 CPT5 Q3


Question
Answer
number
2a
normal data: accept valid dates within 120 years before present (i.e.
23/01/2008)
birthday sometime before todays date;
birthday sometime after todays date;
reason: to check the routine takes into account whether birthday has already
been or not;
A 29/2 as a special day to test for

Marks
3

A day/month instead of birthday

2b

The data values should be any dates within 120 years before the present. If the
reason is just given as they are normal dates when both dates are before or
after 23/1 of any year then 2 marks max.
boundary data:
a birthday just before boundary;
a birthday just after boundary;

AQA Computing A2 Teacher Notes Nelson Thornes Ltd 2009

160

a birthday exactly on boundary;


A yesterday, today tomorrow
reason: to check that age is calculated exactly, taking into account whether
birthday is past, now or future;
// this is the oldest you can be // this is the youngest you can be;

2c

22/1 24/1 Any year within 18872008


R anything that is not valid date format;
erroneous data: a date after todays date;
reason: cant have an age for someone not born yet;
or
erroneous data: a date which makes a person over 120 years old;
(i.e. Before 24/1/1887)
A tomorrow;

reason: no person expected to be over this age;


A outside any expected values // outside range;
Remember that wrong formats or invalid dates are not acceptable answers.
Give mark for correct reason even if no acceptable date value given.
Question 3 June 2007 CPT5 Q3
Question
Answer
number
3a
beta testing: a test prior to commercial release
// testing that involves sending the product to beta test sites outside the
company for real-world exposure;
must convey external testing

Marks
1

A the last stage of testing;

AQA Computing A2 Teacher Notes Nelson Thornes Ltd 2009

161

3b

R error messages
factors to help maintenance: 1 mark per factor (with some relevant
explanation) to max 3
structured program code // no GOTO statements // using iteration/selection
constructs appropriately;
local variables; procedures/functions; with interfaces/parameters;
modules/units;

layout/indentation/white space;
meaningful identifier names; self-documenting code //
comments/annotation;
object oriented programming // use of classes;
use of pre-tested routines/library routines; error logs;

AQA Computing A2 Teacher Notes Nelson Thornes Ltd 2009

162

3c

types of testing. Any 2 of:

system/integration testing;
functional/black box testing;
structural/white box testing;
acceptance testing;
unit/module/subsystem testing;
Alpha testing;
A Dry running/walk-through/inspection testing; R bottom-up/top-down
testing.

Question 4 January 2007 CPT5 Q2


Question Answer
number
4

any normal/typical/valid data;: 1<=Hours ,=35; A 0,= Hours ,= 48


boundary/extreme values;:
eg Hours = 35, 36 & Hours = 0, 48, 49; A -1
test that it correctly calculates premium rate;: Hours >35;
any erroneous/invalid data; any negative value; any non-integer data; any
value over 48;

Marks

1 mark for test data, 1 mark for justification


If justification does not match test data, then 1 mark max.

Question 5 June 2006 CPT5 Q3


Question Answer
number
5
1 mark for test data, 1 mark for justification for 3 sets of test data

Marks
6

1, 50p, 20p, 10p, 5p; simple change of a single coin;


3.85, 15p, 25p, 30p, 35p, 60p, 65p, 70p, 75p, 80p, 85p; change made up of
one of several coins;
40p, 45p, 90p, 95p; change made up of more than one of the same coins:
2x20p;
0p; boundary data: no change / zero coins;
5p; minimum change that can be given;
AQA Computing A2 Teacher Notes Nelson Thornes Ltd 2009

163

1.95; maximum change that can be given // extreme/boundary value;


a negative amount; although the routine that calculates how much change is
due should not allow erroneous change, this routine should still test for
erroneous input;
3p; an amount that is not a multiple of 5p // erroneous data;
not all values need to be listed
R justifications not referring to scenario
R answers which seem to test the coins inserted f the calculation of change
Question 6 June 2006 CPT5 Q4
Question Answer
Number
6
Any two points at 1 mark each:

Marks
2

Bugs/Errors/Mistakes in software/system/code/program/it;
Problem NE
R data errors (T.O.)
Requirements change // adding new tasks;
Parameters change e.g. VAR rate, No of users adjusted, No of licences change;
Performance needs tuning // buffer size needs adjusting // indexing needs to be
switched off
Or on // indexes need to be rebuilt;
Hardware is changed;
Software / system is updated // upgrades;
Adaptive/Corrective/Perfective maintenance not enough without explanation
Keeping up to date NE

Question 7 January 2006 CPT5 Q1


Question Answer
Number
7
Top-down testing;
Bottom-up testing;
Black Box testing;
White Box testing;
Dry run/walk-through;
Unit/Module testing;

Marks
3

A Prototyping;

R Integration/Acceptance/Alpha/Beta/System/Performance/Compatibility
testing;
R anything clearly late in the development cycle;
Mark first 3 responses only
AQA Computing A2 Teacher Notes Nelson Thornes Ltd 2009

164

BUT
beware of expansion on same line.
Question 8 June 2005 CPT5 Q2
Question Answer
number

Marks

Max 2

Any two at 1 mark each:


Top-down (testing);
Bottom-up (testing);
White Box (testing);
Integration/Integrated (testing);
Interface/Stub (testing);
Acceptance (testing);
Alpha (testing);
Beta (testing);
Walkthrough/Dry run/Tracing/Desk checking:
Compatibility (testing):
Performance (testing):
System (testing);
Unit/Module (testing);
R. Functional (testing)
R. Structural (testing)
R. Test cases and examples of test cases

Question 9 June 2004 CPT5 Q2


Question Answer
number
9a
N.B. Must be an automated system (=control) or a system that provides real
time data (=monitoring)
Flight control software;
Software controlling life support systems;
Software controlling hazardous materials with potential for exposure to
humans;
Software controlling mechanical equipment which could cause death
through impact/crushing/cutting;
Any software which provides information to operators where an inaccuracy
or misinterpretation of the data could result in death/injury through an
incorrect decision;
A Air traffic control, railway signalling system, traffic lights, heart rate
monitor, drip feed controller for administering drugs.
9b) i)
Acceptance testing is specified/performed by customer (against original
specifications);
9b) ii)
Poorly/incorrectly specified system//inadequate/inaccurate systems analysis;
Poor training of staff using system//staff use system incorrectly;
AQA Computing A2 Teacher Notes Nelson Thornes Ltd 2009

Marks
Any two at
one mark
each
2

1
1

165

Situation outside specification occurs or example which relates explicitly to


specification or similar, e.g. more users attempt to log on than should;
A Virus has entered system//malicious misuse
R Design flaws, hardware failure, inadequate testing
R Data corrupted
9b) iii)

N.B. Name required


System testing;
Alpha testing
Beta testing;
Performance testing;
A Black Box testing, White Box testing, integration testing, unit/module
testing, top-down testing, interface testing
R Phased testing, bottom-up testing

Question 10 January 2004 CPT5 Q8


Question Answer
number
10a) i)
Strategy: White Box testing;
Justification: Need to follow a path through the code (to discover the
error);
10a) ii) ii) While r >= y 1 mark for identifying(in some way) While statement,
1 mark for correct condition r >= y
R. q := 0 changed to q := 1
10b
r never changes or an alternative that describes/implies the same thing;
A. gets stuck in an infinite loop
10c
If y > 0 Then x = y * (result q) + (remainder r);
R. y cannot equal zero
A. y must always be greater than zero
10d)
Acceptance is specified/performed by customer ;
against original specifications

Any one for


one mark
1

Marks
2

1
1

7.4
Exam practice questions
Question 1 January 2006 CPT5 Q5 c) and d)
Question Answer
number
1a
e) Method
Justification
1 mark
1 mark
Parallel
To check against the pupils food diary to ensure the data
AQA Computing A2 Teacher Notes Nelson Thornes Ltd 2009

Marks
2

166

Direct

Pilot

Phased

1b

collected is correct;
A if new system fails, they have the old one to fall back
on;
It would take too long to check against pupils food diaries
// not a critical system // cheaper than parallel // cheaper
than running two systems;
The new system may not work very well and should be
piloted in one school first (before being rolled out to all
schools in the LEA);
Use the data collection module before the diet checking
one, in case the system refuses to allow acceptable
choices, causing chaos at the checkouts;
R explanation of pilot

data files will have to be entered into the system; R


conversion/transfer of data

users / cafeteria staff / pupils will have to be trained; R printing


labels
new hardware has to be installed/purchased; new software has to be
installed;
I licences
smart cards will have to be updated; pupils will have to be issued
with smart cards;
define/create new operating procedures
A produce documentation/user guide/system guide

Question 2 June 2003 CPT5 Q4


Question Answer
number
2a
i. Old system and new system operate alongside each other/in parallel
until new system proved; (require time limited trial)

2b

Marks
1

ii. Parts of old system gradually replaced in stages by new system;


Do not give mark for a pilot

Information/Data/Files may have to be


converted/copied/reformatted/modified so that compatible with new
system;
Users/operators will have to be trained so that they can use the new
system//Staff needed/hired to maintain new system;
Old data archived;
Make full backup before changing to new system;

AQA Computing A2 Teacher Notes Nelson Thornes Ltd 2009

167

Hardware replaced/upgraded;
System software replaced/upgraded;
2c

NB Emphasis is on changes not performance


Is it possible/How easy is it/How long will it take to correct an error in
software;
Is it possible/How easy is it/How long will it take to change parameters in
system, e.g. VAT rate;
Is it possible/How easy is it/How long will it take to change system to cope
with more users;
Is it possible/How easy it is/How long will it take to change system to cope
with more terminals/workstations;
Is it possible/How easy is it/How long will it take to change system to cater
for more software licences;
Is it possible/How easy is it/How long will it take to change system to work
with different hardware;
Is it possible/How easy is it/How long will it take to update/upgrade
system;
Ho extensive is support documentation;
What is skill level of support staff;
What is availability of support staff;
Can operators/users configure system/change settings;
How long will support be available for;
Is source code available;

A One reference only to documentation;


R How easy is it to add new features/expand system;
R What is standing of developers;

7.6
End of topic questions
1

2
3

Evaluation is systematic assessment of whether something meets its objectives or


specifications and how well it meets the latter in terms of effectiveness, useability,
maintainability.
Effectiveness in meeting requirements: learnability, useability, maintainability.
In addition to requiring criteria for judging effectiveness evaluation of effectiveness requires:
a) planning

AQA Computing A2 Teacher Notes Nelson Thornes Ltd 2009

168

b) planning time
c) execution time.
4 Monitor number of registered users; monitor number of stored files; monitor frequency of file
uploads/downloads; monitor frequency of use by registered users.
5 Observe users class of 7-year-olds using the system: measure improvement in word
spelling as software is used; note how quickly 7-year-olds learn to use the system; note how
easily the 7-year-olds navigate the software; note how long 7-year-olds take to step through
the instructions and to answer.
6 Useability refers to the ease with which a User Interface can be used by its intended audience
to achieve defined goals.
7 Target acquisition time
Latency
Readability
Use of metaphors
Navigability
Target acquisition time: Latency, e.g. moving the mouse pointer to a position over a button.
a) Latency: How long does a user who has initiated an action have to wait before the action is
completed, e.g. a button is clicked to execute an SQL statement that returns a dataset
matching the query?
b) Readability: How easy is it for a user to read commands/guidance text?
c) Use of metaphors: Visual pictures/icons to enable users to intuitively grasp what can be done.
d) Navigability: How easy is it to navigate the user interface?
8 Maintainability of software refers to how easy or difficult it is to fix bugs, change parameters
and respond to changing requirements.
9 Any four from:
a) Is the software modular?
o Procedures/Functions are used that perform a single task and are self-contained.
o

Collections of related procedures are placed in independent units that can be compiled
separately.

Information hiding is supported by the use of separate units.

b) Is the code self-documenting?


o Are meaningful identifier names used for variable names, procedure/function names, etc?
o
c)
d)
e)
f)
g)

Is indentation used to indicate the structure of the code.

Blocks of code have one entry point and one exit point.
Is the use of global variables across units minimised?
Is good use made of local variables?
Are parameter values passed in and out of procedures through procedure interfaces?
Is an object-oriented programming approach used?
o Is inheritance used to allow functionality to be extended?
o

Is polymorphism used to offer different functionality depending on object type?

AQA Computing A2 Teacher Notes Nelson Thornes Ltd 2009

169

h) Is the database created from a DDL script (which itself has been produced using a CASE
tool) so that re-engineering the database can be done using the CASE tool?
i) Does querying of the database use SQL?
j) Is the code commented where clarification is needed?
k) The documentation that accompanies the software is also essential to the maintenance of this
software. Evaluating maintainability of software requires consideration of the following:
l) Is the project supported by analysis and design data dictionaries?
m) Are entities and entity-relationships documented?
n) Is the software accompanied by:
o dataflow diagrams
o

system flow charts

other relevant diagrams?

o) Are algorithms documented?


10 Evaluation should take place early in the project when prototyping for the purpose of
clarifying the customers requirements. Evaluation should take place when designing so that
the effectiveness of different approaches can be made before committing to one particular
design. This should include types of interface. When a particular user interface type has been
settled on, evaluation of different mock-ups of this user interface should be made. This is still
part of the design stage. Evaluation should take place to assess useability and navigability of
the user interface for a range of users. This takes place during the later stages of
implementation when the design is fairly stable. When the final solution is produced further
effectiveness evaluation is necessary to confirm that the design has achieved what it set out to
achieve.
Nelson Thornes is responsible for the solution(s) given and they may not constitute the
only possible solution(s).

AQA Computing A2 Teacher Notes Nelson Thornes Ltd 2009

170

You might also like