Upload
robert-edwards
View
294
Download
0
Embed Size (px)
Citation preview
8/15/2019 a2 Student Book Answers
http://slidepdf.com/reader/full/a2-student-book-answers 1/170
Student book answers
1.1 ........................................................................................................................................... 3
End of topic questions ..................................................................................................... 3
Exam practice questions ................................................................................................. 6
1.2 ........................................................................................................................................... 7
End of topic questions ..................................................................................................... 7Exam 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 ............................................................................................... 302.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 ............................................................................................... 842.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 ....................................................................................................................................... 106End of topic questions ................................................................................................. 106
Exam practice questions ............................................................................................. 111
3.1 ....................................................................................................................................... 112
End of topic questions ................................................................................................. 112
Exam practice questions ............................................................................................. 114
8/15/2019 a2 Student Book Answers
http://slidepdf.com/reader/full/a2-student-book-answers 2/170
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 ....................................................................................................................................... 122End 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 ................................................................................................. 142Exam 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 ....................................................................................................................................... 154End 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
8/15/2019 a2 Student Book Answers
http://slidepdf.com/reader/full/a2-student-book-answers 3/170
1.1
End of topic quest ions
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 decomposedinto 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 module’s or object’s
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 module’s function is carried out
8/15/2019 a2 Student Book Answers
http://slidepdf.com/reader/full/a2-student-book-answers 4/170
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.
9
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.
Parallel veins Branching
network of veins
Non-
vascular
Angiosperms
Vascular
Monocots
Seeds on cones
Seeds in
flowers
Write('Input F: ')
Readln(FTemp)
GetF ← FTemp
ConvertFtoC ← (F - 32)* 5/9 Writeln('Celsius = ', C)
F ← GetF
ConvertTemperature
Display(C) C ← ConvertFtoC(F)
Parallel Branching
8/15/2019 a2 Student Book Answers
http://slidepdf.com/reader/full/a2-student-book-answers 5/170
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
Columbia
Suriname
Argentina
Peru
French
Guyana
Bolivia
VenezuelaGuyana
Ecuador
Brazil
Paraguay
Chile
Uruguay
8/15/2019 a2 Student Book Answers
http://slidepdf.com/reader/full/a2-student-book-answers 6/170
14
(a)
(b) 3
Exam pract ice quest ions
Question Number Answer Marks
1 Information hiding means hiding design details behind a
standard interface.
In software development, a programmer can use alibrary module without needing an intimate knowledge
of the module’s 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 becompleted more quickly. Information hiding also creates
designs that can be kept secret more easily. From a user’s
point of view, information hiding means that when the
internal design of a module changes the user doesn’t have to
be retrained. Outwardly the module should still appear the
same
3
A
E
D
C
B
8/15/2019 a2 Student Book Answers
http://slidepdf.com/reader/full/a2-student-book-answers 7/170
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.
1
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.
1
5 Question
Number
6 Answer 7 Marks
3a 5
3b 2 tables 2
1.2
End of topic quest ions
1 Algorithms are considered to be procedural solutions to problems and problem solving is a human
B
C D
E
A
8/15/2019 a2 Student Book Answers
http://slidepdf.com/reader/full/a2-student-book-answers 8/170
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 basicoperation 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 algorithm’s 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 loop’s variable j between limits i + 1 and n. This is repeated for each value of the outerloop, i.e. for each value of the loop’s variable i between its limits 1 and n - 1. Consider the case
when n = 6.
Element
no.
No. of
comparisons
Element in first column compared with
elements
1 5 2, 3, 4, 5, 6
2 4 3, 4, 5, 6
3 3 4, 5, 6
4 2 5, 6
5 1 6
In general, the number of comparisons becomes 1 + 2 + 3 + 4 + 5 + … + n
This has the sum
b) For large values of n this becomes2
2n
as (n - 1)n = n2 - n and for large n, n
2 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(log 2 n)
n-1 n
2
8/15/2019 a2 Student Book Answers
http://slidepdf.com/reader/full/a2-student-book-answers 9/170
f = O(2n)
f = O(n!)
11 (a)Exponential growth exhibits growth rates that vary according to the form k n, 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. n
3 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 pract ice quest ions
Question 1 – Specimen Paper COMP 3 Q1
Question number Answer Marks
1a 1. A
2. C
3. B
1
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
4
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
4
1.3
End of topic quest ions
1 A finite state machine (FSM) consists of a set of input symbols (input symbol alphabet) and if it
8/15/2019 a2 Student Book Answers
http://slidepdf.com/reader/full/a2-student-book-answers 10/170
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 answeringYES or NO. Therefore, FSA do not write anything at all whilst processing input whereas an FSM
with output does.
8/15/2019 a2 Student Book Answers
http://slidepdf.com/reader/full/a2-student-book-answers 11/170
10
No
Yes
No
Yes
No
8/15/2019 a2 Student Book Answers
http://slidepdf.com/reader/full/a2-student-book-answers 12/170
8/15/2019 a2 Student Book Answers
http://slidepdf.com/reader/full/a2-student-book-answers 13/170
8/15/2019 a2 Student Book Answers
http://slidepdf.com/reader/full/a2-student-book-answers 14/170
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 quest ions
1 11111
8/15/2019 a2 Student Book Answers
http://slidepdf.com/reader/full/a2-student-book-answers 15/170
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.
8/15/2019 a2 Student Book Answers
http://slidepdf.com/reader/full/a2-student-book-answers 16/170
Exam pract ice quest ions
Question 1 – Specimen Paper COMP3 Q6
Question
Number
Answer Marks
1a (i)
1 mark for correctly positioned arrow, ignore data on tape
(ii) 1
1
1
1b 2 marks for correct tape symbols, 1 mark for correct position of arrow 3
1c 3 + 1 or the successor to 3 1
1.5
End of topic quest ions
1
a) The answer is not decidable
b) Undecidable or noncomputable
2
1024
10485761073741824
1099511627776
1125899906842624
1152921504606847000
1.329227995784916 × 10+36
3
a)
24 = 16
210
= 1024
18446744073709552000
1.33 × 1050
b) Intractable
8/15/2019 a2 Student Book Answers
http://slidepdf.com/reader/full/a2-student-book-answers 17/170
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 pract ice quest ions
Question number Answer Marks
1a Let’s 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.
1
1b The problem posed in part (a) belongs to the family of logic
problems known as decision problems.
1
1c First is from the liars group. If the first is from the truth
teller’s group then the statement would be a contradiction.
If the first is from the liar’s group then he has lied and so both are not from the liar’s group. Therefore, the second
must be from the truth teller’s group.
1
The second from the truth teller’s group. 1
1d 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, thehaircutter does not cut his own hair. So, the haircutter’s
hair must be cut by someone else. However, everyone
who cuts another’s hair is called a haircutter but the
island has only one haircutter. Therefore, the question
cannot be answered.
1
2. This type of problem is undecidable. 1
1e 16 1
210
1
264
1
Intractable 1
The planks would take up a large amount of space and it 2
8/15/2019 a2 Student Book Answers
http://slidepdf.com/reader/full/a2-student-book-answers 18/170
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.
2
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.
2
Question number Answer Marks
3 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.
2
1.6
End of topic quest ions
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 bead7 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
8/15/2019 a2 Student Book Answers
http://slidepdf.com/reader/full/a2-student-book-answers 19/170
11 Roman Numerals
12 Identifier
Letter
Digit
V
I
X
I
I
V
I
8/15/2019 a2 Student Book Answers
http://slidepdf.com/reader/full/a2-student-book-answers 20/170
13 UserID
14
a) xy+
b) xy+2/
c) xy+x4-/
d) xy↑
e) xy+2↑
f) xy+xy-/
15
a) x * y
b) (x + y) * 6
c) (x + y) / (x - y)
d) (2 * x + 3 * y) /8
e) ((x +y) ↑ 2) * (6 - x)
Digit HDigit
L
D
R
Pa
Ph
A..Z A..Z
8/15/2019 a2 Student Book Answers
http://slidepdf.com/reader/full/a2-student-book-answers 21/170
Exam pract ice quest ions
Question 1 – Specimen Paper COMP3 CPT4 Q7
Question
number
Answer Marks
1a 4
1b 5 6 2 ;*; +;
No Brackets;
Easy to Compute;
2
1
Question 2 - KB
Question number Answer Marks
2a Yes 1
2b No 1
2c Yes 1
2.1
End of topic quest ions
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
Pri ate
8/15/2019 a2 Student Book Answers
http://slidepdf.com/reader/full/a2-student-book-answers 22/170
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);
BeginHours := h;
Minutes := m;
End ;
Procedure TClock.IncrementTime;
Begin
Minutes := Minutes + 1;
Sleep(600); // wait one minute
If Minutes = 60Then
Begin
Hours := Hours + 1;
Minutes := 0;
If Hours = 24 Then Hours := 0;
End;
8/15/2019 a2 Student Book Answers
http://slidepdf.com/reader/full/a2-student-book-answers 23/170
If Hours = 24Then
Begin
Hours := 0;
DayNumber := DayNumber + 1;
If DayNumber > 31 Then Daynumber := 1;
DayOfWeek := DayOfWeek + 1;
If DayOfWeek > 7 Then DayOfWeek := 1;
End ;
End ;
Function TWatch.GetDayNumber: Integer;
Begin
GetDayNumber := DayNumber;
End ;
Function TWatch.GetDayName: String;
Begin
Case DayOfWeek Of1: GetDayName := 'Sun';
2: GetDayName := 'Mon';
3: GetDayName := 'Tue';
4: GetDayName := 'Wed';
5: GetDayName := 'Thu';
6: GetDayName := 'Fri';
7: GetDayName := 'Sat';
End ;
End ;
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;
8/15/2019 a2 Student Book Answers
http://slidepdf.com/reader/full/a2-student-book-answers 24/170
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;
8/15/2019 a2 Student Book Answers
http://slidepdf.com/reader/full/a2-student-book-answers 25/170
Q6 & Q7Class 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
ThenBegin
Minutes := Minutes + 1;
Seconds := 0; // only required for Exercise 2
If Minutes = 60
Then
Begin
Hours := Hours + 1;
Minutes := 0;
If Hours = 24Then Hours := 0;
End ;
End ;
End ;
Function TClock IntToStrF (i: Integer): String;
8/15/2019 a2 Student Book Answers
http://slidepdf.com/reader/full/a2-student-book-answers 26/170
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
8/15/2019 a2 Student Book Answers
http://slidepdf.com/reader/full/a2-student-book-answers 27/170
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 ;
8/15/2019 a2 Student Book Answers
http://slidepdf.com/reader/full/a2-student-book-answers 28/170
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 ;
8/15/2019 a2 Student Book Answers
http://slidepdf.com/reader/full/a2-student-book-answers 29/170
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 .
8/15/2019 a2 Student Book Answers
http://slidepdf.com/reader/full/a2-student-book-answers 30/170
9 Inheritance diagram of the shapes classes
Exam pract ice quest ionsQuestion 1 – June 2008 CPT4 Q6
Question
number
Answer Marks
1a 2
1b Insert a SetColour procedure; A Function
into the Public section;
R make Colour Public 2
TShape
TRectangle TEllipse
8/15/2019 a2 Student Book Answers
http://slidepdf.com/reader/full/a2-student-book-answers 31/170
1c Yacht = Class/sub-class (Boat)
(Public)
Procedure SetBoatDetails (Override)
Function GetMasts
Function GetEngine
Private
Masts: IntergerEngine: 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 diagramsI any parameters to methods
1
1
1
1
11
Question 2 – January 2008 CPT4 Q4
Question
number
Answer Marks
2a
1 mark for correct boxes
1 mark for correct lines
1 mark for correct line endings
3
2b
4
8/15/2019 a2 Student Book Answers
http://slidepdf.com/reader/full/a2-student-book-answers 32/170
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; 1
3b event-driven programs service an event and wait for another;
non event-driven programs run to completion/ are sequential;
2
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
1
Question 4 – January 2007 CPT4 Q8
Questionnumber Answer Marks
4a
1 mark for all three classes in appropriate single enclosures.
1 k f t i d d t i t di ti
2
8/15/2019 a2 Student Book Answers
http://slidepdf.com/reader/full/a2-student-book-answers 33/170
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
Max 6
1 mark
1 mark
1 mark
1 mark
1 mark
8/15/2019 a2 Student Book Answers
http://slidepdf.com/reader/full/a2-student-book-answers 34/170
A Procedure SetCapacity and Procedure SetTailLift/
Procedure AddNewVan
instead of Procedure SetVehicleDetails
OR
Public class/subclass Van extends/inherits Vehicle (1 mark)
{
public void SetVehicleDetails
public int GetCapacity
public boolean/int GetTailLift
private int Capacity
private boolean/int TailLift
}
A public void SetCapacity and public void SetTailLift//
public void AddNewVan instead of public void
SetVehicleDetailsR any diagrams
I any parameters to methods
1
mark
1
mark
1
mark
1
mark
1
mark
1mark
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
f h l i i d i d f
1 mark
8/15/2019 a2 Student Book Answers
http://slidepdf.com/reader/full/a2-student-book-answers 35/170
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 for keywords Class and StockItem1 mark for keyword Public and correct methods
A text instead of string
1 mark for correct data fields Date & data types
don’t allow the other fields
Private
Author: StringISBN: String
Public
(Procedure) DisplayDetails (override)
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
No marks for a diagrammatic answer. I method parameters
Java version:
Public Class StockItem
1 mark
1 mark
1 mark1 mark
1 mark
1 mark
1 mark
If candidate declared
‘getters’ and
‘setters’ for the baseclass fields then
don’t have to have
DisplayDetails as a
base class method.
8/15/2019 a2 Student Book Answers
http://slidepdf.com/reader/full/a2-student-book-answers 36/170
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 quest ions
2 Product := 1;
For i := 1 To n
Do Product := i * Product;
Factorial := Product;
3
Call number n Output Comment
Call number 1 5
4
Call number 2 4
3
Call number 3 3
2
Call number 4 2
1 1 Procedure call completed
8/15/2019 a2 Student Book Answers
http://slidepdf.com/reader/full/a2-student-book-answers 37/170
Continue call 2 3 3 Procedure call completed
Return to previous call
Continue call 1 4 4 Procedure call completed
4
Call number n Output Comment
Call number 1 5
4 4
Call number 2 4
3 3
Call number 3 3
2 2
Call number 4 2
1 1 Procedure call completed
Return to previous call
Continue call 3 2 Procedure call completed
Return to previous call
Continue call 2 3 Procedure call completed
Return to previous call
Continue call 1 4 Procedure call completed
5
Function Fibonacci(n: Integer): Integer;
Begin
If n=0
Then Fibonacci := 0Else
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/15/2019 a2 Student Book Answers
http://slidepdf.com/reader/full/a2-student-book-answers 38/170
2.3
End of topic quest ions
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;
8/15/2019 a2 Student Book Answers
http://slidepdf.com/reader/full/a2-student-book-answers 39/170
BeginRepeat
Write('Enter Name to be added to list (to finish typeXXX): ');
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 thelist');
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;
8/15/2019 a2 Student Book Answers
http://slidepdf.com/reader/full/a2-student-book-answers 40/170
{$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
8/15/2019 a2 Student Book Answers
http://slidepdf.com/reader/full/a2-student-book-answers 41/170
ThenFinish := True
Else
Begin
NumberOfFriendsStored := NumberOfFriendsStored + 1;
NameList[NumberOfFriendsStored] := NewName;
End ;
Until Finish Or ListFull;
If ListFullThen WriteLn('Can''t add any more names');
End ;
End ;
Procedure PrintListOfNames;
Var i: Integer;
Begin
If Not ListEmptyThen
For i := 1 To NumberOfFriendsStored
Do WriteLn(NameList[i]);
End ;
Procedure OutputNumberOfNamesInList;
Begin
WriteLn('There are ', NumberOfFriendsStored, ' Names in thelist');
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);
8/15/2019 a2 Student Book Answers
http://slidepdf.com/reader/full/a2-student-book-answers 42/170
Pos := Pos + 1;End ;
NameList[Pos] := ''; // clear space
NumberOfFriendsStored := NumberOfFriendsStored - 1;
End ;
Procedure FindName;
Var Name: String; Position: Integer;
BeginWrite('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 thelist');
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 .
8/15/2019 a2 Student Book Answers
http://slidepdf.com/reader/full/a2-student-book-answers 43/170
Exercise 3Program Project1;
{$APPTYPE CONSOLE}
Uses
SysUtils;
Const MaxListSize=30;
Type TFriend = Record
Name: String;
Replied: Boolean;
ComingToParty: Boolean;
End ;
VarExitChosen: 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 theparty');
WriteLn('7) Print list of all those who have not replied yet');
WriteLn('8) Exit Program');
8/15/2019 a2 Student Book Answers
http://slidepdf.com/reader/full/a2-student-book-answers 44/170
Procedure AddNameToList; Var NewName: String; Finish: Boolean;
Begin
Finish := False;
If ListFull
Then WriteLn('Can''t add any more names')
Else
Begin
RepeatWrite('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
8/15/2019 a2 Student Book Answers
http://slidepdf.com/reader/full/a2-student-book-answers 45/170
If NameList[Pos].Name = NThen 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;
8/15/2019 a2 Student Book Answers
http://slidepdf.com/reader/full/a2-student-book-answers 46/170
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;
8/15/2019 a2 Student Book Answers
http://slidepdf.com/reader/full/a2-student-book-answers 47/170
End ;
Until ExitChosen;
End .
8/15/2019 a2 Student Book Answers
http://slidepdf.com/reader/full/a2-student-book-answers 48/170
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;
8/15/2019 a2 Student Book Answers
http://slidepdf.com/reader/full/a2-student-book-answers 49/170
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 ;
8/15/2019 a2 Student Book Answers
http://slidepdf.com/reader/full/a2-student-book-answers 50/170
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 thepointer
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
8/15/2019 a2 Student Book Answers
http://slidepdf.com/reader/full/a2-student-book-answers 51/170
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);
8/15/2019 a2 Student Book Answers
http://slidepdf.com/reader/full/a2-student-book-answers 52/170
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 .
8/15/2019 a2 Student Book Answers
http://slidepdf.com/reader/full/a2-student-book-answers 53/170
Exercise 5Program 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
8/15/2019 a2 Student Book Answers
http://slidepdf.com/reader/full/a2-student-book-answers 54/170
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 ;
8/15/2019 a2 Student Book Answers
http://slidepdf.com/reader/full/a2-student-book-answers 55/170
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 .
8/15/2019 a2 Student Book Answers
http://slidepdf.com/reader/full/a2-student-book-answers 56/170
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
8/15/2019 a2 Student Book Answers
http://slidepdf.com/reader/full/a2-student-book-answers 57/170
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);
8/15/2019 a2 Student Book Answers
http://slidepdf.com/reader/full/a2-student-book-answers 58/170
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 .
8/15/2019 a2 Student Book Answers
http://slidepdf.com/reader/full/a2-student-book-answers 59/170
Exercises 7, 8Program 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
8/15/2019 a2 Student Book Answers
http://slidepdf.com/reader/full/a2-student-book-answers 60/170
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
8/15/2019 a2 Student Book Answers
http://slidepdf.com/reader/full/a2-student-book-answers 61/170
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 thelist');
End;
End;
Begin
InitList(Start);
Repeat
8/15/2019 a2 Student Book Answers
http://slidepdf.com/reader/full/a2-student-book-answers 62/170
'4': DeleteItem(Start,GetName);
'5': ExitChosen := True;
Else WriteLn('Invalid menu choice. Try again');
End;
Until ExitChosen;
End .
8/15/2019 a2 Student Book Answers
http://slidepdf.com/reader/full/a2-student-book-answers 63/170
Exercise 9Program 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
8/15/2019 a2 Student Book Answers
http://slidepdf.com/reader/full/a2-student-book-answers 64/170
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 FoundDo
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
8/15/2019 a2 Student Book Answers
http://slidepdf.com/reader/full/a2-student-book-answers 65/170
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 ;
Else
8/15/2019 a2 Student Book Answers
http://slidepdf.com/reader/full/a2-student-book-answers 66/170
Else
Begin
SearchFor(Name, List, ThisNode, PreviousNode);
If ThisNode = Nil
Then WriteLn('Sorry, the name does not exist in thelist');
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 .
8/15/2019 a2 Student Book Answers
http://slidepdf.com/reader/full/a2-student-book-answers 67/170
Exam pract ice quest ions
Question 1 – January 2003 CPT4 Q1
Question
number
Answer Marks
1 a) i) Data must be given in correct order
1 pheasant 2
2 teal 33 widgeon 5
START 4 partridge 1
5 woodpigeon 0
End Pointer can be blank
1 for correct START and END pointers;
1 for correctly numbered nodes and correct pointers (need all birds)
1
ii) 1 pheasant 7
2 teal 3
3 widgeon 54 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);
1
Max 2
b) The amount of memory taken up can vary;
//The size/length of the structure/linked list can vary;
At run time;
1
1
c) A heap/stack/a pool of available locations;
A pointer holds the address of the allocated block/next available location; 2
8/15/2019 a2 Student Book Answers
http://slidepdf.com/reader/full/a2-student-book-answers 68/170
2.4
End of topic quest ions
1a)
1b)
8/15/2019 a2 Student Book Answers
http://slidepdf.com/reader/full/a2-student-book-answers 69/170
2Stack
Index Data
TopOfStackPointer 3 6
5
4
3 Cup
2 Saucer
1 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);
End ;
Procedure AddItemToStack;
8/15/2019 a2 Student Book Answers
http://slidepdf.com/reader/full/a2-student-book-answers 70/170
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 stacklast
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;
RepeatGetMenuChoice(MenuItem);
Case MenuItem Of
'1': AddItemToStack;
'2': RemoveItemFromStack;
'3': ShowContentsOfStack;
8/15/2019 a2 Student Book Answers
http://slidepdf.com/reader/full/a2-student-book-answers 71/170
'4': ExitChosen := True;
Else WriteLn('Invalid menu choice. Try again');
End ;
Until ExitChosen;
End .
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 ;
Procedure GetMenuChoice( Var Choice: Char);
Begin
W it L
8/15/2019 a2 Student Book Answers
http://slidepdf.com/reader/full/a2-student-book-answers 72/170
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')
ElseBegin
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
Then WriteLn('empty stack')
Else
Begin
8/15/2019 a2 Student Book Answers
http://slidepdf.com/reader/full/a2-student-book-answers 73/170
Begin
ThisNode := TopOfStackPointer;
Repeat
WriteLn(Stack[ThisNode].Data);
ThisNode := Stack[ThisNode].Pointer;
Until ThisNode=0; // end of linked list reached
End ;
End ;
BeginExitChosen := 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 .
5Program 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);
Var NewNode: TNodePtr; NewItem: String;
Begin
Write('Enter item to be added to stack: ');
8/15/2019 a2 Student Book Answers
http://slidepdf.com/reader/full/a2-student-book-answers 74/170
Write( Enter item to be added to stack: );
ReadLn(NewItem);
New (NewNode);
NewNode^.Data := NewItem;
NewNode^.Ptr := Nil;
If Stack = Nil
Then
Stack := NewNode
ElseBegin
NewNode^.Ptr := Stack;
Stack := NewNode;
End ;
End ;
Procedure RemoveItemFromStack ( Var Stack: TNodePtr);
Var ThisNode: TNodePtr;
BeginIf 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;
WriteLn('Menu');
WriteLn;
WriteLn('1) Add an item to the stack');
8/15/2019 a2 Student Book Answers
http://slidepdf.com/reader/full/a2-student-book-answers 75/170
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 ;
BeginInitStack (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');
WriteLn('3) Show contents of stack');
WriteLn('4) Exit Program');
WriteLn;
8/15/2019 a2 Student Book Answers
http://slidepdf.com/reader/full/a2-student-book-answers 76/170
;
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 Data
FrontPointer 1 1 Jones
2 Smith
3 Peters
4 Franklin
BackPointer 5 5 Taylor
6
b)
Queue
Index Data
FrontPointer 3
1
2
3 Peters
4 Franklin
8/15/2019 a2 Student Book Answers
http://slidepdf.com/reader/full/a2-student-book-answers 77/170
BackPointer 5 5 Taylor
6
c)
Queue
Index Data
FrontPointer 3 1 Y
2 Z
3 Peters
4 Franklin
BackPointer 2 5 Taylor
6 X
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;
WriteLn('Menu');
WriteLn;
WriteLn('1) Add an item to the queue');
8/15/2019 a2 Student Book Answers
http://slidepdf.com/reader/full/a2-student-book-answers 78/170
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;
BeginFor Pointer := 1 To MaxQueueSize
Do WriteLn(Pointer, Queue[Pointer]);
End ;
Begin
ExitChosen := False;
R t
8/15/2019 a2 Student Book Answers
http://slidepdf.com/reader/full/a2-student-book-answers 79/170
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}
usesSysUtils;
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;
Write('Enter your choice number: ');
ReadLn(Choice);
End ;
Procedure IncrementPointer(Var Ptr: Integer);
8/15/2019 a2 Student Book Answers
http://slidepdf.com/reader/full/a2-student-book-answers 80/170
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;
BeginFor Pointer := 1 To MaxQueueSize
Do
Begin
Write(Pointer, Queue[Pointer]);
If Pointer = FrontPointer
Then Write('<-- Front');
If Pointer = BackPointer
8/15/2019 a2 Student Book Answers
http://slidepdf.com/reader/full/a2-student-book-answers 81/170
If Pointer = BackPointer
Then Write('<-- Back');
WriteLn;
End ;
End ;
Begin
ExitChosen := False;
RepeatGetMenuChoice(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}
UsesSysUtils;
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;
Begin
Write('Enter item to be added to Queue: ');
ReadLn(NewItem);New (NewNode);
8/15/2019 a2 Student Book Answers
http://slidepdf.com/reader/full/a2-student-book-answers 82/170
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');
End ;
Procedure GetMenuChoice( Var Choice: Char);
BeginWriteLn;
8/15/2019 a2 Student Book Answers
http://slidepdf.com/reader/full/a2-student-book-answers 83/170
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');
WriteLn;
WriteLn('1) Add an item to the queue');
WriteLn('2) Remove an item from the queue');WriteLn('3) Show contents of queue');
8/15/2019 a2 Student Book Answers
http://slidepdf.com/reader/full/a2-student-book-answers 84/170
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': WriteLn('Item popped: ',Queue.Remove);
'3': Queue.PrintQueue;
'4': ExitChosen := True;
Else WriteLn('Invalid menu choice. Try again');
End ;
Until ExitChosen;
End .
Exam pract ice quest ions
Question 1 – May 2007 CPT1 Q5
Question
number
Answer Marks
1a Last (item) in, is the first (item) out/first (item) in is the last (item) out;R. LIFO / FILO
1
1b i) 1
8/15/2019 a2 Student Book Answers
http://slidepdf.com/reader/full/a2-student-book-answers 85/170
All items in the correct locations
ii)
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) including605 as
the first location used;
1
1
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 queueiv) .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
1
1
1
2
Question 2 – January 2007 CPT1 Q4
Question
number
Answer Marks
2a Next item to be added is at position/location/address (Tail + 1); Max 1
8/15/2019 a2 Student Book Answers
http://slidepdf.com/reader/full/a2-student-book-answers 86/170
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; 1
2c
Snake + Eel + Shark at positions 3,4,5;Tail points to 5;
Head points to 2;
I. Dog and Cat crossed through
1
11
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
Max 2
Question 3 – June 2005 CPT1 Q7
Question
Number
Answer Marks
3a First In First Out; or by description
Last In First Out; or by description 2
3b 2
3c 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;
2
Local variables;
Parameters;Return address;
8/15/2019 a2 Student Book Answers
http://slidepdf.com/reader/full/a2-student-book-answers 87/170
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;
2
Question 4 – January 2004 CPT1 Q8
Question
number
Answer Marks
4 Last In First Out; 1
4b) i) 1
4b) ii) 1
4b) iii) 1
4b) iv) 1
4c) To reverse elements/pass parameters/store volatile environment;
A store return address
1
Question 5 – June 2008 CPT4 Q2
Questionnumber
Answer Marks
8/15/2019 a2 Student Book Answers
http://slidepdf.com/reader/full/a2-student-book-answers 88/170
5a) i) Empty entries waste memory // Maximum size // fixed size; 1
5a) ii) Memory used by pointers//takes more time to add/delete notes//indirect
access takes more time; R programming difficulties1
5b) Place next item in first location/location 0/location 1//Implement a
circular array/queue//allow wraparound;1
5c) IsFull/IsQueueFull; 1
Question 6 – January 2007 CPT4 Q6
Question
number
Answer Marks
6a 3
6b AddItem//Add; 1
6c i) Full/FullQueue;
ii) No memory used for pointers;I Faster
R Easier to program
iii) Size is limited by array size;
memory wasted when not full;
1
1
2
Question 7 – January 2006 CPT4 Q2
Question
number
Answer Marks
7a) i) Empty entries waste space // Maximum/fixed/static size
A stack may overflow
ii) Space used by pointers // more complex to program
1
1
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;
1
1
Question 8 – June 2002 CPT4 Q5
Question
number
Answer Marks
8a)4
8/15/2019 a2 Student Book Answers
http://slidepdf.com/reader/full/a2-student-book-answers 89/170
8a)
8b)2
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 mark for each of 2 points
1
1
1
2.5
End of topic quest ions
8/15/2019 a2 Student Book Answers
http://slidepdf.com/reader/full/a2-student-book-answers 90/170
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.
4
5a)
8/15/2019 a2 Student Book Answers
http://slidepdf.com/reader/full/a2-student-book-answers 91/170
b) Three cages: one for A, one for D and one for B, C and E
6a)
Vertex 1 2 3 4 5
1 0 1 1 0 1
2 1 0 0 1 1
3 1 0 0 1 1
4 0 1 1 0 1
5 1 1 1 1 0
b)
Vertex Adjacent vertices
1 2, 3, 5
2 1, 4, 5
3 1, 4, 5
4 2, 3, 5
5 1, 2, 3, 4
7a)
Vertex 1 2 3 4 5
1 0 0 1 0 0
2 1 0 0 0 0
8/15/2019 a2 Student Book Answers
http://slidepdf.com/reader/full/a2-student-book-answers 92/170
2 1 0 0 0 0
3 0 0 0 0 1
4 0 1 1 0 0
5 1 1 0 1 0
b)
Vertex Adjacent vertices
1 3
2 1
3 5
4 2, 3
5 1, 2, 4
8a)
Vertex 1 2 3 4 5
1 ∞ ∞ 1 ∞ ∞
2 20 ∞ ∞ ∞ ∞
3 ∞ ∞ ∞ ∞ 81
4 ∞ 30 -3 ∞ ∞
5 5 8 ∞ 54 ∞
b)
Vertex AdjacentVertices
1 3 3 0
2 1 1 20
3 5 5 81
4 2, 3 2 30 3 −3
5 1, 2, 4 1 5 2 8 4 54
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.
8/15/2019 a2 Student Book Answers
http://slidepdf.com/reader/full/a2-student-book-answers 93/170
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 n−1 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
Exam pract ice quest ions
Question 1 – Specimen Paper COMP 3 Q3
8/15/2019 a2 Student Book Answers
http://slidepdf.com/reader/full/a2-student-book-answers 94/170
Question
number
Answer Marks
1a
or
Max 3
1b i) Max size only limited by memory;Only uses memory it requires;
ii) No pointers required;
max 1
1
1c i) Adjacency matrix;
ii) Faster to insert/delete; fixed size;
1
2
2 6
8/15/2019 a2 Student Book Answers
http://slidepdf.com/reader/full/a2-student-book-answers 95/170
2.6
End of topic quest ions
1 Dry-run of iterative algorithm searching for Davidson
ItemSought First Last Midpoint List[Midpoint] ItemFound SearchFailed
Davidson 1 15 8 King False False
1 7 4 Farmer
1 3 2 Bond
3 3 3 Clark 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
1 Davidson 1 15 8 King False False
2 Davidson 1 7 4 Farmer False False
3 Davidson 1 3 2 Bond False False
4 Davidson 3 3 3 Clark False True
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 testinstead
Procedure BinarySearch1 ( Var List: Array Of String; First, Last:Integer; ItemSought: String);
Var ItemFound, SearchFailed: Boolean; MidPoint: Integer;
Begin
ItemFound := False;
SearchFailed := False;
RepeatNumberOfIterations := NumberOfIterations + 1; // for stats
only
Midpoint := (First + Last) DIV 2; // integer part of division
8/15/2019 a2 Student Book Answers
http://slidepdf.com/reader/full/a2-student-book-answers 96/170
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 Pointer List
[1] [2] [3] [4] [5] [6]
1 8 2 72 1 87 72 28 45 59 36
1
0
87 87 28 45 59 36
72 87 28 45 59 36
3 28 2 72 87 28 45 59 36
2 72 87 87 45 59 36
1
0
72 72 87 45 59 36
28 72 87 45 59 36
4 45 3 28 72 87 45 59 36
3 28 72 87 87 59 36
21
28 72 72 87 59 36
28 45 72 87 59 36
5 59 4 28 45 72 87 59 36
4 28 45 72 87 87 363
2
28 45 72 72 87 36
8/15/2019 a2 Student Book Answers
http://slidepdf.com/reader/full/a2-student-book-answers 97/170
28 45 59 72 87 36
6 36 5 28 45 59 72 87 36
5 28 45 59 72 87 87
4 28 45 59 72 72 87
3 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 Last−1
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
Begin
List[Pointer+1] := List[Pointer];
Pointer := Pointer−
1;Write(First:6, Last:6, CurrentPointer:6, CurrentValue:6,
Pointer:6);
OutputList(List, First, Last);
8/15/2019 a2 Student Book Answers
http://slidepdf.com/reader/full/a2-student-book-answers 98/170
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 programProgram 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
NoMoreSwaps := True;
For Element := 1 To NumberOfItems − 1
DoIf List[Element] > List[Element+1]
Then
Begin
8/15/2019 a2 Student Book Answers
http://slidepdf.com/reader/full/a2-student-book-answers 99/170
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 ;
Procedure OutputList(List:TList; First, Last: Integer);
Var i: Integer;
Begin Write('(');
For i := First To Last-1
Do Write(List[i], ' ,');
8/15/2019 a2 Student Book Answers
http://slidepdf.com/reader/full/a2-student-book-answers 100/170
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);
End ;
End ;
BeginUnsortedList[1]:=56;
UnsortedList[2]:=23;
UnsortedList[3]:=67;
U t dLi t[4] 12
8/15/2019 a2 Student Book Answers
http://slidepdf.com/reader/full/a2-student-book-answers 101/170
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 sor t qu estions
1
List Comment
First Last Pivot
value
Left
pointer
Right
pointer
Pivot [1] [2] [3] [4] [5] [6] [7]
1 7 56 2 7 56 23 67 12 45 99 17 Swap left &
right
3 7 56 23 17 12 45 99 67 Swap right &
pivot
6 5 5 45 23 17 12 56 99 671 4 45 2 4 45 23 17 12 No value
larger than
pivot value
5 4 4 12 23 17 45
1 3 12 2 3 12 23 17 No value
smaller than
pivot value2 1 1 12 23 17
1 0 Last < First
return from
call
2 3 23 3 3 23 17 No value
larger than
pivot value
4 3 3 17 23
2 2 Last = First
Return from
call
4 3 Last < First
return from
call
5 4 Last < First
8/15/2019 a2 Student Book Answers
http://slidepdf.com/reader/full/a2-student-book-answers 102/170
5 4 Last < First
return from
call
6 7 99 7 7 99 67 No value
larger thanpivot value
8 7 7 67 99
6 6 Last = First
return from
call
8 7 Last < First
return fromcall
Exam pract ice quest ions
Question 1 – Jan 2007 CPT4 Q7
Question
number
Answer Marks
1a)
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)
8
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;
1
8/15/2019 a2 Student Book Answers
http://slidepdf.com/reader/full/a2-student-book-answers 103/170
Question 2 – June 2006 CPT4 Q5
Question
number
Answer Marks
2a) 271;
The required item might be the 271st one/last one/ not be present//
Every item accessed;
1
1
8/15/2019 a2 Student Book Answers
http://slidepdf.com/reader/full/a2-student-book-answers 104/170
2b) 9;
Each comparison halves the number of items to be accessed//
271 lies between 28 and 29
1
1
2c)
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;
5
1
1
Question 3 – June 2004 CPT4 Q8
Question
number
Answer Marks
3a) A procedure/routine which calls itself//is defined in terms of itself; R re-
entrant;
A function instead of procedure R program
1
8/15/2019 a2 Student Book Answers
http://slidepdf.com/reader/full/a2-student-book-answers 105/170
iteration Talked Out (no mark)
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
7
3b) ii) Binary search;;
Search;
R any other type of search 2
Question 4 – January 2003 CPT4 Q3
Question
number
Answer Marks
4a) i) 8 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 1
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
4
Question 5 – June 2002 CPT4 Q4
Question
number
Answer Marks
5a) 1, 17, 9, 21, 15, 23;(2 if all right, 1 if 4 of 6)
If > misinterpreted, follow through for 1 mark
2
5b) A bubble sort 1
5c) To detect when all the numbers have been sorted
Efficiency (to stop procedure repeating unnecessarily);
R to detect when numbers have switched
1
8/15/2019 a2 Student Book Answers
http://slidepdf.com/reader/full/a2-student-book-answers 106/170
2.7
End of topic quest ions
1a entities: lorry, queue, loading bay
Attributes of lorry: waiting, being unloadedAttributes of queue: lorries in queue, queue empty
Attributes of loading bay: loading bay free, loading bay in use
b states: no lorry waiting, no lorry being unloadedno 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 Arriving
LorryBeing Unloaded
LorriesQueuing
Loading BayFree
d possible variables: arrival times of lorries, loading times of lorries, number of loading
bays
2
Master
clock
(hours)
Lorries
arriving
Lorries being
unloaded
Lorries in
queue
Lorry hours
in queue
Loading bay
status
05:00 - - 0 0 Free
06:00 Lorry1 Lorry1 0 0 In use
07:00 Lorry1 0 0 In use
08:00 Lorry2 Lorry1 1 1 In use
09:00 Lorry2 0 1 In use10:00 Lorry3 Lorry2 1 2 In use
11:00 Lorry2 1 3 In use
12:00 Lorry4 Lorry3 1 4 In use
13:00 Lorry3 1 5 In use
8/15/2019 a2 Student Book Answers
http://slidepdf.com/reader/full/a2-student-book-answers 107/170
13:00 Lorry3 1 5 In use
14:00 Lorry5 Lorry3 2 7 In use
15:00 Lorry4 1 8 In use
16:00 Lorry4 1 9 In use
17:00 Lorry4 1 10 In use
18:00 Lorry5 0 10 In use
19:00 Lorry5 0 10 In use
20:00 Lorry5 0 10 In use
3
Master
clock(hours
)
Lorries
arriving
Lorries
beingunloaded
in Bay 1
Lorries
beingunloaded
in Bay 2
Lorries
inqueue
Loading
bayhours
free
Loading
Bay 1status
Loading
bay 2status
05:00 - - 0 2 Free Free
06:00 Lorry1 Lorry1 0 3 In use Free
8/15/2019 a2 Student Book Answers
http://slidepdf.com/reader/full/a2-student-book-answers 108/170
06:00 Lorry1 Lorry1 0 3 In use Free
07:00 Lorry1 0 4 In use Free
08:00 Lorry2 Lorry1 Lorry2 0 4 In use In use
09:00 Lorry2 0 5 Free In use
10:00 Lorry3 Lorry3 Lorry2 0 5 In use In use11:00 Lorry3 0 6 In use Free
12:00 Lorry4 Lorry3 Lorry4 0 6 In use In use
13:00 Lorry4 0 7 Free In use
14:00 Lorry5 Lorry5 Lorry4 0 7 In use In use
15:00 Lorry5 0 8 In use Free
16:00 Lorry5 0 9 In use Free
4a entities: passenger, queue, check-in desk
Attributes for passenger: waiting, checking in
Attributes for queue: passengers in queue, queue emptyAttributes for check-in desk: in use, free
b 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)
Passenger
arriving
Passenger
checking in
Passengers
in queue (25
at start)
Passenger
minutes in queue
(from check-indesk opening)
Check-in
desk
status
1 Passenger1 24 24 In use
2 Passenger1 24 48 In use
3 Passenger2 23 71 In use
4 Passenger2 23 94 In use
5 Passenger26 Passenger3 23 117 In use
6 Passenger3 23 140 In use7 Passenger4 22 162 In use
8 Passenger4 22 184 In use
9 Passenger5 21 205 In use
10 Passenger27 Passenger5 22 227 In use
11 Passenger6 21 248 In use
12 Passenger6 21 269 In use13 Passenger7 20 289 In use
14 Passenger7 20 309 In use
15 Passenger28 Passenger8 20 329 In use
16 Passenger8 20 349 In use
8/15/2019 a2 Student Book Answers
http://slidepdf.com/reader/full/a2-student-book-answers 109/170
16 Passenger8 20 349 In use
17 Passenger9 19 368 In use
18 Passenger9 19 387 In use
19 Passenger10 18 405 In use
20 Passenger29 Passenger10 19 424 In use
21 Passenger11 18 442 In use
22 Passenger11 18 460 In use
23 Passenger12 17 477 In use
24 Passenger12 17 494 In use
25 Passenger30 Passenger13 17 511 In use
26 Passenger13 17 528 In use
27 Passenger14 16 544 In use28 Passenger14 16 560 In use
29 Passenger15 15 575 In use
30 Passenger31 Passenger15 16 591 In use
31 Passenger16 15 606 In use
32 Passenger16 15 621 In use
33 Passenger32 Passenger17 15 636 In use
34 Passenger17 15 651 In use
35 Passenger18 14 665 In use
36 Passenger33 Passenger18 15 680 In use
37 Passenger19 14 694 In use
38 Passenger19 14 708 In use
39 Passenger34 Passenger20 14 722 In use
40 Passenger20 14 736 In use
41 Passenger21 13 749 In use
42 Passenger35 Passenger21 14 763 In use43 Passenger22 13 776 In use
44 Passenger22 13 789 In use
45 Passenger36 Passenger23 13 802 In use
46 Passenger23 13 815 In use
47 Passenger24 12 827 In use
48 Passenger37 Passenger24 13 840 In use
49 Passenger25 12 852 In use
50 Passenger25 12 864 In use
51 Passenger38 Passenger26 12 876 In use
52 Passenger26 12 888 In use
53 Passenger27 11 899 In use
54 Passenger39 Passenger27 12 911 In use
55 Passenger28 11 922 In use56 Passenger28 11 933 In use
57 Passenger40 Passenger29 11 944 In use
58 Passenger29 11 955 In use
59 Passenger30 10 965 In use
8/15/2019 a2 Student Book Answers
http://slidepdf.com/reader/full/a2-student-book-answers 110/170
g
60 Passenger41 Passenger30 11 976 In use
61 Passenger31 10 986 In use
62 Passenger31 10 996 In use
63 Passenger32 9 1005 In use
64 Passenger32 9 1014 In use
65 Passenger42 Passenger33 9 1023 In use
66 Passenger33 9 1032 In use
67 Passenger34 8 1040 In use
68 Passenger34 8 1048 In use
69 Passenger35 7 1055 In use
70 Passenger43 Passenger35 8 1063 In use71 Passenger36 7 1070 In use
72 Passenger36 7 1077 In use
73 Passenger37 6 1083 In use
74 Passenger37 6 1089 In use
75 Passenger44 Passenger38 6 1095 In use
76 Passenger38 6 1101 In use
77 Passenger39 5 1106 In use
78 Passenger39 5 1111 In use
79 Passenger40 4 1115 In use
80 Passenger45 Passenger40 5 1120 In use
81 Passenger41 4 1124 In use
82 Passenger41 4 1128 In use
83 Passenger42 3 1131 In use
84 Passenger42 3 1134 In use
85 Passenger46 Passenger43 3 1137 In use86 Passenger43 3 1140 In use
87 Passenger44 2 1142 In use
88 Passenger44 2 1144 In use
89 Passenger45 1 1145 In use
90 Passenger47 Passenger45 2 1147 In use
6 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 notchecked in.Queues would be even longer if more passengers arrive during the peak half-hour.
A second check-in desk would then become necessary.
Exam pract ice quest ionsQuestion
number
Answer Marks
1a A computer model is used to manipulate variables and observe results. 1
1b We may consider simulation because experimenting with the real 1
8/15/2019 a2 Student Book Answers
http://slidepdf.com/reader/full/a2-student-book-answers 111/170
1b We may consider simulation because experimenting with the real
system might cause unknown irremovable effects, or because we canexperiment with a model more cheaply and at a time of our choosing.
1
1c Possible examples include queuing for service, traffic flow, population growth. 1
Question
number
Answer Marks
2a The entities are: ship, queue, berth.
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.2b Possible states are:
no ship waiting in queue, berth free
no ship waiting in queue, ship being unloaded in berthships waiting in queue, ship being unloaded in berth.
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.
2cShips
ArrivingShip
Being Unloaded
ShipsQueuing
BerthFree
2d
Masterclock
(hours)
Shiparriving
Ship beingunloaded
Ships inqueue
Ship hoursin queue
Berthstatus
1 - - 0 - Free
2 Ship1 Ship1 0 - In use
8/15/2019 a2 Student Book Answers
http://slidepdf.com/reader/full/a2-student-book-answers 112/170
p p
3 Ship1 0 0 In use
4 Ship2 Ship1 1 1 In use
5 Ship2 0 1 In use
6 Ship3 Ship2 1 2 In use
7 Ship2 1 3 In use
8 Ship4 Ship3 1 4 In use
9 Ship3 1 5 In use
10 Ship5 Ship3 2 7 In use
2e Possible variables: ship arrival times, unloading times, number of berths, maximum space for ships queuing.
3.1
End of topic quest ions
Qu. Mantissa Exponent m x 2e Denary
1 a 0.1011 10010 0001102=610 0.101110012 x 26 = 101110.012 46.25
b 1.0101 01000 0001002=410 -0.1010112 x 24 = -01010.112 -10.75
c 0.1100 00000 1111112=-110 0.112 x 2-1 = 0.0112 0.375
d 1.0100 00000 1111012=-3
10 -0.11
2 x 2-3 = -0.00011
2 -0.09375
2 a 1.10100 01000 101002=2010 1.10100012 x 25 = 110100.012 52.25
b 1.01100 00000 011112=1510 1.0112 x 20 = 1.0112 1.375
c 1.01010 00000 011102=1410 1.01012 x 2-1 = 0.101012 0.65625
d -1.10001 11010 101102=2210 -1.1000111012 x 27 = -11000111.012 -199.25
e -1.01100 00000 011012=1310 -1.0112 x 2-2 = -0.010112 -0.34375
f 0.00000 00000 111112 special case infinity +∞
g 0.00000 00000 000002 special case zero 0
h -0.00000 00000 111112 special case infinity -∞
3 a 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
8/15/2019 a2 Student Book Answers
http://slidepdf.com/reader/full/a2-student-book-answers 113/170
-9.75 1.0110012 x 24 1.0110 01000 000100
-0.1875 1.012 x 2-2 1.0100 00000 111110
3 b Sign Exponent Mantissa
5.5 1.0112 x 22 0 10001 01 1000 0000
0.375 1.12 x 2-2 0 01101 10 0000 0000
-9.75 -1.001112 x 23 1 10010 00 1110 0000
-0.1875 -1.12 x 2-3 1 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 theresult.
Exam pract ice quest ions
Question 1 – January 2008 CPT4 Q1Question
NumberAnswer Marks
1a BF2 1
8/15/2019 a2 Student Book Answers
http://slidepdf.com/reader/full/a2-student-book-answers 114/170
1b -;1038 2
(1 mark
for sign, 1mark for
value)1c +;191;.125; A 1/8 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)
3
1e To maximise precision in a given number of bits;
A to maximise accuracy in a given number of bitsTo minimise rounding errors;
To allow a wider range of values to be stored;
Max 2
Question 2 – June 2005 CPT4 Q2
Question
NumberAnswer Marks
2a 140 1/4 ;; one mark for correct integer part,
140.25;; one mark for correct fractional part
2
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;
3
8/15/2019 a2 Student Book Answers
http://slidepdf.com/reader/full/a2-student-book-answers 115/170
p p
(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
max 1
1
Question 3 – January 2005 CPT4 Q7
Question
numberAnswer Marks
3a) BE4; must be capital letters 1
b) 190.25 / 190 1/4 ;; one mark for correct integer part,
one mark for correct fractional partone mark for correct working(e.g. correct place values)
3
c) -1052;; 1 mark for workings if result incorrect
1 mark for sign, 1 mark for 1052
2
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
3
ii) starts with 1 0the 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
1
Question 4 – June 2004 CPT4 Q4(b)
Question Answer Marks
number
4a) i) 4
8/15/2019 a2 Student Book Answers
http://slidepdf.com/reader/full/a2-student-book-answers 116/170
(if the answer is wrong give:moving e places to right / exponent processing 2
e or equivalent: 1
markcorrectly identifying negative number: 1 mark follow through if binary representation wrong
ii) To maximise precision in a given number of bits // to minimiserounding 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;
9
Question 5 – June 2003 CPT4 Q4
Question
number
Answer Marks
5a) i) positive 1
ii) < 2-2
1
5b) Correct answer 194.5 or 194 ½
working
If wrong answer, method marks as follows:
exponent 2
8
[clearly defined] 1 markapplication of shift / *28 from correct start point 1 mark
correct interpretation of bits 1 mark
(Basically here, if it is a little inaccurate, give 2 marks, if quite
inaccurate but slightly correct, give 1 mark.)
2
1
c) i) Processing fixed point numbers is quicker than floating point / less
processing is required;More accurate / greater precision;
1
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
1
8/15/2019 a2 Student Book Answers
http://slidepdf.com/reader/full/a2-student-book-answers 117/170
4.1
End of topic quest ions
1 System programs and application programs.
2 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.
3 Processors
a) Storage
b) Input/output devices
c) Data
4 Processor scheduling
a) Memory management
b) I/O management
c) File management5 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 programshould 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, harddrives, DVD R/W drives, high resolution flat screen visual display units, mouse and standard
QWERTY keyboard.
Exam pract ice quest ions
Question 1 – January 2003 CPT2 Q5Question number Answer Marks
1a) OS hides complexities of hardware from the user; 1
1b) Any three @ 1 each
Processor(s)/cpu(s);
Max 3
8/15/2019 a2 Student Book Answers
http://slidepdf.com/reader/full/a2-student-book-answers 118/170
( ) p ( );
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
4.2
End of topic quest ions
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 momentsin 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
c) Washing machine; microwave oven; central heating controller
d) Cable TV set-top box; broadband router; computer network firewall
3 The mobile phone operating system will be different from that of a desktop computer becausethe 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
8/15/2019 a2 Student Book Answers
http://slidepdf.com/reader/full/a2-student-book-answers 119/170
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 takeinto account the instability of mobile phone networks (bandwidth, connection, etc).
4 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.
5 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. Theoperating 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.
6 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 othermachinery, 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 theignition of the gases in the cylinders.
7 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 asthe 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.
Exam pract ice quest ions
Quest ion 1 - KB
Question Number Answer Marks
1 An embedded computer system’s 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
2
8/15/2019 a2 Student Book Answers
http://slidepdf.com/reader/full/a2-student-book-answers 120/170
a large number of different applications. On the contrary the
embedded system’s operating system has to support theexecution of a limited number of applications.
Quest ion 2 - KB
Question Number Answer Marks
2 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 thatwould not be achieved if a server were carrying out a large
amount of general-purpose processing.
2
Quest ion 3 - KB
Question Number Answer Marks
3 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.
3
Quest ion 4 - KB
Question Number Answer Marks
4 Any three from:
1) They have to support application programs which are non-
sequential in nature, i.e. programs which do not have aSTART- 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.
3
5.1End of topic quest ions
1
8/15/2019 a2 Student Book Answers
http://slidepdf.com/reader/full/a2-student-book-answers 121/170
Blind Person Guide Dogprovided with
Guide Dog Blind Personallocated to
2
Person Carkeeps
Car Personregistered to
3
Borrower BookCopyborrows
BookTitle has
Loanmakes of
Exam pract ice quest ions
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 quest ions
8/15/2019 a2 Student Book Answers
http://slidepdf.com/reader/full/a2-student-book-answers 122/170
End of topic quest ions
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 pract ice quest ions
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 quest ions
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),
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),
8/15/2019 a2 Student Book Answers
http://slidepdf.com/reader/full/a2-student-book-answers 123/170
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)
);
2 b)
SELECT BorrowerID, BorrowerNameFROM Borrower, Loan
WHERE Borrower.BorrowerID = Loan.BorrowerID
2 c)SELECT BorrowerID, BorrowerName
COUNT(Loan.AccessionNumber) AS BookCount
FROM Borrower Loan
8/15/2019 a2 Student Book Answers
http://slidepdf.com/reader/full/a2-student-book-answers 124/170
FROM Borrower, Loan
WHERE Borrower.BorrowerID = Loan.BorrowerID
Group By BorrowerID
Exam pract ice quest ions
Question 1 – June 2007 CPT5 Q5
Question
number
Answer Marks
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.
1
1
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.
2
1
1c i) Recipe (RecipeID, Dish, PrepTime, CookTime, NoOfServings,
CookInstructions);
ii) FoodItem (FoodItemID, FoodItemName, PackSize, Price);
iii) RecipeIngredient(FoodItemID, RecipeID, Quantity).
(1 mark for each correct field, 1 mark for correct primary key.
1
1
4
Take off 1 mark for every extra field included.)
1d SELECT FoodItemName, Quantity, PackSize, Price
FROM FoodItem, RecipeId = RecipeIngredient, RecipeWHERE (Recipe.RecipeId = RecipeIngreident.RecipeId)
AND (RecipedIngredient.FoodItemId = FoodItem.FoodItemId)
AND (Recipe.Dish = “Feat Salad”)
ORDER BY FoodItemName
1
11
1
1
1
Max 5
8/15/2019 a2 Student Book Answers
http://slidepdf.com/reader/full/a2-student-book-answers 125/170
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”
Question 2 – January 2007 CPT5 Q3
Question
number
Answer Marks
2a Copyright, Designs and Patents Act (1998); if other laws included T.O. 1
2b Boxes for correct entities: SoftwareLicence SoftwareInstallation (1 mark)
Correct degree of relationship: 1 to many (1 mark)
Suitable name for relationship: (1 mark)
3
8/15/2019 a2 Student Book Answers
http://slidepdf.com/reader/full/a2-student-book-answers 126/170
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
ii )
SoftwareID VARCHAR(10)
ComputerID VARCHAR(6)
DateInstalled DATE
StaffID VARCHAR(3)
PRIMARY KEY (SoftwareID, ComputerID)
FOREIGN KEY (SoftwareID)
REFERENCES Software Licence(SoftwareID)
I NOT NULL
(1 mark for any 3 attributes correctP1 if extra symbols used.
Ignore spaces and case in attribute
names.)
(A char/string/text/alphanumeric
Instead of VARCHARA Date/Time instead of DateA Integer instead of INT
BOD any attributes which are
clearly more than 1 word.)
(1 mark for any 2 attributes correct.)
(If not DDL, give 1mark if composite
key identified.)
2d
SELECT ComputerID, SoftwareName, Version;
FROM SoftwareLicence, SoftwareInstallation;WHERE SoftwareLicence.SoftwareID=SoftwareInstallation.SoftwareID;
ORDER BY ComputerID; A ASC or DESC
4
Extra attributes: T.O.
Accept (instead of FROM WHERE):
FROM SoftwareLicence INNER JOIN
8/15/2019 a2 Student Book Answers
http://slidepdf.com/reader/full/a2-student-book-answers 127/170
A LEFT JOIN
Question 3 – June 2006 CPT 5 Q5
Question
number
Answer Marks
3a i)
R one to many relationship
ii)
Entity-Relationship Diagram; A E-R diagram; A E-R D R E-A-R diagram
2
1
FROM SoftwareLicence INNER JOIN
SoftwareInstallation ON
SoftwareLicence.SoftwareID =
SoftwareInstallation.SoftwareID
P1 for other spurious
punctuation inc.semicolons
Table names prefixed with tbl, P1
If table name and attribute transposed, P1
3b 6
8/15/2019 a2 Student Book Answers
http://slidepdf.com/reader/full/a2-student-book-answers 128/170
3c 6
8/15/2019 a2 Student Book Answers
http://slidepdf.com/reader/full/a2-student-book-answers 129/170
F/T with attribute names
P1 for tbl prefixP1 if table name after attribute name
I extra punctuation
Quest ion 4 – Janu ary 2005 CPT5 Q9
Questionnumber
Answer Marks
4a I Minor spelling
i)
1
8/15/2019 a2 Student Book Answers
http://slidepdf.com/reader/full/a2-student-book-answers 130/170
ii)
iii)
1
1
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
8/15/2019 a2 Student Book Answers
http://slidepdf.com/reader/full/a2-student-book-answers 131/170
Select Student.FirstName, Student.Surname
MarkAwarded.Mark;
From Student, MarkAwareded;
Where MarkAwarded.LifecyclePhaseID = 1;
And Student.StudentID =
MarkAwarded.StudentID ;
Order By Student Surname;
5
Question 5 – June 2004 CPT5 Q9
Question
number
Answer Marks
5a (NB Take note of labelling inside boxes because candidate’s positioning of
labels may be opposite to that shown below.)
Alternative symbols:
Order By Student.Surname Asc
A Ascending
Asc/Ascending must be in correct position
A OrderBy
1
Accept minor mis-
spelling or spaces between parts of
entity name.
A. plural names
I. Box outlines
8/15/2019 a2 Student Book Answers
http://slidepdf.com/reader/full/a2-student-book-answers 132/170
i)
ii)
iii)
iv)
1
1
1
5b ( R. Tbl in front of table name – penalise once.)
i)
Select Surname
From SwimmerWhere SwimmerNo = 6;
1Select Swimmer.Surname isOK
I. Brackets surroundingattributes
ii)
Select SwimmerNoFrom GalaRaceSwimmer
Where (RaceNo = 5); And (GalaNo = 2);
Order By TimeRecordedForRace;
3
I. Brackets surrounding
attributes, table names in
front of attributes unlessincorrect
A. Criteria without
brackets
R. Extra attributes,
A. Asc or Ascending in correct
place i.e. after
Ti R d dF R
8/15/2019 a2 Student Book Answers
http://slidepdf.com/reader/full/a2-student-book-answers 133/170
iii)
Select Swimmer.SurnameFrom Swimmer, GalaRace;
Where (GalaNo = 4);
And (GalaRace.SwimmerNoOfWinner
= Swimmer.SwimmerNo);
3
Total 11
tables, criteria in thissolution but be careful because candidates may
give an alternative
involving extra
TimeRecordedForRace
R. Asc/Ascending in any otherosition and/or with other words
A. Select
Swimmer.Surname,GalaRace.RaceNo From …
OrA. Select Surname, RaceNo
From…
Brackets may be omitted.A. GalaRace.GalaNo = 4
And SwimmerNoOfWinner
Select Surname
From SwimmerWhere SwimmerNo In;
(Select SwimmerNoOfWinner
From GalaRace;Where GalaNo = 4);
R. = in lace of In
Question 6 – June 2003 CPT5 Q8
Question
number
Answer Marks
6a i) 1
1
8/15/2019 a2 Student Book Answers
http://slidepdf.com/reader/full/a2-student-book-answers 134/170
ii)
L other entities
1
6b i)
Select Book.Title
From Book ;
Where BookISBN = “1-57820-082-2”;
ii)Don’t need Book in Select
Select Book.AuthorName, Book.ISBN ;
From Book, BookCopy ;
Where (Book.ISBN = BookCopy.ISBN) ;
And )BookCopy.AccessionNumber = 1234) ;
2
4
A. Title
A. ISBN = “1-57820-
Any extra attributes lose mark where extra attributes
used
R. 1-57820-082-2 Need quotesA. “1-57820-082-2”
R. TblBook – enalise once
Penalise TblBook/TblBookCopy
once
R. quotes on 1234
Any extra attributes lose markwhere extra attributes used
Brackets non-essential. Ma see
A. BoodCopy.ISBN in placeof BOOK.ISBN
A. AccessionNumber in
place of
A. In for =
8/15/2019 a2 Student Book Answers
http://slidepdf.com/reader/full/a2-student-book-answers 135/170
C Mail-merge//Mail-merging 1
Total 9
Question 7 – January 2003 CPT5 Q8
Question
number
Answer Marks
7a
(NB: don’t allow relationship between Ward and PatientMedicalCondition.)
3
7b (For each extra attr ibute lose one mark.)
i)Ward(WardName, NurseInCharge, NoOfBeds)
ii)
1
2
A. NumberOBeds, NameOfNurseInCharge, NurseInChargeName
R. WardId, Name, NurseName, NameOfNurse, BedNo,
8/15/2019 a2 Student Book Answers
http://slidepdf.com/reader/full/a2-student-book-answers 136/170
Patient(PatientNo, Surname, Forename, Address, DOB, Gender, WardName)
iii)
MedicalConditionID(MedicalConditionNumber, Name,
RecommendedStandardTreatment)
iv)
PatientMedicalCondition( PatientNo. MedicalConditionNo)
1
7c (Accept tbl in fr ont 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
3
Total 12
A. PatientId, PatientNumber, PatientSurname, PatientForename,PatientAddress, DateOfBirth, PatientDateOfBirth,
PatientGender, Sex, PatientSex
A. MedicalConditionId, MedicalConditionNumber,
MedicalconditionName, ConditionName, StandardTreatment,Treatment, RecommendedTreatment
R. ConditionNumber ConditionID
A. Attributes rejected in (ii) and (iii) for PatientNo and
MedicalConditionNo
R. If attributes used are not consistent with (ii) and (iii)
6.1
End of topic quest ions1 In serial data transmission, single bits are sent one after another along a single wire
2 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.
8/15/2019 a2 Student Book Answers
http://slidepdf.com/reader/full/a2-student-book-answers 137/170
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.
3 The Baud rate is the rate at which signals on a wire /line may change. One baud is onesignal 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.
4 The greater the bandwidth of the transmission system, the higher is the bit rate that can be
transmitted over that system
5 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.
6 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 thetransmitter and receiver temporarily.
a) The arrival of data at the receiver is signalled by a special bit called a start bit.
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 dealwith the received bits, that is, transfer these into the RAM of the computer.
7 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.
8 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
8/15/2019 a2 Student Book Answers
http://slidepdf.com/reader/full/a2-student-book-answers 138/170
computer serial port to serial port of a printer is as follows:
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.9 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.
Com uter
Computer
Computer
Printer
Printer
Printer
Clear to send pin 8 on printer
Start bit
Clear to send pin 8 on printer
Computer Printer Request to send pin 7 on computerYes, I am
Computer Printer Stop bitThat’s it
Are you ready?
Here it is
I am ready again
Computer Printer Clear to send pin 8 on printerBusy
e.g.
Odd 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 odd number.
e.g.
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
0 0 1 1 0 0 1 1 0
Parity Bit Data Bits
0 0 1 1 0 0 1 1 0
Parity Bit Data Bits
1 0 1 1 0 0 1 1 0
Parity Bit Data Bits
8/15/2019 a2 Student Book Answers
http://slidepdf.com/reader/full/a2-student-book-answers 139/170
bits, which it checks against the received parity bit. If the two are different, an error duringtransmission 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 pract ice quest ions
Question 1 – June 2005 CPT1 Q5
Question
number
Answer Marks
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
2
2
2
1b the number of signal/voltage changes per second;
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
1
1
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
2
Question 2 – January 2008 CPT1 Q6
Question
number
Answer Marks
2a Bits are sent along a single wire/line; bits are sent one after
another;Max 1
8/15/2019 a2 Student Book Answers
http://slidepdf.com/reader/full/a2-student-book-answers 140/170
Question 3 – January 2002 CPT1 Q8
Question
number
Answer Marks
3a Several bits are transmitted simultaneously/at the same time; downseveral wires; 1
A several bits of data; R dataR down two wires A diagram A a byte/word at a time;
1
R Bits of (the) data
2b i Data bit;
Parity (bit);
Signal to start data transfer/strobe;
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 byexampleabove);
Ground;ii Transmission over long distances;
When a high data transfer rate is required;
A No driver is available
Max 2
Max 1
2c Data is transmitted intermittently (rather than as a steady stream);
Sender and receiver are only synchronised when data is beingsent //start bitsynchronises the receiver;
R Description only of start and stop bits
1
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;
2
Question 4 – June 2002 CPT5 Q4
Question
number
Answer Marks
4a) i) Baseband: Single/data signal sent at a time Or single
message/packet/frame sent at a time Or uses single channel Or one4
8/15/2019 a2 Student Book Answers
http://slidepdf.com/reader/full/a2-student-book-answers 141/170
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;
OrMultiple 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, etc4b) i) Two reasons:
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
Max 2
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
number
Answer Marks
5a bits transferred simultaneously I concurrently; R data R bytes
bits sent down many wires at the same time; A bits of data
A a clear diagram;
8/15/2019 a2 Student Book Answers
http://slidepdf.com/reader/full/a2-student-book-answers 142/170
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
Max 1
5b) ii) use serial transmission
6.2
End of topic quest ions
1 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.
2 The term ‘topology’, in the context of networking, refers to the shape, configuration or
structure of the inter-connections connecting devices to the network.
3 An internet is a collection of local area networks and computers that are inter-connected by a
wide area network
8/15/2019 a2 Student Book Answers
http://slidepdf.com/reader/full/a2-student-book-answers 143/170
4 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.
5 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.
6 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.
7 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 Ethernetnetwork 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.
8 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 breakingtemporary connections between each sender and receiver at high speed. As there is never
more than one frame travelling along each connection, collisions cannot occur.
9 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.
10 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.11 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
8/15/2019 a2 Student Book Answers
http://slidepdf.com/reader/full/a2-student-book-answers 144/170
speed of each link to the central computer should remain high because the links are notshared. 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. Althoughcollisions 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 butinstead use radio waves to transmit data back and forth between the computers.
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.12 Google’s 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, Google’s 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 applicationsd tiliti th t t id th t t G l ’ d t t h it
8/15/2019 a2 Student Book Answers
http://slidepdf.com/reader/full/a2-student-book-answers 145/170
of commodity PCs running open source operating systems plus Google written applicationsand utilities that no one outside the company ever gets to see. Google’s 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. Google’s 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.
13 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.
14 A gateway is a device used to connect networks using different protocols so that information
can be passed from one system to another successfully
15 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 Y’s 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
Second Hop
Third Hop
8/15/2019 a2 Student Book Answers
http://slidepdf.com/reader/full/a2-student-book-answers 146/170
Exam pract ice quest ions
Question 1 – June 2002 CPT5 Q4 b) ii) and iii)
Question
number
Answer Marks
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);
Max 2
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
2
Question 2 – January 2005 CPT5 Q10
Question
number
Answer Marks
2a A set of rules/procedures 1
2b Bus; R Ethernet on its own 1
2c Twisted pair//coaxial (cable)//optical fibre//fibre optic; 1
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:
3
8/15/2019 a2 Student Book Answers
http://slidepdf.com/reader/full/a2-student-book-answers 147/170
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;
1
2f a (unique) address/identifier assigned to network card // (unique) hardware
address/identifier;
1
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
2
2h Any one of the following applications for one mark;
Telnet;
Internet browser;
http (client) // web server;
email;
FTP;
TFTP;SMTP;
1
R Non-networked applications such as word processor
2i Internet registry // Internet registrar;
A I.P. registry/registrar
1
Question 3 – 2010 Specimen question paper COMP3 Q5
Question
number
Answer Marks
3a A 192.71.0.1; A any valid number instead of 1
B 192.71.0.2; A any valid number instead of 2
C 192.71.1.1; A any valid number instead of 1
3
8/15/2019 a2 Student Book Answers
http://slidepdf.com/reader/full/a2-student-book-answers 148/170
6.3
End of topic quest ions
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-serverextension, and what the server should do after receiving information from a web-server
extension.
2 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.
3 The common gateway interface or CGI is a gateway between the web server and a web-
server extension. The CGI specification tells the server how to send information to aweb-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.
4 Get /webpage.asp?myname=fred&age=65 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.
6 Dynamic web page content means content that is generated at the time of receipt of the
web browser request.
7 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.8 www.educational-computing.co.uk?surname=bond&age=6
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 arecompiled code presented in low-level form, making it difficult for ISPs to understand
whether the executable could be harmful.
11
8/15/2019 a2 Student Book Answers
http://slidepdf.com/reader/full/a2-student-book-answers 149/170
12
Create a connection
Select a database
Perform a database query
Use returned data, if any
Close connection
13 Delphi, php, VBScript
Exam pract ice quest ions
Question 1 – January 2003 CPT5 Q7b(i) and (ii)
Question number Answer Marks
1b) i) A Fred;
B James;
1
1
1b) ii) A Fred;
B James;
1
1
6 4
8/15/2019 a2 Student Book Answers
http://slidepdf.com/reader/full/a2-student-book-answers 150/170
6.4
End of topic quest ions
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 person’s 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 in2002
2005 Cross-
scripting
virus
a malicious website could load another
website into another frame or window,
then use Javascript to read/write data on
the other website
MySpace and Yahoo
sites affected
Love Bug 2000 worm flooded the internet with emails withthe 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 user’s address book,
and damaging computer files, such as
MP3s.
affected 80 percentof businesses in
Australia and the
United States
Code Red 2001 worm operated in three stages – scanning,
flooding and sleeping. During the
scanning phase, the worm searched for
vulnerable computers and ran damagingcomputer code on them. Next, in the
flooding phase, the worm sent bogusdata packets to the White House
website. The White House, however,
changed their website’s IP address and
was therefore able to avoid the attack.
Blaster 2003 worm wreaked havoc on Microsoft XP,
Windows NT 4.0 and Windows Server2003 users. The worm spread quickly,
8/15/2019 a2 Student Book Answers
http://slidepdf.com/reader/full/a2-student-book-answers 151/170
p q y,
checking for vulnerable computers and
then sending itself to those machines.
The worm was intended to attack
Microsoft’s 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:
- We’ll NEVER send you time sensitive emails to confirm or change your security
details, account numbers, card numbers, PINs or expiry dates.
- We’ll NEVER ask you to input ALL of your security when logging onto internet
banking.
- We’ll 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 it’s
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.
We’re 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 bank ’s page and when you enter your account and securityinformation, 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 you’ve won, or
details of a product you might fancy. Pretty obviously, the sender wants you to
interact with the email in a way that’s financially beneficial to them.Our emails never ask for personal details. The only time we’ll need those is when
you’re securely logged on to our banking or enrolment.
But if you do get mail asking for personal information it’s best to delete it right
away. There could be a dodgy dealer on the other end.
Please DON’T respond to any such email. Remember - we would never ask a
customer to re-register their security details. And we’ll never ask for your securitydetails until you’re safely logged into your account on our website.
The best advice we can give for emails you’re unsure of is, don’t open them. If you
use an email program like Outlook, Eudora or Notes, it’s a good idea to turn off your
‘Preview Pane’ too. Finally, if you receive an attachment you weren’t expecting, or
you don’t know whom it’s from, don’t open them. If you haven’t received an email
virus or worm yet, you will. Sorry, but it’s 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?
8/15/2019 a2 Student Book Answers
http://slidepdf.com/reader/full/a2-student-book-answers 152/170
y
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 - let’s
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 doesn’t make sense. In fact, it’s 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 aren’t usually found in any dictionary. For example using ‘river’
would be a weak password, whereas ‘r!V3r_78’ would be much stronger .
Exam pract ice quest ions
Question 1 – January 2007 CPT5 Q5
Question
Number
Answer Marks
1a If you send the key with the message, anyone can decrypt the message
key would need to be sent by means other than email, otherwise anyone could
intercept the key and use it do decrypt the message;
1
1b Jill.s public key;
Jill.s private key;
1
1
1c the message data is hashed into a message digest; the message digest is
encrypted; with the sender.s private key;
Jill’s software decrypts the signature; using Jack ’s public key; contained in3
digital certificate sent with message; to verify Jack.s public key; decrypt digital
certificate using Certificate Authority.s (trusted third party.s) public key; Jill’s
software then hashes the document data into a message digest; If recalculated
message digest is the same as the original message digest (decryptedsignature); then Jill knows that the signed data has not been changed;Max 4
I decryption of message
Question 2 – January 2006 CPT5 Q7
Question
Number
Answer Marks
2a converting/transforming from plain text into ciphertext/secret code;
A bl d A i i / i / di
max 1
8/15/2019 a2 Student Book Answers
http://slidepdf.com/reader/full/a2-student-book-answers 153/170
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) B’s public key;
ii) B’s private key;
1
1
2c i) a hashing function is applied to the text of the message;
the result/message digest is encrypted;
using B’s 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 Authority’s public key;
to verify B’s public key;
digital signature is decrypted;
using B’s 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
max 4
Question 3 – January 2003 CPT5 Q5
Question
number
Answer Marks
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 computer ’s operator;
Electronic eavesdropping of telephone wires and local area networks is
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;
Recipient’s private key used to decrypt e-mail;
2
ii) E-mail encrypted by sender using private key;
Recipient decrypts e-mail using sender’s public key;
2
7.1
8/15/2019 a2 Student Book Answers
http://slidepdf.com/reader/full/a2-student-book-answers 154/170
End of topic quest ions
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
maintenance6a) 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?
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 requiredfrom the proposed system? Establish if hard copy output is required.
H ft ill t t b i d? A k t t t f th t
8/15/2019 a2 Student Book Answers
http://slidepdf.com/reader/full/a2-student-book-answers 155/170
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
member’s 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.
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.
7 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.
8/15/2019 a2 Student Book Answers
http://slidepdf.com/reader/full/a2-student-book-answers 156/170
Through a process of refinement to progress, in conjunction with users, to a final working
system. This process is called evolutionary, iterative development:
to discover errors in design
to discover problems.
8 Once one phase is complete, it is not revisited. The customer doesn’t get to see thedeveloping 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 doesn’t 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
customer’s requirements. There is no opportunity for the customer to correct the
developer’s error. The waterfall model communicates by written documents forwardsthrough 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.
9 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.10 The spiral model is more appropriate because you are not yet a professional software
developer and you will be working on your own.
11 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.
12 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.
Context diagram
Level 1 DFD
Level 2 DFD
13 Business algorithms are algorithms supplied by the end user. These are algorithms used bythe 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 sortMerge sort
H t
8/15/2019 a2 Student Book Answers
http://slidepdf.com/reader/full/a2-student-book-answers 157/170
Heap sort
Quick sort
Bucket sort
Radix sort
Distribution sort
Shuffle sort15 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 inwhich 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 itis 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 asnake does not contain ground. It is, in fact, a uses relationship.
17 Analyst doesn’t 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 customer’s needs/requirements.
Analyst fails to specify in the clearest terms the customer’s requirements to the
customer so customer agrees to the development of a solution that is not exactly
what they want.
Analyst fails to communicate to the developer precisely what the system must do
and therefore the developer develops a solution which doesn’t match the
customer’s expectations.
Exam pract ice quest ions
Question
number
Answer Marks
1 Problem definition, feasibility study, analysis, design,
implementation, testing, maintenance.
3
2a Any three from: Interview, survey, observation, examination
of the paperwork.
3
8/15/2019 a2 Student Book Answers
http://slidepdf.com/reader/full/a2-student-book-answers 158/170
p p
2b 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
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.
3
3a Specification 1
3b Design 1
3c Design 1
3d Specification 1
7.2
End of topic quest ions
1
8/15/2019 a2 Student Book Answers
http://slidepdf.com/reader/full/a2-student-book-answers 159/170
2
7.3
Exam pract ice quest ionsQuestion 1 – June 2008 CPT5 Q1eStartDateTime EndDateTime Mileage OverdueHours Normal Erroneous Boundary
01/12/07 06:00 01/12/07
15:30
15 2 1
16/12/07 18:00 12/12/07
09:00
237 3
04/12/07 23:00 04/12/07
08:30
5 2 1
8/15/2019 a2 Student Book Answers
http://slidepdf.com/reader/full/a2-student-book-answers 160/170
03/12/07 08:00 03/12/07
09:00
0 0 1
01/12/07 06:00 01/12/07
15:30
0 1.5 1 I
01/12/07 06:00 01/12/0715:30
0 -2 1 I
04/12/07 08:30 05/12/07
23:00
57 0 1 A
01/12/07 06:00 01/12/07
15:30
15 3
Question 2 –
January 2008 CPT5 Q3Question
number
Answer Marks
2a normal data: accept valid dates within 120 years before present (i.e.
23/01/2008)
birthday sometime before today’s date;
birthday sometime after today’s 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
A day/month instead of birthday
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.
3
2b boundary data:
a birthday just before boundary;a birthday just after boundary;
4
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;
22/1 – 24/1 Any year within 1887 – 2008
2c R anything that is not valid date format;
erroneous data: a date after today’s date; reason: can’t 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’;
2
8/15/2019 a2 Student Book Answers
http://slidepdf.com/reader/full/a2-student-book-answers 161/170
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
number
Answer Marks
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
A the last stage of testing;
1
8
8/15/2019 a2 Student Book Answers
http://slidepdf.com/reader/full/a2-student-book-answers 162/170
R error messages3b 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;
3
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
t ti
2
8/15/2019 a2 Student Book Answers
http://slidepdf.com/reader/full/a2-student-book-answers 163/170
testing.
Question 4 – January 2007 CPT5 Q2
Question
number
Answer Marks
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;
1 mark for test data, 1 mark for justification
If justification does not match test data, then 1 mark max.
6
Question 5 – June 2006 CPT5 Q3
Question
number
Answer Marks
5 1 mark for test data, 1 mark for justification for 3 sets of test data
£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;
6
£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
QuestionNumber
Answer Marks
6 Any two points at 1 mark each: 2
8/15/2019 a2 Student Book Answers
http://slidepdf.com/reader/full/a2-student-book-answers 164/170
Any two points at 1 mark each:
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 beswitched 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
2
Question 7 – January 2006 CPT5 Q1
Question
Number
Answer Marks
7 Top-down testing;
Bottom-up testing;
Black Box testing;White Box testing;
Dry run/walk-through;
Unit/Module testing; A Prototyping;
R Integration/Acceptance/Alpha/Beta/System/Performance/Compatibility
testing;
R anything clearly late in the development cycle;
Mark first 3 responses only
3
BUT
beware of expansion on same line.
Question 8 – June 2005 CPT5 Q2
Question
number
Answer Marks
8 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);
Max 2
8/15/2019 a2 Student Book Answers
http://slidepdf.com/reader/full/a2-student-book-answers 165/170
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
number
Answer Marks
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.
Any two at
one mark
each
2
9b) i) Acceptance testing is specified/performed by customer (against originalspecifications);
1
9b) ii) Poorly/incorrectly specified system//inadequate/inaccurate systems analysis;Poor training of staff using system//staff use system incorrectly;
1
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 testingR Phased testing, bottom-up testing
Any one for
one mark
1
Question 10 – January 2004 CPT5 Q8
8/15/2019 a2 Student Book Answers
http://slidepdf.com/reader/full/a2-student-book-answers 166/170
Question 10 January 2004 CPT5 Q8
Question
number
Answer Marks
10a) i) Strategy: White Box testing;
Justification: Need to follow a path through the code (to discover the
error);
2
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
2
10b r never changes or an alternative that describes/implies the same thing;
A. gets stuck in an infinite loop1
10c If y > 0 Then x = y * (result q) + (remainder r);
R. y cannot equal zeroA. y must always be greater than zero
1
10d) Acceptance is specified/performed by “customer” ;
against original specifications
1
7.4
Exam pract ice quest ions
Question 1 – January 2006 CPT5 Q5 c) and d)
Question
number
Answer Marks
1ae) Method
1 mark
Justification
1 mark
Parallel To check against the pupil’s food diary to ensure the data
2
collected is correct;
A if new system fails, they have the old one to fall back
on;
Direct It would take too long to check against pu pil’s food diaries
// not a critical system // cheaper than parallel // cheaper
than running two systems;
Pilot 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);
Phased 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 pilot1b data files will have to be entered into the system; R
conversion/transfer of data3
8/15/2019 a2 Student Book Answers
http://slidepdf.com/reader/full/a2-student-book-answers 167/170
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 issuedwith smart cards;
define/create new operating procedures
A produce documentation/user guide/system guide
Question 2 – June 2003 CPT5 Q4
Question
number
Answer Marks
2a i. Old system and new system operate alongside each other/in parallel
until new system proved; (require time limited trial)
ii. Parts of old system gradually replaced in stages by new system;
Do not give mark for a pilot
1
1
2b Information/Data/Files may have to beconverted/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;
2
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
3
8/15/2019 a2 Student Book Answers
http://slidepdf.com/reader/full/a2-student-book-answers 168/170
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 quest ions
1 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.
2 Effectiveness in meeting requirements: learnability, useability, maintainability.
3 In addition to requiring criteria for judging effectiveness evaluation of effectiveness requires:
a) planning
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
LatencyReadability
Use of metaphors
Navigability
8/15/2019 a2 Student Book Answers
http://slidepdf.com/reader/full/a2-student-book-answers 169/170
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.
o 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 Is indentation used to indicate the structure of the code.c) Blocks of code have one entry point and one exit point.
d) Is the use of global variables across units minimised?
e) Is good use made of local variables?
f) Are parameter values passed in and out of procedures through procedure interfaces?
g) 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?
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
o other relevant diagrams?
o) Are algorithms documented?
8/15/2019 a2 Student Book Answers
http://slidepdf.com/reader/full/a2-student-book-answers 170/170
10 Evaluation should take place early in the project when prototyping for the purpose of
clarifying the customer’s 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).