0% found this document useful (0 votes)
1 views

Ch. 1 - Programming

The document outlines a series of programming tasks and algorithms related to data structures and pseudo-code. It includes exercises on sorting numbers, implementing algorithms, and modifying a skeleton program to handle various functionalities such as error handling and editing source code. Additionally, it provides specific tasks for coding, testing, and documenting results with source code and screen captures.

Uploaded by

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

Ch. 1 - Programming

The document outlines a series of programming tasks and algorithms related to data structures and pseudo-code. It includes exercises on sorting numbers, implementing algorithms, and modifying a skeleton program to handle various functionalities such as error handling and editing source code. Additionally, it provides specific tasks for coding, testing, and documenting results with source code and screen captures.

Uploaded by

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

Name: ________________________

1 -1 Class: ________________________

Date: ________________________

Time: 368 minutes

Marks: 283 marks

Comments:

GEMS Metropole School Page 1 of 236


The algorithm, represented using pseudo-code in the figure below, describes a method to
1. rearrange four numbers in a data structure.

Numbers[0] ← 45

Numbers[1] ← 19

Numbers[2] ← 62

Numbers[3] ← 12

FOR X ← 1 TO 3
Y ←X−1
N ← Numbers[X]
WHILE Y > −1 AND N < Numbers[Y]
Numbers[Y + 1] ← Numbers[Y]

Y ← Y − 1
ENDWHILE
Numbers[Y + 1] ← N
ENDFOR

GEMS Metropole School Page 2 of 236


Complete the table below by hand-tracing the algorithm in the figure above.

You may not need to use all the rows in the table below.

The first row of the table below has already been completed for you.

Numbers
X Y N
[0] [1] [2] [3]

45 19 62 12

(Total 5 marks)

Describe one difference between a global variable and a local variable.


2.
_______________________________________________________________________

_______________________________________________________________________

_______________________________________________________________________

_______________________________________________________________________
(Total 2 marks)

GEMS Metropole School Page 3 of 236


The algorithm, represented using pseudo-code, in the figure below outputs a series of integers.
3. The output depends upon the value entered by the user.

OUTPUT "Enter an integer greater than 1: "


INPUT Number
X ← 2

Count 0 ←
WHILE Number > 1
Multi ←
FALSE
WHILE (Number MOD X) = 0
IF NOT Multi THEN
OUTPUT X
ENDIF
Count ← Count + 1

Multi ← TRUE

Number ← Number DIV X


ENDWHILE
X ←X + 1
ENDWHILE
OUTPUT Count

The table below lists the MOD and DIV operators for each of the available programming
languages. You should refer to the row for your programming language.

Programming language MOD DIV


C# % /
Java % /
Pascal mod div
Python % //
VB.NET Mod \

What you need to do:

Task 1
Write a program to implement the algorithm in the figure above.

Task 2
Test that your program works:

• run your program, then enter the number 23


• run your program, then enter the number 25
• run your program, then enter the number 1260

Evidence that you need to provide

(a) Your PROGRAM SOURCE CODE for Task 1.


(9)

GEMS Metropole School Page 4 of 236


(b) SCREEN CAPTURE(S) showing the tests described in Task 2.
(1)
(Total 10 marks)

State the identifier for:


4.
(a) a variable that is used to store a Boolean value.

___________________________________________________________________

___________________________________________________________________
(1)

(b) a user-defined subroutine that returns only one value that is an integer.

___________________________________________________________________

___________________________________________________________________
(1)

(c) a user-defined subroutine that returns only one value that is a single character.

___________________________________________________________________

___________________________________________________________________
(1)

(d) a user-defined subroutine that contains exception handling.

___________________________________________________________________

___________________________________________________________________
(1)
(Total 4 marks)

The Skeleton Program uses a number of data structures.


5.
(a) State the identifier of a data structure that stores values of more than one data type.

___________________________________________________________________

___________________________________________________________________
(1)

(b) State the identifier of a data structure that stores values of only one data type.

___________________________________________________________________

___________________________________________________________________
(1)
(Total 2 marks)

GEMS Metropole School Page 5 of 236


When the Skeleton Program detects an error it outputs an error code which is a number
6. between 1 and 11.

The error codes could be replaced by more helpful error messages.

Complete the table below by writing the most appropriate error code from the Skeleton Program
next to each proposed error message.

Proposed error message Error code

Duplicate label found

File not found

No assembled code to run

No source code to display

Unknown opcode

(Total 5 marks)

This question refers to the subroutine PassTwo.


7.
State two conditions that need to be met for error code 6 to be reported during the assembly
process of the program.

_______________________________________________________________________

_______________________________________________________________________

_______________________________________________________________________

_______________________________________________________________________
(Total 2 marks)

This question refers to the subroutine ExtractOperand.


8.
(a) Describe the purpose of the FOR loop and the IF statement inside it.

___________________________________________________________________

___________________________________________________________________

___________________________________________________________________

___________________________________________________________________
(2)

GEMS Metropole School Page 6 of 236


(b) Describe the purpose of the IF statement after the FOR loop.

___________________________________________________________________

___________________________________________________________________

___________________________________________________________________

___________________________________________________________________
(2)

(c) Describe why a WHILE loop might have been a better choice than a FOR loop.

___________________________________________________________________

___________________________________________________________________

___________________________________________________________________

___________________________________________________________________
(2)
(Total 6 marks)

This question extends the functionality of the Skeleton Program.


9.
The functionality of the SKP opcode is to be changed so that it increments the value stored in the
accumulator by 1

For example, if the accumulator contained 4, then executing the instruction


SKP
would change the value in the accumulator to 5

What you need to do:

Task 1
Amend the subroutine ExecuteSKP so that it adds 1 to the accumulator and then updates the
status register if required. The Registers data structure should be passed as a parameter.

Task 2
Amend the call to ExecuteSKP in the Execute subroutine as required.

Task 3
Test that the changes you have made work by conducting the following test:
• run your amended Skeleton Program
• enter L
• load prog2
• enter A
• enter R

Evidence that you need to provide

(a) Your PROGRAM SOURCE CODE for the entire subroutine ExecuteSKP and the entire
subroutine Execute.
(4)
GEMS Metropole School Page 7 of 236
(b) SCREEN CAPTURE(S) showing the requested test described in Task 3.

The SCREEN CAPTURE(S) only need to show all of Frame 0 and all of the final frame.
(1)
(Total 5 marks)

This question adds validation to the Skeleton Program. The subroutine EditSourceCode asks
10. the user to enter a line number. The line number must be an integer and the number of an
existing line in the file containing the program.

For example, the last line (line 11) of prog2.txt is:


FINAL: 0

Therefore, a valid line number for prog2.txt would be an integer between 1 and 11 inclusive.

What you need to do:

Task 1
Amend the subroutine EditSourceCode to check that the line number entered by the user is a
valid existing line number. If an invalid value is entered the subroutine should output an
appropriate error message. The program must not continue until a valid line number has been
entered.

Task 2
Test that the changes you have made work by conducting the following test:

• run your amended Skeleton Program


• enter L
• load prog2
• enter E
• enter Q
• enter 22
• enter 0
• enter 2

Evidence that you need to provide

(a) Your PROGRAM SOURCE CODE for the entire subroutine EditSourceCode.
(5)

(b) SCREEN CAPTURE(S) showing the requested test described in Task 2.


(1)
(Total 6 marks)

This question adds a memory address check to the Skeleton Program.


11.
Each time a JSR opcode is executed the return address is stored in memory. The memory
location used for this could already contain an instruction or data.

If storing a return address will overwrite an instruction or data, then an appropriate error message
should be output using the ReportRunTimeError subroutine. The original code in the
ExecuteJSR subroutine should only be carried out if there is no error.

GEMS Metropole School Page 8 of 236


What you need to do:

Task 1
Amend the ExecuteJSR subroutine. If storing a return address would overwrite an instruction or
data, the ReportRunTimeError subroutine should be called with an appropriate error message.

One method of completing this task would require the addition of extra parameter(s) to the
ExecuteJSR subroutine.

Task 2
If your solution requires additional parameter(s) for the ExecuteJSR subroutine amend the call to
ExecuteJSR in the Execute subroutine.

Task 3
Test that the changes you have made work by conducting the following test:

• run your amended Skeleton Program


• enter L
• load prog3
• enter A
• enter R

Evidence that you need to provide

(a) Your PROGRAM SOURCE CODE for the entire subroutine ExecuteJSR and the entire
subroutine Execute if you have made changes in Task 2.
(4)

(b) SCREEN CAPTURE(S) showing the requested test described in Task 3.

The SCREEN CAPTURE(S) only need to show the final frame and the contents of the
stack before execution terminates.
(1)
(Total 5 marks)

This question extends the functionality of the Skeleton Program. The option to edit the source
12. code is to be extended to allow lines to be deleted or inserted within a loaded source code
program.

The options within the EditSourceCode subroutine should now be:

E – Edit this line

D – Delete the current line

I – Insert a new line above this line

C – Cancel edit

Option D should delete the current line without changing the size of the data structure. The lines
after the deleted line need to be moved within the data structure so that there is no gap in the
source code.

GEMS Metropole School Page 9 of 236


Figure 1 shows an example where line 10 is being deleted. As a result lines 11 to 13 move. The
size of the data structure does not change.

Figure 1

You must write your own delete routine and not use any built-in delete function that might be
available in the programming language you are using.

Option I should allow the user to enter a new line to be inserted above the chosen line without
changing the size of the data structure. The lines after the inserted line need to be moved within
the data structure so they are not overwritten.

You should check that there is sufficient space in the data structure to accommodate a new line.
If there is not sufficient space, an error message should be displayed.

Figure 2 shows an example where lines 4 to 11 move and a new line 4 is inserted. The size of
the data structure does not change.

Figure 2

GEMS Metropole School Page 10 of 236


You must write your own insert routine and not use any built-in insert function that might be
available in the programming language you are using.

What you need to do:

Task 1
Amend the EditSourceCode subroutine to include the delete line option.

Task 2
Test that the changes you have made work by conducting the following test:

• run your amended Skeleton Program


• enter L
• load prog1
• enter E
• enter 10
• enter D

Task 3
Amend the EditSourceCode subroutine to include the insert line option.

Task 4
Test that the changes you have made work by conducting the following test:

• run your amended Skeleton Program


• enter L
• load prog2
• enter E
• enter 4
• enter I
• enter LABEL: SKP

Evidence that you need to provide

(a) Your PROGRAM SOURCE CODE for the entire subroutine EditSourceCode.
(12)

(b) SCREEN CAPTURE(S) showing the requested test described in Task 2.

The SCREEN CAPTURE(S) only need to show the test from entering option E until after
the edited source code has been displayed.
(1)

(c) SCREEN CAPTURE(S) showing the requested test described in Task 4.

The SCREEN CAPTURE(S) only need to show the test from entering option E until after
the edited source code has been displayed.
(1)
(Total 14 marks)

GEMS Metropole School Page 11 of 236


The algorithm, represented using pseudo-code in the figure below, describes a method to access
13. numbers in the data structure, List, shown in Table 1.

SUBROUTINE A(S, X, Y)
P ← -1
WHILE P = -1 AND X <= Y
Z ← (X + Y) DIV 2
IF List[Z] = S THEN
P ←Z
ELSE
IF List[Z] < S THEN
X ← Z + 1
ELSE
Y ← Z – 1
ENDIF
ENDIF
ENDWHILE
RETURN P
ENDSUBROUTINE

The DIV operator calculates the whole number part resulting from an integer division, for
example, 10 DIV 3 = 3

Complete Table 2 by hand-tracing the algorithm in the figure above when the following statement
is executed.

Result ← A(38, 0, 18)

You may not need to use all the rows in Table 2.

The first row of Table 2 has already been completed for you.

GEMS Metropole School Page 12 of 236


Table 1
List
[0] [1] [2] [3] [4] [5] [6] [7] [8] [9][10][11][12][13][14][15][16][17][18]
2 8 12 18 25 29 36 42 49 51 57 61 68 71 79 83 84 91 97

Table 2

S X Y P Z List[Z]

38 0 18 −1

Result:

(Total 5 marks)

GEMS Metropole School Page 13 of 236


The code below shows an algorithm represented using pseudo-code.
14.
C ← 0

D ← 0

S ← 0

T ←0
WHILE C < 3 AND D < 3
T ←T+1
N1 ← generate random integer between 1 and 6 inclusive

N2 ← generate random integer between 1 and 6 inclusive


OUTPUT N1, N2
S ←S + N1 + N2
IF N1 = 6 OR N2 = 6 THEN
C ←
C + 1
ENDIF
IF N1 = N2 THEN
D ← D + 1
ENDIF
ENDWHILE
A ←S DIV (T * 2)
OUTPUT C, D, A

The DIV operator calculates the whole number part resulting from an integer division, for
example, 10 DIV 3 = 3

The table below lists the DIV operators for each of the available programming languages. You
should refer to the row for your programming language.

Programming language DIV

C# /

Java /

Pascal div

Python //

VB.NET \

GEMS Metropole School Page 14 of 236


What you need to do:

Task 1
Write a program to implement the algorithm in the figure above.

Task 2
Test that your program works:
• run your program.

Evidence that you need to provide

(a) Your PROGRAM SOURCE CODE for Task 1.


(8)

(b) SCREEN CAPTURE(S) showing the test described in Task 2.


(1)
(Total 9 marks)

State the most appropriate data type to use for whole numbers.
15.
_______________________________________________________________________

_______________________________________________________________________
(Total 1 mark)

State the identifier of a variable in the Skeleton Program that can only represent whole
16. numbers.

_______________________________________________________________________

_______________________________________________________________________
(Total 1 mark)

State the identifier and data type of a variable in the Skeleton Program that can only represent
17. two different values.

_______________________________________________________________________

_______________________________________________________________________

_______________________________________________________________________

_______________________________________________________________________
(Total 2 marks)

The Skeleton Program uses the data structure Answer.


18.
(a) State what the second element of this data structure, Answer[1], is used for.

___________________________________________________________________

___________________________________________________________________
(1)

GEMS Metropole School Page 15 of 236


(b) Explain the purpose of the third element of this data structure, Answer[2], and how it is
used.

___________________________________________________________________

___________________________________________________________________

___________________________________________________________________

___________________________________________________________________

___________________________________________________________________

___________________________________________________________________
(3)
(Total 4 marks)

The grid size of the puzzle is currently 9 and sub-grids are 3 x 3.


19.
If the grid size were to be increased to 16, the sub-grids would be 4 x 4 and the hexadecimal
digits 0 1 2 3 4 5 6 7 8 9 A B C D E F could be used to solve the puzzle.

Describe two changes that would need to be made to the subroutine DisplayGrid to enable
this.

You should not make any changes to the Skeleton Program to answer this question.

_______________________________________________________________________

_______________________________________________________________________

_______________________________________________________________________

_______________________________________________________________________
(Total 2 marks)

Explain the differences between definite and indefinite iteration.


20.
_______________________________________________________________________

_______________________________________________________________________

_______________________________________________________________________

_______________________________________________________________________
(Total 2 marks)

State the identifier of a subroutine in the Skeleton Program that contains definite iteration.
21.
_______________________________________________________________________

_______________________________________________________________________
(Total 1 mark)

GEMS Metropole School Page 16 of 236


State the identifier of a subroutine in the Skeleton Program that contains indefinite iteration.
22.
_______________________________________________________________________

_______________________________________________________________________
(Total 1 mark)

Explain what exception handling is used for.


23.
_______________________________________________________________________

_______________________________________________________________________

_______________________________________________________________________

_______________________________________________________________________
(Total 2 marks)

State the identifier of a subroutine in the Skeleton Program that performs exception handling
24. and give an example of a circumstance that might cause an exception within that subroutine.

_______________________________________________________________________

_______________________________________________________________________

_______________________________________________________________________

_______________________________________________________________________
(Total 2 marks)

What is a subroutine?
25.
_______________________________________________________________________

_______________________________________________________________________
(Total 1 mark)

The use of subroutines promotes code re-use.


26.
Describe, with references to subroutine(s) in the Skeleton Program, an example of how a
subroutine has been re-used.

_______________________________________________________________________

_______________________________________________________________________
(Total 1 mark)

Describe an advantage of re-using subroutines.


27.
_______________________________________________________________________

_______________________________________________________________________
(Total 1 mark)

GEMS Metropole School Page 17 of 236


The chart below shows an incomplete hierarchy chart for part of the Skeleton Program.
28.

Complete the table below by writing the labels that should appear in each of the boxes (a) to
(d) in the chart above.

Box Label
cp
(a)

(b)

(c)

(d)

(Total 2 marks)

GEMS Metropole School Page 18 of 236


This question adds further validation to the Skeleton Program.
29.
When a puzzle is loaded, some cells already contain numbers. These cells are referred to as
protected cells.

The figure below shows the numbers in the puzzle grid cells when puzzle1 is first loaded. These
are the protected cells for this puzzle.

The Skeleton Program is to be changed so that the user cannot change the contents of any
protected cells.

The subroutine SolvePuzzle needs to be modified so that the user cannot change a digit in a
protected cell but can still enter a digit into an empty cell or change a digit that they have
previously entered.

What you need to do:

Task 1
Amend the subroutine SolvePuzzle so that it checks every cell reference entered by the user
against the protected cell references in Puzzle and only allows the contents of the cell to be
changed if the cell referenced by CellInfo is not a protected cell.

If a protected cell is referenced, an appropriate error message should be displayed.

GEMS Metropole School Page 19 of 236


Task 2
Test that the changes you have made work by conducting the following test:
• run your amended Skeleton Program
• enter P
• load puzzle1
• enter S
• enter 117
• enter 323
• enter 993
• enter 853
• enter 854

Evidence that you need to provide

(a) Your PROGRAM SOURCE CODE for the entire subroutine SolvePuzzle.
(7)

(b) SCREEN CAPTURE(S) showing the requested test described in Task 2.

The SCREEN CAPTURE(S) need(s) to show the puzzle grid before and after the described
test.
(1)
(Total 8 marks)

This question adds further validation to the Skeleton Program. The subroutine SolvePuzzle
30. asks the user to enter coordinates and a digit. The Skeleton Program is to be changed so that if
the digit entered by the user already exists in the referenced row, column or sub-grid, the digit
cannot be used.

The figure below shows the numbers in the puzzle grid cells of puzzle1 when first loaded.

GEMS Metropole School Page 20 of 236


What you need to do:

Task 1
Write a new subroutine, DuplicateDigit, which takes PuzzleGrid, Row, Column and Digit as
parameters. The subroutine should return True if the digit entered by the user is already present
in the row, column or sub-grid of the cell the user has entered. Otherwise, the subroutine should
return False.

Task 2
Amend the subroutine SolvePuzzle so that it uses DuplicateDigit to check the user input and
only allows the digit to be placed into the puzzle grid if the digit is not already present in the row,
column or sub-grid of the cell the user has entered. If the digit is already present, an appropriate
message should be given to the user.

Task 3
Test that the changes you have made work by conducting the following test:
• run your amended Skeleton Program
• enter L
• load puzzle1
• enter S
• enter 178
• enter 819
• enter 124
• enter 989
• enter 555

Evidence that you need to provide

(a) Your PROGRAM SOURCE CODE for the entire subroutine DuplicateDigit and the entire
subroutine SolvePuzzle.
(8)

(b) SCREEN CAPTURE(S) showing the requested test described in Task 3.

The SCREEN CAPTURE(S) need(s) to show the puzzle grid before and after the described
test.
(1)
(Total 9 marks)

This question extends the functionality of the Skeleton Program.


31.
The user is to be allowed to clear the contents of the most recently changed cells. To do this,
they will enter a negative integer when prompted to enter a row, column and digit. The integer will
represent the number of cells to be cleared.

For example, if the user enters -3, the three most recently entered digits should each be
replaced by a space in the puzzle grid and the Answer data structure should be updated.

If the number of cells to be cleared is greater than the number of entries in the Answer data
structure, all digits entered by the user should be cleared.

GEMS Metropole School Page 21 of 236


What you need to do:

Task 1
Write a new subroutine, ClearEntries, that clears the required number of previously entered
digit(s) from the puzzle grid and updates the Answer data structure as described above.

Task 2
Amend the subroutine SolvePuzzle to test user input for a negative value. If the user input is a
negative integer, the subroutine should call ClearEntries with the necessary parameters and
then re-display the puzzle grid.

Task 3
Test that the changes you have made work by conducting the following test:
• run your amended Skeleton Program
• enter P
• load puzzle1
• enter S
• enter -x
• enter -1
• enter -5

Evidence that you need to provide

(a) Your PROGRAM SOURCE CODE for the entire subroutine ClearEntries and the entire
subroutine SolvePuzzle.
(12)

(b) SCREEN CAPTURE(S) showing the requested test described in Task 3.

The SCREEN CAPTURE(S) need(s) to show the puzzle grid before and after the described
test.
(1)
(Total 13 marks)

Graphics
32.
The Skeleton Program accompanying this Preliminary Material is a simple graphics program
that uses ASCII art.

ASCII art is a technique used to represent images using the 95 printable characters in the ASCII
character set. ASCII art is used where text can be printed but bitmapped graphics cannot, for
example in console mode programming environments. It requires monospaced fonts (such as
Courier New) which position the characters neatly in columns.

Different techniques can be used in ASCII art for different effects. Here are some examples:

GEMS Metropole School Page 22 of 236


Very elaborate images have been made with different characters emulating different shades for
the pixels.

Figure 1 shows an ASCII art image loaded from the image1.txt data file.

Figure 1

The Skeleton Program uses printable ASCII characters to display images. The program allows
the user to load an image from a text file. The option "S - Save image" saves the image in
such a way that it can be viewed in a text editor, such as Notepad or TextEdit.

The Skeleton Program can also load greyscale images where the shade of each pixel is
encoded by an 8-bit integer. 8-bit integer encoding allows 256 possible shades of grey. The
program changes the greyscale values into ASCII characters. Figure 2 shows the image created
when loading the greyscale.txt data file.

GEMS Metropole School Page 23 of 236


Figure 2

The data files ascii.txt, image2.txt and image3.txt available with this Preliminary Material
also contain parts of images.

A sentinel value is a special value after the end of a series of data values. It is a terminator for
33. the series of data values but is not treated as part of the series. A sentinel value is used when
you do not know how many data values are in the series.

The algorithm, represented using pseudo-code below, is an attempt at a method to add numbers
that are input as a series terminated by the sentinel value -1

X ← 0

Result ← 0
WHILE X ≠ -1
INPUT X
Result ← Result + X
ENDWHILE
OUTPUT Result

GEMS Metropole School Page 24 of 236


(a) Complete the table below by hand-tracing the algorithm shown above. You may not need to
use all the rows in the table.

The first row of the table has already been completed for you.

The sequence of numbers for input is: 4, 6, 3, 2, -1

X Result Output

0 0 -

(3)

(b) Comment on the result of the trace and describe how the algorithm should be modified.

___________________________________________________________________

___________________________________________________________________

___________________________________________________________________

___________________________________________________________________
(2)
(Total 5 marks)

The algorithm, represented using pseudo-code below, outputs a series of integers or the
34. message No result. The output depends upon the value entered by the user.

GEMS Metropole School Page 25 of 236


OUTPUT "Enter an integer greater than 1: "
INPUT X
Product ←1
Factor ←0
WHILE Product < X
Factor ← Factor + 1

Product ← Product * Factor


ENDWHILE
IF X = Product THEN
Product ← 1

FOR N ← 1 TO Factor

Product ←
Product * N
OUTPUT N
ENDFOR
ELSE
OUTPUT "No result"
ENDIF

What you need to do:

Task 1
Write a program to implement the algorithm.

Task 2
Test that your program works:
• run your program, then enter the number 720
• run your program, then enter the number 600

Evidence that you need to provide

(a) Your PROGRAM SOURCE CODE for Task 1.


(9)

(b) SCREEN CAPTURE(S) showing the tests described in Task 2.


(1)

(c) What is true for all valid inputs for X that output a number of numbers which is not true for
all other valid inputs that output No result?
(1)
(Total 11 marks)

State the name of an identifier for:


35.
(a) a variable that is used to store a Boolean value.

___________________________________________________________________

___________________________________________________________________
(1)

GEMS Metropole School Page 26 of 236


(b) a user-defined subroutine that returns only one value that must be a string.

___________________________________________________________________

___________________________________________________________________
(1)

(c) a user-defined subroutine that uses nested indefinite iteration.

___________________________________________________________________

___________________________________________________________________
(1)
(Total 3 marks)

This question refers to the constants set at the beginning of the Skeleton Program.
36.
It is a good programming technique to use a named constant rather than the value it represents.

State a reason why each of the following are set as constants. Your answers for part (a) and (b)
must be different.

(a) EMPTY_STRING

___________________________________________________________________

___________________________________________________________________
(1)

(b) MAX_WIDTH

___________________________________________________________________

___________________________________________________________________
(1)
(Total 2 marks)

This question refers to the subroutine LoadGreyScaleImage


37.
Describe two possible errors that could cause an exception in this subroutine.

_______________________________________________________________________

_______________________________________________________________________

_______________________________________________________________________

_______________________________________________________________________
(Total 2 marks)

GEMS Metropole School Page 27 of 236


The diagram below shows an incomplete hierarchy chart for part of the Skeleton Program.
38.

(a) What is the purpose of a hierarchy chart?

___________________________________________________________________

___________________________________________________________________
(1)

(b) What does each box in a hierarchy chart represent?

___________________________________________________________________

___________________________________________________________________
(1)

(c) What should be written in box (a) in the diagram?

___________________________________________________________________

___________________________________________________________________
(1)
(Total 3 marks)

This question refers to the subroutines Graphics and LoadFile


39.
(a) State what values are passed in the parameter Header to the subroutine LoadFile when
LoadFile is called for the first time in the subroutine Graphics

___________________________________________________________________

___________________________________________________________________
(1)

GEMS Metropole School Page 28 of 236


(b) Explain how the content of HeaderLine is processed after it has been assigned a value.

___________________________________________________________________

___________________________________________________________________

___________________________________________________________________

___________________________________________________________________

___________________________________________________________________

___________________________________________________________________
(3)
(Total 4 marks)

This question refers to the subroutine ConvertChar


40.
With reference to the fact that 0 represents the darkest greyscale (black) and 255 represents the
lightest greyscale (white), explain the purpose of ConvertChar

_______________________________________________________________________

_______________________________________________________________________

_______________________________________________________________________

_______________________________________________________________________
(Total 2 marks)

This question refers to the text file image3.txt and the subroutine LoadAsciiImage
41.
The first line of the text file image3.txt contains:

Cat,59,25,A

(a) Explain the effect of changing the first line to Cat,25,59,A and then calling
LoadAsciiImage

___________________________________________________________________

___________________________________________________________________

___________________________________________________________________

___________________________________________________________________
(2)

GEMS Metropole School Page 29 of 236


(b) Explain the effect of changing the first line to Cat,59,59,A and then calling
LoadAsciiImage

___________________________________________________________________

___________________________________________________________________

___________________________________________________________________

___________________________________________________________________
(2)

(c) Explain the effect of changing the first line to Cat,59,10,A and then calling
LoadAsciiImage

___________________________________________________________________

___________________________________________________________________

___________________________________________________________________

___________________________________________________________________
(2)
(Total 6 marks)

This question refers to the subroutine DisplayImage


42.
Explain what effect swapping around the nested iteration structure in this subroutine would have
on the image output, assuming that the image width and height are equal.

Written in pseudo-code the altered iteration structure would be:

FOR ThisColumn ← 0 TO Header.Width – 1


FOR ThisRow ← 0 TO Header.Height – 1
OUTPUT Grid[ThisRow, ThisColumn]
ENDFOR
OUTPUT newline
ENDFOR

_______________________________________________________________________

_______________________________________________________________________

_______________________________________________________________________

_______________________________________________________________________

_______________________________________________________________________

_______________________________________________________________________
(Total 3 marks)

GEMS Metropole School Page 30 of 236


This question extends the functionality of the Skeleton Program. A mirror image is to be
43. produced from the loaded image. For example, Figure 1 shows the image loaded from the
ascii.txt data file. Figure 2 shows the mirror image.

Figure 1 Figure 2

What you need to do:

Task 1
Write a new subroutine MirrorImage that produces a mirror image of the image loaded into Grid
and stores it in a new data structure. The subroutine then displays the mirror image.

Task 2
Amend subroutine DisplayMenu to include the new option:

M – Mirror image

Task 3
Amend subroutine Graphics to call MirrorImage when the user chooses option M

Task 4
Test that the changes you have made work by conducting the following test:
• run the program
• enter L
• load image1
• enter M

Evidence that you need to provide

(a) Your PROGRAM SOURCE CODE for the entire subroutines MirrorImage, DisplayMenu
and Graphics
(6)

(b) SCREEN CAPTURE(S) showing the requested test, including the menu and the display of
the mirror image.
(1)
(Total 7 marks)

GEMS Metropole School Page 31 of 236


This question refers to the subroutine LoadGreyScaleImage
44.
A greyscale image can contain a hidden message, which has been encrypted using a key. The
message can be revealed by decrypting the image using the method described below.

If an image contains a hidden message, the key to use is the integer value of the digit at the end
of the image title in the first line of the file. For example, if the image title is image4 then the key
is 4

When decrypting a message from an image file, each greyscale value is used in turn with the key
to produce a result. The key is subtracted from the greyscale value and the result is interpreted
according to the table below.

The table describes the rules that should be followed to determine what secret character, if any,
is hidden in the greyscale image.

Value of result Interpretation

0 The decrypted character is the space character.

> 0 AND ≤ 26 The result is the position in the alphabet of the decrypted character.

The result means that the character was not part of the message that
> 26 was encrypted, and should be represented by an underscore character,
ie the _ character.

Example 1
Greyscale value is 1 and the key is 0
1–0=1
The decrypted character is A as this is the first letter in the alphabet. This should be appended to
the hidden message.

Example 2
Greyscale value is 5 and the key is 3
5–3=2
The decrypted character is B as this is the second letter in the alphabet. This should be
appended to the hidden message.

Example 3
Greyscale value is 7 and the key is 7
7–7=0
The decrypted character is a space as the result was 0. This should be appended to the hidden
message.

Example 4
Greyscale value is 52 and the key is 1
52 – 1 = 51
The result is greater than 26 so the greyscale value was not an encrypted character and an
underscore character should be added to the hidden message.

The hidden message is built by concatenating each of the decrypted characters.

GEMS Metropole School Page 32 of 236


What you need to do:

Task 1
Write a new subroutine, FindSecretChar, which takes as parameters the PixelValue and Key,
where Key is the key used to decrypt the hidden character. The subroutine should return the
decrypted character if the pixel value was a character from the message, otherwise it should
return the underscore character.

Task 2
Amend the subroutine LoadGreyScaleImage to:
• get the key from the image title
• call the subroutine FindSecretChar in the appropriate place and build up the hidden
message from the returned characters
• output the complete hidden message.

Task 3
Test that the changes you have made work by conducting the following test:
• run the program
• enter L
• load greyscale

Evidence that you need to provide

(a) Your PROGRAM SOURCE CODE for the entire subroutines FindSecretChar and
LoadGreyScaleImage
(9)

(b) SCREEN CAPTURE(S) showing the requested test, including the display of the message
and the image.
(1)
(Total 10 marks)

This question extends the functionality of the Skeleton Program. A new option, C, is to be added
45. to compress an existing ASCII art image file using run-length encoding and store it in a new file.

The number of symbols in a run of symbols is to be counted and this count, separated by a
comma from the symbol, is stored in the new file. Each count and symbol pair should be put on a
new line.

For example, Figure 1 shows the contents of the ascii.txt data file.

Figure 1

TestImage1,5,3,A

###@@@@@AABB!!!

GEMS Metropole School Page 33 of 236


The compressed file will contain the file header followed by several value pairs and the file type
in the header should be changed from A to C, as shown in Figure 2.

Figure 2

TestImage1,5,3,C

3,#

5,@

2,A

2,B

3,!

You can assume that there are no newline characters in the ASCII art image file.

What you need to do:

Task 1
Write a new subroutine, CompressFile

This subroutine is to:


• ask the user for the name of the file to be compressed
• read the existing file header and change the file type to C to indicate that this is a
compressed file
• create a new file with the existing filename preceded by CMP, for example, if the file read in
was image2 the new filename should be CMPimage2
• save the edited file header to the new file
• save each pair of symbol count and symbol separated by a comma on a new line to the
new file.

Task 2
Amend subroutine DisplayMenu to include the new option:

C – Compress file

Task 3
Amend subroutine Graphics to call CompressFile when the user chooses option C

Task 4
Test that the changes you have made work by conducting the following test:
• run the program
• enter C
• enter the file name image2
• load the file CMPimage2 into a text editor.

GEMS Metropole School Page 34 of 236


Evidence that you need to provide

(a) Your PROGRAM SOURCE CODE for the entire subroutine CompressFile
(12)

(b) SCREEN CAPTURE(S) showing the requested test, including the menu and all of the
contents of the file CMPimage2 in the text editor.
(1)
(Total 13 marks)

AQA Board Game


46.
The Skeleton Program accompanying this Preliminary Material is a two-player board game.
The players are referred to as Player A and Player B. The board contains 64 squares, arranged
in an 8 × 8 grid. The squares containing Xs are not used. Each player has a maximum of 12
pieces. The number of pieces and their starting positions are determined by the contents of a text
file. The pieces’ IDs consist of the player’s letter and consecutive numbers 1 to 12.

GEMS Metropole School Page 35 of 236


Figure 1 shows a game with 12 pieces that has been loaded from the game1.txt text file.

Player A has twelve pieces with IDs a1 to a12, occupying rows 0 to 2.

Player B has twelve pieces with IDs b1 to b12, occupying rows 5 to 7.

GEMS Metropole School Page 36 of 236


Figure 2 shows a game with eight pieces that has been loaded from the game2.txt text file.

Player A has eight pieces with IDs a1 to a8, occupying rows 0 to 1.

Player B has eight pieces with IDs b1 to b8, occupying rows 6 to 7.

GEMS Metropole School Page 37 of 236


The rules are:

• Player A always starts.


• Players take turns to move.
• A move consists of advancing one of the player’s own pieces one square forward along the
diagonal (left or right) while remaining on the board.
For example, in Figure 2 piece a6, currently at row 1, column 2, could move to row 2,
column 1 or row 2, column 3.
• An alternative move is a jump over one of the player’s own pieces that is diagonally
immediately in front of the piece to be moved.
For example, in Figure 2 piece a2, currently at row 0, column 3, could move to row 2,
column 1 or row 2, column 5.
• When a piece reaches the opposite end of the board (row 7 for Player A, row 0 for Player
B) it is promoted to a dame and the letter of the ID is changed to uppercase. The dame is
moved to an empty square in the player’s first row (row 0 for Player A, row 7 for Player B).
If there is no empty square in the player’s first row the dame stays where it is and cannot
move.

The Skeleton Program presents the user with the current state of the board and shows the
possible moves that the player whose turn it is can make.

The player enters the ID of the piece they want to move, followed by the row and column of the
board square to which they want to move the piece.

The program confirms if the move was a jump and, if so which piece was jumped over.

When a player has no possible moves available when it is their turn, the game ends and that
player has lost the game.

GEMS Metropole School Page 38 of 236


Figure 3 shows a game with eight pieces that has been loaded from the game3.txt text file.

GEMS Metropole School Page 39 of 236


Figure 4 shows a game with 12 pieces that has been loaded from the game4.txt text file.

State one difference between local and global variables and give two reasons why it is good
47. practice to use local variables.

_______________________________________________________________________

_______________________________________________________________________
(Total 3 marks)

GEMS Metropole School Page 40 of 236


The algorithm below, represented using pseudo-code, outputs a numeric result.
48. The numeric result depends upon the value entered by the user.

OUTPUT "Enter a positive whole number: "


INPUT NumberIn
NumberOut ← 0

Count ← 0
WHILE NumberIn > 0
Count ← Count + 1

PartValue ← NumberIn MOD 2


NumberIn ← NumberIn DIV 2
FOR i ← 1 TO Count – 1

PartValue ← PartValue * 10
ENDFOR
NumberOut ←
NumberOut + PartValue
ENDWHILE
OUTPUT "The result is: " NumberOut

The table below lists the MOD and DIV operators for each of the available programming
languages. You should refer to the row for your programming language.

Programming language MOD DIV

C# % /

Java % /

Pascal mod div

Python % //

VB.Net Mod \

What you need to do:

Task 1
Write a program to implement the algorithm above.

Task 2
Test that your program works:
• run your program, then enter the number 22
• run your program, then enter the number 29
• run your program, then enter the number -1

Evidence that you need to provide

(a) Your PROGRAM SOURCE CODE for Task 1.


(11)

GEMS Metropole School Page 41 of 236


(b) SCREEN CAPTURE(S) showing the test described in Task 2.
(1)

(c) What is the purpose of this algorithm?


(1)
(Total 13 marks)

State the name of an identifier for:


49.
(a) a variable that is used to store a Boolean value.

___________________________________________________________________

___________________________________________________________________
(1)

(b) a user-defined subroutine that returns a single Boolean value.

___________________________________________________________________

___________________________________________________________________
(1)
(Total 2 marks)

The Skeleton Program uses several data structures.


50.
State the identifier of the data structure that stores values of more than one data type.

_______________________________________________________________________

_______________________________________________________________________
(Total 1 mark)

What is the specific purpose of the exception handling construct in the subroutine SetUpBoard?
51.
_______________________________________________________________________

_______________________________________________________________________
(Total 1 mark)

This question refers to the subroutines Game and ListPossibleMoves.


52.
Describe what is contained in the parameter PlayersPieces when ListPossibleMoves is
called for the first time in the subroutine Game.

_______________________________________________________________________

_______________________________________________________________________
(Total 1 mark)

GEMS Metropole School Page 42 of 236


The chart below shows an incomplete hierarchy for part of the Skeleton Program.
53.
With reference to the Skeleton Program and the chart below, answer questions (a) to (c).

(a) What should be written in box (a) in the chart?

___________________________________________________________________

___________________________________________________________________
(1)

(b) What should be written in box (b) in the chart?

___________________________________________________________________

___________________________________________________________________
(1)

(c) What should be written in box (c) in the chart?

___________________________________________________________________

___________________________________________________________________
(1)
(Total 3 marks)

GEMS Metropole School Page 43 of 236


This question refers to the subroutine CreateNewBoard.
54.
Describe what the selection structure in this subroutine does.

_______________________________________________________________________

_______________________________________________________________________

_______________________________________________________________________

_______________________________________________________________________

_______________________________________________________________________

_______________________________________________________________________
(Total 3 marks)

This question refers to the subroutine SelectMove.


55.
Explain what happens in the first WHILE loop that terminates when a valid piece has been found.

_______________________________________________________________________

_______________________________________________________________________

_______________________________________________________________________

_______________________________________________________________________

_______________________________________________________________________

_______________________________________________________________________

_______________________________________________________________________

_______________________________________________________________________

_______________________________________________________________________

_______________________________________________________________________
(Total 5 marks)

(a) This question refers to the subroutine SelectMove. This subroutine makes three calls to the
56. subroutine DisplayErrorCode to notify the user of errors. The error codes passed as
parameters are to be made more informative for the user.

What you need to do:

Task 1
Modify the subroutine DisplayErrorCode so that meaningful error messages are
displayed for each type of error explaining the circumstances which caused each error. The
error code should also be displayed.

GEMS Metropole School Page 44 of 236


Task 2
Test that the changes you have made work by conducting the following test:

• run the program


• enter Y
• load game1.txt
• enter the string a4
• enter the string a9
• enter 3
• enter 4
• enter a
• enter 9
• enter 3
• enter 0

Evidence that you need to provide

(i) Your PROGRAM SOURCE CODE for the entire subroutine DisplayErrorCode
(3)

(ii) SCREEN CAPTURE(S) showing the requested test including the list of possible
moves for Player A.
(1)

(b) This question refers to the subroutine ValidJump. The rules of the game are to be
amended. Instead of jumping over their own piece, a player can only jump over an
opponent’s piece.

What you need to do:

Task 1
Amend the subroutine ValidJump so that a jump is only possible if the middle piece
belongs to the opponent.

Task 2
Test that the changes you have made work by conducting the following test:

• run the program


• enter Y
• load game3.txt
• enter the string a5
• enter 5
• enter 0

Evidence that you need to provide

(i) Your PROGRAM SOURCE CODE for the entire subroutine ValidJump.
(2)

(ii) SCREEN CAPTURE(S) showing the requested test including the list of possible
moves before the jump and your test input, and then the board display after the
jump.
(1)

GEMS Metropole School Page 45 of 236


(c) This question refers to the subroutine PrintResult. The rules of the game are to be
amended. The game still ends when a player cannot make a move, but the winner is to be
determined using a formula that calculates a score for each player. The winner is the player
with the lowest score. The formula to calculate the score is shown in the information box
below.

What you need to do:

Task 1
Create a new subroutine CountNumberOfPieces. This subroutine is to count the number of
pieces a player has on the board.

Task 2
Amend the subroutine PrintResult to implement the formula given in the information box
above and output the score for each player and display the winner.

You must consider the possibility of a draw.

Task 3
• run the program
• enter Y
• load game4.txt

Evidence that you need to provide

(i) Your PROGRAM SOURCE CODE for the entire subroutine.


CountNumberOfPieces and the entire subroutine PrintResult.
(9)

(ii) SCREEN CAPTURE(S) showing all the output from the requested test including the
board display.
(1)

(d) This question will further change the rules of the game.

When a piece is promoted to a dame, the player who the new dame belongs to now
chooses one of the opponent’s pieces. This piece is removed from the board and the dame
is placed in the square the removed piece was in.

(i) State the identifier of the data structure that now needs to be passed as a parameter
into the subroutine MoveDame.
(1)

GEMS Metropole School Page 46 of 236


What you need to do:

Task 1
Amend the subroutine MoveDame.

This subroutine is to:

• ask the player the piece ID of the opponent’s piece they want to remove
• check that the piece is an opponent’s piece and is on the board
• remove the opponent’s piece
• return the coordinates for the new dame.

Task 2
Amend the calls to MoveDame from within the subroutine MovePiece.

You will need to amend the parameter list of the subroutine heading of MovePiece
and the call to MovePiece from within the subroutine MakeMove.

Task 3
Test that the changes you have made work by conducting the following test:

• run the program


• enter Y
• load game3.txt
• move a2 to row 7, column 0
• take piece b1

Task 4
• move b5 to row 0, column 3
• take piece a6

Evidence that you need to provide

(ii) Your PROGRAM SOURCE CODE for the entire subroutine MoveDame and the entire
subroutine MakeMove.
(9)

(iii) SCREEN CAPTURE(S) showing the requested test including the board display after
piece b1 has been taken.
(1)

(iv) SCREEN CAPTURE(S) showing the requested test including the board display after
piece a6 has been taken.
(1)
(Total 29 marks)

GEMS Metropole School Page 47 of 236


Morse code
57.
The Skeleton Program accompanying this Preliminary Material is a program for converting
between plain text and Morse code.

Samuel Morse invented a code that allowed the transmission of text using simple on-off signals.
The code differentiates between short and long signals, usually represented as dots and dashes.

For example, ships within line of sight could use a light turned on and off to communicate with
each other. Early telegraph communication used electrical pulses that were converted into
sound.

Each letter of the alphabet is represented by a unique combination of dots and dashes. Different
letters may have a different number of dots and / or dashes. For example, the letter T is
represented by a single dash and the letter H is represented by four dots.

Morse codes for each letter in the alphabet are shown in Table 1.

Table 1
A .–
B –...
C –.–.
D –..
E .
F ..–.
G ––.
H ....
I ..
J .–––
K –.–
L .–..
M ––
N –.
O –––
P .––.
Q ––.–
R .–.
S ...
T –
U ..–
V ...–
W .––
X –..–
Y –.––
Z ––..

GEMS Metropole School Page 48 of 236


The codes can be represented using a tree, as shown in Figure 1. Starting at the root of the tree,
taking a left branch generates a dash and taking a right branch generates a dot.

For example, the letter D has a Morse code generated by first taking the left branch (dash), then
two right branches (dot, dot). So the code for the letter D is dash, dot, dot.

Figure 1

However, there can be confusion over where letters start and end. For example, the signals for
the letters TEA (T is dash; E is dot and A is dot, dash) are the same as for the letter X (X is dash,
dot, dot, dash).

To indicate where a letter ends when writing Morse codes, a space is placed between signals
representing letters, shown in this Preliminary Material with a ⌂ character. So TEA becomes:

GEMS Metropole School Page 49 of 236


A Morse code message can be decoded using the diagram in Figure 1. For each new group of
dots and / or dashes, start at the root of the tree. When reading a dash, take the left branch,
when reading a dot, take the right branch. When the end of the signal is reached the node of the
tree reached represents the letter corresponding to that signal.

For example, the message is decoded as shown in Figure 2 and Figure 3.

The group decodes as N:

Figure 2

GEMS Metropole School Page 50 of 236


The group decodes as O:

Figure 3

When writing Morse code, each letter is separated from the next letter by one space and a word
is separated from the next word by three spaces. There are no spaces after the last letter in a
message.

Two English messages and their Morse codes are shown in Table 2.

Table 2

English message Morse code


SOS ...⌂–––⌂...
TEA X –⌂.⌂.–⌂⌂⌂–..–

When using light or sound to transmit Morse code, a short pause is required between two
signals.
The rules of transmission when using light or sound are:

• a transmission may have leading and trailing spaces


• a transmission consists of time units, each of which is either on or off (light / sound or no
light / sound)
• a dot is one time unit of light / sound followed by an interval of no light / sound lasting one
time unit
• a dash is three time units of light / sound followed by an interval of no light / sound lasting
one time unit
• There is an interval of no light / sound between characters lasting an extra two time units
(making 3 time units in total between characters)
• There is an interval of no light / sound between words lasting an extra four time units
(making 7 time units in total between words – 1 unit after the dot / dash, 2 extra units after
the character and 4 extra units after the word)

GEMS Metropole School Page 51 of 236


Examples of transmission signals are shown in Table 3.

Table 3

Message Morse code Transmission signals


SOS ...⌂–––⌂... =⌂=⌂=⌂⌂⌂===⌂===⌂===⌂⌂⌂=⌂=⌂=⌂
TEA X –⌂.⌂.–⌂⌂⌂–..– ===⌂⌂⌂=⌂⌂⌂=⌂===⌂⌂⌂⌂⌂⌂⌂===⌂=⌂=⌂===⌂

GEMS Metropole School Page 52 of 236


The transmission signal contained in the Data File Message.txt is shown in Figure 4.

Figure 4

Index Signal

0 =
1 =
2 =
3 ⌂
4 ⌂
5 ⌂
6 =
7 ⌂
8 ⌂
9 ⌂
10 =
11 ⌂
12 =
13 =
14 =
15 ⌂
16 ⌂
17 ⌂
18 ⌂
19 ⌂
20 ⌂
21 ⌂
22 =
23 =
24 =
25 ⌂
26 =
27 ⌂
28 =
29 ⌂
30 =
31 =
32 =
33 ⌂

GEMS Metropole School Page 53 of 236


The Skeleton Program stores each letter of the alphabet in the data structure Letter. The
Morse code for each letter is stored in the data structure MorseCode.

Index Letter Morse code

0 SPACE SPACE

1 A .-
2 B -...
3 C -.-.
4 D -..
5 E .
6 F ..-.
7 G --.
8 H ....
9 I ..
10 J .---
11 K -.-
12 L .-..
13 M --
14 N -.
15 O ---
16 P .--.
17 Q --.-
18 R .-.
19 S ...
20 T -
21 U ..-
22 V ...-
23 W .--
24 X -..-
GEMS Metropole School Page 54 of 236
25 Y -.--
26 Z --..
The data structure Letter stores the data shown at the nodes of the tree in Figure 1. Two
further data structures, Dash and Dot, are used to represent the information on how the nodes
are connected. These connections are known as pointers.

For example, the letter A is stored at index 1 in Letter. The left branch from A goes to W, stored
at index 23, so Dash at index 1 stores the pointer value 23. The right branch from A goes to R,
stored at index 18, so Dot at index 1 stores the pointer value 18.

GEMS Metropole School Page 55 of 236


When there is no node to the left or right, the pointer value is 0 (zero).

Index Dash Letter Dot

0 20 SPACE 5

1 23 A 18

2 0 B 0

3 0 C 0

4 24 D 2

5 1 E 9

6 0 F 0

7 17 G 26

8 0 H 0

9 21 I 19

10 0 J 0

11 25 K 3

12 0 L 0

13 15 M 7

14 11 N 4

15 0 O 0

16 0 P 0

17 0 Q 0

18 0 R 12

19 22 S 8

20 13 T 14

21 0 U 6

22 0 V 0

23 10 W 16

24 0 X 0

25 0 Y 0

26 0 Z 0

The Skeleton Program presents the user with a menu that allows the user to choose between
sending and receiving a message using Morse code.

Receiving a message involves reading a text file containing a transmission string (see Figure 4)
and converting this first into dots and dashes and then into letters of the alphabet.

Sending a message asks the user to enter a message using uppercase letters and spaces. The
program will then output the dots and dashes of the equivalent Morse code message, including
the correct number of spaces between characters and words.

GEMS Metropole School Page 56 of 236


The algorithm below, represented using pseudo-code, describes a method to test whether an
58. integer greater than 2 is prime or not.

INPUT Number
Root ←
1
WHILE (Root * Root) < Number
Root ← Root + 1
ENDWHILE
d ← 2

FactorFound ←
FALSE
WHILE (FactorFound = FALSE) AND (d <= Root)
r ←Number MOD d
IF r = 0 THEN
FactorFound ← TRUE
ENDIF
d ←
d + 1
ENDWHILE
IF FactorFound = FALSE THEN
OUTPUT "Prime"
ELSE
OUTPUT "Not prime"
ENDIF

The MOD operator calculates the remainder resulting from an integer division, for example, 10
MOD 3 = 1.

(a) Complete the table below by hand-tracing the algorithm. Use 5 as the input value. You may
not need to use all the rows in the table.

Number Root d FactorFound r Output

(3)

GEMS Metropole School Page 57 of 236


(b) Complete the table below by hand-tracing the algorithm. Use 25 as the input value. You
may not need to use all the rows in the table.

Number Root d FactorFound r Output

(3)
(Total 6 marks)

The algorithm, represented using pseudo-code below, outputs a series of numbers. The contents
59. of the series depends on the initial value entered by the user.

Number 0←
WHILE (Number < 1) OR (Number > 10)
OUTPUT “Enter a positive whole number: ”
INPUT Number
IF Number > 10 THEN
OUTPUT “Number too large.”
ELSE
IF Number < 1 THEN
OUTPUT “Not a positive number.”
ENDIF
ENDIF
ENDWHILE
c ← 1

FOR k ←
0 TO Number − 1
OUTPUT c
c ←
(c * (Number − 1 − k)) DIV (k + 1)
ENDFOR

GEMS Metropole School Page 58 of 236


The Div operator calculates the result of an integer division, for example, 10 DIV 3 = 3.

What you need to do:

Task 1
Write a program to implement the algorithm above.

Task 2
Test the program by showing the result of entering:
−3
then 11
then 10

Evidence that you need to provide

(a) Your PROGRAM SOURCE CODE for Task 1.


(9)

(b) SCREEN CAPTURE(S) showing the test described in Task 2.


(1)
(Total 10 marks)

State the name of an identifier for:


60.
(a) a variable that is used to store a Boolean value.

___________________________________________________________________

___________________________________________________________________
(1)

(b) a user-defined subroutine that returns a single character.

___________________________________________________________________

___________________________________________________________________
(1)
(Total 2 marks)

GEMS Metropole School Page 59 of 236


Mark schemes
5 marks for AO2 (apply)
1.

1 mark for area A correct;


1 mark for area B correct;
1 mark for area C correct;
1 mark for area D correct;
1 mark for area E correct;

Award a mark if the values in an area are correct regardless of which row they are on so long as
they are in the correct overall sequence in a column.

I. duplicated values instead of blanks

Max 4 if any errors


[5]

GEMS Metropole School Page 60 of 236


2 marks for AO1 (knowledge)
2.
Global variable can be used anywhere in program // global variable is declared in outmost block /
outside subroutines;
Local variable can only be used in the block / subroutine in which it is declared;

Alternative answer 1:

Local variables only use memory when the program block they are in is executing; global
variables use memory the entire time the program is executing;

Alternative answer 2:

Local variables only exist when the program block they are in is executing; global variables exist
the entire time the program is running;

A. local variables are stored on a stack / in a stack frame; global variables are generally stored
elsewhere in the memory;
[2]

(a) 9 marks for AO3 (programming)


3.
Mark as follows:
1) Correct variable declarations for Number, X, Count, Multi;

Note to examiners
If a language allows variables to be used without explicit declaration (eg Python) then
this mark should be awarded if the correct variables exist in the program code and
the first value they are assigned is of the correct data type.

2) Correct prompt "Enter an integer greater than 1: " and Number


assigned integer value entered by user;
3) Correct initialisation of X and Count before outer WHILE loop;
4) Correct outer WHILE loop with syntax allowed by the programming language
and correct condition for termination of the outer loop;
5) Correct assignment of Multi in outer loop;
6) Correct inner WHILE loop syntax allowed by the programming language and
correct condition for termination of the loop;
7) IF statement with correct condition and output within inner loop;
8) Correct incrementation of Count and correct assignment to Multi and Number
within inner WHILE loop;
9) Correct assignments of X in outer loop;

I. minor differences in case and spelling

Max 8 if code does not function correctly


9

GEMS Metropole School Page 61 of 236


(b) Mark is for AO3 (evaluate)

**** SCREEN CAPTURE ****


Must match code from (a), including prompts on screen capture matching those in
code.
Code for (a) must be sensible.

Screen capture showing:


'23' being entered and ‘23’ displayed followed, by '1'
'25' being entered and the message '5' displayed, followed by '2'
'1260' being entered and ‘2 3 5 7’ displayed, followed by '6'

(Accept on same or separate lines)

Enter a number greater than 1: 23


23
1
>>>
Enter a number greater than 1: 25
5
2
>>>
Enter a number greater than 1: 1260
2
3
5
7
6
>>>

Alternative:

Enter a number greater than 1: 23


23
1
>>>
Enter a number greater than 1: 25
5
2
>>>
Enter a number greater than 1: 1260
2 3 5 7
6
>>>

GEMS Metropole School Page 62 of 236


VB.Net

Console.Write("Enter an integer greater than 1: ") 'MP2


Dim Number As Integer = Console.ReadLine()
Dim X As Integer = 2 'MP1
Dim Count As Integer = 0 'MP3
Dim Multi As Boolean
While Number > 1 'MP4
Multi = False 'MP5
While (Number Mod X) = 0 'MP6
If Not Multi Then 'MP7
Console.WriteLine(X)
End If
Count = Count + 1
Multi = True
Number = Number \ X 'MP8
End While
X = X + 1 'MP9
End While
Console.WriteLine(Count)

Python 3

Number = int(input("Enter a number greater than 1: ")) # MP2


X = 2 # MP1
Count = 0 # MP3
while Number > 1: # MP4
Multi = False # MP5
while Number % X == 0: # MP6
if not Multi: # MP7
print(X, end = ' ')
Count += 1 #
Multi = True #
Number = Number // X # MP8
X = X + 1 # MP9
print(Count)

Python 2

Number = int(raw_input("Enter a number greater than 1: ")) # MP2


X = 2 # MP1
Count = 0 # MP3
while Number > 1: # MP4
Multi = False # MP5
while Number % X == 0: # MP6
if not Multi: # MP7
print X
Count += 1 #
Multi = True #
Number = Number // X # MP8
X = X + 1 # MP9
print Count

GEMS Metropole School Page 63 of 236


Pascal

var
Number, X, Count : integer; // MP1
Multi : boolean;

begin
write('Enter a number greater than 1: ');
readln(Number); // MP2
X := 2;
Count := 0; // MP3
while Number > 1 do // MP4
begin
Multi := false; // MP5
while Number Mod X = 0 do // MP6
begin
if not Multi // MP7
then
writeln(X);
Count := Count + 1;
Multi := true;
Number := Number DIV X; // MP8
end;
X := X + 1; // MP9
end;
writeln(Count);
readln;
end.

C#

bool multi;
Console.Write("Enter an integer greater than 1: ");
int number = Convert.ToInt32(Console.ReadLine()); // MP2
int x = 2; // MP1
int count = 0; // MP3
while (number > 1) // MP4
{
multi = false; // MP5
while (number % x == 0) // MP6
{
if (!multi) // MP7
{
Console.WriteLine(x);
}
count++;
multi = true;
number = number / x; // MP8
}
x++; // MP9
}
Console.WriteLine(count);

GEMS Metropole School Page 64 of 236


Java

Console.println("Enter an integer greater than 1: ");


int number = Integer.parseInt(Console.readLine()); // MP2
int x = 2; // MP1
int count = 0; // MP3
while (number > 1) { // MP4
boolean multi = false; // MP5
while (number % x == 0) { // MP6
if (!multi) { // MP7
Console.writeLine(x);
}
count += 1;
multi = true;
number = number / x; // MP8
}
x += 1; // MP9
}
Console.writeLine(count);
1
[10]

(a) Mark is for AO1 (understand)


4.
FileExists / Finished;

A. OpCodeExists, Found (Pascal only)


R. if any additional code
R. if spelt incorrectly
I. case & spacing
1

(b) Mark is for AO1 (understand)

ConvertToDecimal;

R. if any additional code


R. if spelt incorrectly
I. case & spacing
1

(c) Mark is for AO1 (understand)

GetMenuOption;

R. if any additional code


R. if spelt incorrectly
I. case & spacing
1

GEMS Metropole School Page 65 of 236


(d) Mark is for AO1 (understand)

LoadFile / PassTwo;

A. Readline (Java only)


R. if any additional code
R. if spelt incorrectly
I. case & spacing
1
[4]

(a) Mark is for AO1 (understand)


5.
AssemblerInstruction;

A. Memory / SymbolTable;
R. if any additional code
R. if spelt incorrectly
I. case & spacing

Max 1
1

(b) Mark is for AO1 (understand)

SourceCode / Registers / OpCodeValues;

A. Memory / SymbolTable; (if neither given in part (a))


R. if any additional code
R. if spelt incorrectly
I. case & spacing

Max 1
1
[2]

5 marks are for AO2 (analyse)


6.
Proposed error message Error code

Duplicate label found 3

File not found 1

No assembled code to run 10

No source code to display 7

Unknown opcode 5

1 mark for each correct error code


R. if more than one error code assigned to an error message
[5]

GEMS Metropole School Page 66 of 236


2 marks for AO2 (analyse)
7.
Operand is not empty / an empty string;
Operand is not an existing label // Operand is not in the symbol table; NE. invalid operand
Operand is not (the string representation of) a number;

Max 2
[2]

(a) 2 marks for AO2 (analyse)


8.
Check each character in the line / operand; A. iterate over each character in the line /
operand
Store the position of an ‘*’ // store position of comment symbol if there is one
// store position of the start of a comment;
2

(b) 2 marks for AO2 (analyse)

If there is an ‘*’ // if there is a comment (symbol);


Only use the characters to left of ‘*’ // remove the comment (from the string);
2

(c) 2 marks for AO2 (analyse)

When code encounters a ‘*’ // When code encounters a comment (symbol);


Can stop iteration when */comment is encountered // no need to examine to the end
of the string;

Alternative answer:

If there are multiple asterisks, it finds the first one (rather than the last one);
Additional asterisks within the comment will not affect assembly;

R. a variable (ThisPosition) to hold the position wouldn't be needed


2
[6]

(a) 4 marks for AO3 (programming)


9.
Mark as follows:

1) Add required parameter to subroutine call in Execute;


2) Add required parameter to ExecuteSKP definition;
3) Add 1 to Registers[ACC];
4) Update status register (by calling SetFlags with correct parameters);

Max 3 if any errors


4

GEMS Metropole School Page 67 of 236


(b) Mark is for AO3 (evaluate)

**** SCREEN CAPTURE ****


Must match code from (a), including prompts on screen capture matching those in
code.
Code for (a) must be sensible.

Screen capture showing (values changing from Frame 0 to Frame 5 shown


highlighted):

GEMS Metropole School Page 68 of 236


VB.Net

Sub ExecuteSKP(Registers() As Integer) ' MP2


Registers(ACC) += 1 'MP3
SetFlags(Registers(ACC), Registers) 'MP4
End Sub

Sub Execute(ByVal SourceCode() As String, ByVal Memory() As


AssemblerInstruction)
Dim Registers() As Integer = {0, 0, 0, 0, 0}
SetFlags(Registers(ACC), Registers)
Registers(PC) = 0
Registers(TOS) = HI_MEM
Dim FrameNumber As Integer = 0
DisplayFrameDelimiter(FrameNumber)
DisplayCurrentState(SourceCode, Memory, Registers)
Dim OpCode As String = Memory(Registers(PC)).OpCode
While OpCode <> "HLT"
FrameNumber += 1
Console.WriteLine()
DisplayFrameDelimiter(FrameNumber)
Dim Operand As Integer = Memory(Registers(PC)).OperandValue
Console.WriteLine($"* Current Instruction Register: {OpCode}
{Operand}")
Registers(PC) += 1
Select Case OpCode
Case "LDA"
ExecuteLDA(Memory, Registers, Operand)
Case "STA"
ExecuteSTA(Memory, Registers, Operand)
Case "LDA#"
ExecuteLDAimm(Registers, Operand)
Case "ADD"
ExecuteADD(Memory, Registers, Operand)
Case "JMP"
ExecuteJMP(Registers, Operand)
Case "JSR"
ExecuteJSR(Memory, Registers, Operand)
Case "CMP#"
ExecuteCMPimm(Registers, Operand)
Case "BEQ"
ExecuteBEQ(Registers, Operand)
Case "SUB"
ExecuteSUB(Memory, Registers, Operand)
Case "SKP"
ExecuteSKP(Registers) 'MP1
Case "RTN"
ExecuteRTN(Memory, Registers)
End Select
If Registers(ERR) = 0 Then
OpCode = Memory(Registers(PC)).OpCode
DisplayCurrentState(SourceCode, Memory, Registers)
Else
OpCode = "HLT"
End If
End While
Console.WriteLine("Execution terminated")
End Sub

GEMS Metropole School Page 69 of 236


Python 3

def ExecuteSKP(Registers): # MP2


Registers[ACC] = Registers[ACC] + 1 # MP3
Registers = SetFlags(Registers[ACC], Registers) # MP4

def Execute(SourceCode, Memory):


Registers = [0, 0, 0, 0, 0]
Registers = SetFlags(Registers[ACC], Registers)
Registers[PC] = 0
Registers[TOS] = HI_MEM
FrameNumber = 0
DisplayFrameDelimiter(FrameNumber)
DisplayCurrentState(SourceCode, Memory, Registers)
OpCode = Memory[Registers[PC]].OpCode
while OpCode != "HLT":
FrameNumber += 1
print()
DisplayFrameDelimiter(FrameNumber)
Operand = Memory[Registers[PC]].OperandValue
print("* Current Instruction Register: ", OpCode, Operand)
Registers[PC] = Registers[PC] + 1
if OpCode == "LDA":
Registers = ExecuteLDA(Memory, Registers, Operand)
elif OpCode == "STA":
Memory = ExecuteSTA(Memory, Registers, Operand)
elif OpCode == "LDA#":
Registers = ExecuteLDAimm(Registers, Operand)
elif OpCode == "ADD":
Registers = ExecuteADD(Memory, Registers, Operand)
elif OpCode == "JMP":
Registers = ExecuteJMP(Registers, Operand)
elif OpCode == "JSR":
Memory, Registers = ExecuteJSR(Memory, Registers, Operand)
elif OpCode == "CMP#":
Registers = ExecuteCMPimm(Registers, Operand)
elif OpCode == "BEQ":
Registers = ExecuteBEQ(Registers, Operand)
elif OpCode == "SUB":
Registers = ExecuteSUB(Memory, Registers, Operand)
elif OpCode == "SKP":
ExecuteSKP(Registers) # MP1
elif OpCode == "RTN":
Registers = ExecuteRTN(Memory, Registers)
if Registers[ERR] == 0:
OpCode = Memory[Registers[PC]].OpCode
DisplayCurrentState(SourceCode, Memory, Registers)
else:
OpCode = "HLT"
print("Execution terminated")

GEMS Metropole School Page 70 of 236


Python 2

def ExecuteSKP(Registers): # MP2


Registers[ACC] = Registers[ACC] + 1 # MP3
Registers = SetFlags(Registers[ACC], Registers) # MP4

def Execute(SourceCode, Memory):


Registers = [0, 0, 0, 0, 0]
Registers = SetFlags(Registers[ACC], Registers)
Registers[PC] = 0
Registers[TOS] = HI_MEM
FrameNumber = 0
DisplayFrameDelimiter(FrameNumber)
DisplayCurrentState(SourceCode, Memory, Registers)
OpCode = Memory[Registers[PC]].OpCode
while OpCode != "HLT":
FrameNumber += 1
print
DisplayFrameDelimiter(FrameNumber)
Operand = Memory[Registers[PC]].OperandValue
print "* Current Instruction Register: ", OpCode, Operand
Registers[PC] = Registers[PC] + 1
if OpCode == "LDA":
Registers = ExecuteLDA(Memory, Registers, Operand)
elif OpCode == "STA":
Memory = ExecuteSTA(Memory, Registers, Operand)
elif OpCode == "LDA#":
Registers = ExecuteLDAimm(Registers, Operand)
elif OpCode == "ADD":
Registers = ExecuteADD(Memory, Registers, Operand)
elif OpCode == "JMP":
Registers = ExecuteJMP(Registers, Operand)
elif OpCode == "JSR":
Memory, Registers = ExecuteJSR(Memory, Registers, Operand)
elif OpCode == "CMP#":
Registers = ExecuteCMPimm(Registers, Operand)
elif OpCode == "BEQ":
Registers = ExecuteBEQ(Registers, Operand)
elif OpCode == "SUB":
Registers = ExecuteSUB(Memory, Registers, Operand)
elif OpCode == "SKP":
ExecuteSKP(Registers) # MP1
elif OpCode == "RTN":
Registers = ExecuteRTN(Memory, Registers)
if Registers[ERR] == 0:
OpCode = Memory[Registers[PC]].OpCode
DisplayCurrentState(SourceCode, Memory, Registers)
else:
OpCode = "HLT"
print "Execution terminated"

GEMS Metropole School Page 71 of 236


Pascal

procedure ExecuteSKP(var Registers: TRegisters); // MP2


begin
Registers[ACC] := Registers[ACC] + 1; // MP3
SetFlags(Registers[ACC], Registers); // MP4
end;

procedure Execute(var SourceCode: TSourceCode; var Memory: TMemory);


var
Registers: TRegisters;
OpCode: string;
Operand, FrameNumber: integer;
begin
Registers := TRegisters.create(0, 0, 0, 0, 0);
SetFlags(Registers[ACC], Registers);
Registers[PC] := 0;
Registers[TOS] := HI_MEM;
FrameNumber := 0;
DisplayFrameDelimiter(FrameNumber);
DisplayCurrentState(SourceCode, Memory, Registers);
OpCode := Memory[Registers[PC]].OpCode;
while OpCode <> 'HLT' do
begin
FrameNumber := FrameNumber + 1;
writeln;
DisplayFrameDelimiter(FrameNumber);
Operand := Memory[Registers[PC]].OperandValue;
writeln('* Current Instruction Register: ', OpCode, ' ', Operand);
Registers[PC] := Registers[PC] + 1;
if OpCode = 'LDA' then ExecuteLDA(Memory, Registers, Operand);
if OpCode = 'STA' then ExecuteSTA(Memory, Registers, Operand);
if OpCode = 'LDA#' then ExecuteLDAimm(Registers, Operand);
if OpCode = 'ADD' then ExecuteADD(Memory, Registers, Operand);
if OpCode = 'JMP' then ExecuteJMP(Registers, Operand);
if OpCode = 'JSR' then ExecuteJSR(Memory, Registers, Operand);
if OpCode = 'CMP#' then ExecuteCMPimm( Registers, Operand);
if OpCode = 'BEQ' then ExecuteBEQ(Registers, Operand);
if OpCode = 'SUB' then ExecuteSUB(Memory, Registers, Operand);
if OpCode = 'SKP' then ExecuteSKP(Registers); // MP1
if OpCode = 'RTN' then ExecuteRTN(Memory, Registers);
if Registers[ERR] = 0
then
begin
OpCode := Memory[Registers[PC]].OpCode;
DisplayCurrentState(SourceCode, Memory, Registers);
end
else
OpCode := 'HLT';
end;
writeln('Execution terminated');
end;

GEMS Metropole School Page 72 of 236


C#

private static void ExecuteSKP(int[] registers) // MP2


{
registers[ACC] = registers[ACC] + 1; // MP3
SetFlags(registers[ACC], registers); // MP4
}

private static void Execute(string[] sourceCode, AssemblerInstruction[]


memory)
{
int[] registers = new int[] { 0, 0, 0, 0, 0 };
int frameNumber = 0, operand = 0;
SetFlags(registers[ACC], registers);
registers[PC] = 0;
registers[TOS] = HI_MEM;
DisplayFrameDelimiter(frameNumber);
DisplayCurrentState(sourceCode, memory, registers);
string opCode = memory[registers[PC]].opCode;
while (opCode != "HLT")
{
frameNumber++;
Console.WriteLine();
DisplayFrameDelimiter(frameNumber);
operand = memory[registers[PC]].operandValue;
Console.WriteLine($"* Current Instruction Register: {opCode}
{operand}");
registers[PC] = registers[PC] + 1;
switch (opCode)
{
case "LDA":
ExecuteLDA(memory, registers, operand); break;
case "STA":
ExecuteSTA(memory, registers, operand); break;
case "LDA#":
ExecuteLDAimm(registers, operand); break;
case "ADD":
ExecuteADD(memory, registers, operand); break;
case "JMP":
ExecuteJMP(registers, operand); break;
case "JSR":
ExecuteJSR(memory, registers, operand); break;
case "CMP#":
ExecuteCMPimm(registers, operand); break;
case "BEQ":
ExecuteBEQ(registers, operand); break;
case "SUB":
ExecuteSUB(memory, registers, operand); break;
case "SKP":
ExecuteSKP(registers); break; // MP1
case "RTN":
ExecuteRTN(memory, registers); break;
}
if (registers[ERR] == 0)
{
opCode = memory[registers[PC]].opCode;
DisplayCurrentState(sourceCode, memory, registers);
}
else
{

GEMS Metropole School Page 73 of 236


opCode = "HLT";
}
}
Console.WriteLine("Execution terminated");
}

GEMS Metropole School Page 74 of 236


Java

void executeSKP(int[] registers) { // MP4


registers[ACC] = registers[ACC] + 1; // MP2
setFlags(registers[ACC], registers); // MP3
}

void execute(String[] sourceCode, AssemblerInstruction[] memory)

{
int[] registers = {0, 0, 0, 0, 0} ;
setFlags(registers[ACC], registers);
registers[PC] = 0;
registers[TOS] = HI_MEM;
int frameNumber = 0;
displayFrameDelimiter(frameNumber);
displayCurrentState(sourceCode, memory, registers);
String opCode = memory[registers[PC]].opCode;
while (!opCode.equals("HLT")) {
frameNumber += 1;
Console.println();
displayFrameDelimiter(frameNumber);
int operand = memory[registers[PC]].operandValue;
Console.println("* Current instruction Register: " + opCode + " " +
operand);
registers[PC] = registers[PC] + 1;
switch (opCode) {
case "LDA":
executeLDA(memory, registers, operand); break;
case "STA":
executeSTA(memory, registers, operand); break;
case "LDA#":
executeLDAimm(registers, operand); break;
case "ADD":
executeADD(memory, registers, operand); break;
case "JMP":
executeJMP(registers, operand); break;
case "JSR":
executeJSR(memory, registers, operand); break;
case "CMP#":
executeCMPimm(registers, operand); break;
case "BEQ":
executeBEQ(registers, operand); break;
case "SUB":
executeSUB(memory, registers, operand); break;
case "SKP":
executeSKP(registers); break; // MP1
case "RTN":
executeRTN(memory, registers); break;
default:
break;
}
if (registers[ERR] == 0) {
opCode = memory[registers[PC]].opCode;
displayCurrentState(sourceCode, memory, registers);
} else {
opCode = "HLT";
}
}
Console.println("Execution terminated");

GEMS Metropole School Page 75 of 236


}
1
[5]

(a) 5 marks for AO3 (programming)


10.
Mark as follows:

1) Check for non-integer input;


2) Check within valid lower boundary;
3) Check within valid upper boundary;
4) At least 2 correct checks will be repeated until valid data is input at which point
the loop exits;
5) Output suitable error message(s) under appropriate circumstances based upon
at least 2 correct checks; R. if message is displayed when it should not be

Max 4 if any errors


5

(b) Mark is for AO3 (evaluate)

**** SCREEN CAPTURE ****

Must match code from (a), including prompts on screen capture matching those in
code.
Code for (a) must be sensible.

Screen capture showing:

Enter your choice: E


Enter line number of code to edit: Q
Not a valid number
Enter line number of code to edit: 22
Not a valid line number
Enter line number of code to edit: 0
Not a valid line number
Enter line number of code to edit: 2
SUB NUM1
E - Edit this line
C - Cancel edit
Enter your choice:

GEMS Metropole School Page 76 of 236


VB.Net

Sub EditSourceCode(ByRef SourceCode() As String)


Dim Choice As String = EMPTY_STRING
Dim LineNumber As Integer
Do
Console.Write("Enter line number of code to edit: ")
Dim Temp As String = Console.ReadLine ' MP1
If Not Integer.TryParse(Temp, LineNumber) Then
LineNumber = -1
Console.WriteLine("Not a valid number") ' MP5
End If
Loop Until LineNumber > 0 And LineNumber <=
Convert.ToInt32(SourceCode(0)) ' MP2, MP3, MP4

Console.WriteLine(SourceCode(LineNumber))
While Choice <> "C"
Choice = EMPTY_STRING
While Choice <> "E" And Choice <> "C"
Console.WriteLine("E - Edit this line")
Console.WriteLine("C - Cancel edit")
Console.Write("Enter your choice: ")
Choice = Console.ReadLine()
End While
If Choice = "E" Then
Console.Write("Enter the new line: ")
SourceCode(LineNumber) = Console.ReadLine()
End If
DisplaySourceCode(SourceCode)
End While
End Sub

Python 3

def EditSourceCode(SourceCode):
LineNumber = 0
NumberOfLines = int(SourceCode[0])
while LineNumber not in range(1, NumberOfLines + 1): # MP2, MP3, MP4
try: # MP1
LineNumber = int(input("Enter line number of code to edit: "))
if LineNumber not in range(1, NumberOfLines + 1):
print("Not a valid line number") # MP5
except:
print("Not a valid number")
print(SourceCode[LineNumber])
Choice = EMPTY_STRING
while Choice != "C":
Choice = EMPTY_STRING
while Choice != "E" and Choice != "C":
print("E - Edit this line")
print("C - Cancel edit")
Choice = input("Enter your choice: ")
if Choice == "E":
SourceCode[LineNumber] = input("Enter the new line:")
DisplaySourceCode(SourceCode)
return SourceCode

GEMS Metropole School Page 77 of 236


Alternative method:

def EditSourceCode(SourceCode):
LineNumberStr = input("Enter line number of code to edit: ")
Valid = False
while not Valid:
if LineNumberStr.isdigit() and int(LineNumberStr) > 0 and
int(LineNumberStr) <= int(SourceCode[0]): # MP1, MP2, MP3, MP4
Valid = True
LineNumber = int(LineNumberStr)
else:
print("Not a valid line number") # MP5
LineNumberStr = input("Enter line number of code to edit: ")
print(SourceCode [LineNumber])
Choice = EMPTY_STRING
while Choice != "C":
Choice = EMPTY_STRING
while Choice != "E" and Choice != "C":
print("E - Edit this line")
print("C - Cancel edit")
Choice = input("Enter your choice: ")
if Choice == "E":
SourceCode[LineNumber] = input("Enter the new line:")
DisplaySourceCode(SourceCode)
return SourceCode

Python 2

def EditSourceCode(SourceCode):
LineNumber = 0
NumberOfLines = int(SourceCode[0])
while LineNumber not in range(1, NumberOfLines + 1): # MP2, MP3, MP4
try: # MP1
LineNumber = int(raw_input("Enter line number of code to edit: ")
.replace("\r", ""))
if LineNumber not in range(1, NumberOfLines + 1):
print "Not a valid line number" # MP5
except:
print "Not a valid number"
print SourceCode[LineNumber]
Choice = EMPTY_STRING
while Choice != "C":
Choice = EMPTY_STRING
while Choice != "E" and Choice != "C":
print "E - Edit this line"
print "C - Cancel edit"
Choice = raw_input("Enter your choice: ") .replace("\r", "")
if Choice == "E":
SourceCode[LineNumber] = raw_input("Enter the new line: ")
.replace("\r", "")
DisplaySourceCode(SourceCode)
return SourceCode

GEMS Metropole School Page 78 of 236


Alternative method:

def EditSourceCode(SourceCode):
LineNumberStr = raw_input("Enter line number of code to edit: ")
.replace("\r", "")
Valid = False
while not Valid:
if LineNumberStr.isdigit() and int(LineNumberStr) > 0 and
int(LineNumberStr) <= int(SourceCode[0]): # MP1, MP2, MP3, MP4
Valid = True
LineNumber = int(LineNumberStr)
else:
print "Not a valid line number" # MP5
LineNumberStr = raw_input("Enter line number of code to edit: ")
.replace("\r", "")
print SourceCode [LineNumber]
Choice = EMPTY_STRING
while Choice != "C":
Choice = EMPTY_STRING
while Choice != "E" and Choice != "C":
print "E - Edit this line"
print "C - Cancel edit"
Choice = raw_input("Enter your choice: ") .replace("\r", "")
if Choice == "E":
SourceCode[LineNumber] = raw_input("Enter the new line:")
.replace("\r", "")
DisplaySourceCode(SourceCode)
return SourceCode

GEMS Metropole School Page 79 of 236


Pascal

procedure EditSourceCode(var SourceCode: TSourceCode);


var
LineNumber, NumberOfLines: integer;
Choice: string;
begin
LineNumber := 0;
NumberOfLines := StrToInt(SourceCode[0]);
while (LineNumber < 1) or (LineNumber >= NumberOfLines) do // MP2,
MP3, MP4
begin
try // MP1
write('Enter line number of code to edit: ');
readln(LineNumber);
if (LineNumber < 1) or (LineNumber >= NumberOfLines)
then
writeln('Not a valid line number'); // MP5
except
writeln('Not a valid number');
end;
end;
writeln(SourceCode[LineNumber]);
Choice := EMPTY_STRING;
while Choice <> 'C' do
begin
Choice := EMPTY_STRING;
while (Choice <> 'E') and (Choice <> 'C') do
begin
writeln('E - Edit this line');
writeln('C - Cancel edit');
write('Enter your choice: ');
readln(Choice);
end;
if Choice = 'E'
then
begin
writeln('Enter the new line:');
readln(SourceCode[LineNumber]);
end;
DisplaySourceCode(SourceCode);
end;
end;

GEMS Metropole School Page 80 of 236


C#

private static void EditSourceCode(string[] sourceCode)


{
int lineNumber = 0;
int numberOfLines = Convert.ToInt32(sourceCode[0]);
while (lineNumber < 1 || lineNumber >= numberOfLines) // MP2, MP3, MP4
{
Try // MP1
{
Console.Write("Enter line number of code to edit: ");
lineNumber = Convert.ToInt32(Console.ReadLine());
if (lineNumber < 1 || lineNumber >= numberOfLines)
{
Console.WriteLine("Not a valid line number"); // MP5
}
}
catch (Exception)
{
Console.WriteLine("Not a valid number");
}
}
Console.WriteLine(sourceCode[lineNumber]);
string choice = EMPTY_STRING;
while (choice != "C")
{
choice = EMPTY_STRING;
while (choice != "E" && choice != "C")
{
Console.WriteLine("E - Edit this line");
Console.WriteLine("C - Cancel edit");
Console.Write("Enter your choice: ");
choice = Console.ReadLine();
}
if (choice == "E")
{
Console.WriteLine("Enter the new line:");
sourceCode[lineNumber] = Console.ReadLine();
}
DisplaySourceCode(sourceCode);
}
}

GEMS Metropole School Page 81 of 236


Java

void editSourceCode(String[] sourceCode) {


int lineNumber;
do {
Console.print("Enter line number of code to edit: ");
try { // MP1
lineNumber = Integer.parseInt(Console.readLine());
} catch (Exception e) {
lineNumber = 0;
}
if (lineNumber < 1 || lineNumber > sourceCode.length + 1)
{
Console.println("Invalid line number please try again."); // MP5
}
} while (lineNumber < 1 || lineNumber > sourceCode.length + 1); //
MP2, MP3, MP4
Console.println(sourceCode[lineNumber]);
String choice = EMPTY_STRING;
while (!choice.equals("C")) {
choice = EMPTY_STRING;
while (!choice.equals("E") && !choice.equals("C")) {
Console.println("E - Edit this line");
Console.println("C - Cancel edit");
Console.print("Enter your choice: ");
choice = Console.readLine();
}
if (choice.equals("E")) {
Console.print("Enter the new line: ");
sourceCode[lineNumber] = Console.readLine();
displaySourceCode(sourceCode);
}
}
}
1
[6]

(a) 2 marks for AO3 (design) and 2 marks for AO3 (programming)
11.
Marking guidance:

Evidence of AO3 design – 2 points:

Evidence of design to look for in response:

1) Check in ExecuteJSR that stack does not overwrite instruction / data;


2) Recognise that instructions for JSR should only be executed if no error;

Note: AO3 (design) points are for selecting appropriate techniques to use to solve
the problem, so should be credited whether the syntax of programming language
statements is correct or not and regardless of whether the solution works.

GEMS Metropole School Page 82 of 236


Evidence of AO3 programming – 2 points:

Evidence of programming to look for in response:

3) Correct value for number of program lines passed into subroutine // check that
memory location pointed to by TOS is empty;
4) ReportRunTimeError called with suitable message in appropriate place;

Max 3 if code does not function correctly


4

(b) Mark is for AO3 (evaluate)

**** SCREEN CAPTURE ****

Must match code from (a), including prompts on screen capture matching those in
code.
Code for (a) must be sensible.

****** Frame 7 ***********************************************


* Current Instruction Register: JSR 7
Run time error: Memory Address Error
Stack contents:
----
| 3 |
| 14 |
----
Execution terminated

GEMS Metropole School Page 83 of 236


VB.Net

Sub ExecuteJSR(ByRef Memory() As AssemblerInstruction, ByRef Registers()


As Integer, ByVal Address As Integer, ByVal MaxLines As Integer)
Dim StackPointer As Integer = Registers(TOS) - 1
If StackPointer <= MaxLines Then 'MP1
ReportRunTimeError("Memory Address Error", Registers) 'MP4
Else 'MP2
Memory(StackPointer).OperandValue = Registers(PC)
Registers(PC) = Address
Registers(TOS) = StackPointer
End If
DisplayStack(Memory, Registers)
End Sub

Sub Execute(ByVal SourceCode() As String, ByVal Memory() As


AssemblerInstruction)
Dim Registers() As Integer = {0, 0, 0, 0, 0}
SetFlags(Registers(ACC), Registers)
Registers(PC) = 0
Registers(TOS) = HI_MEM
Dim FrameNumber As Integer = 0
DisplayFrameDelimiter(FrameNumber)
DisplayCurrentState(SourceCode, Memory, Registers)
Dim OpCode As String = Memory(Registers(PC)).OpCode
While OpCode <> "HLT"
FrameNumber += 1
Console.WriteLine()
DisplayFrameDelimiter(FrameNumber)
Dim Operand As Integer = Memory(Registers(PC)).OperandValue
Console.WriteLine($"* Current Instruction Register: {OpCode}
{Operand}")
Registers(PC) += 1
Select Case OpCode
Case "LDA"
ExecuteLDA(Memory, Registers, Operand)
Case "STA"
ExecuteSTA(Memory, Registers, Operand)
Case "LDA#"
ExecuteLDAimm(Registers, Operand)
Case "ADD"
ExecuteADD(Memory, Registers, Operand)
Case "JMP"
ExecuteJMP(Registers, Operand)
Case "JSR"
ExecuteJSR(Memory, Registers, Operand,
Int(SourceCode(0))) 'MP3
Case "CMP#"
ExecuteCMPimm(Registers, Operand)
Case "BEQ"
ExecuteBEQ(Registers, Operand)
Case "SUB"
ExecuteSUB(Memory, Registers, Operand)
Case "SKP"
ExecuteSKP()
Case "RTN"
ExecuteRTN(Memory, Registers)
End Select
If Registers(ERR) = 0 Then
OpCode = Memory(Registers(PC)).OpCode

GEMS Metropole School Page 84 of 236


DisplayCurrentState(SourceCode, Memory, Registers)
Else
OpCode = "HLT"
End If
End While
Console.WriteLine("Execution terminated")
End Sub

GEMS Metropole School Page 85 of 236


Python 3

def ExecuteJSR(Memory, Registers, Address, MaxLines):


StackPointer = Registers[TOS] - 1
if StackPointer <= MaxLines: # MP1
ReportRunTimeError("Memory Address Error", Registers) # MP4
else: # MP2
Memory[StackPointer].OperandValue = Registers[PC]
Registers[PC] = Address
Registers[TOS] = StackPointer
DisplayStack(Memory, Registers)
return Memory, Registers

def Execute(SourceCode, Memory):


Registers = [0, 0, 0, 0, 0]
Registers = SetFlags(Registers[ACC], Registers)
Registers[PC] = 0
Registers[TOS] = HI_MEM
FrameNumber = 0
DisplayFrameDelimiter(FrameNumber)
DisplayCurrentState(SourceCode, Memory, Registers)
OpCode = Memory[Registers[PC]].OpCode
while OpCode != "HLT":
FrameNumber += 1
print()
DisplayFrameDelimiter(FrameNumber)
Operand = Memory[Registers[PC]].OperandValue
print("* Current Instruction Register: ", OpCode, Operand)
Registers[PC] = Registers[PC] + 1
if OpCode == "LDA":
Registers = ExecuteLDA(Memory, Registers, Operand)
elif OpCode == "STA":
Memory = ExecuteSTA(Memory, Registers, Operand)
elif OpCode == "LDA#":
Registers = ExecuteLDAimm(Registers, Operand)
elif OpCode == "ADD":
Registers = ExecuteADD(Memory, Registers, Operand)
elif OpCode == "JMP":
Registers = ExecuteJMP(Registers, Operand)
elif OpCode == "JSR":
Memory, Registers = ExecuteJSR(Memory, Registers, Operand,
int(SourceCode[0])) # MP3
elif OpCode == "CMP#":
Registers = ExecuteCMPimm(Registers, Operand)
elif OpCode == "BEQ":
Registers = ExecuteBEQ(Registers, Operand)
elif OpCode == "SUB":
Registers = ExecuteSUB(Memory, Registers, Operand)
elif OpCode == "SKP":
ExecuteSKP()
elif OpCode == "RTN":
Registers = ExecuteRTN(Memory, Registers)
if Registers[ERR] == 0:
OpCode = Memory[Registers[PC]].OpCode
DisplayCurrentState(SourceCode, Memory, Registers)
else:
OpCode = "HLT"
print("Execution terminated")

GEMS Metropole School Page 86 of 236


Alternative method:

def ExecuteJSR(Memory, Registers, Address):


StackPointer = Registers[TOS] - 1
if Memory[StackPointer].OperandString != "" or
Memory[StackPointer].OpCode != "": # MP1, MP3
ReportRunTimeError("Memory Address Error", Registers) # MP4
else: #MP2
Memory[StackPointer].OperandValue = Registers[PC]
Registers[PC] = Address
Registers[TOS] = StackPointer
DisplayStack(Memory, Registers)
return Memory, Registers

GEMS Metropole School Page 87 of 236


Python 2

def ExecuteJSR(Memory, Registers, Address, MaxLines):


StackPointer = Registers[TOS] - 1
if StackPointer <= MaxLines: # MP1
ReportRunTimeError("Memory Address Error", Registers) # MP4
else: # MP2
Memory[StackPointer].OperandValue = Registers[PC]
Registers[PC] = Address
Registers[TOS] = StackPointer
DisplayStack(Memory, Registers)
return Memory, Registers

def Execute(SourceCode, Memory):


Registers = [0, 0, 0, 0, 0]
Registers = SetFlags(Registers[ACC], Registers)
Registers[PC] = 0
Registers[TOS] = HI_MEM
FrameNumber = 0
DisplayFrameDelimiter(FrameNumber)
DisplayCurrentState(SourceCode, Memory, Registers)
OpCode = Memory[Registers[PC]].OpCode
while OpCode != "HLT":
FrameNumber += 1
print
DisplayFrameDelimiter(FrameNumber)
Operand = Memory[Registers[PC]].OperandValue
print "* Current Instruction Register: ", OpCode, Operand
Registers[PC] = Registers[PC] + 1
if OpCode == "LDA":
Registers = ExecuteLDA(Memory, Registers, Operand)
elif OpCode == "STA":
Memory = ExecuteSTA(Memory, Registers, Operand)
elif OpCode == "LDA#":
Registers = ExecuteLDAimm(Registers, Operand)
elif OpCode == "ADD":
Registers = ExecuteADD(Memory, Registers, Operand)
elif OpCode == "JMP":
Registers = ExecuteJMP(Registers, Operand)
elif OpCode == "JSR":
Memory, Registers = ExecuteJSR(Memory, Registers, Operand,
int(SourceCode[0])) # MP3
elif OpCode == "CMP#":
Registers = ExecuteCMPimm(Registers, Operand)
elif OpCode == "BEQ":
Registers = ExecuteBEQ(Registers, Operand)
elif OpCode == "SUB":
Registers = ExecuteSUB(Memory, Registers, Operand)
elif OpCode == "SKP":
ExecuteSKP()
elif OpCode == "RTN":
Registers = ExecuteRTN(Memory, Registers)
if Registers[ERR] == 0:
OpCode = Memory[Registers[PC]].OpCode
DisplayCurrentState(SourceCode, Memory, Registers)
else:
OpCode = "HLT"
print "Execution terminated"

GEMS Metropole School Page 88 of 236


Alternative method:

def ExecuteJSR(Memory, Registers, Address):


StackPointer = Registers[TOS] - 1
if Memory[StackPointer].OperandString != "" or
Memory[StackPointer].OpCode != "": # MP1, MP3
ReportRunTimeError("Memory Address Error", Registers) # MP4
else: #MP2
Memory[StackPointer].OperandValue = Registers[PC]
Registers[PC] = Address
Registers[TOS] = StackPointer
DisplayStack(Memory, Registers)
return Memory, Registers

GEMS Metropole School Page 89 of 236


Pascal

procedure ExecuteJSR(var Memory: TMemory; var Registers: TRegisters;


Address: integer; MaxLines: integer);
var
StackPointer: integer;
begin
StackPointer := Registers[TOS] - 1;
if StackPointer <= MaxLines // MP1
then
ReportRunTimeError('Memory Address Error', Registers) // MP4
else // MP2
begin
Memory[StackPointer].OperandValue := Registers[PC];
Registers[PC] := Address;
Registers[TOS] := StackPointer;
end;
DisplayStack(Memory, Registers)
end;

procedure Execute(var SourceCode: TSourceCode; var Memory: TMemory);


var
Registers: TRegisters;
OpCode: string;
Operand, FrameNumber: integer;
begin
Registers := TRegisters.create(0, 0, 0, 0, 0);
SetFlags(Registers[ACC], Registers);
Registers[PC] := 0;
Registers[TOS] := HI_MEM;
FrameNumber := 0;
DisplayFrameDelimiter(FrameNumber);
DisplayCurrentState(SourceCode, Memory, Registers);
OpCode := Memory[Registers[PC]].OpCode;
while OpCode <> 'HLT' do
begin
FrameNumber := FrameNumber + 1;
writeln;
DisplayFrameDelimiter(FrameNumber);
Operand := Memory[Registers[PC]].OperandValue;
writeln('* Current Instruction Register: ', OpCode, ' ', Operand);
Registers[PC] := Registers[PC] + 1;
if OpCode = 'LDA' then ExecuteLDA(Memory, Registers, Operand);
if OpCode = 'STA' then ExecuteSTA(Memory, Registers, Operand);
if OpCode = 'LDA#' then ExecuteLDAimm(Registers, Operand);
if OpCode = 'ADD' then ExecuteADD(Memory, Registers, Operand);
if OpCode = 'JMP' then ExecuteJMP(Registers, Operand);
if OpCode = 'JSR' then ExecuteJSR(Memory, Registers, Operand,
StrToInt(SourceCode[0])); // MP3
if OpCode = 'CMP#' then ExecuteCMPimm( Registers, Operand);
if OpCode = 'BEQ' then ExecuteBEQ(Registers, Operand);
if OpCode = 'SUB' then ExecuteSUB(Memory, Registers, Operand);
if OpCode = 'SKP' then ExecuteSKP();
if OpCode = 'RTN' then ExecuteRTN(Memory, Registers);
if Registers[ERR] = 0
then
begin
OpCode := Memory[Registers[PC]].OpCode;
DisplayCurrentState(SourceCode, Memory, Registers);
end

GEMS Metropole School Page 90 of 236


else
OpCode := 'HLT';
end;
writeln('Execution terminated');
end;

Alternative method:

procedure ExecuteJSR(var Memory: TMemory; var Registers: TRegisters;


Address: integer);
var
StackPointer: integer;
begin
StackPointer := Registers[TOS] - 1;
if (Memory[StackPointer].OperandString <> EMPTY_STRING) or
Memory[StackPointer].OpCode <> EMPTY_STRING // MP1, MP3
then
ReportRunTimeError('Memory Address Error', Registers) // MP4
else // MP2
begin
Memory[StackPointer].OperandValue := Registers[PC];
Registers[PC] := Address;
Registers[TOS] := StackPointer;
end;
DisplayStack(Memory, Registers)
end;

GEMS Metropole School Page 91 of 236


C#

private static void ExecuteJSR(AssemblerInstruction[] memory, int[]


registers, int address, int maxLines)
{
int stackPointer = registers[TOS] - 1;
if (stackPointer <= maxLines) // MP1
{
ReportRunTimeError("Memory Address Error", registers); // MP4
}
else // MP2
{
memory[stackPointer].operandValue = registers[PC];
registers[PC] = address;
registers[TOS] = stackPointer;
}
DisplayStack(memory, registers);
}

private static void Execute(string[] sourceCode, AssemblerInstruction[]


memory)
{
int[] registers = new int[] { 0, 0, 0, 0, 0 };
int frameNumber = 0, operand = 0;
SetFlags(registers[ACC], registers);
registers[PC] = 0;
registers[TOS] = HI_MEM;
DisplayFrameDelimiter(frameNumber);
DisplayCurrentState(sourceCode, memory, registers);
string opCode = memory[registers[PC]].opCode;
while (opCode != "HLT")
{
frameNumber++;
Console.WriteLine();
DisplayFrameDelimiter(frameNumber);
operand = memory[registers[PC]].operandValue;
Console.WriteLine($"* Current Instruction Register: {opCode}
{operand}");
registers[PC] = registers[PC] + 1;
switch (opCode)
{
case "LDA":
ExecuteLDA(memory, registers, operand); break;
case "STA":
ExecuteSTA(memory, registers, operand); break;
case "LDA#":
ExecuteLDAimm(registers, operand); break;
case "ADD":
ExecuteADD(memory, registers, operand); break;
case "JMP":
ExecuteJMP(registers, operand); break;
case "JSR":
ExecuteJSR(memory, registers, operand,
Convert.ToInt32(sourceCode[0])); break; // MP3
case "CMP#":
ExecuteCMPimm(registers, operand); break;
case "BEQ":
ExecuteBEQ(registers, operand); break;
case "SUB":
ExecuteSUB(memory, registers, operand); break;

GEMS Metropole School Page 92 of 236


case "SKP":
ExecuteSKP(); break;
case "RTN":
ExecuteRTN(memory, registers); break;
}
if (registers[ERR] == 0)
{
opCode = memory[registers[PC]].opCode;
DisplayCurrentState(sourceCode, memory, registers);
}
else
{
opCode = "HLT";
}
}
Console.WriteLine("Execution terminated");
}

Alternative method:

private static void ExecuteJSR(AssemblerInstruction[] memory, int[]


registers, int address)
{
int stackPointer = registers[TOS] - 1;
if (memory[stackPointer].operandString != "") // MP1, MP3
{
ReportRunTimeError("Memory Address Error", registers); // MP4
}
else // MP2
{
memory[stackPointer].operandValue = registers[PC];
registers[PC] = address;
registers[TOS] = stackPointer;
}
DisplayStack(memory, registers);
}

GEMS Metropole School Page 93 of 236


Java

void executeJSR(AssemblerInstruction[] memory, int[] registers, int


address, int maxLines) {
int stackPointer = registers[TOS] - 1;
if (stackPointer <= maxLines) { // MP1
reportRunTimeError("Memory Address Error", registers); // MP4
} else { // MP2
memory[stackPointer].operandValue = registers[PC] ;
registers[PC] = address;
registers[TOS] = stackPointer;
}
displayStack(memory, registers);

void execute(String[] sourceCode, AssemblerInstruction[] memory) {


int[] registers = {0, 0, 0, 0, 0} ;
setFlags(registers[ACC], registers);
registers[PC] = 0;
registers[TOS] = HI_MEM;
int frameNumber = 0;
displayFrameDelimiter(frameNumber);
displayCurrentState(sourceCode, memory, registers);
String opCode = memory[registers[PC]].opCode;
while (!opCode.equals("HLT")) {
frameNumber += 1;
Console.println();
displayFrameDelimiter(frameNumber);
int operand = memory[registers[PC]].operandValue;
Console.println("* Current instruction Register: " + opCode + " " +
operand);
registers[PC] = registers[PC] + 1;
switch (opCode) {
case "LDA":
executeLDA(memory, registers, operand); break;
case "STA":
executeSTA(memory, registers, operand); break;
case "LDA#":
executeLDAimm(registers, operand); break;
case "ADD":
executeADD(memory, registers, operand); break;
case "JMP":
executeJMP(registers, operand); break;
case "JSR":
executeJSR(memory, registers, operand,
Integer.parseInt(sourceCode[0])); // MP3
break;
case "CMP#":
executeCMPimm(registers, operand); break;
case "BEQ":
executeBEQ(registers, operand); break;
case "SUB":
executeSUB(memory, registers, operand); break;
case "SKP":
executeSKP(); break;
case "RTN":
executeRTN(memory, registers); break;
default:
break;

GEMS Metropole School Page 94 of 236


}
if (registers[ERR] == 0) {
opCode = memory[registers[PC]].opCode;
displayCurrentState(sourceCode, memory, registers);
} else {
opCode = "HLT";
}
}
Console.println("Execution terminated");
}

Alternative Answer:

void executeJSR(AssemblerInstruction[] memory, int[] registers, int


address) {
int stackPointer = registers[TOS] - 1;
if
(!memory[stackPointer].operandString.equals(EMPTY_STRING)||
!memory[stackPointer].opCode.equals(EMPTY_STRING)) // MP1, MP3{
reportRunTimeError("Memory Address Error", registers); // MP4
} else { // MP2
memory[stackPointer].operandValue = registers[PC] ;
registers[PC] = address;
registers[TOS] = stackPointer;
}
displayStack(memory, registers);
}
1
[5]

GEMS Metropole School Page 95 of 236


(a) 3 marks for AO3 (design) and 9 marks for AO3 (programming)
12.
Level Description Mark
Range

3 A line of reasoning has been followed to arrive at a logically 9–12


structured working or almost fully working programmed
solution.
All of the appropriate design decisions have been taken.
The last line of source code may not be displayed correctly
(if last line not moved due to exclusive boundary).

2 There is evidence that a line of reasoning has been partially 5–8


followed. There is evidence of some appropriate design
work. The subroutine EditSourceCode has been amended
and has some added functionality.
1 An attempt has been made to amend the subroutine 1–4
EditSourceCode. Some appropriate programming
statements have been written. There is little evidence to
suggest that a line of reasoning has been followed or that
the solution has been designed. The statements written may
or may not be syntactically correct and the subroutines will
have very little or none of the extra required functionality. It
is unlikely that any of the key design elements of the task
have been recognised.

Marking guidance:

Evidence of AO3 design – 3 marks:

Evidence of design to look for in response:

1) Adjust the number of lines stored in SourceCode (ie update SourceCode[0])


2) Loop through program lines consecutively or equivalent
3) Move program lines after specified location in SourceCode

Note: AO3 (design) points are for selecting appropriate techniques to use to solve
the problem, so should be credited whether the syntax of programming language
statements is correct or not and regardless of whether the solution works.

A. design evidence in option D or I code.

GEMS Metropole School Page 96 of 236


Evidence of AO3 programming – 9 marks:

Evidence of programming to look for in response:

4) Insert D / I / both in addition to existing options in the menu and add D / I /


both to conditions of WHILE loop
5) Add selection to test for option D / I / both after WHILE loop
6) Use correct range to loop through program lines in both options, D and I
7) Correctly adjust the number of lines stored in SourceCode in both options, D
and I
8) Within loop, move line referenced by loop counter one location in correct
direction in option D
9) Within loop, move line referenced by loop counter one location in correct
direction in option I
10) For option I get user input of new line
11) For option I insert new line if there is space, otherwise display error message
12) Insert line entered by user in correct row of SourceCode

Max 11 if code does not function correctly


12

(b) Mark is for AO3 (evaluate)

**** SCREEN CAPTURE ****


Must match code from (a), including prompts on screen capture matching those in
code.
Code for (a) must be sensible.

Screen capture showing (for ease of reference inserted line highlighted):

GEMS Metropole School Page 97 of 236


(c) Mark is for AO3 (evaluate)

**** SCREEN CAPTURE ****


Must match code from (a), including prompts on screen capture matching those in
code.
Code for (a) must be sensible.

Screen capture showing (for ease of reference inserted line highlighted):

GEMS Metropole School Page 98 of 236


VB.Net

Sub EditSourceCode(ByRef SourceCode() As String)


Dim LineNumber As Integer
...
While Choice <> "C"
Choice = Empty_String
While Choice <> "E" And Choice <> "C" And Choice <> "D" And Choice <>
"I"
Console.WriteLine("E - Edit this line")
Console.WriteLine("C - Cancel edit")
Console.WriteLine("D - Delete this line") 'MP4
Console.WriteLine("I - Insert a new line above this line")
Console.Write("Enter your choice: ")
Choice = Console.ReadLine()
End While
If Choice = "E" Then
...
End If
If Choice = "D" Then 'MP5
Dim NumberOfLines As Integer = Convert.ToInt32(SourceCode(0))
NumberOfLines -= 1
SourceCode(0) = Convert.ToString(NumberOfLines) 'MP1, MP7 part
For ThisLine = LineNumber To NumberOfLines 'MP2, MP6 part
SourceCode(ThisLine) = SourceCode(ThisLine + 1) 'MP3, MP8
Next
End If
If Choice = "I" Then 'MP5 alt.
If Convert.ToInt32(SourceCode(0)) < HI_MEM - 1 Then 'MP11 part
Console.Write("Enter the new line:")
Dim NewLine As String = Console.ReadLine() 'MP10
Dim NumberOfLines As Integer = Convert.ToInt32(SourceCode(0))
NumberOfLines += 1
SourceCode(0) = Convert.ToString(NumberOfLines) 'MP1 alt. / MP7
part
For ThisLine = NumberOfLines To LineNumber + 1 Step -1 'MP2
alt., MP6 part
SourceCode(ThisLine) = SourceCode(ThisLine - 1) 'MP3 alt., MP9
Next
SourceCode(LineNumber) = NewLine 'MP12
Else
Console.WriteLine("Error - can't add a new line. Program is at
maximum length") 'MP11 part
End If
End If
DisplaySourceCode(SourceCode)
End While
End Sub

GEMS Metropole School Page 99 of 236


Python 3

def EditSourceCode(SourceCode):
LineNumber = int(input("Enter line number of code to edit: "))
print(SourceCode[LineNumber])
Choice = EMPTY_STRING
while Choice != "C":
Choice = EMPTY_STRING
while Choice != "E" and Choice != "D" and Choice != "I" and Choice !=
"C":
print("E - Edit this line")
print("D - Delete this line") # MP4
print("I - Insert a new line above this line")
print("C - Cancel edit")
Choice = input("Enter your choice: ")
if Choice == "E":
SourceCode[LineNumber] = input("Enter the new line:")
if Choice == "D": # MP5
NumberOfLines = int(SourceCode[0]) #
NumberOfLines -= 1 #
SourceCode[0] = str(NumberOfLines) # MP1, MP7 part
for ThisLine in range(LineNumber, NumberOfLines + 1): # MP2, MP6
part
SourceCode[ThisLine] = SourceCode[ThisLine + 1] # MP3, MP8
if Choice == "I": # MP5 alt
if int(SourceCode[0]) < HI_MEM - 1: # MP11 part
print("Enter the new line:") #
NewLine = input() # MP10
NumberOfLines = int(SourceCode[0]) #
NumberOfLines += 1 #
SourceCode[0] = str(NumberOfLines) # MP1 alt./MP7 part
for ThisLine in range(NumberOfLines, LineNumber, - 1): # MP2
alt., MP6 part
SourceCode[ThisLine] = SourceCode[ThisLine - 1] # MP3 alt.,
MP9
SourceCode[LineNumber] = NewLine # MP12
else:
print("Error - can't add a new line. Program is at maximum
length") # MP11 part
DisplaySourceCode(SourceCode)
return SourceCode

GEMS Metropole School Page 100 of 236


Python 2

def EditSourceCode(SourceCode):
LineNumber = int(raw_input("Enter line number of code to edit: ")
.replace("\r", ""))
print SourceCode[LineNumber]
Choice = EMPTY_STRING
while Choice != "C":
Choice = EMPTY_STRING
while Choice != "E" and Choice != "D" and Choice != "I" and Choice !=
"C": #
print "E - Edit this line"
print "D - Delete this line" # MP4
print "I - Insert a new line above this line" #
print "C - Cancel edit"
Choice = raw_input("Enter your choice: ") .replace("\r", "")
if Choice == "E":
SourceCode[LineNumber] = raw_input("Enter the new line:")
.replace("\r", "")
if Choice == "D": # MP5
NumberOfLines = int(SourceCode[0]) #
NumberOfLines -= 1 #
SourceCode[0] = str(NumberOfLines) # MP1, MP7 part
for ThisLine in range(LineNumber, NumberOfLines + 1): # MP2, MP6
part
SourceCode[ThisLine] = SourceCode[ThisLine + 1] # MP3, MP8
if Choice == "I": # MP5 alt.
if int(SourceCode[0]) < HI_MEM - 1: # MP11 part
print "Enter the new line:" #
NewLine = raw_input() # MP10
NumberOfLines = int(SourceCode[0]) #
NumberOfLines += 1 #
SourceCode[0] = str(NumberOfLines) # MP1 alt./MP7 part
for ThisLine in range(NumberOfLines, LineNumber, - 1): # MP2
alt., MP6 part
SourceCode[ThisLine] = SourceCode[ThisLine - 1] # MP3 alt.,
MP9
SourceCode[LineNumber] = NewLine # MP12
else:
print "Error - can't add a new line. Program is at maximum
length" # MP11 part
DisplaySourceCode(SourceCode)
return SourceCode

GEMS Metropole School Page 101 of 236


Pascal

procedure EditSourceCode(var SourceCode: TSourceCode);


var
LineNumber, NumberOfLines, ThisLine: integer;
Choice: string;
NewLine: string;
begin
write('Enter line number of code to edit: ');
readln(LineNumber);
writeln(SourceCode[LineNumber]);
Choice := EMPTY_STRING;
while Choice <> 'C' do
begin
Choice := EMPTY_STRING;
while (Choice <> 'E') and (Choice <> 'D') and (Choice <> 'I') and
(Choice <> 'C') do //
begin
writeln('E - Edit this line');
writeln('D - Delete this line'); // MP4
writeln('I - Insert a new line above this line'); //
writeln('C - Cancel edit');
write('Enter your choice: ');
readln(Choice);
end;
if Choice = 'E'
then
begin
writeln('Enter the new line:');
readln(SourceCode[LineNumber]);
end;
if Choice = 'D' // MP5
then
begin
NumberOfLines := StrToInt(SourceCode[0]); //
NumberOfLines := NumberOfLines - 1; //
SourceCode[0] := IntToStr(NumberOfLines); // MP1, MP7 part
for ThisLine := LineNumber to NumberOfLines do // MP2, MP6
part
SourceCode[ThisLine] := SourceCode[ThisLine + 1]; // MP3
alt., MP8
end;
if Choice = 'I' // MP5 alt.
then
begin
if StrToInt(SourceCode[0]) < HI_MEM - 1 // MP11 part
then
begin
writeln('Enter the new line:'); //
readln(NewLine); // MP10
NumberOfLines := StrToInt(SourceCode[0]); //
NumberOfLines := NumberOfLines + 1; //
SourceCode[0] := IntToStr(NumberOfLines); // MP1 alt. MP7
part
for ThisLine := NumberOfLines downto LineNumber + 1 do //
MP2 alt., MP6 part
SourceCode[ThisLine] := SourceCode[ThisLine - 1]; // MP3
alt., MP9
SourceCode[LineNumber] := NewLine; // MP12
end

GEMS Metropole School Page 102 of 236


else
writeln('Error - can't add a new line as program is at
maximum length');
end; // MP11 part
DisplaySourceCode(SourceCode);
end;
end;

GEMS Metropole School Page 103 of 236


C#

private static void EditSourceCode(string[] sourceCode)


{
int lineNumber = 0;
int numberOfLines = Convert.ToInt32(sourceCode[0]);
while (lineNumber < 1 || lineNumber >= numberOfLines)
{
try
{
Console.Write("Enter line number of code to edit: ");
lineNumber = Convert.ToInt32(Console.ReadLine());
if (lineNumber < 1 || lineNumber >= numberOfLines)
{
Console.WriteLine("Not a valid line number");
}
}
catch (Exception)
{
Console.WriteLine("Not a valid number");
}
}
Console.WriteLine(sourceCode[lineNumber]);
string choice = EMPTY_STRING;
while (choice != "C")
{
choice = EMPTY_STRING;
while (choice != "E" && choice != "C" && choice != "D" && choice !=
"I")
{
Console.WriteLine("E - Edit this line");
Console.WriteLine("D - Delete this line"); // MP4
Console.WriteLine("C - Cancel edit");
Console.WriteLine("I - Insert a new line above this line");
Console.Write("Enter your choice: ");
choice = Console.ReadLine();
}
if (choice == "E")
{
Console.WriteLine("Enter the new line:");
sourceCode[lineNumber] = Console.ReadLine();
}
if (choice == "D") // MP5
{
numberOfLines--;
sourceCode[0] = numberOfLines.ToString(); // MP1, MP7 part
for (int thisLine = lineNumber; thisLine < numberOfLines + 1;
thisLine++) // MP2, MP6 part
{
sourceCode[thisLine] = sourceCode[thisLine + 1]; // MP3, MP8
}
}
if (choice == "I") // MP5 alt.
{
if (Convert.ToInt32(sourceCode[0]) < HI_MEM - 1) // MP11 part
{
Console.WriteLine("Enter the new line:");
string newLine = Console.ReadLine(); // MP10
numberOfLines = Convert.ToInt32(sourceCode[0]);
numberOfLines++;

GEMS Metropole School Page 104 of 236


sourceCode[0] = numberOfLines.ToString(); // MP1 alt./ MP7 part
for (int thisLine = numberOfLines; thisLine > lineNumber;
thisLine--) //MP2 alt / MP6 part
{
sourceCode[thisLine] = sourceCode[thisLine - 1];
} // MP3 alt. MP9
sourceCode[lineNumber] = newLine; // MP12
}
else
{
Console.WriteLine("Error - can't add a new line as program is at
maximum length"); // MP11 part
}
}
DisplaySourceCode(sourceCode);
}
}

GEMS Metropole School Page 105 of 236


Java
void editsourceCode(String[] sourceCode) {
int lineNumber;
do {
Console.print("Enter line number of code to edit: ");
try {
lineNumber = Integer.parseInt(Console.readLine());
} catch (Exception e) {
lineNumber = 0;
}
if (lineNumber < 1 || lineNumber > sourceCode.length + 1) {
Console.println("Invalid line number please try again.");
}
} while (lineNumber < 1 || lineNumber > sourceCode.length + 1);
Console.println(sourceCode[lineNumber]);
String choice = EMPTY_STRING;
while (!choice.equals("C")) {
choice = EMPTY_STRING;
while (!choice.equals("E") && !choice.equals("C") &&
!choice.equals("D") && !choice.equals("I")) {
Console.println("E - Edit this line");
Console.println("D - Delete the current line"); // MP4
Console.println("I - Insert a new line above this line");
Console.println("C - Cancel edit");
Console.print("Enter your choice: ");
choice = Console.readLine();
}
if (choice.equals("E")) {
Console.print("Enter the new line: ");
sourceCode[lineNumber] = Console.readLine();
} else if (choice.equals("D")) { // MP5
for (int line = lineNumber; line < sourceCode.length-1; line++) //
MP2, MP6 part{
sourceCode[line] = sourceCode[line+1]; // MP3, MP8
sourceCode[0] =
Integer.toString(Integer.parseInt(sourceCode[0])-1); // MP1 / MP7 part
}
} else if (choice.equals("I")) { // MP5 alt.
if (Integer.parseInt(sourceCode[0]) < HI_MEM - 1) // MP11 part {
Console.println("Enter the new line:");
String newLine = Console.readLine(); // MP10
for (int line = sourceCode.length-1; line > lineNumber;
line--) // MP2 alt / MP6 part{
sourceCode[line] = sourceCode[line-1]; // MP3 alt MP9
}
sourceCode[lineNumber] = newLine; // MP12
sourceCode[0] =
Integer.toString(Integer.parseInt(sourceCode[0])+1); // MP1 alt / MP7
part
} else {
Console.println("Error - program is at maximum length"); // MP11
part
}
}
displaySourceCode(sourceCode);
}
}
1
[14]

GEMS Metropole School Page 106 of 236


5 marks for AO2 (apply)
13.

1 mark for each correct set of values in the correct sequence (boxed in red);

Max 4 if any errors

A. entries within a boxed area sharing a row (e.g. 9 and 8 on the same row).

GEMS Metropole School Page 107 of 236


Alternative Answer Layout:
1 mark for each correct set of values in the correct sequence (4 sets boxed in red, 1 set in
disjointed boxes in green and shaded light grey);

[5]

(a) 8 marks for AO3 (programming)


14.
Mark as follows:
1) Correct variable declarations for C, D, S, T and initialisation;

Note to examiners:
If a language allows variables to be used without explicit declaration, (eg Python),
then this mark should be awarded if the correct variables exist in the program code
and the first value they are assigned is of the correct data type.

2) Correct WHILE loop syntax allowed by the programming language and correct
condition for termination of the loop;
3) Correct generation of two random numbers between 1 and 6 and output within
loop;
4) Correct running total assigned to S and updating of T;
5) Correct condition to increment C within the loop;
6) Correct condition to increment D with the loop;
7) Correct calculation of A outside the loop;
8) Correct output outside loop;

I. case

Max 7 if code does not function correctly

GEMS Metropole School Page 108 of 236


VB.Net

Sub Main()
Dim Rnd As Random = New Random()
Dim C As Integer = 0 '
Dim D As Integer = 0 '
Dim S As Integer = 0 '
Dim T As Integer = 0 ' MP1
While C < 3 And D < 3 ' MP2
T += 1
Dim N1 As Integer = Rnd.Next(1, 7) '
Dim N2 As Integer = Rnd.Next(1, 7) ' MP3
Console.WriteLine($"{N1} {N2}") '
S = S + N1 + N2 ' MP4
If N1 = 6 Or N2 = 6 Then '
C += 1 ' MP5
End If
If N1 = N2 Then '
D += 1 ' MP6
End If
End While
Dim A AS Integer = S \ (T * 2) ' MP7
Console.WriteLine($"{C} {D} {A}") ' MP8
Console.ReadLine()
End Sub

Python 3

import random

C = 0 #
D = 0 #
S = 0 #
T = 0 # MP1
while C < 3 and D < 3: # MP2
T += 1
N1 = random.randint(1,6) #
N2 = random.randint(1,6) # MP3
print(N1, N2) #
S = S + N1 + N2 # MP4
if N1 == 6 or N2 == 6: #
C += 1 # MP5
if N1 == N2: #
D += 1 # MP6
A = S // (T*2) # MP7
print(C, D, A) # MP8

GEMS Metropole School Page 109 of 236


Python 2

import random

C = 0 #
D = 0 #
S = 0 #
T = 0 # MP1
while C < 3 and D < 3: # MP2
T += 1 #
N1 = random.randint(1,6) #
N2 = random.randint(1,6) # MP3
print N1, N2 #
S = S + N1 + N2 # MP4
if N1 == 6 or N2 == 6: #
C += 1 # MP5
if N1 == N2: #
D += 1 # MP6
A = S // (T*2) # MP7
print C, D, A # MP8

Pascal

{$APPTYPE CONSOLE} {$R+}

uses SysUtils;
var A, C, D, S, T, N1, N2: integer;
begin
C := 0; //
D := 0; //
S := 0; //
T := 0; // MP1
while (C < 3) and (D < 3) do // MP2
begin
T := T + 1; //
N1 := random(6) + 1; //
N2 := random(6) + 1; // MP3
writeln(N1, N2); //
S := S + N1 + N2; // MP4
if (N1 = 6) or (N2 = 6) then //
C := C + 1; // MP5
if N1 = N2 then //
D := D + 1; // MP6
end;
A := S div (T*2); // MP7
writeln(C, D, A); // MP8
readln;
end.

GEMS Metropole School Page 110 of 236


C#

Random R = new Random();


int C = 0, D = 0, S = 0, T = 0; // MP1
int N1, N2, A;
while ((C < 3) && (D < 3)) // MP2
{
T++; //
N1 = R.Next(1, 7); //
N2 = R.Next(1, 7); // MP3
Console.WriteLine($"{N1} {N2}"); //
S = S + N1 + N2; // MP4
if ((N1 == 6) || (N2 == 6)) //
{ //
C++; // MP5
}
if (N1 == N2) //
{ //
D++; // MP6
}
}
A = S / (T * 2); // MP7
Console.WriteLine($"{C} {D} {A}"); // MP8
Console.ReadLine();

Java

Random r = new Random();


int c = 0; //
int d = 0; //
int s = 0; //
int t = 0; // MP1
int n1, n2, a;
while ((c < 3) && (d < 3)) // MP2
{
t++; //
n1 = r.nextInt(6) + 1; //
n2 = r.nextInt(6) + 1; // MP3
Console.writeLine(n1 + " " + n2); //
s = s + n1 + n2; // MP4
if ((n1 == 6) || (n2 == 6)) //
{ //
c++; // MP5
}
if (n1 == n2) //
{ //
d++; // MP6
}
}
a = s / (t * 2); // MP7
Console.writeLine(c + " " + d + " " + a); // MP8
8

GEMS Metropole School Page 111 of 236


(b) Mark is for AO3 (evaluate)

**** SCREEN CAPTURE ****


Must match code from (a).
Code for (a) must be sensible.

As this output is from a random number generator, the output from candidates will not
be the values below. However:
Output should show two digits between 1 and 6 on each line except the final line.
On the final line it should show the correct number of lines containing at least one 6,
number of doubles and another integer.
Number of lines containing at least one 6 and/or number of doubles must be 3

Screen capture showing:


15
43
31
42
22
33
16
65
35
63
323
>>>

I. missing spaces
A. each digit on a new line
1
[9]

Mark is for AO1 (knowledge)


15.
Integer / int;
[1]

Mark is for AO2 (analyse)


16.
Line / Row / Column / ErrorCount / ResponseNumber;

A. GRID_SIZE (Python only)


R. Digit
R. if any additional code
R. if spelt incorrectly
I. case and spacing
[1]

GEMS Metropole School Page 112 of 236


1 mark for AO1 (knowledge) and 1 mark for AO2 (analyse)
17.
Identifier (AO2): OK / InputError / Finished / Solved / Correct / Incomplete;
Data type (AO1): Boolean / bool;

R. if any additional code


R. if spelt incorrectly
I. case and spacing
[2]

(a) Mark is for AO2 (analyse)


18.
(Stores the string equivalent of User’s) score;
1

(b) 3 marks for AO2 (analyse)

It stores (the string equivalent of) the number of digits/attempts/guesses/answers the


player has placed/made // stores (the string equivalent of) the number of steps made
(towards a solution);

Max 1

It is incremented every time a digit is accepted / valid;


If the user has placed a digit // if the user has placed one or more digits:
… the (user’s attempted) solution can be checked;
… the partial solution can be saved;
… the digit is placed into the Answer
( ) array at the correct position;
… the user’s solution is displayed before exiting the program;
… the score is displayed;

Max 2
3
[4]

2 marks for AO3 (design)


19.
Row/Column heading numbers need to be extended;
Row/Column headers formatted to occupy two positions;
Sub-grid lines need to extended horizontally; I. vertically
Grid lines need to extended horizontally; I. vertically
Sub-grid lines need to be after 4 rows / columns // column / row need to be divisible by 4 for
sub-grid lines // the 3s need to be changed to 4s;

R. reference to alterations outside the DisplayGrid subroutine.

Max 2
[2]

GEMS Metropole School Page 113 of 236


2 marks for AO1 (understand)
20.
Definite iteration: the number of iterations is known (at the time of execution);
Indefinite iteration: the number of iterations depends on a condition (that is tested before /
after each iteration);

NE. indefinite iteration: number of iterations not known


[2]

Mark is for AO2 (analyse)


21.
ResetDataStructures / LoadSolution / ResetAnswer / TransferAnswerIntoGrid
/ DisplayGrid / KeepPuzzle / CheckSolution / DisplayResults;

R. if any additional code


R. if spelt incorrectly
I case and spacing
[1]

Mark is for AO2 (analyse)


22.
LoadPuzzleFile / TransferPuzzleIntoGrid / LoadPartSolvedPuzzle /
SolvePuzzle / GetMenuOption / NumberPuzzle;

R. if any additional code


R. if spelt incorrectly
I case and spacing
[1]

2 marks for AO1 (understand)


23.
To stop a program from crashing;
To deal with (an anticipated) run-time error A. clear description of an example of a
run-time error;
To avoid structure of code becoming too complex as a result of trying to check for potential
errors before they might occur;

Max 2
[2]

GEMS Metropole School Page 114 of 236


2 marks for AO2 (analyse)
24. 1 mark for identifier and 1 mark for exception

LoadPuzzleFile – file does not exist // index error if more lines in file than Puzzle can
accommodate;
LoadSolution – file does not exist // not enough lines in file;
TransferPuzzleIntoGrid – input conversion error // index error if string length < 3;
LoadPartSolvedPuzzle – file does not exist // index error if more lines in file than
Answer can accommodate;
SolvePuzzle – row/column/1st character/2nd character entered not a digit/number/integer //
input conversion error;

A. KeepPuzzle – file does not exist (Java only)


A. readLine – end of file (Java only)

A. other exceptions that could occur

R. if any additional code


R. if spelt incorrectly
I. case and spacing

Max 2
[2]

Mark is for AO1 (knowledge)


25.
Named / (reference to) identifier / callable ‘out of line’ block of code (that may be called by
simply writing its name in a program statement);

A. subroutine is used to give a block of code a name (and this name can be used to
execute this group of statements)
[1]

Mark is for AO2 (analyse)


26.
LoadPuzzle is called more than once (from NumberPuzzle and also from
LoadPartSolvedPuzzle)
// DisplayGrid is called more than once (from within SolvePuzzle)
//ResetDataStructures is called more than once (from NumberPuzzle and twice from
LoadPuzzle);

A. readLine / print is called more than once (Java only)


NE. ‘called more than once’ without an appropriate subroutine name
[1]

GEMS Metropole School Page 115 of 236


Mark is for AO1 (understanding)
27.
Saves time as code can be written once and called in many places;
Reduced storage space of (source) code;
Reduces testing time as less code to test;
Avoids errors because code cannot be written differently if it is used in multiple places;
Program code will be easier to understand / maintain;

MAX 1
[1]

2 marks for AO2 (analyse)


28.
Box Label

(a) ResetDataStructures

(b) LoadPuzzleFile

(c) LoadSolution

(d) TransferPuzzleIntoGrid

1 mark for 2 correct labels


2 marks for 4 correct labels

A. labels written in different order


I. case and spacing
R. if any additional code
R. if spelt incorrectly
[2]

GEMS Metropole School Page 116 of 236


(a) 7 marks for AO3 (programming)
29.
Marking guidance:

Evidence of AO3 programming – 7 points:

Evidence of programming to look for in response:

1. Loop structure;
2. Check through each element of Puzzle // check Puzzle until end of entries
reached // check until a protected cell is found;
3. Compare first two characters of CellInfo with first two characters of Puzzle
line // compare the string values of Row and Column with the first two characters
of the Puzzle line;
4. Ifprotected cell found …;
4. If protected cell found …;
5. … give appropriate error message to user A. ‘Invalid input’ also being output;
6. Only if it is not a protected cell update content of cell; DPT. Incorrect
identification of a protected cell
7. Code in correct place in SolvePuzzle;

Max 6 if any errors

GEMS Metropole School Page 117 of 236


VB.Net

Sub SolvePuzzle(PuzzleGrid(,) As Char, Puzzle() As String, Answer() As


String)
Dim CellInfo As String
Dim InputError As Boolean
Dim Digit As Char
Dim Row, Column As Integer
DisplayGrid(PuzzleGrid)
If PuzzleGrid(0, 0) <> "X" Then
Console.WriteLine("No puzzle loaded")
Else
Console.WriteLine("Enter row column digit: ")
Console.WriteLine("(Press Enter to stop)")
CellInfo = Console.ReadLine()
While CellInfo <> EMPTY_STRING
InputError = False
If CellInfo.Length <> 3 Then
InputError = True
Else
Digit = CellInfo(2)
Try
Row = Int32.Parse(CellInfo(0))
Catch
InputError = True
End Try
Try
Column = Int32.Parse(CellInfo(1))
Catch
InputError = True
End Try
If (Digit < "1") Or (Digit > "9") Then
InputError = True
End If
End If
If InputError Then
Console.WriteLine("Invalid input")
Else
' MP7: code inserted in correct place
Dim ProtectedCell As Boolean = False
Dim Line As Integer = 0
While Not ProtectedCell And Puzzle(Line) <> EMPTY_STRING
' MP1 ' MP2
If Puzzle(Line)(0) = Row.ToString() And Puzzle(Line)(1) =
Column.ToString() Then ' MP3
ProtectedCell = True
End If
Line += 1
End While
If ProtectedCell Then' MP4
Console.WriteLine("You can't change a protected cell.") ' MP5
Else ' MP6
PuzzleGrid(Row, Column) = Digit
Answer(2) = (Int32.Parse(Answer(2)) + 1).ToString()
Answer(Int32.Parse(Answer(2)) + 2) = CellInfo
DisplayGrid(PuzzleGrid)
End If
End If
Console.WriteLine("Enter row column digit: ")
Console.WriteLine("(Press Enter to stop)")

GEMS Metropole School Page 118 of 236


CellInfo = Console.ReadLine()
End While
End If
End Sub

Python 3

def SolvePuzzle(PuzzleGrid, Puzzle, Answer):


DisplayGrid(PuzzleGrid)
if PuzzleGrid[0][0] != 'X':
print("No puzzle loaded")
else:
print("Enter row column digit: ")
print("(Press Enter to stop)")
CellInfo = input()
while CellInfo != EMPTY_STRING:
InputError = False
if len(CellInfo) != 3:
InputError = True
else:
Digit = CellInfo[2]
try:
Row = int(CellInfo[0])
except:
InputError = True
try:
Column = int(CellInfo[1])
except:
InputError = True
if (Digit < '1' or Digit > '9'):
InputError = True
if InputError:
print("Invalid input")
else:
# MP7: code inserted in correct place
Protected = False
Line = 0
while Puzzle[Line] != EMPTY_STRING:
# MP1 MP2
if CellInfo[:2] == Puzzle[Line][:2]: # MP3
Protected = True # MP4
Line += 1
if Protected:
print("You can’t change a protected cell") # MP5
else: # MP6
PuzzleGrid[Row][Column] = Digit
Answer[2] = str(int(Answer[2]) + 1)
Answer[int(Answer[2]) + 2] = CellInfo
DisplayGrid(PuzzleGrid)
print("Enter row column digit: ")
print("(Press Enter to stop)")
CellInfo = input()
return PuzzleGrid, Answer

GEMS Metropole School Page 119 of 236


Python 2

def SolvePuzzle(PuzzleGrid, Puzzle, Answer):


DisplayGrid(PuzzleGrid)
if PuzzleGrid[0][0] != 'X':
print "No puzzle loaded"
else:
print "Enter row column digit: "
print "(Press Enter to stop)"
CellInfo = raw_input()
while CellInfo != EMPTY_STRING:
InputError = False
if len(CellInfo) != 3:
InputError = True
else:
Digit = CellInfo[2]
try:
Row = int(CellInfo[0])
except:
InputError = True
try:
Column = int(CellInfo[1])
except:
InputError = True
if (Digit < '1' or Digit > '9'):
InputError = True
if InputError:
print "Invalid input"
else:
# MP7: code inserted in correct place
Protected = False
Line = 0
while Puzzle[Line] != EMPTY_STRING:
# MP1 MP2
if CellInfo[:2] == Puzzle[Line][:2]: # MP3
Protected = True
Line += 1
if Protected: # MP4
print("You can't change a protected cell") # MP5
else: # MP6
PuzzleGrid[Row][Column] = Digit
Answer[2] = str(int(Answer[2]) + 1)
Answer[int(Answer[2]) + 2] = CellInfo
DisplayGrid(PuzzleGrid)
print "Enter row column digit: "
print "(Press Enter to stop)"
CellInfo = raw_input()
return PuzzleGrid, Answer

GEMS Metropole School Page 120 of 236


Pascal

procedure SolvePuzzle(var PuzzleGrid: TPuzzleGrid; Puzzle: TPuzzle; var


Answer: TAnswer);
var
CellInfo: string;
InputError: boolean;
Digit: char;
Line, Row, Column: integer;
Protected: boolean;
begin
DisplayGrid(PuzzleGrid);
if PuzzleGrid[0, 0] <> 'X' then
writeln('No puzzle loaded')
else
begin
writeln('Enter row column digit: ');
writeln('(Press Enter to stop)');
readln(CellInfo);
while CellInfo <> EMPTY_STRING do
begin
InputError := False;
if length(CellInfo) <> 3 then
InputError := True
else
begin
Digit := CellInfo[3];
try
Row := strToInt(CellInfo[1]);
except
InputError := True;
end;
try
Column := strToInt(CellInfo[2]);
except
InputError := True;
end;
if (Digit < '1') or (Digit > '9') then
InputError := True;
end;
if InputError then
writeln('Invalid input')
else // MP7 code inserted in correct place
begin
Protected := False;
Line := 0;
while Puzzle[Line] <> EMPTY_STRING do // MP1, MP2
begin
if (CellInfo[1] = Puzzle[Line][1]) and (CellInfo[2] =
Puzzle[Line][2]) then // MP3
Protected := True;
Inc(Line);
end;
if Protected then // MP4
writeln('You can''t change a protected cell') // MP5
else // MP6
begin
PuzzleGrid[Row, Column] := Digit;
Answer[2] := intToStr(strToInt(Answer[2]) + 1);
Answer[strToInt(Answer[2]) + 2] := CellInfo;

GEMS Metropole School Page 121 of 236


DisplayGrid(PuzzleGrid);
end;
end;
writeln('Enter row column digit: ');
writeln('(Press Enter to stop)');
readln(CellInfo);
end;
end;
end;

GEMS Metropole School Page 122 of 236


C#

private static void SolvePuzzle(char[,] puzzleGrid, string[]


puzzle, string[] answer)
{
int row = 0, column = 0;
char digit = ' ';
DisplayGrid(puzzleGrid);
if (puzzleGrid[0, 0] != 'X')
{
Console.WriteLine("No puzzle loaded");
}
else
{
Console.WriteLine("Enter row column digit: ");
Console.WriteLine("(Press Enter to stop)");
string cellInfo = Console.ReadLine();
while (cellInfo != EMPTY_STRING)
{
bool inputError = false;
if (cellInfo.Length != 3)
{
inputError = true;
}
else
{
digit = cellInfo[2];
try
{
row = Convert.ToInt32(cellInfo[0].ToString());
}
catch (Exception)
{
inputError = true;
}
try
{
column = Convert.ToInt32(cellInfo[1].ToString());
}
catch (Exception)
{
inputError = true;
}
if (digit < '1' || digit > '9')
{
inputError = true;
}
}
if (inputError)
{
Console.WriteLine("Invalid input");
}
else
{ // MP7: code inserted in correct place
bool protectedCell = false;
int line = 0;
while (puzzle[line] != EMPTY_STRING) // MP1, MP2
{
if (cellInfo[0] == puzzle[line][0] && cellInfo[1] ==
puzzle[line][1]) // MP3

GEMS Metropole School Page 123 of 236


{
protectedCell = true;
}
line++;
}
if (protectedCell) // MP4
{
Console.WriteLine("You can't change a protected cell"); // MP5
}
else
{ // MP6
puzzleGrid[row, column] = digit;
answer[2] = (Convert.ToInt32(answer[2]) + 1).ToString();
answer[Convert.ToInt32(answer[2]) + 2] = cellInfo;
DisplayGrid(puzzleGrid);
}
}
Console.WriteLine("Enter row column digit: ");
Console.WriteLine("(Press Enter to stop)");
cellInfo = Console.ReadLine();
}
}
}

GEMS Metropole School Page 124 of 236


Java

void solvePuzzle(char[][] puzzleGrid, String[] puzzle, String[] answer)


{
String cellInfo;
boolean inputError;
char digit = ' ';
int row = 0, column = 0;
displayGrid(puzzleGrid);
if (puzzleGrid[0][0] != 'X')
{
Console.writeLine("No puzzle loaded");
}
else
{
Console.writeLine("Enter row column digit: ");
Console.writeLine("(Press Enter to stop)");
cellInfo = Console.readLine();
while (!cellInfo.equals(EMPTY_STRING))
{
inputError = false;
if (cellInfo.length() != 3)
{
inputError = true;
}
else
{
digit = cellInfo.charAt(2);
try
{
row = Integer.parseInt(cellInfo.charAt(0) + EMPTY_STRING);
}
catch (Exception ex)
{
inputError = true;
}
try
{
column = Integer.parseInt(cellInfo.charAt(1) + EMPTY_STRING);
}
catch (Exception ex)
{
inputError = true;
}
if ((digit < '1') || (digit > '9'))
{
inputError = true;
}
if (inputError)
{
Console.writeLine("Invalid input");
}
else
{ // MP7: code inserted in correct place
boolean protectedValue = false;
int line = 0;
while (!puzzle[line].equals(EMPTY_STRING)) { // MP1, MP2
if (cellInfo.charAt(0) == puzzle[line].charAt(0) &&
cellInfo.charAt(1) == puzzle[line].charAt(1)) { // MP3
protectedValue = true; // MP4

GEMS Metropole School Page 125 of 236


}
line++;
}
if (protectedValue) { // MP4
Console.writeLine("You can't change a protected cell");// MP5
}
else
{// MP6
puzzleGrid[row][column] = digit;
answer[2] = (Integer.parseInt(answer[2]) + 1) + EMPTY_STRING;
answer[Integer.parseInt(answer[2]) + 2] = cellInfo;

displayGrid(puzzleGrid);
}
}
Console.writeLine("Enter row column digit: ");
Console.writeLine("(Press Enter to stop)");
cellInfo = Console.readLine();
}
}
}
7

(b) Mark is for AO3 (evaluate)

**** SCREEN CAPTURE ****


Must match code from (a), including prompts on screen capture matching those in
code.

Code for (a) must be sensible.

Screen capture showing:

Enter your choice: S

GEMS Metropole School Page 126 of 236


Enter row column digit:
(Press Enter to stop)
117
You can’t change a protected cell
Enter row column digit:
(Press Enter to stop)
323
You can’t change a protected cell
Enter row column digit:
(Press Enter to stop)
993
You can’t change a protected cell
Enter row column digit:
(Press Enter to stop)
853

Enter row column digit:


(Press Enter to stop)
854

GEMS Metropole School Page 127 of 236


A. grid displaying between incorrect attempts
1
[8]

(a) 2 marks for AO3 (design) and 6 marks for AO3 (programming)
30.
Marking guidance:

Evidence of AO3 design – 2 points:

Evidence of design to look for in response:

1. Identify the need for a loop containing a conditional statement;


2. Recognise that subgrid boundaries need to be calculated;

Note: AO3 (design) points are for selecting appropriate techniques to use to solve
the problem, so should be credited whether the syntax of programming language
statements is correct or not and regardless of whether the solution works.

GEMS Metropole School Page 128 of 236


Evidence of AO3 programming – 6 points:

Evidence of programming to look for in response:

3. Subroutine heading with correct parameters and return value;


4. Check both row and column for duplicate I. failing to check location at which
digit is to be placed;
5. Correctly calculate subgrid boundaries;
6. Check each digit in a subgrid for duplicate (does not depend on MP5 above);
7. Call in correct place in SolvePuzzle so that grid updated only under correct
circumstances / if digit is valid / if subroutine returns true R. if returned value not
used;
8. Give appropriate error message (under at least some correct circumstances
and is never displayed when it shouldn’t be) A. error message in
DuplicateDigit;

Max 7 if any errors

VB.Net

Function DuplicateDigit(PuzzleGrid(,) As Char, Row As Integer, Column As


Integer, Digit As Char) As Boolean ' MP3
Dim duplicateFound As Boolean = False
Dim i As Integer
For i = 1 To GRID_SIZE ' MP1
If PuzzleGrid(i, Column) = Digit Or PuzzleGrid(Row, i) = Digit Then
duplicateFound = True ' MP4
End If
Next
Dim endr As Integer = ((Row - 1) \ 3 + 1) * 3 ' MP2
Dim endc As Integer = ((Column - 1) \ 3 + 1) * 3
Dim r, c As Integer
For r = endr - 2 To endr
For c = endc - 2 To endc ‘' MP5
If PuzzleGrid(r, c) = Digit Then
duplicateFound = True ' MP6
End If
Next
Next
Return duplicateFound
End Function

GEMS Metropole School Page 129 of 236


Sub SolvePuzzle(PuzzleGrid(,) As Char, Puzzle() As String, Answer() As
String)
Dim CellInfo As String
Dim InputError As Boolean
Dim Digit As Char
Dim Row, Column As Integer
DisplayGrid(PuzzleGrid)
If PuzzleGrid(0, 0) <> "X" Then
Console.WriteLine("No puzzle loaded")
Else
Console.WriteLine("Enter row column digit: ")
Console.WriteLine("(Press Enter to stop)")
CellInfo = Console.ReadLine()
While CellInfo <> EMPTY_STRING
InputError = False
If CellInfo.Length <> 3 Then
InputError = True
Else
Digit = CellInfo(2)
Try
Row = Int32.Parse(CellInfo(0))
Catch
InputError = True
End Try
Try
Column = Int32.Parse(CellInfo(1))
Catch
InputError = True
End Try
If (Digit < "1") Or (Digit > "9") Then
InputError = True
End If
End If
If InputError Then
Console.WriteLine("Invalid input")
Else
' MP7: call subroutine in correct place
If DuplicateDigit(PuzzleGrid, Row, Column, Digit) Then
Console.WriteLine("Duplicate digit entered.") ' MP8
Else
PuzzleGrid(Row, Column) = Digit
Answer(2) = (Int32.Parse(Answer(2)) + 1).ToString()
Answer(Int32.Parse(Answer(2)) + 2) = CellInfo
DisplayGrid(PuzzleGrid)
End If
End If
Console.WriteLine("Enter row column digit: ")
Console.WriteLine("(Press Enter to stop)")
CellInfo = Console.ReadLine()
End While
End If
End Sub

GEMS Metropole School Page 130 of 236


Alternative Solution DuplicateDigit subroutine:

Function DuplicateDigit(PuzzleGrid(,) As Char, Row As Integer, Column As


Integer, Digit As Char) As Boolean ' MP3
Dim duplicateFound As Boolean = False
Dim i As Integer
For i = 1 To GRID_SIZE ' MP1
If PuzzleGrid(i, Column) = Digit Or PuzzleGrid(Row, i) = Digit Then
duplicateFound = True ' MP4
End If
Next
Dim startR As Integer = ((Row - 1) \ 3) * 3 + 1 ' MP2
Dim startC As Integer = ((Column - 1) \ 3) * 3 + 1
Dim r, c As Integer
For r = startR To startR + 2
For c = startC To startC + 2 '' MP5
If PuzzleGrid(r, c) = Digit Then
duplicateFound = True ' MP6
End If
Next
Next
Return duplicateFound
End Function

Python 3

def DuplicateDigit(PuzzleGrid, Row, Column, Digit): # MP3


Duplicate = False
for X in range(1, GRID_SIZE + 1): # MP1
if PuzzleGrid[X][Column] == Digit: # MP4
Duplicate = True
for Y in range(1, GRID_SIZE + 1):
if PuzzleGrid[Row][Y] == Digit: # MP4
Duplicate = True
SubGridStartX = ((Row - 1) // 3) * 3 + 1 # MP2
SubGridStartY = ((Column - 1) // 3) * 3 + 1
for X in range(SubGridStartX, SubGridStartX + 3):
for Y in range(SubGridStartY, SubGridStartY + 3): # MP5
if PuzzleGrid[X][Y] == Digit:
Duplicate = True # MP6
return Duplicate

GEMS Metropole School Page 131 of 236


def SolvePuzzle(PuzzleGrid, Puzzle, Answer):
DisplayGrid(PuzzleGrid)
if PuzzleGrid[0][0] != 'X':
print("No puzzle loaded")
else:
print("Enter row column digit: ")
print("(Press Enter to stop)")
CellInfo = input()
while CellInfo != EMPTY_STRING:
InputError = False
if len(CellInfo) != 3:
InputError = True
else:
Digit = CellInfo[2]
try:
Row = int(CellInfo[0])
except:
InputError = True
try:
Column = int(CellInfo[1])
except:
InputError = True
if (Digit < '1' or Digit > '9'):
InputError = True
if InputError:
print("Invalid input")
else:
if DuplicateDigit(PuzzleGrid, Row, Column, Digit): # MP7
print("Duplicate digit") # MP8
else:
PuzzleGrid[Row][Column] = Digit
Answer[2] = str(int(Answer[2]) + 1)
Answer[int(Answer[2]) + 2] = CellInfo
DisplayGrid(PuzzleGrid)
print("Enter row column digit: ")
print("(Press Enter to stop)")
CellInfo = input()
return PuzzleGrid, Answer

Python 2

def DuplicateDigit(PuzzleGrid, Row, Column, Digit): # MP3


Duplicate = False
for X in range(1, GRID_SIZE + 1): # MP1
if PuzzleGrid[X][Column] == Digit: # MP4
Duplicate = True
for Y in range(1, GRID_SIZE + 1):
if PuzzleGrid[Row][Y] == Digit: # MP4
Duplicate = True
SubGridStartX = ((Row - 1) // 3) * 3 + 1 # MP2
SubGridStartY = ((Column - 1) // 3) * 3 + 1
for X in range(SubGridStartX, SubGridStartX + 3):
for Y in range(SubGridStartY, SubGridStartY + 3): # MP5
if PuzzleGrid[X][Y] == Digit:
Duplicate = True # MP6
return Duplicate

GEMS Metropole School Page 132 of 236


def SolvePuzzle(PuzzleGrid, Puzzle, Answer):
DisplayGrid(PuzzleGrid)
if PuzzleGrid[0][0] != 'X':
print "No puzzle loaded"
else:
print "Enter row column digit: "
print "(Press Enter to stop)"
CellInfo = raw_input()
while CellInfo != EMPTY_STRING:
InputError = False
if len(CellInfo) != 3:
InputError = True
else:
Digit = CellInfo[2]
try:
Row = int(CellInfo[0])
except:
InputError = True
try:
Column = int(CellInfo[1])
except:
InputError = True
if (Digit < '1' or Digit > '9'):
InputError = True
if InputError:
print "Invalid input"
else:
# MP7: call subroutine in correct place
if DuplicateDigit(PuzzleGrid, Row, Column, Digit):
print("Duplicate digit") # MP8
else:
PuzzleGrid[Row][Column] = Digit
Answer[2] = str(int(Answer[2]) + 1)
Answer[int(Answer[2]) + 2] = CellInfo
DisplayGrid(PuzzleGrid)
print "Enter row column digit: "
print "(Press Enter to stop)"
CellInfo = raw_input()
return PuzzleGrid, Answer

GEMS Metropole School Page 133 of 236


Pascal

function DuplicateDigit(PuzzleGrid: TPuzzleGrid; Row, Column: integer;


Digit: string): boolean; // MP3
var
Duplicate: boolean;
X, Y, SubGridStartX, SubGridStartY: integer;
begin
Duplicate := False;
for X := 1 to GRID_SIZE do // MP1
if PuzzleGrid[X, Column] = Digit then // MP4
Duplicate := True;
for Y := 1 to GRID_SIZE do
if PuzzleGrid[Row, Y] = Digit then // MP4
Duplicate := True;
SubGridStartX := ((Row - 1) div 3) * 3 + 1; // MP2
SubGridStartY := ((Column - 1) div 3) * 3 + 1;
for X := SubGridStartX to SubGridStartX + 2 do
for Y := SubGridStartY to (SubGridStartY + 2) do // MP5
if PuzzleGrid[X, Y] = Digit then
Duplicate := True; // MP6
DuplicateDigit := Duplicate;
end;

GEMS Metropole School Page 134 of 236


procedure SolvePuzzle(var PuzzleGrid: TPuzzleGrid; Puzzle:
TPuzzle; var Answer: TAnswer);
var
CellInfo: string;
InputError: boolean;
Digit: char;
Row, Column: integer;
begin
DisplayGrid(PuzzleGrid);
if PuzzleGrid[0, 0] <> 'X' then
writeln('No puzzle loaded')
else
begin
writeln('Enter row column digit: ');
writeln('(Press Enter to stop)');
readln(CellInfo);
while CellInfo <> EMPTY_STRING do
begin
InputError := False;
if length(CellInfo) <> 3 then
InputError := True
else
begin
Digit := CellInfo[3];
try
Row := strToInt(CellInfo[1]);
except
InputError := True;
end;
try
Column := strToInt(CellInfo[2]);
except
InputError := True;
end;
if (Digit < '1') or (Digit > '9') then
InputError := True;
end;
if InputError then
writeln('Invalid input')
else // MP7: call subroutine in correct place
if DuplicateDigit(PuzzleGrid, Row, Column, Digit) then
writeln('Duplicate digit') // MP8
else
begin
PuzzleGrid[Row, Column] := Digit;
Answer[2] := intToStr(strToInt(Answer[2]) + 1);
Answer[strToInt(Answer[2]) + 2] := CellInfo;
DisplayGrid(PuzzleGrid);
end;
writeln('Enter row column digit: ');
writeln('(Press Enter to stop)');
readln(CellInfo);
end;
end;
end;

GEMS Metropole School Page 135 of 236


C#

private static bool DuplicateDigit(char[,] puzzleGrid, int row, int


column, char digit) // MP3
{
bool duplicate = false;
for (int x = 1; x < GRID_SIZE + 1; x++) // MP1
{
if (puzzleGrid[x,column] == digit) // MP4
{
duplicate = true;
}
}
for (int y = 1; y < GRID_SIZE + 1; y++)
{
if (puzzleGrid[row,y] == digit) // MP4
{
duplicate = true;
}
}
int subGridStartX = ((row - 1) / 3) * 3 + 1; // MP2
int subGridStartY = ((column - 1) / 3) * 3 + 1;
for (int x = subGridStartX; x < subGridStartX + 3; x++)
{
for (int y = subGridStartY; y < subGridStartY + 3; y++)// MP5
{
if (puzzleGrid[x, y] == digit)
{
duplicate = true; // MP6
}
}
}
return duplicate;
}

GEMS Metropole School Page 136 of 236


private static void SolvePuzzle(char[,] puzzleGrid, string[] puzzle,
string[] answer)
{
int row = 0, column = 0;
char digit = ' ';
DisplayGrid(puzzleGrid);
if (puzzleGrid[0, 0] != 'X')
{
Console.WriteLine("No puzzle loaded");
}
else
{
Console.WriteLine("Enter row column digit: ");
Console.WriteLine("(Press Enter to stop)");
string cellInfo = Console.ReadLine();
while (cellInfo != EMPTY_STRING)
{
bool inputError = false;
if (cellInfo.Length != 3)
{
inputError = true;
}
else
{
digit = cellInfo[2];
try
{
row = Convert.ToInt32(cellInfo[0].ToString());
}
catch (Exception)
{
inputError = true;
}
try
{
column = Convert.ToInt32(cellInfo[1].ToString());
}
catch (Exception)
{
inputError = true;
}
if (digit < '1' || digit > '9')
{
inputError = true;
}
}
if (inputError)
{
Console.WriteLine("Invalid input");
}
else
{// MP7: call subroutine in correct place
if (DuplicateDigit(puzzleGrid, row, column, digit))
{
Console.WriteLine("Duplicate digit"); // MP8
}
else
{
puzzleGrid[row, column] = digit;
answer[2] = (Convert.ToInt32(answer[2]) + 1).ToString();
answer[Convert.ToInt32(answer[2]) + 2] = cellInfo;
GEMS Metropole School Page 137 of 236
DisplayGrid(puzzleGrid);
}
}
Console.WriteLine("Enter row column digit: ");
Console.WriteLine("(Press Enter to stop)");
cellInfo = Console.ReadLine();
}
}
}

Java

boolean duplicateDigit(char [][] puzzleGrid, int row, int column, char


digit) // MP3
{
boolean duplicate = false;
for (int x = 1; x <= GRID_SIZE; x++) {// MP1
if (puzzleGrid[x][column] == digit) {// MP4
duplicate = true;
}
}
for (int y = 1; y <= GRID_SIZE; y++) {
if (puzzleGrid[row][y] == digit) {// MP4
duplicate = true;
}
}
int subGridStartX = ((row - 1) / 3) * 3 + 1; // MP2
int subGridStartY = ((column - 1) / 3) * 3 + 1;
for (int x = subGridStartX; x < subGridStartX + 3; x++) {
for (int y = subGridStartY; y < subGridStartY + 3; y++) {// MP5
if (puzzleGrid[x][y] == digit) {
duplicate = true; // MP6
}
}
}
return duplicate;
}

GEMS Metropole School Page 138 of 236


void solvePuzzle(char[][] puzzleGrid, String[] puzzle, String[] answer)
{
String cellInfo;
boolean inputError;
char digit = ' ';
int row = 0, column = 0;
displayGrid(puzzleGrid);
if (puzzleGrid[0][0] != 'X')
{
Console.writeLine("No puzzle loaded");
}
else
{
Console.writeLine("Enter row column digit: ");
Console.writeLine("(Press Enter to stop)");
cellInfo = Console.readLine();
while (!cellInfo.equals(EMPTY_STRING))
{
inputError = false;
if (cellInfo.length() != 3)
{
inputError = true;
}
else
{
digit = cellInfo.charAt(2);
try
{
row = Integer.parseInt(cellInfo.charAt(0) + EMPTY_STRING);
}
catch (Exception ex)
{
inputError = true;
}
try
{
column = Integer.parseInt(cellInfo.charAt(1) + EMPTY_STRING);
}
catch (Exception ex)
{
inputError = true;
}
if ((digit < '1') || (digit > '9'))
{
inputError = true;
}
}
if (inputError)
{
Console.writeLine("Invalid input");
}
else
{// MP7: call subroutine in correct place
if (duplicateDigit(puzzleGrid, row, column, digit)) {
Console.writeLine("Duplicate digit");// MP8
}
else
{

8

GEMS Metropole School Page 139 of 236


(b) Mark is for AO3 (evaluate)

**** SCREEN CAPTURE ****


Must match code from (a), including prompts on screen capture matching those in
code.
Code for (a) must be sensible.

Screen capture showing:

Enter your choice: S

Enter row column digit:


(Press Enter to stop)
178
Duplicate digit
Enter row column digit:
(Press Enter to stop)
819
Duplicate digit
Enter row column digit:
(Press Enter to stop)
124
Duplicate digit
Enter row column digit:
(Press Enter to stop)
989
Duplicate digit
Enter row column digit:
(Press Enter to stop)
555

GEMS Metropole School Page 140 of 236


1
[9]

(a) 3 marks for AO3 (design) and 9 marks for AO3 (programming)
31.
Level Description Mark
Range

3 A line of reasoning has been followed to arrive at a logically 9–12


structured working or almost fully working programmed
solution.
All of the appropriate design decisions have been taken.

2 There is evidence that a line of reasoning has been partially 5–8


followed. There is evidence of some appropriate design
work. This is a partially working programmed solution.

1 An attempt has been made to write the subroutine 1–4


ClearEntries. Some appropriate programming statements
have been written. There is little evidence to suggest that a
line of reasoning has been followed or that the solution has
been designed. The statements written may or may not be
syntactically correct and the subroutines will have very little
or none of the extra required functionality. It is unlikely that
any of the key design elements of the task have been
recognised.

GEMS Metropole School Page 141 of 236


Marking guidance:

Evidence of AO3 design – 3 marks:

Evidence of design to look for in response:

1) Recognise a loop required that repeats depending on value entered by user.


2) Dealing with non-integer input.
3) Attempt to identify minus sign / negative number in input.

Note: AO3 (design) points are for selecting appropriate techniques to use to solve
the problem, so should be credited whether the syntax of programming language
statements is correct or not and regardless of whether the solution works.

Evidence of AO3 programming – 9 marks:

Evidence of programming to look for in response:

4) Create ClearEntries subroutine with correct parameters.


5) Extract number of cells to be cleared.
6) Extract row/column from entry in Answer within loop.
7) Extract row and column from entry in Answer within loop.
8) Replace entry in PuzzleGrid with space within loop DPT. incorrect row and/or
column
9) Correct number of cells cleared if number to clear is less than or equal to
number of entries DPT. incorrect string used to clear in MP8.
10) Correct number of cells cleared in all circumstances.
11) Update answer count in Answer[2].
12) Display grid after subroutine call.

Max 11 if code does not function correctly

VB.Net

Sub ClearEntries(PuzzleGrid(,) As Char, Answer() As String,


EntriesToClear As Integer) 'MP4
Dim Line, Row, Column As Integer
Dim CellInfo As String
If EntriesToClear > Int32.Parse(Answer(2)) Then 'MP9
EntriesToClear = Int32.Parse(Answer(2)) 'MP10
End If
For i As Integer = 0 To EntriesToClear - 1 'MP1
' loop won't execute if Answer(2) = "0"
Line = Int32.Parse(Answer(2)) + 2
CellInfo = Answer(Line)
Row = Int32.Parse(CellInfo(0)) 'MP6
Column = Int32.Parse(CellInfo(1)) 'MP7
PuzzleGrid(Row, Column) = SPACE 'MP8
Answer(2) = (Int32.Parse(Answer(2)) - 1).ToString() 'MP11
Next
End Sub

GEMS Metropole School Page 142 of 236


Sub SolvePuzzle(PuzzleGrid(,) As Char, Puzzle() As String, Answer() As
String)
Dim CellInfo As String
Dim InputError As Boolean
Dim Digit As Char
Dim Row, Column As Integer
DisplayGrid(PuzzleGrid)
If PuzzleGrid(0, 0) <> "X" Then
Console.WriteLine("No puzzle loaded")
Else
Console.WriteLine("Enter row column digit: ")
Console.WriteLine("(Press Enter to stop)")
CellInfo = Console.ReadLine()
While CellInfo <> EMPTY_STRING
InputError = False
If CellInfo(0) = "-" Then 'MP3
Try
Dim EntriesToClear As Integer = Int32.Parse(CellInfo) * - 1
'MP5
ClearEntries(PuzzleGrid, Answer, EntriesToClear)
DisplayGrid(PuzzleGrid) 'MP12
Catch ex As Exception 'MP2
Console.WriteLine("Invalid number of entries to be cleared.")
End Try
Else
If CellInfo.Length <> 3 Then
InputError = True
Else
Digit = CellInfo(2)
Try
Row = Int32.Parse(CellInfo(0))
Catch
InputError = True
End Try
Try
Column = Int32.Parse(CellInfo(1))
Catch
InputError = True
End Try
If (Digit < "1") Or (Digit > "9") Then
InputError = True
End If
If InputError Then
Console.WriteLine("Invalid input")
Else
PuzzleGrid(Row, Column) = Digit
Answer(2) = (Int32.Parse(Answer(2)) + 1).ToString()
Answer(Int32.Parse(Answer(2)) + 2) = CellInfo
DisplayGrid(PuzzleGrid)
End If
End If
End If
Console.WriteLine("Enter row column digit: ")
Console.WriteLine("(Press Enter to stop)")
CellInfo = Console.ReadLine()
End While
End If
End Sub

GEMS Metropole School Page 143 of 236


Alternative solution

Sub ClearEntries(PuzzleGrid(,) As Char, Answer() As String,


EntriesToClear As Integer)
Dim Line, Row, Column As Integer
Dim CellInfo As String
Line = Int32.Parse (Answer(2)) + 2
While EntriesToClear > 0 And Line > 2
CellInfo = Answer(Line)
Row = Int32.Parse(CellInfo(0))
Column = Int32.Parse(CellInfo(1))
PuzzleGrid(Row, Column) = SPACE
Answer(2) = (Int32.Parse(Answer(2)) - 1).ToString()
Line -= 1
EntriesToClear -= 1
End While
End Sub

Python 3

def ClearEntries(PuzzleGrid, Answer, NumberInput): # MP4


StepsDone = int(Answer[2])
if NumberInput > StepsDone:
StepsToRemove = StepsDone # MP10
else:
StepsToRemove = NumberInput # MP9
for Count in range(StepsToRemove): # MP1
PreviousStep = Answer[int(Answer[2]) + 2]
Row = int(PreviousStep[0]) # MP6
Column = int(PreviousStep[1]) # MP7
PuzzleGrid[Row][Column] = SPACE # MP8
Answer[2] = str(int(Answer[2]) - 1) # MP11
return PuzzleGrid, Answer

GEMS Metropole School Page 144 of 236


def SolvePuzzle(PuzzleGrid, Puzzle, Answer):
DisplayGrid(PuzzleGrid)
if PuzzleGrid[0][0] != 'X':
print("No puzzle loaded")
else:
print("Enter row column digit: ")
print("(Press Enter to stop)")
CellInfo = input()
while CellInfo != EMPTY_STRING:
InputError = False
if CellInfo[0] == '-': # MP3
try:
NumberInput = -int(CellInfo) # MP5
PuzzleGrid, Answer = ClearEntries(PuzzleGrid, Answer,
NumberInput)
DisplayGrid(PuzzleGrid) # MP12
except: # MP2
print("Not a valid integer")
else:
if len(CellInfo) != 3:
InputError = True
else:
Digit = CellInfo[2]
try:
Row = int(CellInfo[0])
Column = int(CellInfo[1])
except:
InputError = True
if (Digit < '1' or Digit > '9'):
InputError = True
if InputError:
print("Invalid input")
else:
PuzzleGrid[Row][Column] = Digit
Answer[2] = str(int(Answer[2]) + 1)
Answer[int(Answer[2]) + 2] = CellInfo
DisplayGrid(PuzzleGrid)
print("Enter row column digit: ")
print("(Press Enter to stop)")
CellInfo = input()
return PuzzleGrid, Answer

Alternative solution

while CellInfo != EMPTY_STRING:


if CellInfo[0] == "-":
if CellInfo[1:].isdigit():
PuzzleGrid, Answer = ClearEntries(PuzzleGrid, Answer, CellInfo[1:])
DisplayGrid(PuzzleGrid)
else:
InputError = False

GEMS Metropole School Page 145 of 236


def ClearEntries(PuzzleGrid, Answer, Steps):
StepsToRemove = int(Steps)
for Count in range(StepsToRemove):
if int(Answer[2]) > 0:
PreviousStep = Answer[int(Answer[2]) + 2]
Answer[int(Answer[2]) + 2] = EMPTY_STRING
Answer[2] = str(int(Answer[2]) - 1)
Row = int(PreviousStep[0])
Column = int(PreviousStep[1])
PuzzleGrid[Row][Column] = SPACE
#DisplayGrid(PuzzleGrid)
return PuzzleGrid, Answer

Python 2

def ClearEntries(PuzzleGrid, Answer, NumberInput): # MP4


StepsDone = int(Answer[2])
if NumberInput > StepsDone:
StepsToRemove = StepsDone # MP10
else:
StepsToRemove = NumberInput # MP9
for Count in range(StepsToRemove): # MP1
PreviousStep = Answer[int(Answer[2]) + 2]
Row = int(PreviousStep[0]) # MP6
Column = int(PreviousStep[1]) # MP7
PuzzleGrid[Row][Column] = SPACE # MP8
Answer[2] = str(int(Answer[2]) - 1) # MP11
return PuzzleGrid, Answer

GEMS Metropole School Page 146 of 236


def SolvePuzzle(PuzzleGrid, Puzzle, Answer):
DisplayGrid(PuzzleGrid)
if PuzzleGrid[0][0] != 'X':
print "No puzzle loaded"
else:
print "Enter row column digit: "
print "(Press Enter to stop)"
CellInfo = raw_input()
while CellInfo != EMPTY_STRING:
InputError = False
if CellInfo[0] == '-': # MP3
try:
NumberInput = -int(CellInfo) # MP5
PuzzleGrid, Answer = ClearEntries(PuzzleGrid, Answer,
NumberInput)
DisplayGrid(PuzzleGrid) # MP12
except: # MP2
print("Not a valid integer")
else:
if len(CellInfo) != 3:
InputError = True
else:
Digit = CellInfo[2]
try:
Row = int(CellInfo[0])
except:
InputError = True
try:
Column = int(CellInfo[1])
except:
InputError = True
if (Digit < '1' or Digit > '9'):
InputError = True
if InputError:
print "Invalid input"
else:
PuzzleGrid[Row][Column] = Digit
Answer[2] = str(int(Answer[2]) + 1)
Answer[int(Answer[2]) + 2] = CellInfo
DisplayGrid(PuzzleGrid)
print "Enter row column digit: "
print "(Press Enter to stop)"
CellInfo = raw_input()
return PuzzleGrid, Answer

GEMS Metropole School Page 147 of 236


Pascal

procedure ClearEntries(var PuzzleGrid: TPuzzleGrid; var Answer: TAnswer;


NumberInput: integer); // MP4
var
StepsDone, StepsToRemove, Count, Row, Column: integer;
PreviousStep: string;
begin
StepsDone := strToInt(Answer[2]);
if NumberInput > StepsDone then
StepsToRemove := StepsDone // MP10
else
StepsToRemove := NumberInput; // MP9
for Count := 1 to StepsToRemove do // MP1
begin
PreviousStep := Answer[strToInt(Answer[2]) + 2];
Row := strToInt(PreviousStep[1]); // MP6
Column := strToInt(PreviousStep[2]); // MP7
PuzzleGrid[Row, Column] := SPACE; // MP8
Answer[2] := intToStr(strToInt(Answer[2]) - 1); // MP11
end;
end;

GEMS Metropole School Page 148 of 236


procedure SolvePuzzle(var PuzzleGrid: TPuzzleGrid; Puzzle: TPuzzle; var
Answer: TAnswer);
var
CellInfo: string;
InputError: boolean;
Digit: char;
Row, Column, NumberInput: integer;
begin
DisplayGrid(PuzzleGrid);
if PuzzleGrid[0, 0] <> 'X' then
writeln('No puzzle loaded')
else
begin
writeln('Enter row column digit: ');
writeln('(Press Enter to stop)');
readln(CellInfo);
while CellInfo <> EMPTY_STRING do
begin
InputError := False;
if CellInfo[1] = '-' then // MP3
try
NumberInput := -strToInt(CellInfo); // MP5
ClearEntries(PuzzleGrid, Answer, NumberInput);
DisplayGrid(PuzzleGrid); // MP12
except // MP2
writeln('Not a valid integer')
end
else
begin
if length(CellInfo) <> 3 then
InputError := True
else
begin
writeln('got past new code');
readln;
Digit := CellInfo[3];
try
Row := strToInt(CellInfo[1]);
except
InputError := True;
end;
try
Column := strToInt(CellInfo[2]);
except
InputError := True;
end;
if (Digit < '1') or (Digit > '9') then
InputError := True;
end;
if InputError then
writeln('Invalid input')
else
begin
PuzzleGrid[Row, Column] := Digit;
Answer[2] := intToStr(strToInt(Answer[2]) + 1);
Answer[strToInt(Answer[2]) + 2] := CellInfo;
DisplayGrid(PuzzleGrid);
end;
end;
writeln('Enter row column digit: ');
writeln('(Press Enter to stop)');
GEMS Metropole School Page 149 of 236
readln(CellInfo);
end;
end;
end;

C#

private static void ClearEntries(char[,] puzzleGrid, string[] answer, int


numberInput) // MP4
{
int stepsToRemove = 0, row, column;
string previousStep = "";
int stepsDone = Convert.ToInt32(answer[2]);
if (numberInput > stepsDone)
{
stepsToRemove = stepsDone; // MP10
}
else
{
stepsToRemove = numberInput; // MP9
}
for (int count = 0; count < stepsToRemove; count++) // MP1
{
previousStep = answer[Convert.ToInt32(answer[2]) + 2];
row = Convert.ToInt32(previousStep[0].ToString());// MP6
column = Convert.ToInt32(previousStep[1].ToString());// MP7
puzzleGrid[row, column] = SPACE; // MP8
answer[2] = (Convert.ToInt32(answer[2]) - 1).ToString();// MP11
}
}

GEMS Metropole School Page 150 of 236


private static void SolvePuzzle(char[,] puzzleGrid, string[] puzzle,
string[] answer)
{
int row = 0, column = 0;
char digit = ' ';
int numberInput;
DisplayGrid(puzzleGrid);
if (puzzleGrid[0, 0] != 'X')
{
Console.WriteLine("No puzzle loaded");
}
else
{
Console.WriteLine("Enter row column digit: ");
Console.WriteLine("(Press Enter to stop)");
string cellInfo = Console.ReadLine();
while (cellInfo != EMPTY_STRING)
{
bool inputError = false;
if (cellInfo[0] == '-') // MP3
{
try
{
numberInput = -Convert.ToInt32(cellInfo); // MP5
ClearEntries(puzzleGrid, answer, numberInput);
DisplayGrid(puzzleGrid); // MP12
}
catch (Exception) // MP2
{
Console.WriteLine("Not a valid integer");
}
}
else
{
if (cellInfo.Length != 3)
{
inputError = true;
}
else

GEMS Metropole School Page 151 of 236


digit = cellInfo[2];
try
{
row = Convert.ToInt32(cellInfo[0].ToString());
}
catch (Exception)
{
inputError = true;
}
try
{
column = Convert.ToInt32(cellInfo[1].ToString());
}
catch (Exception)
{
inputError = true;
}
if (digit < '1' || digit > '9')
{
inputError = true;
{
}
if (inputError)
{
Console.WriteLine("Invalid input");
}
else
{
puzzleGrid[row, column] = digit;
answer[2] = (Convert.ToInt32(answer[2]) + 1).ToString();
answer[Convert.ToInt32(answer[2]) + 2] = cellInfo;
DisplayGrid(puzzleGrid);
}
}
Console.WriteLine("Enter row column digit: ");
Console.WriteLine("(Press Enter to stop)");
cellInfo = Console.ReadLine();
}
}
}

GEMS Metropole School Page 152 of 236


Java

void clearEntries(char [][] puzzleGrid, String[] answer, int numberInput)


// MP 4
{
int stepsToRemove = 0;
int stepsDone = Integer.parseInt(answer[2]);
if (numberInput > stepsDone) {
stepsToRemove = stepsDone; // MP 10
}
else
{
stepsToRemove = numberInput; // MP 9
}
for (int count = 0; count < stepsToRemove; count++) {// MP 1
String previousStep = answer[Integer.parseInt(answer[2])+2];
int row = Integer.parseInt(previousStep.charAt(0) + EMPTY_STRING); //
MP 6
int column = Integer.parseInt(previousStep.charAt(1) + EMPTY_STRING);
// MP 7
puzzleGrid[row][column] = SPACE; // MP 8
answer[2] = (Integer.parseInt(answer[2]) - 1) + EMPTY_STRING; // MP
11
}
}

GEMS Metropole School Page 153 of 236


void solvePuzzle(char[][] puzzleGrid, String[] puzzle, String[] answer)
{
String cellInfo;
boolean inputError;
char digit = ' ';
int row = 0, column = 0, numberInput;
displayGrid(puzzleGrid);
if (puzzleGrid[0][0] != 'X')
{
Console.writeLine("No puzzle loaded");
}
else
{
Console.writeLine("Enter row column digit: ");
Console.writeLine("(Press Enter to stop)");
cellInfo = Console.readLine();
while (!cellInfo.equals(EMPTY_STRING))
{
inputError = false;
if (cellInfo.charAt(0) == '-') {// MP 3
try {
numberInput = -Integer.parseInt(cellInfo); // MP 5
clearEntries(puzzleGrid, answer, numberInput);
displayGrid(puzzleGrid); // MP 12
} catch (Exception e) {// MP 2
Console.writeLine("Not a valid integer");
}
}
else
{
if (cellInfo.length() != 3)
{
inputError = true;
}
else
{
digit = cellInfo.charAt(2);

12

GEMS Metropole School Page 154 of 236


(b) Mark is for AO3 (evaluate)

**** SCREEN CAPTURE ****


Must match code from (a), including prompts on screen capture matching those in
code.
Code for (a) must be sensible.

Enter your choice: S

Enter row column digit:


(Press Enter to stop)
−x
not a valid integer
Enter row column digit:
(Press Enter to stop)
−1

GEMS Metropole School Page 155 of 236


Enter row column digit:
(Press Enter to stop)
−5

1
[13]

(a) 3 marks for AO2 (apply)


33.

GEMS Metropole School Page 156 of 236


X Result Output

0 0 -

4 4

6 10

3 13

2 15

−1 14 14

1 mark for correct X column (4, 6, 3, 2, -1);


1 mark for correct Result column (4, 10, 13, 15);
1 mark for final Result value (14) and Output column (14);

Max 2 if any errors


3

(b) 2 marks for AO2 (analyse)

The result is wrong // The sentinel value should not have been used in the
calculation; Subtract the last value // input first value before the WHILE loop and swap
the instructions within the WHILE loop // add 1 to result after loop is finished;

A. not add the value if it is the sentinel value


2
[5]

GEMS Metropole School Page 157 of 236


(a) 9 marks for AO3 (programming)
34.
Mark as follows:
1) Correct variable declarations for X, Product, Factor,

Note to examiners
If a language allows variables to be used without explicit declaration (eg
Python) then this mark should be awarded if the correct variables exist in
the program code and the first value they are assigned is of the correct
data type.

2) Correct prompt "Enter an integer greater than 1: " and X


assigned integer value entered by user;
3) Correct initialisation of Product and Factor before WHILE loop;
4) WHILE loop with syntax allowed by the programming language and correct
condition for termination of the loop;
5) Correct incrementation of Factor and correct assignment to Product
within WHILE loop;
6) IF statement with correct condition and ELSE part after the WHILE loop;
7) Correct re-initialisation of Product within THEN part;
8) FOR loop with syntax allowed by the programming language over correct
range within THEN part;
9) Correct assignment to Product and output of N within FOR loop;

I. minor differences in case and spelling


DPT. use of incorrect variable name

Max 8 if code does not function correctly


9

VB.Net
Dim X As Integer '
Dim Product As Integer '
Dim Factor As Integer '1
Console.Write("Enter an integer greater than 1: ") '
X = Console.ReadLine '2
Product = 1 '
Factor = 0 '3
While Product < X '4
Factor += 1 '
Product *= Factor '5
End While
If X = Product Then '6
Product = 1 '7
For N = 1 To Factor '8
Product = Product * N '
Console.WriteLine(N) '9
Next
Else
Console.WriteLine("No result")
End If

GEMS Metropole School Page 158 of 236


Python 3
# X, Product, Factor are integers # 1
print("Enter an integer greater than 1: ") #
X = int(input()) # 2
Product = 1 #
Factor = 0 # 3
while Product < X: # 4
Factor += 1 #
Product = Product * Factor # 5
if X == Product: # 6
Product = 1 # 7
for N in range(1, Factor + 1): # 8
Product = Product * N #
print(N) # 9
else:
print("No result")

Python 2
# X, Product, Factor are integers # 1
print "Enter an integer greater than 1: " #
X = int(raw_input()) # 2
Product = 1 #
Factor = 0 # 3
while Product < X: # 4
Factor += 1 #
Product = Product * Factor # 5
if X == Product: # 6
Product = 1 # 7
for N in range(1, Factor + 1): # 8
Product = Product * N #
print N # 9
else:
print "No result"

GEMS Metropole School Page 159 of 236


Pascal
program question3;
{$APPtype CONSOLE}
uses SysUtils;
var
X, Product, Factor, N: integer; // 1
begin
write('Enter an integer greater than 1: '); //
readln(X); // 2
Product := 1; //
Factor := 0; // 3
while Product < X do // 4
begin
Factor := Factor + 1; //
Product := Product * Factor; // 5
end;
if X = Product // 6
then
begin
Product := 1; // 7
for N := 1 to Factor do // 8
begin
Product := Product * N; //
writeln(N); // 9
end;
end
else
writeln('No result');
readln;
end.

C#
int x, product, factor; // 1
Console.Write("Enter an integer greater than 1: "); //
x = Convert.ToInt32(Console.ReadLine()); // 2
product = 1; //
factor = 0; // 3
while (product < x) // 4
{
factor++; //
product = product * factor; // 5
}
if (x == product) // 6
{
product = 1; // 7
for (int n = 1; n < factor + 1; n++) // 8
{
product = product * n; //
Console.WriteLine(n); // 9
}
}
else
{
Console.WriteLine("No result");
}
Console.ReadLine();

GEMS Metropole School Page 160 of 236


Java
Console.write("Enter an integer greater than 1: "); //
int x = Integer.parseInt(Console.readLine()); // 2
int product = 1; //
int factor = 0; // 3 // 1
while (product < x) { // 4
factor = factor + 1; //
product = product * factor; // 5
}
if (x == product) { // 6
product = 1; // 7
for (int n = 1; n <= factor; n++) { // 8
product = product * n; //
Console.writeLine(n); // 9
}
} else {
Console.writeLine("No result");
}

(b) Mark is for AO3 (evaluate)

**** SCREEN CAPTURE ****


Must match code from part (a), including prompts on screen capture matching those
in code.
Code for part (a) must be sensible.

Screen capture showing:


'720' being entered and 1 2 3 4 5 6 displayed
(Accept on same or separate lines)
'600' being entered and the message 'No result' displayed

Enter an integer greater than 1: 720


1
2
3
4
5
6
>>>
Enter an integer greater than 1: 600
No result
>>>
1

(c) Mark is for AO2 (analyse)

X is equal to the product of a sequence of (consecutive) whole numbers starting at 1


// X is a factorial number (greater than 1)
// X is the factorial of a positive integer (greater than 1);
1
[11]

GEMS Metropole School Page 161 of 236


(a) Mark is for AO1 (understand)
35.
FileFound / FileTypeOK / ProgramEnd;

R. if any additional code


R. if spelt incorrectly
I. case & spacing
1

(b) Mark is for AO1 (understand)

ConvertChar //
GetMenuOption (Python only);

R. if any additional code


R. if spelt incorrectly
I. case & spacing
1

(c) Mark is for AO1 (understand)

EditImage;

R. if any additional code


R. if spelt incorrectly
I. case & spacing
1
[3]

(a) Mark is for AO1 (understand)


36.
It is easier to read / understand / more descriptive (the identifier) than "";
It will never change // a change in value would invalidate the name EMPTY_STRING,
R. the value never changes in this program;
If there was a requirement to change the representation of the empty string it would
only need to be changed in one place;
The value cannot be accidentally changed elsewhere in the code (Do NOT accept
for Python);

A. since the name is uppercase this tells the programmer not to alter it. (Python only)

Max 1
1

GEMS Metropole School Page 162 of 236


(b) Mark is for AO1 (understand)

(These are the maximum dimensions and) may be changed easily if the program
requirements change // a change would only need to be made in one place; It is
easier to read/understand than the actual values;
The value cannot be accidentally changed elsewhere in the code (Do NOT accept
for Python);

A. since the name is uppercase this tells the programmer not to alter it. (Python only)
R. if answer is the same as (a)

Max 1
1
[2]

All marks for AO2 (analyse)


37.
NextPixel is not (a string that can be converted to) an integer;
File no longer available; R. file could not be opened as already open
Pixel data stored in wrong format, R. file does not have .txt extension;
Not enough lines in the file N.E. Empty file;
Not enough characters in a line;
A. Not enough data in file for given size of image; if neither of the 2 points above have
been given
Header height larger than MAX_HEIGHT, A. larger than 100;
Header width larger than MAX_WIDTH, A. larger than 100;

Max 2
[2]

(a) Mark is for AO1 (understanding)


38.
To represent the structure of the program // which subroutine is called from which
subroutine;
To aid decomposition of a problem;
To aid with stepwise refinement;

Max 1
1

(b) Mark is for AO1 (understanding)

A subroutine/procedure/function/method; A. module
1

(c) Mark is for AO2 (analyse)

ConvertChar;

R. if any additional code


R. if spelt incorrectly
I. case & spacing
1
[3]

GEMS Metropole School Page 163 of 236


(a) Mark is for AO2 (analyse)
39.
The default values of the file header;
Empty string, MAX_WIDTH, MAX_HEIGHT, empty string;

A. '''' / '' / EMPTY_STRING for empty string


A. 100 for MAX_WIDTH and/or MAX_HEIGHT

Max 1
1

(b) 3 marks for AO2 (analyse)

The string is split into separate parts;


Delimited by a comma;
Each part is assigned to a field of the header record;
A. File type is used to determine which subroutine is called;

Max 3
3
[4]

All marks for AO2 (analyse)


40.
Each range of greyscale values is assigned a different ASCII character;
A. Omission of range if an example range is given

The lighter greyscales have less dense/smaller coverage


// the darker greyscales have denser/larger coverage
// the characters used give an effect appropriate for the greyscale value;
[2]

(a) 2 marks for AO2 (analyse)


41.
When the image is displayed/loaded it will not be the intended image
// the pixels will be misaligned;
As the line breaks will now be in the wrong places // image width is shorter but length
is longer;
A. there will be no error message / exception;

Max 2
2

(b) 2 marks for AO2 (analyse)

The image is now a larger dimension;


There will not be enough data in the file;
The bottom rows of the image will consist of dots;
The code will cause an exception // "Error: Image data error" will be displayed;

Max 2
2

GEMS Metropole School Page 164 of 236


(c) 2 marks for AO2 (analyse)

The lower part of the picture will not be displayed/loaded // only the upper part of the
picture will be displayed/loaded;
Only the top 10 rows are displayed/loaded // the bottom 49 rows are not
displayed/loaded // only the cat’s head is displayed/loaded // the cat’s body has been
removed;

Max 2
2
[6]

All marks for AO2 (analyse)


42.
1) Each line/row of output across would consist of column pixels // Each column of
output would consist of row pixels;
2) The bottom left corner of the image would now be top right // top right corner of the
image would now be bottom left;
3) This would in effect be a flip/inversion;
4) across the diagonal;
5) … top left to bottom right // leading (diagonal);

Max 2 if overall effect is not clear.


Max 3
[3]

(a) 1 mark for AO3 (design) and 5 marks for AO3 (programming)
43.
Mark as follows:

AO3 (design) – 1 mark:

1) Declare a new grid to receive mirror image;

AO3 (programming) – 5 marks:

2) Create subroutine header with required parameters, I. extra parameters;


3) Column reference adjusted for mirror image;
4) Nested loops with correct ranges;
5) Add menu option in DisplayMenu;
6) Add call to MirrorImage in suitable place with parameters that match
subroutine definition in code, A. call to MirrorImage in suitable place with grid
and header parameters if subroutine definition not provided;

Max 5 if code does not function correctly.


6

GEMS Metropole School Page 165 of 236


VB.Net
Sub MirrorImage(ByVal Grid(,) As String, ByVal Header As FileHeader) '2
Dim NewGrid(Header.Height - 1, Header.Width - 1) As String '1
For Row = 0 To Header.Height – 1 '
For Column = 0 To Header.Width – 1 '4
NewGrid(Row, Column) = Grid(Row, Header.Width - 1 -Column) '3
Next
Next
DisplayImage(NewGrid, Header)
End Sub

Sub DisplayMenu()
Console.WriteLine()
Console.WriteLine("Main Menu")
Console.WriteLine("=========")
Console.WriteLine("L - Load graphics file")
Console.WriteLine("D - Display image")
Console.WriteLine("E - Edit image")
Console.WriteLine("S - Save image")
Console.WriteLine("X - Exit program")
Console.WriteLine("M - Mirror image") '5
End Sub

Sub Graphics()
Dim MenuOption As Char
Dim Grid(MAX_WIDTH - 1, MAX_HEIGHT - 1) As String
ClearGrid(Grid)
Dim Header As FileHeader
SetHeader(Header)
Dim ProgramEnd As Boolean = False
While Not ProgramEnd
DisplayMenu()
MenuOption = GetMenuOption()
If MenuOption = "L" Then
LoadFile(Grid, Header)
ElseIf MenuOption = "D" Then
DisplayImage(Grid, Header)
ElseIf MenuOption = "E" Then
Grid = EditImage(Grid, Header)
ElseIf MenuOption = "S" Then
SaveImage(Grid, Header)
ElseIf MenuOption = "X" Then
ProgramEnd = True
ElseIf MenuOption = "M" Then
MirrorImage(Grid, Header) '6
Else
Console.WriteLine("You did not choose a valid menu option. Try
again")
End If
End While
Console.WriteLine("You have chosen to exit the program")
Console.Write("Do you want to save the image as a graphics file? (Y/N)
")
Dim Answer As String = Console.ReadLine()
If Answer = "Y" Or Answer = "y" Then
SaveFile(Grid, Header)
End If
End Sub

GEMS Metropole School Page 166 of 236


Alternative answer for MirrorImage subroutine
Sub MirrorImage(ByVal Grid(,) As String, ByVal Header As FileHeader) '2
For Row = 0 To Header.Height – 1 '
For Column = 0 To Header.Width – 1 '4
Console.Write(Grid(Row, Header.Width - 1 - Column)) '3
Next
Console.WriteLine()
Next
End Sub

Python 3
def MirrorImage(Grid, Header): # 2
NewGrid = [[EMPTY_STRING for Column in range(MAX_WIDTH)] for Row in
range(MAX_HEIGHT)]
NewGrid = ClearGrid(NewGrid) # 1
for ThisRow in range(Header.Height): #
for NewColumn in range(Header.Width): # 4
NewGrid[ThisRow][NewColumn] = Grid[ThisRow][Header.Width -NewColumn
- 1] # 3
DisplayImage(NewGrid, Header)

def DisplayMenu():
print()
print("Main Menu")
print("=========")
print("L - Load graphics file")
print("D - Display image")
print("E - Edit image")
print("S - Save image")
print("M - Mirror image") # 5
print("X - Exit program")
print()

GEMS Metropole School Page 167 of 236


def Graphics():
Grid = [['' for Column in range(MAX_WIDTH)] for Row in
range(MAX_HEIGHT)]
Grid = ClearGrid(Grid)
Header = FileHeader()
ProgramEnd = False
while not ProgramEnd:
DisplayMenu()
MenuOption = GetMenuOption()
if MenuOption == 'L':
Grid, Header = LoadFile(Grid, Header)
elif MenuOption == 'D':
DisplayImage(Grid, Header)
elif MenuOption == 'E':
Grid = EditImage(Grid, Header)
elif MenuOption == 'S':
SaveImage(Grid, Header)
elif MenuOption == 'M':
Grid = MirrorImage(Grid, Header) # 6
elif MenuOption == 'X':
ProgramEnd = True
else:
print("You did not choose a valid menu option. Try again")
print("You have chosen to exit the program")
Answer = input("Do you want to save the image as a graphics file? (Y/N)
")
if Answer == "Y" or Answer == "y":
SaveFile(Grid, Header)

Python 2
def MirrorImage(Grid, Header): # 2
NewGrid = [[EMPTY_STRING for Column in range(MAX_WIDTH)] for Row in
range(MAX_HEIGHT)]
NewGrid = ClearGrid(NewGrid) # 1
for ThisRow in range(Header.Height):
for NewColumn in range(Header.Width): # 4
NewGrid[ThisRow][NewColumn] = Grid[ThisRow][Header.Width -NewColumn
- 1] # 3
DisplayImage(NewGrid, Header)

def DisplayMenu():
print
print "Main Menu"
print "========="
print "L - Load graphics file"
print "D - Display image"
print "E - Edit image"
print "S - Save image"
print "M - Mirror image" # 5
print "X - Exit program"
print

GEMS Metropole School Page 168 of 236


def Graphics():
Grid = [['' for Column in range(MAX_WIDTH)] for Row in
range(MAX_HEIGHT)]
Grid = ClearGrid(Grid)
Header = FileHeader()
ProgramEnd = False
while not ProgramEnd:
DisplayMenu()
MenuOption = GetMenuOption()
if MenuOption == 'L':
Grid, Header = LoadFile(Grid, Header)
elif MenuOption == 'D':
DisplayImage(Grid, Header)
elif MenuOption == 'E':
Grid = EditImage(Grid, Header)
elif MenuOption == 'S':
SaveImage(Grid, Header)
elif MenuOption == 'M':
Grid = MirrorImage(Grid, Header) # 6
elif MenuOption == 'X':
ProgramEnd = True
else:
print "You did not choose a valid menu option. Try again"
print "You have chosen to exit the program"
Answer = raw_input("Do you want to save the image as a graphics file?
(Y/N) ")
if Answer == "Y" or Answer == "y":
SaveFile(Grid, Header)

Pascal
procedure MirrorImage(var Grid: TGrid; Header: FileHeader); // 2
var
NewGrid: TGrid;
ThisRow, NewColumn: integer;
begin
ClearGrid(NewGrid); // 1
for ThisRow := 0 to Header.Height - 1 do
for NewColumn := 0 to Header.Width - 1 do // 4
NewGrid[ThisRow, NewColumn] := Grid[ThisRow, Header.Width -
NewColumn - 1]; // 3
DisplayImage(NewGrid, Header) ;
Grid := NewGrid;
end;

procedure DisplayMenu();
begin
writeln;
writeln('Main Menu');
writeln('=========');
writeln('L - Load graphics file');
writeln('D - Display image');
writeln('E - Edit image');
writeln('S - Save image');
writeln('M - Mirror image'); // 5
writeln('X - Exit program');
writeln;
end;

GEMS Metropole School Page 169 of 236


procedure Graphics();
var
Grid: TGrid;
Header: FileHeader;
ProgramEnd: boolean;
MenuOption: char;
Answer: char;
begin
ClearGrid(Grid);
SetHeader(Header);
ProgramEnd := false;
while not ProgramEnd do
begin
DisplayMenu();
MenuOption := GetMenuOption();
case MenuOption of
'L': LoadFile(Grid, Header);
'D': DisplayImage(Grid, Header);
'E': EditImage(Grid, Header);
'S': SaveImage(Grid, Header);
'M': MirrorImage(Grid, Header); // 6
'X': ProgramEnd := true;
else
writeln('You did not choose a valid menu option. Try again');
end;
end;
writeln('You have chosen to exit the program');
write('Do you want to save the image as a graphics file? (Y/N) ');
readln(Answer);
if (Answer = 'Y') or (Answer = 'y')
then
SaveFile(Grid, Header);
readln;
end;

GEMS Metropole School Page 170 of 236


C#
private static void MirrorImage(string[,] grid, FileHeader header)
{ // 2
string[,] newGrid = new string[MaxHeight, MaxWidth]; // 1
ClearGrid(newGrid);
for (int thisRow = 0; thisRow < header.Height; thisRow++) //
{
for (int newColumn = 0; newColumn < header.Width; newColumn++)
// 4
{
newGrid[thisRow, newColumn] = grid[thisRow, header.Width -
newColumn - 1]; // 3
}
}
DisplayImage(newGrid, header);
}

private static void DisplayMenu()


{
Console.WriteLine();
Console.WriteLine("Main Menu");
Console.WriteLine("=========");
Console.WriteLine("L - Load graphics file");
Console.WriteLine("D - Display image");
Console.WriteLine("E - Edit image");
Console.WriteLine("S - Save image");
Console.WriteLine("M - Mirror image"); // 5
Console.WriteLine("X - Exit program");
Console.WriteLine();
}

GEMS Metropole School Page 171 of 236


private static void Graphics()
{
string[,] grid = new string[MaxHeight, MaxWidth];
ClearGrid(grid);
FileHeader header = new FileHeader();
bool programEnd = false;
char menuOption;
char answer;
while (!programEnd)
{
DisplayMenu();
menuOption = GetMenuOption();
if (menuOption == 'L')
{
LoadFile(grid, header);
}
else if (menuOption == 'D')
{
DisplayImage(grid, header);
}
else if (menuOption == 'E')
{
EditImage(grid, header);
}
else if (menuOption == 'S')
{
SaveImage(grid, header);
}
else if (menuOption == 'M')
{
MirrorImage(grid, header); // 6
}
else if (menuOption == 'X')
{
programEnd = true;
}
else
{
Console.WriteLine("You did not choose a valid menu option.
Try again");
}
}
Console.WriteLine("You have chosen to exit the program");
Console.Write("Do you want to save the image as a graphics file?
(Y/N) ");
answer = Convert.ToChar(Console.ReadLine());
if (answer == 'Y' || answer == 'y')
{
SaveFile(grid, header);
}
}

GEMS Metropole School Page 172 of 236


Java
void mirrorImage(String[][] grid, FileHeader header) { // 2
String[][] newGrid = new String[MAX_HEIGHT][MAX_WIDTH]; // 1
clearGrid(newGrid);
for (int row = 0; row < header.height; row++) { //
for (int column = 0; column < header.width; column++) {// 4
newGrid[row][column] = grid[row][header.width - 1 -column];
// 3
}
}
displayImage(newGrid, header);
}

void displayMenu() {
Console.writeLine();
Console.writeLine("Main Menu");
Console.writeLine("=========");
Console.writeLine("L - Load graphics file");
Console.writeLine("D - Display image");
Console.writeLine("M - Mirror image"); // 5
Console.writeLine("E - Edit image");
Console.writeLine("S - Save image");
Console.writeLine("X - Exit program");
Console.writeLine();
}
void graphics() {
String[][] grid = new String[MAX_HEIGHT][MAX_WIDTH];
clearGrid(grid);
FileHeader header = new FileHeader();
boolean programEnd = false;
while (!programEnd) {
displayMenu();
char menuOption = GetMenuOption();
if ( menuOption == 'L') {
loadFile(grid, header);
} else if ( menuOption == 'D') {
displayImage(grid, header);
} else if (menuOption == 'M') {
mirrorImage(grid, header); // 6
} else if ( menuOption == 'E') {
editImage(grid, header);
} else if ( menuOption == 'S') {
saveImage(grid, header);
} else if ( menuOption == 'X') {
programEnd = true;
} else {
Console.writeLine("You did not choose a valid menu option.
Try again");
}
}
Console.writeLine("You have chosen to exit the program");
Console.write("Do you want to save the image as a graphics file?
(Y/N) ");
String answer = Console.readLine();
if ( answer.equals("Y") || answer.equals("y")) {
saveFile(grid, header);
}
}

GEMS Metropole School Page 173 of 236


(b) Mark is for AO3 (evaluate)

**** SCREEN CAPTURE ****


Must match code from (a), including prompts on screen capture matching those in
code.
Code for (a) must be sensible.

Screen capture showing:

Main Menu
=========
L - Load graphics file
D - Display image
E - Edit image
S - Save image
M - Mirror image
X - Exit program

Enter your choice: M

Cat
===

1
[7]

GEMS Metropole School Page 174 of 236


(a) 3 marks for AO3 (design) and 6 marks for AO3 (programming)
44.
Level Description Mark
Range

3 A line of reasoning has been followed to arrive at a logically 7–9


structured working or almost fully working programmed solution.
All of the appropriate design decisions have been taken. The
hidden message may not have been built entirely correctly.

2 There is evidence that a line of reasoning has been partially 4–6


followed. There is evidence of some appropriate design work.
The subroutine LoadGreyScaleImage has been amended with
a call to FindSecretChar in an appropriate place.

1 An attempt has been made to write the subroutine 1–3


FindSecretChar. Some appropriate programming statements
have been written. There is little evidence to suggest that a line
of reasoning has been followed or that the solution has been
designed. The statements written may or may not be
syntactically correct and the subroutines will have very little or
none of the extra required functionality. It is unlikely that any of
the key design elements of the task have been recognised.

Marking guidance:

Evidence of AO3 design – 3 marks:

Evidence of design to look for in response:

1) check whether value of pixel is in the correct range


2) convert a range of integers to a range of letters
3) call FindSecretChar with PixelValue and Key as parameters.

Note: AO3 (design) points are for selecting appropriate techniques to use to solve
the problem, so should be credited whether the syntax of programming language
statements is correct or not and regardless of whether the solution works.

Evidence of AO3 programming – 6 marks:

Evidence of programming to look for in response:

4) correct subroutine header and parameters for FindSecretChar, I. return type


5) generate underscore if no decrypted character found // generate space if
PixelValue – Key is zero
6) always returns the correct character
7) extract the key from the file header
8) concatenate hidden message and returned character within FOR loop
9) output the hidden message after FOR loop.

Max 8 if code does not function correctly.


9

GEMS Metropole School Page 175 of 236


VB.Net
Function FindSecretChar(ByVal PixelValue As Integer, ByVal Key As
Integer) As Char '4
Dim NewValue As Integer = PixelValue - Key
If NewValue = 0 Then
Return " " '6
ElseIf NewValue >= 1 And NewValue <= 26 Then '1
Return Chr(NewValue + Asc("A") – 1) '2
Else
Return "_" '5
End If
End Function

Sub LoadGreyScaleImage(ByVal FileIn As StreamReader, ByVal Grid(,) As


String, ByVal Header As FileHeader)
Try
Dim NextPixel As String
Dim PixelValue As Integer
Dim HiddenMessage As String = ""
Dim Key As Integer =
CInt(Header.Title.Substring(Header.Title.Length - 1, 1)) '7
For Row = 0 To Header.Height - 1
For Column = 0 To Header.Width - 1
NextPixel = FileIn.ReadLine()
PixelValue = CInt(NextPixel)
HiddenMessage += FindSecretChar(PixelValue, Key) '3, 8
Grid(Row, Column) = ConvertChar(PixelValue)
Next
Next
Console.WriteLine(HiddenMessage) '9
Catch
DisplayError("Image data error")
End Try
End Sub

GEMS Metropole School Page 176 of 236


Python 3
def FindSecretChar(PixelValue, Key): # 4
Character = '_' # 5
NewValue = PixelValue - Key
if NewValue == 0:
Character = ' ' # 6
elif NewValue in range(1, 27): # 1
Character = chr(ord('A') + NewValue - 1) # 2
return Character

def LoadGreyScaleImage(FileIn, Grid, Header):


try:
Key = int(Header.Title[-1]) # 7
HiddenMessage = EMPTY_STRING
for Row in range(Header.Height):
for Column in range(Header.Width):
NextPixel = FileIn.readline()
PixelValue = int(NextPixel)
HiddenMessage = HiddenMessage + FindSecretChar(PixelValue, Key) #
3, 8
Grid[Row][Column] = ConvertChar(PixelValue)
print(HiddenMessage) # 9
except:
DisplayError("Image data error")
return Grid

Python 2
def FindSecretChar(PixelValue, Key): # 4
Character = '_' # 5
NewValue = PixelValue - Key
if NewValue == 0:
Character = ' ' # 6
elif NewValue in range(1, 27): # 1
Character = chr(ord('A') + NewValue - 1) # 2
return Character

def LoadGreyScaleImage(FileIn, Grid, Header):


try:
Key = int(Header.Title[-1]) # 7
HiddenMessage = EMPTY_STRING
for Row in range(Header.Height):
for Column in range(Header.Width):
NextPixel = FileIn.readline()
PixelValue = int(NextPixel)
HiddenMessage = HiddenMessage + FindSecretChar(PixelValue, Key) #
3, 8
Grid[Row][Column] = ConvertChar(PixelValue)
print HiddenMessage # 9
except:
DisplayError("Image data error")
return Grid

GEMS Metropole School Page 177 of 236


Pascal
function FindSecretChar(PixelValue, Key: integer): char; // 4
var
Character: char;
NewValue: integer;
begin
Character := '_'; // 5
NewValue:= PixelValue - Key;
if NewValue = 0
then
Character := ' ' // 6
else
if (NewValue >= 1) And (NewValue <= 26) // 1
then
Character := chr(ord('A') + NewValue - 1); // 2
FindSecretChar := Character;
end;

procedure LoadGreyScaleImage(var FileIn: text; var Grid:


TGrid; var Header: FileHeader);
var
Row, Column: integer;
NextPixel, HiddenMessage: string;
PixelValue, Key: integer;
Begin
try
Key := strToInt(rightStr(Header.Title, 1)); // 7
HiddenMessage := EMPTY_STRING;
for Row := 0 to Header.Height - 1 do
for Column := 0 to Header.Width - 1 do
begin
readln(FileIn, NextPixel);
PixelValue := strToInt(NextPixel);
HiddenMessage := HiddenMessage + FindSecretChar(PixelValue,
Key); // 3, 8
Grid[Row, Column] := ConvertChar(PixelValue);
end;
writeln(HiddenMessage); // 9
except
DisplayError('Image data error');
end;
end;

GEMS Metropole School Page 178 of 236


C#
private static char FindSecretChar(int pixelValue, int key) // 4
{
char character;
int newValue;
character = '_'; // 5
newValue = pixelValue - key;
if (newValue == 0)
{
character = ' '; // 6
}
else
{
if (newValue >= 1 && newValue <= 26) // 1
{
character = ((char)((int)'A' + newValue - 1)); // 2
}
}
return character;
}

private static void LoadGreyScaleImage(StreamReader fileIn, string[,]


grid, FileHeader header)
{
string nextPixel;
int pixelValue;
int key;
string hiddenMessage;
try
{
key = Convert.ToInt32(header.title[header.title.Length -
1].ToString()); // 7
hiddenMessage = EMPTY_STRING;
for (int row = 0; row < header.Height; row++)
{
for (int column = 0; column < header.Width; column++)
{
nextPixel = fileIn.ReadLine();
pixelValue = Convert.ToInt32(nextPixel);
hiddenMessage = hiddenMessage +
FindSecretChar(pixelValue, key); // 3, 8
grid[row, column] = ConvertChar(pixelValue);
}
}
Console.WriteLine(hiddenMessage); // 9
}
catch (Exception)
{
DisplayError("Image data error");
}
}

GEMS Metropole School Page 179 of 236


Java
char findSecretChar(int pixelValue, int key) { // 4
char character = '_'; // 5
int newValue = pixelValue - key;
if (newValue == 0) {
character = ' '; // 6
} else if (newValue >= 1 && newValue < 27) { // 1
character = (char)((int)('A') + newValue - 1); // 2
}
return character;
}

void loadGreyScaleImage(BufferedReader fileIn, String[][] grid,


FileHeader header) {
try {
int key =
Integer.parseInt(header.title.charAt(header.title.length()-1) + ""); // 7
String hiddenMessage = EMPTY_STRING;
for (int row = 0; row < header.height; row++) {
for (int column = 0; column < header.width; column++) {
String nextPixel = fileIn.readLine();
int pixelValue = Integer.parseInt(nextPixel);
grid[row][column] = convertChar(pixelValue);
hiddenMessage = hiddenMessage +
findSecretChar(pixelValue, key); // 3, 8
}
}
Console.println(hiddenMessage); // 9
} catch (Exception e) {
displayError("Image data error");
}
}

(b) Mark is for AO3 (evaluate)

**** SCREEN CAPTURE ****


Must match code from (a), including prompts on screen capture matching those in
code.
Code for (a) must be sensible.

Screen capture showing:

Enter your choice: L


Enter filename to load: greyscale
H__E___L___P ME

TestImage2
==========
##&#.
&:#+&
####

A. hyphen instead of underscore character


1
[10]

GEMS Metropole School Page 180 of 236


(a) 3 marks for AO3 (design) and 9 marks for AO3 (programming)
45.
Level Description Mark
Range

3 A line of reasoning has been followed to arrive at a logically 9–12


structured working or almost fully working programmed solution.
All of the appropriate design decisions have been taken.
The last value pair may not have been saved.

2 There is evidence that a line of reasoning has been partially 5–8


followed. There is evidence of some appropriate design work.
Consecutive pixels are counted and most value pairs saved to a
new file, delimiter may be missing.

1 An attempt has been made to write the subroutine 1–4


CompressFile. Some appropriate programming statements
have been written. There is little evidence to suggest that a line
of reasoning has been followed or that the solution has been
designed. The statements written may or may not be
syntactically correct and the subroutines will have very little or
none of the extra required functionality. It is unlikely that any of
the key design elements of the task have been recognised.
Some appropriate programming statements from the LoadFile
subroutine may have been used for reading a file.

Marking guidance:

Evidence of AO3 design – 3 points:

Evidence of design to look for in response:

1) Attempts to create new file with modified file name


2) Structure that compares current character with previous character
3) Under some circumstances counts consecutive symbols correctly

Note: AO3 (design) points are for selecting appropriate techniques to use to solve
the problem, so should be credited whether the syntax of programming language
statements is correct or not and regardless of whether the solution works.

GEMS Metropole School Page 181 of 236


Evidence of AO3 programming – 9 points:

Evidence of programming to look for in response:

4) Ask user for file name


5) Open existing file for reading and new file for writing
6) Edit file header correctly
7) Initialise symbol count for first run of symbols
8) Check each pixel in the file
9) Save first symbol count and symbol to file
10) Save each symbol count and symbol to file (except first and last pairs)
11) Save last symbol count and symbol to file
12) Reset symbol count for next run of symbols

Max 11 if code does not function correctly.


12

VB.Net
Sub CompressFile()
Console.Write("Enter the filename containing the data to compress: ")
Dim FileName As String = Console.ReadLine '4
Dim FileIn As StreamReader = New StreamReader(FileName) '5
Dim HeaderLine As String = FileIn.ReadLine()
Dim Fields() As String = HeaderLine.Split(",")
Dim Header As FileHeader
Header.Title = Fields(0)
Header.Width = CInt(Fields(1))
Header.Height = CInt(Fields(2))
Header.FileType = "C" '6
Dim FileData As String = FileIn.ReadLine()
FileIn.Close()
Dim FileOut As StreamWriter = New StreamWriter("CMP" & FileName) '1, 5
FileOut.WriteLine(Header.Title + "," + CStr(Header.Width) + "," +
CStr(Header.Height) + "," + Header.FileType) '2
Dim Count As Integer = 1 '7
Dim LastChar As Char = FileData(0)
For Pos = 1 To FileData.Length – 1 '8
If FileData(Pos) = LastChar Then '2
Count += 1 '3
Else
FileOut.WriteLine(CStr(Count) + "," + LastChar) '9, 10
Count = 1 '12
LastChar = FileData(Pos)
End If
Next
FileOut.WriteLine(CStr(Count) + "," + LastChar) '11
FileOut.Close()
End Sub

GEMS Metropole School Page 182 of 236


Python 3
def CompressFile():
FileFound = False
Header = FileHeader()
FileName = input("Which graphics file do you want to compress? ") # 4
try:
FileIn = open(FileName + ".txt", 'r')
FileFound = True
FileOut = open("CMP" + FileName + ".txt", 'w') # 1, 5
HeaderLine = FileIn.readline()
HeaderLine = HeaderLine[0:-2] + "C" # 6
FileOut.write(HeaderLine + "\n") # 2
ImageData = FileIn.readline()
PrevPixelChar = ImageData[0]
PixelCount = 0 # 7
for NextPixelChar in ImageData: # 8
if NextPixelChar == PrevPixelChar: # 2
PixelCount += 1 # 3
else:
FileOut.write(str(PixelCount) + "," + PrevPixelChar + "\n") # 9,
10
PrevPixelChar = NextPixelChar
PixelCount = 1 # 12
FileOut.write(str(PixelCount) + "," + PrevPixelChar + "\n") # 11
FileOut.close()
FileIn.close()
except:
if not FileFound:
DisplayError("File not found")
else:
DisplayError("Error during compression")

GEMS Metropole School Page 183 of 236


Python 2
def CompressFile():
FileFound = False
Header = FileHeader()
FileName = raw_input("Which graphics file do you want to compress? ") #
4
try:
FileIn = open(FileName + ".txt", 'r')
FileFound = True
FileOut = open("CMP" + FileName + ".txt", 'w') # 1, 5
HeaderLine = FileIn.readline()
HeaderLine = HeaderLine[0:-2] + "C" # 6
FileOut.write(HeaderLine + "\n") # 2
ImageData = FileIn.readline()
PrevPixelChar = ImageData[0]
PixelCount = 0 # 7
for NextPixelChar in ImageData: # 8
if NextPixelChar == PrevPixelChar: # 2
PixelCount += 1 # 3
else:
FileOut.write(str(PixelCount) + "," + PrevPixelChar + "\n") # 9,
10
PrevPixelChar = NextPixelChar
PixelCount = 1 # 12
FileOut.write(str(PixelCount) + "," + PrevPixelChar + "\n") # 11
FileOut.close()
FileIn.close()
except:
if not FileFound:
DisplayError("File not found")
else:
DisplayError("Error during compression")

GEMS Metropole School Page 184 of 236


Pascal
procedure CompressFile();
var
FileFound: boolean;
Header: FileHeader;
FileIn, FileOut: text;
FileName, HeaderLine: string;
Fields: array[0 .. 4] of string;
i, PixelCount: integer;
PrevPixelChar, NextPixelChar: char;
begin
FileFound := false;
write('Which graphics file do you want to compress? ');
readln(FileName); // 4
try
assignFile(FileIn, FileName + '.txt');
reset(FileIn);
FileFound := true;
assignFile(FileOut, 'CMP' + FileName); // 1, 5
rewrite(FileOut);
readln(FileIn, HeaderLine);
HeaderLine := leftStr(HeaderLine, length(HeaderLine) - 1) + 'C'; // 6
writeln(FileOut, HeaderLine); // 2
PixelCount := 1; // 7
read(FileIn, PrevPixelChar);
while not eoln(FileIn) do // 8
begin
read(FileIn, NextPixelChar);
if NextPixelChar = PrevPixelChar // 2
then
PixelCount := PixelCount + 1 // 3
else
begin
writeln(FileOut, PixelCount, ',', PrevPixelChar); // 9, 10
PrevPixelChar := NextPixelChar;
PixelCount := 1; // 12
end;
end;
writeln(FileOut, PixelCount, ',', PrevPixelChar); // 11
closeFile(FileOut);
closeFile(FileIn);
except
if not FileFound
then
DisplayError('File not found')
else
DisplayError('Error during compression');
end;
end;

GEMS Metropole School Page 185 of 236


C#
private static void CompressFile()
{
bool fileFound = false;
string headerLine, imageData;
char prevPixelChar;
int pixelCount = 0; // 7
FileHeader header = new FileHeader();
Console.Write("Which graphics file do you want to compress? ");
string fileName = Console.ReadLine(); // 4
try
{
StreamReader filein = new StreamReader(fileName + ".txt");
fileFound = true; // 5
StreamWriter fileOut = new StreamWriter("CMP" + fileName +
".txt"); // 1, 5
headerLine = filein.ReadLine();
headerLine = headerLine.Substring(0, headerLine.Length -1) + "C";
// 6
fileOut.WriteLine(headerLine);
imageData = filein.ReadLine();
prevPixelChar = imageData[0];
foreach (char nextPixelChar in imageData) // 8
{
if (nextPixelChar == prevPixelChar) // 2
{
pixelCount++; // 3
}
else
{
fileOut.WriteLine(pixelCount + "," + prevPixelChar); //
9, 10
prevPixelChar = nextPixelChar;
pixelCount = 1; // 12
}
}
fileOut.WriteLine(pixelCount + "," + prevPixelChar); // 11
fileOut.Close();
filein.Close();
}
catch (Exception)
{
if (!fileFound)
{
DisplayError("File not found");
}
else
{
DisplayError("Error during compression");
}
}
}

GEMS Metropole School Page 186 of 236


Java
void compressFile ()
{
Console.write("Enter filename to compress: ");
String fileName = Console.readLine(); // 4
try {
BufferedReader fileIn = new BufferedReader(new
FileReader(fileName + ".txt")); // 5
BufferedWriter fileOut = new BufferedWriter(new FileWriter("CMP"
+ fileName + ".txt")); // 1, 5
String headerLine = fileIn.readLine();
headerLine = headerLine.substring(0, headerLine.length()-1) +
"C"; // 6
fileOut.write(headerLine + "\n");
String imageData = fileIn.readLine();
char previousPixelChar = imageData.charAt(0);
int pixelCount = 0; // 7
for (int pos = 0; pos < imageData.length(); pos++) { // 8
char nextPixelChar = imageData.charAt(pos);
if (nextPixelChar == previousPixelChar) { // 2
pixelCount++; // 3
} else {
fileOut.write(pixelCount + "," + previousPixelChar +
"\n"); // 9, 10
previousPixelChar = nextPixelChar;
pixelCount = 1; // 12
}
}
fileOut.write(pixelCount + "," + previousPixelChar + "\n"); // 11
fileIn.close();
fileOut.close();
} catch (IOException e) {
}
}

GEMS Metropole School Page 187 of 236


(b) Mark is for AO3 (evaluate)

**** SCREEN CAPTURE ****


Must match code from (a), including prompts on screen capture matching those in
code.
Code for (a) must be sensible.

Screen capture showing:

Enter your choice: C


Which graphics file do you want to compress? image2

1
[13]

GEMS Metropole School Page 188 of 236


All marks for AO1 (knowledge)
47.
Difference:
global variables accessible to all parts of the program
// declared in main program block
// local variables declared in subroutine
// accessible only in the program block/subroutine in which it was declared;

Reason:
memory allocated to local variables can be reused when subroutine not in use;
local variable only exists while the program block/subroutine is executing;
using local variables makes subroutines self-contained;
A. prevents accidental changes;
A. easier debugging/maintenance;
Max 2
[3]

(a) All marks for AO3 (programming)


48.
Mark as follows:
1) Correct variable declarations for NumberIn, NumberOut, Count,
PartValue;

Note to examiners
If a language allows variables to be used without explicit declaration (eg
Python) then this mark should be awarded if the correct variables exist in
the program code and the first value they are assigned is of the correct
data type.

2) Correct prompt "Enter a positive whole number: " and NumberIn


assigned value entered by user;
3) Correct initialisation of NumberOut and Count;
4) WHILE loop with syntax allowed by the programming language and
correct condition for termination of the loop;
5) Correct incrementation of Count within WHILE loop;
6) Correct assignment to PartValue within WHILE loop but before FOR loop;
7) Correct updating of NumberIn within WHILE loop but before FOR loop;
8) FOR loop with syntax allowed by the programming language over correct
range;
9) Correct assignment to PartValue inside FOR loop;
10) Correct calculation of NumberOut after FOR loop but within WHILE loop;
11) Output statement giving correct output after WHILE loop;

I. Ignore minor differences in case and spelling

Max 10 if code does not function correctly

GEMS Metropole School Page 189 of 236


VB.net

Dim NumberIn, NumberOut, Count, PartValue As Integer


Console.Write("Enter a positive whole number: ")
NumberIn = Console.ReadLine
NumberOut = 0
Count = 0
While NumberIn > 0
Count += 1
PartValue = NumberIn Mod 2
NumberIn \= 2
For i = 1 To Count - 1
PartValue *= 10
Next
NumberOut += PartValue
End While
Console.WriteLine("The result is: " &38; NumberOut)
Console.ReadLine()

Python 3

NumberIn = int(input('Enter a positive whole number: '))


NumberOut = 0
Count = 0
while NumberIn > 0:
Count += 1
PartValue = NumberIn % 2
NumberIn = NumberIn // 2
for i in range(1, Count):
PartValue = PartValue * 10
NumberOut = NumberOut + PartValue
print('The result is: ', NumberOut)

Python 2

NumberIn = int(raw_input('Enter a positive whole number: '))


NumberOut = 0
Count = 0
while NumberIn > 0:
Count += 1
PartValue = NumberIn % 2
NumberIn = NumberIn // 2
for i in range(1, Count):
PartValue = PartValue * 10
NumberOut = NumberOut + PartValue
print 'The result is: ', NumberOut

Pascal

var
NumberIn, NumberOut, Count, PartValue, i: integer;
begin
write('Enter a positive whole number: ');
readln(NumberIn);
NumberOut := 0;
Count := 0;
while NumberIn > 0 do

GEMS Metropole School Page 190 of 236


begin
Count := Count + 1;
PartValue := NumberIn mod 2;
NumberIn := NumberIn div 2;
for i := 1 to Count - 1 do
PartValue := PartValue * 10;
NumberOut := NumberOut + PartValue;
end;
writeln('The result is: ', NumberOut);
end;

C#

int count = 0, partValue, numberIn, numberOut = 0;


Console.Write("Enter a positive whole number: ");
numberIn = Convert.ToInt32(Console.ReadLine());
while (numberIn > 0)
{
count++;
partValue = numberIn % 2;
numberIn = numberIn / 2;
for (int i = 1; i > count; i++)
{
partValue = partValue * 10;
}
numberOut = numberOut + partValue;
}
Console.WriteLine("The result is: " + numberOut );
Console.ReadLine();

Java

Console.writeLine("Enter a positive whole number: ");


int numberIn = Integer.parseInt(Console.readLine());
int numberOut = 0;
int count = 0;
int partValue;
while (numberIn > 0) {
count++;
partValue = numberIn % 2;
numberIn = numberIn / 2;
for (int i = 1; i > count; i++) {
partValue = partValue * 10;
}
numberOut = numberOut + partValue;
}
Console.writeLine("The result is: " + numberOut);
11

GEMS Metropole School Page 191 of 236


(b) Mark is for AO3 (evaluate)

**** SCREEN CAPTURE ****


Must match code from part (a), including prompts on screen capture matching
those in code.
Code for part (a) must be sensible.

Screen capture showing:


'22' being entered and the message 'The result is: 10110' displayed
'29' being entered and the message 'The result is: 11101' displayed
'-1' being entered and the message 'The result is: 0' displayed
Enter a positive whole number: 22
The result is: 10110
>>>
Enter a positive whole number: 29
The result is: 11101
>>>
Enter a positive whole number: -1
The result is: 0
>>>
1

(c) Mark is for AO2 (analyse)

converts from (positive) decimal/denary to binary;


1
[13]

(a) Mark is for AO1 (understand)


49.
Valid
/ValidPiece
/ValidMove
/Found
/EndOfList
/Jumping
/GameEnd
/FileFound;
A. CanJump;

R. if any additional code


R. if spelt incorrectly
I. case & spacing
1

(b) Mark is for AO1 (understand)

/ValidMove
/ValidJump
/ListEmpty;

A. setUpBoard (for Java only)


R. if any additional code
R. if spelt incorrectly
I. case & spacing
1
[2]
GEMS Metropole School Page 192 of 236
Mark is for AO1 (understand)
50.
MoveRecord
/ListOfMoves;

R. if any additional code


R. if spelt incorrectly
R. case & spacing
[1]

Mark is for AO1 (understand)


51.
catch any file errors // stop program crashing if file doesn’t exist ;
[1]

Mark is for AO2 (analyse)


52.
positions of player A’s pieces;
A. the contents of (the data structure/variable) A // pointer/address to A // A;
[1]

(a) Mark is for AO2 (analyse)


53.
DisplayBoard;

R. if any additional code


R. if spelt incorrectly
I. case & spacing
1

(b) Mark is for AO2 (analyse)

PrintResult;

R. if any additional code


R. if spelt incorrectly
I. case & spacing
1

(c) Mark is for AO2 (analyse)

PrintLine;
A. PrintRow / PrintMiddleRow;

Max 1
R. if any additional code
R. if spelt incorrectly
I. case & spacing
1
[3]

GEMS Metropole School Page 193 of 236


1 mark is for AO1 (understand)
54.
it checks whether the sum of row and column are an even number;

2 marks for AO2 (analyse)

to blank out a square if it can’t be used;


to store a space if it can be used;
A. for 1 mark: creates the checker board pattern;
[3]

All marks for AO2 (analyse)


55.
1) User is asked to enter a Piece ID;
2) the ListOfMoves is searched (sequentially) // linear search of ListOfMoves //
ListOfMoves is stepped through;
3) for an occurrence of the piece ID entered;
4) until either the piece ID is found or the end of ListOfMoves is encountered;
5) if end of list is encountered user is asked again to enter the Piece ID;
[5]

(a) (i) All marks for AO3 (programming)


56.
Mark as follows:
1 mark for error codes 1 to 3 tested (using IF, nested IF or CASE)
A. Error messages in a data structure and accessed via error code as index
1 mark for appropriate error messages (A. similar wording but same meaning as):
'Error code 1 - Not a valid piece'
'Error code 2 - Not a valid move'
'Error code 3 - Not a number'
1 mark outputting error code (1, 2, 3 or 4)

Note:
Messages such as “Error Code 1 – not valid” are not detailed enough and
are not creditworthy.

VB.net

Sub DispayErrorCode(ByVal ErrorNumber As Integer)


Console.WriteLine("Error Code " & ErrorNumber)
If ErrorNumber = 1 Then
Console.WriteLine("not a valid piece")
ElseIf ErrorNumber = 2 Then
Console.WriteLine("not a valid move")
ElseIf ErrorNumber = 3 Then
Console.WriteLine("not a number")
ElseIf ErrorNumber = 4 Then
Console.WriteLine("file error")
End If
End Sub

GEMS Metropole School Page 194 of 236


Python 3

def DisplayErrorCode(ErrorNumber):
print('Error Code ', ErrorNumber, ' - ', end='')
if ErrorNumber == 1:
print('not a valid piece')
elif ErrorNumber == 2:
print('not a valid move')
elif ErrorNumber == 3:
print('not a number')
elif ErrorNumber == 4:
print('file error')

Python 2

def DisplayErrorCode(ErrorNumber):
print 'Error Code ', ErrorNumber
if ErrorNumber == 1:
print 'not a valid piece'
elif ErrorNumber == 2:
print 'not a valid move'
elif ErrorNumber == 3:
print 'not a number'
elif ErrorNumber == 4:
print 'file error'

Pascal

procedure DisplayErrorCode(ErrorNumber: integer);


begin
write('Error Code ', ErrorNumber, ' - ');
case ErrorNumber of
1 : writeln('not a valid piece');
2 : writeln('not a valid move');
3 : writeln('not a number');
4 : writeln('file error');
end;
end;

C#

private static void DisplayErrorCode(int errorNumber)


{
Console.WriteLine("Error Code " + errorNumber);
if (errorNumber == 1)
{
Console.WriteLine("not a valid piece");
}
else if (errorNumber == 2)
{
Console.WriteLine("not a valid move");
}
else if (errorNumber == 3)
{
Console.WriteLine("not a number");
}

GEMS Metropole School Page 195 of 236


else if (errorNumber == 4)
{
Console.WriteLine("file error");
}
}

Java

void displayErrorCode(int errorNumber) {


Console.write("Error Code " + errorNumber + " - ");
if (errorNumber == 1) {
Console.writeLine("not a valid piece");
} else if (errorNumber == 2) {
Console.writeLine("not a valid move");
} else if (errorNumber == 3) {
Console.writeLine("not a number");
} else if (errorNumber == 4) {
Console.writeLine("file error");
}
}
Alternative Example
void displayErrorCode(int errorNumber) {
Console.write("Error " + errorNumber + " - ");
switch (errorNumber) {
case 1:
Console.writeLine("not a valid piece.");
break;
case 2:
Console.writeLine("not a valid move");
break;
case 3:
Console.writeLine("not a number");
break;
case 4:
Console.writeLine("file error");
break;
}
}
3

(ii) Mark is for AO3 (evaluate)

**** SCREEN CAPTURE ****


Must match code from part (ai), including prompts on screen capture
matching those in code.
Code for part (ai) must be sensible.

Screen capture showing:


Next Player: a
a5 can jump to 3 , 2
a6 can jump to 3 , 0
a6 can jump to 3 , 4
a7 can jump to 3 , 2
a7 can jump to 3 , 6
a8 can jump to 3 , 4
a9 can move to 3 , 0
a9 can move to 3 , 2
a10 can move to 3 , 2
a10 can move to 3 , 4

GEMS Metropole School Page 196 of 236


a11 can move to 3 , 4
a11 can move to 3 , 6
a12 can move to 3 , 6
There are 13 possible moves
Which piece do you want to move? a4
Error code 1 – not a valid piece
Which piece do you want to move? a9
Which row do you want to move to? 3
Which column do you want to move to? 4
Error code 2 – not a valid move
Which row do you want to move to? a
Which column do you want to move to? 9
Error code 3 – not a number
Which row do you want to move to? 3
Which column do you want to move to? 0
1

(b) (i) 1 mark for AO3 (design) and 1 mark for AO3 (programming)

Mark as follows:

AO3 (design) – 1 mark:

1) choosing the final if statement to amend;

AO3 (programming) – 1 mark:

2) correct logic statement;

VB.net

Function ValidJump(ByVal Board(,) As String, ByVal


PlayersPieces(,) As Integer, ByVal Piece As String, ByVal
NewRow As Integer, ByVal NewColumn As Integer) As Boolean
Dim Valid As Boolean
Dim MiddlePiece, Player, OppositePiecePlayer,
MiddlePiecePlayer As String
Dim Index, CurrentRow, CurrentColumn, MiddlePieceRow,
MiddlePieceColumn As Integer
Valid = False
MiddlePiece = ""
Player = Left(Piece, 1).ToLower()
If Len(Piece) = 2 Then
Index = CInt(Right(Piece, 1))
Else
Index = CInt(Right(Piece, 2))
End If
If Player = "a" Then
OppositePiecePlayer = "b"
Else
OppositePiecePlayer = "a"
End If
If NewRow >= 0 And NewRow < BoardSize And NewColumn
>= 0 And NewColumn < BoardSize Then
If Board(NewRow, NewColumn) = Space Then
CurrentRow = PlayersPieces(Index, Row)
CurrentColumn = PlayersPieces(Index, Column)
MiddlePieceRow = (CurrentRow + NewRow) \ 2
MiddlePieceColumn = (CurrentColumn + NewColumn) \ 2

GEMS Metropole School Page 197 of 236


MiddlePiece = Board(MiddlePieceRow, MiddlePieceColumn)
MiddlePiecePlayer = Left(MiddlePiece, 1).ToLower()
If MiddlePiecePlayer = OppositePiecePlayer
Then
Valid = True
End If
End If
End If
Return Valid
End Function

Alternative logic statement:

MiddlePiecePlayer = OppositePiecePlayer and


MiddlePiecePlayer != ' ':

Python 3

def ValidJump(Board, PlayersPieces, Piece, NewRow, NewColumn):


Valid = False
MiddlePiece = ''
Player = Piece[0].lower()
Index = int(Piece[1:])
if Player == 'a':
OppositePiecePlayer = 'b'
else:
OppositePiecePlayer = 'a'
if NewRow in range(BOARD_SIZE) and NewColumn in range(BOARD_SIZE):
if Board[NewRow][NewColumn] == SPACE:
CurrentRow = PlayersPieces[Index][ROW]
CurrentColumn = PlayersPieces[Index][COLUMN]
MiddlePieceRow = (CurrentRow + NewRow) // 2
MiddlePieceColumn = (CurrentColumn + NewColumn) // 2
MiddlePiece = Board[MiddlePieceRow][MiddlePieceColumn]
MiddlePiecePlayer = MiddlePiece[0].lower()
if MiddlePiecePlayer == OppositePiecePlayer:
Valid = True
return Valid

Alternative logic statement:

MiddlePiecePlayer == OppositePiecePlayer and


MiddlePiecePlayer != ' ':

Python 2

def ValidJump(Board, PlayersPieces, Piece, NewRow, NewColumn):


Valid = False
MiddlePiece = ''
Player = Piece[0].lower()
Index = int(Piece[1:])
if Player == 'a':
OppositePiecePlayer = 'b'
else:
OppositePiecePlayer = 'a'
if NewRow in range(BOARD_SIZE) and NewColumn in range(BOARD_SIZE):
if Board[NewRow][NewColumn] == SPACE:
CurrentRow = PlayersPieces[Index][ROW]
CurrentColumn = PlayersPieces[Index][COLUMN]
MiddlePieceRow = (CurrentRow + NewRow) // 2
GEMS Metropole School Page 198 of 236
MiddlePieceColumn = (CurrentColumn + NewColumn) // 2
MiddlePiece = Board[MiddlePieceRow][MiddlePieceColumn]
MiddlePiecePlayer = MiddlePiece[0].lower()
if MiddlePiecePlayer == OppositePiecePlayer and
MiddlePiecePlayer != ' ':
Valid = True
return Valid

Pascal

function ValidJump(Board: TBoard; PlayersPieces: TPieces;


Piece: string; NewRow, NewColumn: integer): boolean;
var
Valid: boolean;
MiddlePiece: string;
Player, OppositePiecePlayer, MiddlePiecePlayer: string;
Index, CurrentRow, CurrentColumn, MiddlePieceRow,
MiddlePieceColumn: integer;
begin
Valid := false;
MiddlePiece := '';
Player := LowerCase(LeftStr(Piece, 1));
if Length(Piece) = 2 then
Index := StrtoInt(RightStr(Piece, 1))
else
Index := StrtoInt(RightStr(Piece, 2));
if Player = 'a' then
OppositePiecePlayer := 'b'
else
OppositePiecePlayer := 'a';
if (NewRow >= 0) and (NewRow < BoardSize) and (NewColumn >= 0) and
(NewColumn < BoardSize) then
if Board[NewRow, NewColumn] = Space then
begin
CurrentRow := PlayersPieces[Index, Row];
CurrentColumn := PlayersPieces[Index, Column];
MiddlePieceRow := (CurrentRow + NewRow) div 2;
MiddlePieceColumn := (CurrentColumn + NewColumn) div 2;
MiddlePiece := Board[MiddlePieceRow, MiddlePieceColumn];
MiddlePiecePlayer := LowerCase(LeftStr(MiddlePiece, 1));
if (MiddlePiecePlayer = OppositePiecePlayer) then
Valid := true;
end;
ValidJump := Valid;
end;

Alternative logic statement:

(MiddlePiecePlayer = OppositePiecePlayer) and (MiddlePiecePlayer <> '


')

C#

private static bool ValidJump(string[,] board, int[,] playersPieces,


string piece, int newRow, int newColumn)
{
string middlePiece = "";
string player, oppositePiecePlayer, middlePiecePlayer;
int index, currentRow, currentColumn, middlePieceRow,
middlePieceColumn;

GEMS Metropole School Page 199 of 236


player = piece[0].ToString().ToLower();
if (piece.Length == 2)
{
index = Convert.ToInt32(piece[1].ToString());
}
else
{
index = Convert.ToInt32(piece.Substring(1));
}
if (player == "a")
{
oppositePiecePlayer = "b";
}
else
{
oppositePiecePlayer = "a";
}
if (newRow >= 0 && newRow < BoardSize && newColumn >= 0 &&
newColumn < BoardSize)
{
if (board[newRow, newColumn] == Space)
{
currentRow = playersPieces[index, Row];
currentColumn = playersPieces[index, Column];
middlePieceRow = (currentRow + newRow) / 2;
middlePieceColumn = (currentColumn + newColumn) / 2;
middlePiece = board[middlePieceRow, middlePieceColumn];
middlePiecePlayer = middlePiece[0].ToString().ToLower();
if (middlePiecePlayer == oppositePiecePlayer)
{
return true;
}
}
}
return false;
}

Alternative logic statement:

(middlePiecePlayer == oppositePiecePlayer) && middlePiecePlayer != "


"

Java

boolean validJump(String[][] board, int[][] playersPieces, String


piece, int newRow, int newColumn) {
boolean valid = false;
String oppositePiecePlayer, middlePiecePlayer, player, middlePiece;
int index, currentRow, currentColumn, middlePieceRow,
middlePieceColumn;
player = (piece.charAt(0) + "").toLowerCase();
index = Integer.parseInt(piece.substring(1));
if (player.equals("a")) {
oppositePiecePlayer = "b";
} else {
oppositePiecePlayer = "a";
}

GEMS Metropole School Page 200 of 236


if (newRow >= 0 && newRow < BOARD_SIZE && newColumn >= 0 &&
newColumn < BOARD_SIZE) {
if (board[newRow][newColumn].equals(SPACE)) {
currentRow = playersPieces[index][ROW];
currentColumn = playersPieces[index][COLUMN];
middlePieceRow = (currentRow + newRow) / 2;
middlePieceColumn = (currentColumn + newColumn) / 2;
middlePiece = board[middlePieceRow][middlePieceColumn];
middlePiecePlayer = (middlePiece.charAt(0) + "").toLowerCase();
if (middlePiecePlayer.equals(oppositePiecePlayer)) {
valid = true;
}
}
}
return valid;
}
}
1

(ii) Mark is for AO3 (evaluate)

**** SCREEN CAPTURE ****


Must match code from part (bi), including prompts on screen capture
matching those in code.
Code for part (bi) must be sensible.

Screen capture showing:


Next Player: a
a1 can move to 1 , 0
a1 can move to 1 , 2
a2 can move to 7 , 0
a3 can move to 3 , 6
a5 can move to 4 , 3
a5 can jump to 5 , 0
a6 can jump to 5 , 2
a7 can move to 3 , 4
a7 can move to 3 , 6
There are 9 possible moves
Which piece do you want to move? a5
Which row do you want to move to? 5
Which column do you want to move to? 0
jumped over b1

GEMS Metropole School Page 201 of 236


Player A:
[[9, 0, 0], [0, 1, 0], [6, 1, 0], [2, 7, 0], [0, 7, 0], [5, 0, 0],
[3, 0, 0], [2, 5, 0], [1, 6, 0], [-1, -1, 0], [-1, -1, 0], [-1, -1,
0], [-1, -1, 0]]
Player B:
[[8, 0, 0], [4, 1, 0], [7, 2, 0], [5, 6, 0], [5, 4, 0], [1, 4, 0],
[6, 3, 0], [6, 5, 0], [6, 7, 0], [-1, -1, 0], [-1, -1, 0], [-1, -1,
0], [-1, -1, 0]]

GEMS Metropole School Page 202 of 236


(c) (i) 2 marks for AO3 (design) and 7 marks for AO3 (programming)

Mark
Level Description
Range

A line of reasoning has been followed to arrive at a


logically structured working or almost fully working
3 7-9
programmed solution. All of the appropriate design
decisions have been taken.

There is evidence that a line of reasoning has been


2 partially followed. There is evidence of some appropriate 4-6
design work.

An attempt has been made to write and amend the


subroutine PrintResult. Some appropriate
programming statements have been written. There is
little evidence to suggest that a line of reasoning has
been followed or that the solution has been designed.
1 1-3
The statements written may or may not be syntactically
correct and the subroutines will have very little or none
of the extra required functionality. It is unlikely that any
of the key design elements of the task have been
recognised.

Marking guidance:

Evidence of AO3 design – 2 points:

Evidence of design to look for in response:

1) subroutine CountNumberOfPieces with interface so can be


used for both A and B
2) A method for checking piece exists on board

Evidence of AO3 programming – 7 points:

Evidence of programming to look for in response:

3) in CountNumberOfPieces count variable initialised, updated and returned


correctly
A. counting non-dames only
4) in CountNumberOfPieces loop through A/B/PlayersPieces
5) use value stored in A/B [0,1] as the number of dames
6) formula given in Q correctly programmed
7) comparing the two players’ scores and output winner correctly
8) output calculated scores
9) sensible output in case of a draw

GEMS Metropole School Page 203 of 236


VB.net

Function CountNumberOfPieces(ByVal PlayersPieces(,) As Integer) As


Integer
Dim Count As Integer = 0
For Index = 1 To NumberOfPieces
If PlayersPieces(Index, Row) > -1 Then
Count += 1
End If
Next
Return Count
End Function

Sub PrintResult(ByVal A(,) As Integer, ByVal B(,) As Integer, ByVal


NextPlayer As String)
Console.WriteLine("Game ended")
Dim TotalA As Integer = CountNumberOfPieces(A)
Dim TotalB As Integer = CountNumberOfPieces(B)
TotalA = A(0, 0) - TotalA - 10 * A(0, 1)
TotalB = B(0, 0) - TotalB - 10 * B(0, 1)
If TotalA < TotalB Then
Console.WriteLine("A won this game with a score of " & TotalA)
Console.WriteLine("B got a score of " & TotalB)
ElseIf TotalB < TotalA Then
Console.WriteLine("B won this game with a score of " & TotalB)
Console.WriteLine("A got a score of ", TotalA)
Else
Console.WriteLine("It was a draw. Both players got a score of " &
TotalA)
End If
PrintPlayerPieces(A, B)
End Sub

Python 3

def CountNumberOfPieces(PlayersPieces):
Count = 0
for Index in range(1, NUMBER_OF_PIECES + 1):
if PlayersPieces[Index][ROW] > -1:
# allow COLUMN instead of ROW
Count += 1
return Count

def PrintResult(A, B, NextPlayer):


print('Game ended')
TotalA = CountNumberOfPieces(A)
TotalB = CountNumberOfPieces(B)
TotalA = A[0][0] - TotalA - 10 * A[0][1]
TotalB = B[0][0] - TotalB - 10 * B[0][1]
if TotalA < TotalB:
print('A won this game with a score of ', TotalA)
print('B got a score of ', TotalB)
elif TotalB < TotalA:
print('B won this game with a score of ', TotalB)
print('A got a score of ', TotalA)
else:
print('it was a draw. Both players got a score of ', TotalA)
PrintPlayerPieces(A, B)

GEMS Metropole School Page 204 of 236


Python 2

def CountNumberOfPieces(PlayersPieces):
Count = 0
for Index in range(1, NUMBER_OF_PIECES + 1):
if PlayersPieces[Index][ROW] > -1:
# allow COLUMN instead of ROW
Count += 1
return Count
def PrintResult(A, B, NextPlayer):
print 'Game ended'
TotalA = CountNumberOfPieces(A)
TotalB = CountNumberOfPieces(B)
TotalA = A[0][0] - TotalA - 10 * A[0][1]
TotalB = B[0][0] - TotalB - 10 * B[0][1]
if TotalA < TotalB:
print 'A won this game with a score of ', TotalA
print 'B got a score of ', TotalB
elif TotalB < TotalA:
print 'B won this game with a score of ', TotalB
print 'A got a score of ', TotalA
else:
print 'it was a draw. Both players got a score of ', TotalA
PrintPlayerPieces(A, B)

Pascal

function CountNumberOfPieces(PlayersPieces: TPieces):


integer;
var Count, Index: integer;
begin
Count := 0;
for Index := 1 to NumberOfPieces do
if PlayersPieces[Index, ROW] > -1 then
// allow Column instead of Row
Count := Count + 1;
CountNumberOfPieces := Count;
end;

procedure PrintResult(A, B: TPieces; NextPlayer: string);


var TotalA, TotalB: integer;
begin
writeln('Game ended');
TotalA := CountNumberOfPieces(A);
TotalB := CountNumberOfPieces(B);
TotalA := A[0, 0] - TotalA - 10 * A[0, 1];
TotalB := B[0, 0] - TotalB - 10 * B[0, 1] ;
if TotalA < TotalB then
begin
writeln('A won this game with a score of ', TotalA);
writeln('B got a score of ', TotalB);
end
else
if TotalB < TotalA then
begin
writeln('B won this game with a score of ', TotalB);
writeln('A got a score of ', TotalA);
end

GEMS Metropole School Page 205 of 236


else
writeIn('it was a draw. Both players got a score of ', TotalA);
PrintPlayerPieces(A, B);
end;

C#

private static int CountNumberOfPieces(int[,] playersPieces)


{
int count = 0;
for (int index = 1; index < NumberOfPieces + 1; index++)
{
if (playersPieces[index,Row] > -1) // allow Column instead of Row
{
count++;
}
}
return count;
}

private static void PrintResult(int[,] a, int[,] b, string


nextPlayer)
{
int totalA, totalB;
Console.WriteLine("Game ended");
totalA = CountNumberOfPieces(a);
totalB = CountNumberOfPieces(b);
totalA = a[0, 0] - totalA - 10 * a[0, 1];
totalB = b[0, 0] - totalB - 10 * b[0, 1];
if (totalA < totalB)
{
Console.WriteLine("A won this game with a score of " + totalA);
Console.WriteLine("B got a score of " + totalB);
}
else if (totalB < totalA)
{
Console.WriteLine("B won this game with a score of " + totalB);
Console.WriteLine("A got a score of " + totalA);
}
else
{
Console.WriteLine("it was a draw. Both players got a score of " +
totalA);
}
PrintPlayerPieces(a, b);
}

Java

int countNumberOfPieces(int[][] playerPieces) {


int count = 0;
for (int index = 1; index < NUMBER_OF_PIECES + 1; index++) {

GEMS Metropole School Page 206 of 236


if (playerPieces[index][ROW] > -1) {
count++;
}
}
return count;
}

void printResult(int[][] a, int[][] b, String nextPlayer)


{
Console.writeLine("Game ended");
int totalA = countNumberOfPieces(a);
int totalB = countNumberOfPieces(b);
totalA = a[0][0] - totalA - 10 * a[0][1];
totalB = b[0][0] - totalB - 10 * b[0][1];
if (totalA < totalB) {
Console.writeLine("A won with a score of " + totalA);
Console.writeLine("B got a score of " + totalB);
} else if (totalB < totalA) {
Console.writeLine("B won with a score of " + totalB);
Console.writeLine("A got a score of " + totalA);
} else {
Console.writeLine("it was a draw. Both players got a score of " +
totalA);
}
printPlayerPieces(a, b);
}
2

(ii) Mark is for AO3 (evaluate)

**** SCREEN CAPTURE ****


Must match code from part (ci), including prompts on screen capture
matching those in code.
Code for part (ci) must be sensible.

Screen capture showing:


Enter the filename: game4.txt

GEMS Metropole School Page 207 of 236


Player A:
[[15, 2, 0], [1, 2, 0], [0, 3, 0], [0, 5, 0], [1, 6, 0], [0, 1, 1],
[1, 0, 1], [1, 4, 0], [2, 7, 0], [2, 1, 0], [2, 3, 0], [2, 5, 0], [3,
6, 0]]
Player B:
[[15, 0, 0], [4, 3, 0], [5, 0, 0], [5, 6, 0], [5, 4, 0], [4, 1, 0],
[3, 2, 0], [6, 5, 0], [6, 7, 0], [3, 0, 0], [3, 4, 0], [4, 5, 0], [4,
7, 0]]

Next Player: a
There are 0 possible moves
Game ended
A won this game with a score of -17
B got a score of 3
1

(d) (i) Mark is for AO2 (analyse)

OpponentsPieces;

R. if any additional code


R. if spelt incorrectly
I. case & spacing
1

GEMS Metropole School Page 208 of 236


(ii) 2 marks for AO3 (design) and 7 marks for AO3 (programming)

Mark
Level Description
Range

A line of reasoning has been followed to arrive at a


logically structured working or almost fully working
3 programmed solution. 7-9

All of the appropriate design decisions have been taken.

There is evidence that a line of reasoning has been


2 partially followed. There is evidence of some appropriate 4-6
design work.

An attempt has been made to amend the subroutine


MoveDame. Some appropriate programming statements
have been written. There is little evidence to suggest
that a line of reasoning has been followed or that the
1 solution has been designed. The statements written may 1-3
or may not be syntactically correct and the subroutines
will have very little or none of the extra required
functionality. It is unlikely that any of the key design
elements of the task have been recognised.

Marking guidance:

Evidence of AO3 design – 2 points:

Evidence of design to look for in response:

1) validate that chosen piece is an opponent’s existing piece


2) return updated OpponentsPieces from subroutine MoveDame
(parameter by reference)

Evidence of AO3 programming – 7 points:

Evidence of programming to look for in response:

3) user prompt for which piece to take


4) extracting player letter from chosen piece
5) extracting index from chosen piece
6) retrieving coodinates from OpponentsPieces
7) set opponent’s piece coordinates to -1
8) new dame’s coordinates set to taken piece’s coordinates
9) update parameters in calls to MovePiece in subroutine
MakeMove (parameter by reference)

A. solutions that ask the user to input the row and column of the piece to be removed.

GEMS Metropole School Page 209 of 236


VB.net

Sub MoveDame(ByRef OpponentsPieces(,) As Integer, ByRef NewRow As


Integer, ByRef NewColumn As Integer, ByVal Player As String)
Dim Opponent As String = ""
Dim ChosenPiece As String
Dim Index As Integer
NewRow = -1
While Player = Opponent Or NewRow = -1
Console.Write("Which piece do you want to take?")
ChosenPiece = Console.ReadLine
Opponent = ChosenPiece.Substring(0, 1).ToLower
Index = CInt(ChosenPiece.Substring(1, ChosenPiece.Length - 1))
NewRow = OpponentsPieces(Index, Row)
NewColumn = OpponentsPieces(Index, Column)
End While
OpponentsPieces(Index, Row) = -1
OpponentsPieces(Index, Column) = -1
End Sub

Sub MakeMove(ByRef Board(,) As String, ByRef


PlayersPieces(,) As Integer, ByRef OpponentsPieces(,) As Integer,
ByVal ListOfMoves() As MoveRecord, ByVal PieceIndex As Integer)
Dim Piece, MiddlePiece As String
Dim NewRow, NewColumn, PlayersPieceIndex, CurrentRow,
CurrentColumn, MiddlePieceRow, MiddlePieceColumn As Integer
Dim Jumping As Boolean
PlayersPieces(0, 0) = PlayersPieces(0, 0) + 1
If PieceIndex > 0 Then
Piece = ListOfMoves(PieceIndex).Piece
NewRow = ListOfMoves(PieceIndex).NewRow
NewColumn = ListOfMoves(PieceIndex).NewColumn
If Len(Piece) = 2 Then
PlayersPieceIndex = CInt(Right(Piece, 1))
Else
PlayersPieceIndex = CInt(Right(Piece, 2))
End If
CurrentRow = PlayersPieces(PlayersPieceIndex, Row)
CurrentColumn = PlayersPieces(PlayersPieceIndex, Column)
Jumping = ListOfMoves(PieceIndex).CanJump
MovePiece(Board, PlayersPieces, OpponentsPieces, Piece, NewRow,
NewColumn)
If Jumping Then
MiddlePieceRow = (CurrentRow + NewRow) \ 2
MiddlePieceColumn = (CurrentColumn + NewColumn) \ 2
MiddlePiece = Board(MiddlePieceRow, MiddlePieceColumn)
Console.WriteLine("jumped over " & MiddlePiece)
End If
End If
End Sub

GEMS Metropole School Page 210 of 236


Sub MovePiece(ByRef Board(,) As String, ByRef PlayersPieces(,) As
Integer, ByRef OpponentsPieces(,) As Integer, ByVal ChosenPiece As
String, ByVal NewRow As Integer, ByVal NewColumn As Integer)
Dim Index, CurrentRow, CurrentColumn As Integer
Dim Player As String
If Len(ChosenPiece) = 2 Then
Index = CInt(Right(ChosenPiece, 1))
Else
Index = CInt(Right(ChosenPiece, 2))
End If
CurrentRow = PlayersPieces(Index, Row)
CurrentColumn = PlayersPieces(Index, Column)
Board(CurrentRow, CurrentColumn) = Space
If NewRow = BoardSize - 1 And PlayersPieces(Index, Dame) = 0 Then
Player = "a"
PlayersPieces(0, 1) = PlayersPieces(0, 1) + 1
PlayersPieces(Index, Dame) = 1
ChosenPiece = ChosenPiece.ToUpper()
MoveDame(OpponentsPieces, NewRow, NewColumn, Player)
Else
If NewRow = 0 And PlayersPieces(Index, Dame) = 0 Then
Player = "b"
PlayersPieces(0, 1) = PlayersPieces(0, 1) + 1
PlayersPieces(Index, Dame) = 1
ChosenPiece = ChosenPiece.ToUpper()
MoveDame(OpponentsPieces, NewRow, NewColumn, Player)
End If
End If
PlayersPieces(Index, Row) = NewRow
PlayersPieces(Index, Column) = NewColumn
Board(NewRow, NewColumn) = ChosenPiece
End Sub

Python 3

def MoveDame(Player, OpponentsPieces):


NewRow = -1
Opponent = ''
while Player == Opponent or NewRow == -1:
ChosenPiece = input('Which piece do you want to take? ')
Opponent = ChosenPiece[0].lower()
Index = int(ChosenPiece[1:])
NewRow = OpponentsPieces[Index][ROW]
NewColumn = OpponentsPieces[Index][COLUMN]
OpponentsPieces[Index][ROW] = -1
OpponentsPieces[Index][COLUMN] = -1
return NewRow, NewColumn, OpponentsPieces
def MovePiece(Board, PlayersPieces, OpponentsPieces, ChosenPiece,
NewRow, NewColumn):
Index = int(ChosenPiece[1:])
CurrentRow = PlayersPieces[Index][ROW]
CurrentColumn = PlayersPieces[Index][COLUMN]
Board[CurrentRow][CurrentColumn] = SPACE

GEMS Metropole School Page 211 of 236


if NewRow == BOARD_SIZE - 1 and PlayersPieces[Index][DAME] == 0:
Player = 'a'
PlayersPieces[0][1] += 1
PlayersPieces[Index][DAME] = 1
ChosenPiece = ChosenPiece.upper()
NewRow, NewColumn, OpponentsPieces = MoveDame(Player,
OpponentsPieces)
elif NewRow == 0 and PlayersPieces[Index][DAME] == 0:
Player = 'b'
PlayersPieces[0][1] += 1
PlayersPieces[Index][DAME] = 1
ChosenPiece = ChosenPiece.upper()
NewRow, NewColumn, OpponentsPieces = MoveDame(Player,
OpponentsPieces)
PlayersPieces[Index][ROW] = NewRow
PlayersPieces[Index][COLUMN] = NewColumn
Board[NewRow][NewColumn] = ChosenPiece
return Board, PlayersPieces, OpponentsPieces

def MakeMove(Board, PlayersPieces, OpponentsPieces, ListOfMoves,


PieceIndex):
PlayersPieces[0][0] += 1
if PieceIndex > 0:
Piece = ListOfMoves[PieceIndex].Piece
NewRow = ListOfMoves[PieceIndex].NewRow
NewColumn = ListOfMoves[PieceIndex].NewColumn
PlayersPieceIndex = int(Piece[1:])
CurrentRow = PlayersPieces[PlayersPieceIndex][ROW]
CurrentColumn = PlayersPieces[PlayersPieceIndex][COLUMN]
Jumping = ListOfMoves[PieceIndex].CanJump
Board, PlayersPieces, OpponentsPieces = MovePiece(Board,
PlayersPieces, OpponentsPieces, Piece, NewRow, NewColumn)
if Jumping:
MiddlePieceRow = (CurrentRow + NewRow) // 2
MiddlePieceColumn = (CurrentColumn + NewColumn) // 2
MiddlePiece = Board[MiddlePieceRow][MiddlePieceColumn]
print('jumped over ', MiddlePiece)
return Board, PlayersPieces, OpponentsPieces

Python 2

def MoveDame(Player, OpponentsPieces):


NewRow = -1
Opponent = ''
while Player == Opponent or NewRow == -1:
ChosenPiece = raw_input('Which piece do you want to take? ')
Opponent = ChosenPiece[0].lower()
Index = int(ChosenPiece[1:])
NewRow = OpponentsPieces[Index][ROW]
NewColumn = OpponentsPieces[Index][COLUMN]
OpponentsPieces[Index][ROW] = -1
OpponentsPieces[Index][COLUMN] = -1
return NewRow, NewColumn, OpponentsPieces

GEMS Metropole School Page 212 of 236


def MovePiece(Board, PlayersPieces, OpponentsPieces, ChosenPiece,
NewRow, NewColumn):
Index = int(ChosenPiece[1:])
CurrentRow = PlayersPieces[Index][ROW]
CurrentColumn = PlayersPieces[Index][COLUMN]
Board[CurrentRow][CurrentColumn] = SPACE

if NewRow == BOARD_SIZE - 1 and PlayersPieces[Index][DAME] == 0:


Player = 'a'
PlayersPieces[0][1] += 1
PlayersPieces[Index][DAME] = 1
ChosenPiece = ChosenPiece.upper()
NewRow, NewColumn, OpponentsPieces = MoveDame(Player,
OpponentsPieces)
elif NewRow == 0 and PlayersPieces[Index][DAME] == 0:
Player = 'b'
PlayersPieces[0][1] += 1
PlayersPieces[Index][DAME] = 1
ChosenPiece = ChosenPiece.upper()
NewRow, NewColumn, OpponentsPieces = MoveDame(Player,
OpponentsPieces)
PlayersPieces[Index][ROW] = NewRow
PlayersPieces[Index][COLUMN] = NewColumn
Board[NewRow][NewColumn] = ChosenPiece
return Board, PlayersPieces, OpponentsPieces

def MakeMove(Board, PlayersPieces, OpponentsPieces, ListOfMoves,


PieceIndex):
PlayersPieces[0][0] += 1
if PieceIndex > 0:
Piece = ListOfMoves[PieceIndex].Piece
NewRow = ListOfMoves[PieceIndex].NewRow
NewColumn = ListOfMoves[PieceIndex].NewColumn
PlayersPieceIndex = int(Piece[1:])
CurrentRow = PlayersPieces[PlayersPieceIndex][ROW]
CurrentColumn = PlayersPieces[PlayersPieceIndex][COLUMN]
Jumping = ListOfMoves[PieceIndex].CanJump
Board, PlayersPieces, OpponentsPieces = MovePiece(Board,
PlayersPieces, OpponentsPieces, Piece, NewRow, NewColumn)
if Jumping:
MiddlePieceRow = (CurrentRow + NewRow) // 2
MiddlePieceColumn = (CurrentColumn + NewColumn) // 2
MiddlePiece = Board[MiddlePieceRow][MiddlePieceColumn]
print 'jumped over ', MiddlePiece
return Board, PlayersPieces, OpponentsPieces

Pascal

procedure MoveDame(Player: string; var OpponentsPieces:


TPieces; var NewRow, NewColumn: integer);
var
Opponent, ChosenPiece: string;
Index: integer;

GEMS Metropole School Page 213 of 236


begin
NewRow := -1;
Opponent := '';
while (Player = Opponent) or (NewRow = -1) do
begin
write('Which piece do you want to take? ');
readln(ChosenPiece);
Opponent := LowerCase(LeftStr(ChosenPiece,1));
if Length(ChosenPiece) = 2 then
Index := StrtoInt(RightStr(ChosenPiece,1))
else
Index := StrtoInt(RightStr(ChosenPiece,2));
NewRow := OpponentsPieces[Index, Row];
NewColumn := OpponentsPieces[Index][Column];
end;
OpponentsPieces[Index, Row] := -1;
OpponentsPieces[Index, Column] := -1;
end;

procedure MakeMove(var Board: TBoard; var PlayersPieces,


OpponentsPieces: TPieces; ListOfMoves: TList;
PieceIndex: integer);
var
Piece, MiddlePiece: string;
NewRow, NewColumn, PlayersPieceIndex, CurrentRow, CurrentColumn:
integer;
MiddlePieceRow, MiddlePieceColumn: integer;
Jumping: boolean;
begin
PlayersPieces[0, 0] := PlayersPieces[0, 0] + 1;
if PieceIndex > 0 then
begin
Piece := ListOfMoves[PieceIndex].Piece;
NewRow := ListOfMoves[PieceIndex].NewRow;
NewColumn := ListOfMoves[PieceIndex].NewColumn;
if Length(Piece) = 2 then
PlayersPieceIndex := StrtoInt(RightStr(Piece, 1))
else
PlayersPieceIndex := StrtoInt(RightStr(Piece, 2));
CurrentRow := PlayersPieces[PlayersPieceIndex, Row];
CurrentColumn := PlayersPieces[PlayersPieceIndex, Column];
Jumping := ListOfMoves[PieceIndex].CanJump;
MovePiece(Board, PlayersPieces, OpponentsPieces, Piece, NewRow,
NewColumn);
if Jumping then
begin
MiddlePieceRow := (CurrentRow + NewRow) div 2;
MiddlePieceColumn := (CurrentColumn + NewColumn) div 2;
MiddlePiece := Board[MiddlePieceRow, MiddlePieceColumn];
end;
end;
end;

GEMS Metropole School Page 214 of 236


procedure MovePiece(var Board: TBoard; var PlayersPieces,
OpponentsPieces: TPieces;
ChosenPiece: string; NewRow, NewColumn: integer);
var
Index, CurrentRow, CurrentColumn: integer;
Player: string;
begin
if Length(ChosenPiece) = 2 then
Index := StrtoInt(RightStr(ChosenPiece,1))
else
Index := StrtoInt(RightStr(ChosenPiece,2));
CurrentRow := PlayersPieces[Index, Row];
CurrentColumn := PlayersPieces[Index, Column];
Board[CurrentRow, CurrentColumn] := Space;

if (NewRow = BoardSize-1) and (PlayersPieces[Index, Dame] = 0) then


begin
Player := 'a';
PlayersPieces[0,1] := PlayersPieces[0,1] + 1;
PlayersPieces[Index, Dame] := 1;
ChosenPiece := UpperCase(ChosenPiece);
MoveDame(Player, OpponentsPieces, NewRow, NewColumn);
end
else
if (NewRow = 0) and (PlayersPieces[Index, Dame] = 0) then
begin
Player := 'b';
PlayersPieces[0, 1] := PlayersPieces[0, 1] + 1;
PlayersPieces[Index, Dame] := 1;
ChosenPiece := UpperCase(ChosenPiece);
MoveDame(Player, OpponentsPieces, NewRow, NewColumn);
end;
PlayersPieces[Index, Row] := NewRow;
PlayersPieces[Index, Column] := NewColumn;
Board[NewRow, NewColumn] := ChosenPiece;
end;

procedure MakeMove(var Board: TBoard; var PlayersPieces,


OpponentsPieces: TPieces; ListOfMoves: TList; PieceIndex: integer);
var
Piece, MiddlePiece: string;
NewRow, NewColumn, PlayersPieceIndex, CurrentRow, CurrentColumn:
integer;
MiddlePieceRow, MiddlePieceColumn: integer;
Jumping: boolean;
begin
PlayersPieces[0, 0] := PlayersPieces[0, 0] + 1;
if PieceIndex > 0 then
begin
Piece := ListOfMoves[PieceIndex].Piece;
NewRow := ListOfMoves[PieceIndex].NewRow;
NewColumn := ListOfMoves[PieceIndex].NewColumn;
if Length(Piece) = 2 then
PlayersPieceIndex := StrtoInt(RightStr(Piece, 1))

GEMS Metropole School Page 215 of 236


else
PlayersPieceIndex := StrtoInt(RightStr(Piece, 2));
CurrentRow := PlayersPieces[PlayersPieceIndex, Row];
CurrentColumn := PlayersPieces[PlayersPieceIndex, Column];
Jumping := ListOfMoves[PieceIndex].CanJump;
MovePiece(Board, PlayersPieces, OpponentsPieces, Piece, NewRow,
NewColumn);
if Jumping then
begin
MiddlePieceRow := (CurrentRow + NewRow) div 2;
MiddlePieceColumn := (CurrentColumn + NewColumn) div 2;
MiddlePiece := Board[MiddlePieceRow, MiddlePieceColumn];
end;
end;
end;

C#

private static void MoveDame(string[,] board, string player, ref int


newRow, ref int newColumn, int[,] opponentsPieces)
{
string opponent, chosenPiece;
int index = 0;
newRow = -1;
opponent = "";
while ((player == opponent) || (newRow == -1))
{
Console.Write("Which piece do you want to take?");
chosenPiece = Console.ReadLine();
opponent = chosenPiece[0].ToString().ToLower();
index = Convert.ToInt32(chosenPiece.Substring(1));
newRow = opponentsPieces[index, Row];
newColumn = opponentsPieces[index, Column];
}
opponentsPieces[index, Row] = -1;
opponentsPieces[index, Column] = -1;
}
private static void MovePiece(string[,] board, int[,] playersPieces,
string chosenPiece, int newRow, int newColumn, int[,]
opponentsPieces)
{
int index, currentRow, currentColumn;
string player;
if (chosenPiece.Length == 2)
{
index = Convert.ToInt32(chosenPiece[1].ToString());
}
else
{
index = Convert.ToInt32(chosenPiece.Substring(1));
}
currentRow = playersPieces[index, Row];
currentColumn = playersPieces[index, Column];
board[currentRow, currentColumn] = Space;

GEMS Metropole School Page 216 of 236


if (newRow == BoardSize - 1 && playersPieces[index, Dame] == 0)
{
player = "a";
playersPieces[0, 1] = playersPieces[0, 1] + 1;
playersPieces[index, Dame] = 1;
chosenPiece = chosenPiece.ToUpper();
MoveDame(board, player, ref newRow, ref newColumn,
opponentsPieces);
}
else if (newRow == 0 && playersPieces[index, Dame] == 0)
{
player = "b";
playersPieces[0, 1] = playersPieces[0, 1] + 1;
playersPieces[index, Dame] = 1;
chosenPiece = chosenPiece.ToUpper();
MoveDame(board, player, ref newRow, ref newColumn,
opponentsPieces);
}
playersPieces[index, Row] = newRow;
playersPieces[index, Column] = newColumn;
board[newRow, newColumn] = chosenPiece;
}
private static void MakeMove(string[,] board, int[,] playersPieces,
int[,] opponentsPieces, MoveRecord[] listOfMoves, int pieceIndex)
{
string piece, middlePiece;
int newRow, newColumn, playersPieceIndex, currentRow,
currentColumn;
int middlePieceRow, middlePieceColumn;
bool jumping;
playersPieces[0, 0] = playersPieces[0, 0] + 1;
if (pieceIndex > 0)
{
piece = listOfMoves[pieceIndex].Piece;
newRow = listOfMoves[pieceIndex].NewRow;
newColumn = listOfMoves[pieceIndex].NewColumn;
playersPieceIndex = Convert.ToInt32(piece.Substring(1));
currentRow = playersPieces[playersPieceIndex, Row];
currentColumn = playersPieces[playersPieceIndex, Column];
jumping = listOfMoves[pieceIndex].CanJump;
MovePiece(board, playersPieces, piece, newRow, newColumn,
opponentsPieces);
if (jumping)
{
middlePieceRow = (currentRow + newRow) / 2;
middlePieceColumn = (currentColumn + newColumn) / 2;
middlePiece = board[middlePieceRow, middlePieceColumn];
Console.WriteLine("jumped over " + middlePiece);
}
}
}

Java

int[] moveDame(String player, int [][] opponentsPieces) {


int newRow = -1;
int newColumn = 0;
String opponent = "";
int index = 0;

GEMS Metropole School Page 217 of 236


while (player.equals(opponent) || newRow == -1) {
Console.writeLine("Which piece do you want to take?");
String chosenPiece = Console.readLine();
opponent = chosenPiece.substring(0, 1).toLowerCase();
index = Integer.parseInt(chosenPiece.substring(1));
newRow = opponentsPieces[index][ROW];
newColumn = opponentsPieces[index][COLUMN];
}
opponentsPieces[index][ROW] = -1;
opponentsPieces[index][COLUMN] = -1;
return new int[]{newRow, newColumn};
}
void movePiece(String[][] board, int[][] playersPieces, int[][]
opponentsPieces, String chosenPiece, int newRow, int newColumn) {
int index = Integer.parseInt(chosenPiece.substring(1));
int currentRow = playersPieces[index][ROW];
int currentColumn = playersPieces[index][COLUMN];
board[currentRow][currentColumn] = SPACE;
String player;
if (newRow == BOARD_SIZE - 1 && playersPieces[index][DAME] == 0) {
player = "a";
playersPieces[0][1] += 1;
playersPieces[index][DAME] = 1;
chosenPiece = chosenPiece.toUpperCase();
int[] rtnInts = moveDame(player, opponentsPieces);
newRow = rtnInts[0];
newColumn = rtnInts[1];
} else if (newRow == 0 && playersPieces[index][DAME] == 0) {
player = "b";
playersPieces[0][1] += 1;
playersPieces[index][DAME] = 1;
chosenPiece = chosenPiece.toUpperCase();
int[] rtnInts = moveDame(player, opponentsPieces);
newRow = rtnInts[0];
newColumn = rtnInts[1];
}
playersPieces[index][ROW] = newRow;
playersPieces[index][COLUMN] = newColumn;
board[newRow][newColumn] = chosenPiece;
}
void makeMove(String[][] board, int[][] playersPieces, int[][]
opponentsPieces, MoveRecord[] listOfMoves, int pieceIndex) {
playersPieces[0][0] += 1;
if (pieceIndex > 0) {
String piece = listOfMoves[pieceIndex].piece;
int newRow = listOfMoves[pieceIndex].newRow;
int newColumn = listOfMoves[pieceIndex].newColumn;
int playersPieceIndex = Integer.parseInt(piece.substring(1));
int currentRow = playersPieces[playersPieceIndex][ROW];
int currentColumn = playersPieces[playersPieceIndex][COLUMN];
boolean jumping = listOfMoves[pieceIndex].canJump;
movePiece(board, playersPieces, opponentsPieces, piece, newRow,
newColumn);

GEMS Metropole School Page 218 of 236


if (jumping) {
int middlePieceRow = (currentRow + newRow) / 2;
int middlePieceColumn = (currentColumn + newColumn) / 2;
String middlePiece = board[middlePieceRow][middlePieceColumn];
Console.writeLine("jumped over " + middlePiece);
}
}
}
9

(iii) Mark is for AO3 (evaluate)

**** SCREEN CAPTURE ****


Must match code from part (dii), including prompts on screen capture
matching those in code.
Code for part (dii) must be sensible.

Screen capture showing:

Do you want to load a saved game? (Y/N): y


Enter the filename: game3.txt

GEMS Metropole School Page 219 of 236


Player A:
[[8, 0, 0], [0, 1, 0], [6, 1, 0], [2, 7, 0], [0, 7, 0], [3, 2, 0],
[3, 0, 0], [2, 5, 0], [1, 6, 0], [-1, -1, 0], [-1, -1, 0], [-1, -1,
0], [-1, -1, 0]]
Player B:
[[8, 0, 0], [4, 1, 0], [7, 2, 0], [5, 6, 0], [5, 4, 0], [1, 4, 0],
[6, 3, 0], [6, 5, 0], [6, 7, 0], [-1, -1, 0], [-1, -1, 0], [-1, -1,
0], [-1, -1, 0]]

Next Player: a
a1 can move to 1 , 0
a1 can move to 1 , 2
a2 can move to 7 , 0
a3 can move to 3 , 6
a5 can move to 4 , 3
a7 can move to 3 , 4
a7 can move to 3 , 6
a8 can jump to 3 , 4
There are 8 possible moves
Which piece do you want to move? a2
Which row do you want to move to? 7
Which column do you want to move to? 0
Which piece do you want to take? b1

GEMS Metropole School Page 220 of 236


Player A:
[[9, 1, 0], [0, 1, 0], [4, 1, 1], [2, 7, 0], [0, 7, 0], [3, 2, 0],
[3, 0, 0], [2, 5, 0], [1, 6, 0], [-1, -1, 0], [-1, -1, 0], [-1, -1,
0], [-1, -1, 0]]
Player B:
[[8, 0, 0], [-1, -1, 0], [7, 2, 0], [5, 6, 0], [5, 4, 0], [1, 4, 0],
[6, 3, 0], [6, 5, 0], [6, 7, 0], [-1, -1, 0], [-1, -1, 0], [-1, -1,
0], [-1, -1, 0]]

(iv) Mark is for AO3 (evaluate)

**** SCREEN CAPTURE ****


Must match code from part (dii), including prompts on screen capture
matching those in code.
Code for part (dii) must be sensible.

Screen capture showing:

GEMS Metropole School Page 221 of 236


Next Player: b
b2 can move to 6 , 1
b3 can move to 4 , 5
b3 can move to 4 , 7
b4 can move to 4 , 3
b4 can move to 4 , 5
b5 can move to 0 , 3
b5 can move to 0 , 5
b6 can move to 5 , 2
b6 can jump to 4 , 5
b7 can jump to 4 , 3
b7 can jump to 4 , 7
b8 can jump to 4 , 5
There are 12 possible moves
Which piece do you want to move? b5
Which row do you want to move to? 0
Which column do you want to move to? 3
Which piece do you want to take? a6

GEMS Metropole School Page 222 of 236


Player A:
[[9, 1, 0], [0, 1, 0], [4, 1, 1], [2, 7, 0], [0, 7, 0], [3, 2, 0],
[-1, -1, 0], [2, 5, 0], [1, 6, 0], [-1, -1, 0], [-1, -1, 0], [-1, -1,
0], [-1, -1, 0]]
Player B:
[[9, 1, 0], [-1, -1, 0], [7, 2, 0], [5, 6, 0], [5, 4, 0], [3, 0, 1],
[6, 3, 0], [6, 5, 0], [6, 7, 0], [-1, -1, 0], [-1, -1, 0], [-1, -1,
0], [-1, -1, 0]]

1
[29]

GEMS Metropole School Page 223 of 236


(a) All marks for A02 (apply)
58.
Number Root d FactorFound r Output

5 1

2 False 1

3 2

4 Prime

1 mark for correct columns Root and d


1 mark 1 mark for correct column r
1 mark 1 mark for correct columns FactorFound and Output

Max 2 marks if any incorrect values written in table

I. Annotation indicating ‘no value’

I. Indication of repeating values


I. Quotes
I. Case & spelling for FactorFound & Output
A. T, F instead of True False
3

GEMS Metropole School Page 224 of 236


(b) All marks for A02 (apply)

Number Root d FactorFound r Output

25 1

5 2 False 1

3 1

4 1

5 0

True

6 Not prime

1 mark for correct columns Root and d


1 mark for correct column r
1 mark for correct columns FactorFound and Output

Max 2 marks if any incorrect values written in table


3
[6]

GEMS Metropole School Page 225 of 236


(a) All marks for AO3 (programming)
59.
Mark as follows:

1. correct variable declarations for Number, c, k;

Note to examiners
If a language allows variables to be used without explicit declaration (eg
Python) then this mark should be awarded if the correct variables exist in the
program code and the first value they are assigned is of the correct data type.

2. WHILE loop with syntax allowed by the programming language and one correct
condition for termination of the loop;
3. second correct condition for while loop;
4. correct prompt "Enter a positive whole number: " and Number assigned
value entered by user;
5. correct syntax for the IF statements inside attempt at loop;
A. IF … ELSEIF;
6. correct contents in IF statements;
7. FOR loop with syntax allowed by the programming language over correct range;
8. correct assignment to c inside FOR loop;
9. output statement giving correct output; A. accept without spaces

I. Ignore minor differences in case and spelling


R. real Number

Max 8 if code does not function correctly


9

VB.NET
Sub Main()
Dim Number As Integer
Dim c As Integer
Number = 0
While Number < 1 Or Number > 10
Console.Write("Enter a positive whole number: ")
Number = Console.ReadLine
If Number > 10 Then
Console.WriteLine("Number too large")
Else
If Number < 1 Then
Console.WriteLine("Not a positive number.")
End If
End If
End While
c = 1
For k = 0 To Number - 1
Console.WriteLine(c)
c = (c * (Number - 1 - k)) \ (k + 1)
Next
Console.ReadLine()
End Sub

GEMS Metropole School Page 226 of 236


Python 2
Number = 0
while Number < 1 or Number > 10:
Number = int(raw_input("Enter a positive whole number: "))
if Number > 10:
print "Number too large"
elif Number < 1:
print "Not a positive number"
c = 1
for k in range(Number):
print c
c = (c * (Number - 1 - k)) // (k + 1)

Python 3

Number = 0
while Number < 1 or Number > 10:
Number = int(input("Enter a positive whole number: "))
if Number > 10:
print("Number too large")
elif Number < 1:
print ("Not a positive number")
c = 1
for k in range(Number):
print c
c = (c * (Number - 1 - k)) // (k + 1)

Pascal
var
Number, c, k : Integer;
begin
Number := 0;
while (Number < 1) or (Number > 10) do
begin
write('Enter a positive whole number: ');
readln(Number);
if Number > 10 then
writeln('Number too large')
else
if Number < 1 then
writeln('Not a positive number.')
end;
c := 1;
for k := 0 to (Number - 1) do
begin
writeln(c);
c := (c * (Number - 1 - k)) div (k + 1);
end;
readln;
end.

GEMS Metropole School Page 227 of 236


C#
static void Main(string[] args)
{
int Number = 0;
while (Number < 1 || Number > 10)
{
Console.WriteLine("Enter a positive whole number: ");
Number = Convert.ToInt32(Console.ReadLine());
if (Number > 10)
{
Console.WriteLine("Number too large.");
}
else
{
if (Number < 1)
{
Console.WriteLine("Not a positive number.");
}
}
}
int c = 1;
for (int k = 0; k < Number ; k++)
{
Console.WriteLine(c);
c = (c * (Number - 1 - k)) / (k + 1);
}
Console.ReadLine();
}

Java
int number = 0;
while (number < 1 || number > 10)
{
Console.writeLine(("Enter a positive whole number: "));
number = Integer.parseInt(Console.readLine());
if (number > 10)
{
Console.writeLine("Number too large");
}
else if (number < 1)
{
Console.writeLine("Not a positive number");
}
}
int c = 1;
for (int k = 0; k < number; k++)
{
Console.write(c + " ");
c = (c * (number - 1 - k) / (k + 1));
}

(b) Mark is for AO3 (evaluate)

**** SCREEN CAPTURE ****


Must match code from part (a), including prompts on screen capture matching those
in code.
Code for part (a) must be sensible.

GEMS Metropole School Page 228 of 236


Screen capture showing:
'-3' being entered and the message 'Not a positive number.' displayed
'11' being entered and the message 'Number too large.' displayed
'10' being entered and line of numbers displayed

Enter a positive whole number: -3


Not a positive number.
Enter a positive whole number: 11
Number too large.
Enter a positive whole number: 10
1 9 36 84 126 126 84 36 9 1

>

A. Alternative layout :
Enter a positive whole number: -3
Not a positive number.
Enter a positive whole number: 11
Number too large.
Enter a positive whole number: 10
1
9
36
84
126
126
84
36
9
1
>

A. input on new line


1
[10]

(a) Mark is for AO1 (understanding)


60.
LetterEnd // ProgramEnd ;

R. if any additional code


R. if spelt incorrectly
I. case & spacing
1

(b) Mark is for AO1 (understanding)

GetMenuOption // Decode ; A. GetNextSymbol

R. if any additional code


R. if spelt incorrectly
I. case & spacing
1
[2]

GEMS Metropole School Page 229 of 236


Examiner reports
Just under forty percent of students attained full marks in this question, which required
1. completion of a trace table in accordance with a pseudo-code algorithm. The most common error
here was entering the correct value in the wrong column, which might be due to errors of
transposition rather than any misconceptions.

This question required students to describe a difference between a global and a local variable,
2. and fewer than half of students succeeded in providing a description that secured both marks.
Although there was an understanding that the scope of a local variable is more limited, this was
often phrased too vaguely to be fully creditworthy.

Converting pseudocode to program code was carried out successfully by most students, with
3. approximately ninety percent of students picking up either full marks or eight out of nine on part
(a). The most common way in which a mark was dropped was reversing the logic of the selection
statement.

Where the code was sound, the evidence mark of part (b) was almost always awarded. Students
are reminded of the importance of ensuring that screenshot evidence is legible in all such
questions.

For each of the four question parts, most students gained the mark. Here, students were required
4. to identify a variable and three subroutines. The most common way in which marks could not be
awarded was by the inclusion of additional code, such as parentheses alongside subroutine
identifiers.

For both question parts, most students gained the mark. As this question related to data
5. structures rather than subroutines, additional code was less frequently included here.

Here, students were required to demonstrate an understanding of the skeleton code by


6. identifying error codes that would be generated under certain circumstances. Seventy percent of
students picked up either full marks or four out of five.

This question continued to examine students’ understanding of the error codes within the
7. skeleton program, and the majority were awarded both marks on offer. In circumstances where
one mark was obtained but two points had been made, there was often a re-phrasing of the first
point in an attempt to pick up the second mark.

This question comprised three parts, each of which asked about some aspect of the same
8. subroutine. In previous exams, this might have been presented as a single six mark question
rather than a series of related three-mark questions, and in such questions the scale of the
required answer presented a challenge to some students.

This format provided some structure, and most student marks were concentrated between two
and five out of six. Where marks were not awarded, it was quite common for an otherwise
creditworthy answer to be placed next to the wrong question. This suggests that marks were lost
due to a misunderstanding of the question rather than a misunderstanding of the code.

GEMS Metropole School Page 230 of 236


This question was the first that required changes to be made to the skeleton program, and
9. answers were of a good quality, with around seventy percent of students securing either full
marks or three out of four on part (a).

Where a mark was dropped in an otherwise correct response, it was that awarded for updating
the status register, which was missed out rather than being attempted incorrectly.

This question required addition of validation code; the requirement was that any specified line
10. number should exist within the assembly program. Although the lower bound was generally
correct, since it would always be 1, the upper bound was commonly hard-coded rather than
determined using a variable. Since the length of the assembly program could vary, hard-coding
was not enough for the mark.

Approximately half of the students secured either full marks or four out of five for part (a),
although very few students were awarded two or three marks. That indicates that this question
marks the beginning of the stage in which individual programming marks were cherry-picked due
to constraints of time or understanding.

This question was skipped more than any other question.


11.
Of those who made an attempt, three quarters secured either full marks or three out of four on
part (a). A range of different approaches was taken, including some not anticipated by the mark
scheme. These were always given credit, some obtaining full marks, and this underscores the
fact that there are usually many correct answers to a programming question, not just one.

There were two components to this question – adding the facility to insert an instruction and the
12. facility to remove one. As is often the case with the last question on the paper, there were many
partial attempts, and this question lent itself to such attempts. Some students attempted to write
code for insertion only, and others for deletion only. Only a minority of those who made any
attempt at all were awarded zero marks for part (a), with students securing marks for modifying
the menu and handling the new inputs even if they did not complete the task.

Parts (b) and (c) required screenshot evidence for a successful deletion and insertion
respectively. Given that a large number of students had only attempted one of these two pieces
of functionality, a high number of non-attempts were registered. Nevertheless, the majority of
students who made a partial attempt at part (a) also attempted the corresponding screenshot
evidence question.

Most students were able to secure either four or five marks on the trace table question. Where
13. students secured four marks, the mark that was dropped was the final mark. This required the
result of the algorithm to be given.

This question was completed well by students with the majority of students achieved a high
14. mark. The most common mistake was related to the requirement to generate a random integer
between 1 and 6 inclusive. Some students were unable to write the correct syntax for random
integer generation. Others wrote syntactically-correct code that produced an integer in the wrong
range, such as between 0 and 6 inclusive.

Where students were unfamiliar with the syntax for random integer generation, subsequent
marks were still secured. Commonly, variables were used to store integers that were not
randomly generated, but these variables were subsequently processed correctly. This enabled
students to demonstrate their programming abilities in spite of an early error or omission.

GEMS Metropole School Page 231 of 236


The majority of students gained both marks.
15.
The majority of students gained both marks.
16.
The majority of students gained both marks.
17.
The majority of students gained the mark for part (a).
18.
A partial understanding was demonstrated by the majority of students on part (b). The element of
the data structure in question fulfilled multiple roles, but in many cases, only one role was
identified. Students should always consider the number of available marks when answering a
question.

Many students secured both marks for this question, with only twenty-seven percent failing to
19. pick up any marks.

The question required changes to be described that would apply to a single subroutine of the
skeleton program. Some students, in describing changes outside this subroutine, dropped a
mark. Others described the same change in two different ways and only gained one mark.

Many students failed to secure full marks in this question, with responses that were insufficiently
20. specific rather than incorrect. The most common way in which a mark was dropped was to
correctly define definite iteration, and then to present indefinite iteration as the opposite of
definite iteration. Where a mark is available for providing a definition, a standalone definition
should be provided.

This question required students to identify subroutines that contained examples of definite and
21. indefinite iteration. The majority of students secured this mark.

This question required students to identify subroutines that contained examples of definite and
22. indefinite iteration. The majority of students secured this mark.

Most students secured the first mark of this question by identifying that an exception stops a
23. program from crashing. Many fewer students recognised that exception handling is relevant to
run time errors. 'Errors', in isolation, did not demonstrate a sufficient level of understanding.

The majority of students were able to identify a subroutine that performed exception handling, as
24. required by this question. Of those who correctly identified the subroutine, most were able to
identify a relevant circumstance that might cause an exception.

The most common reason for dropping a mark on this question was to give more than just the
subroutine's name. For example, LoadPuzzleFile was creditworthy, whereas def
LoadPuzzleFile or LoadPuzzleFile(PuzzleName, Puzzle) was not.

Many students dropped the mark on this question by providing an incomplete answer. Only a
25. very small number of answers were incorrect, but many more were incomplete. Stating only that
a subroutine is a named section of code was insufficient on its own, and was a commonly-given
answer.

The majority of students secured the mark for this question.


26.

GEMS Metropole School Page 232 of 236


This question was another question for which responses scoring zero were more likely to be
27. incomplete than incorrect. Students were asked to describe rather than state, showing
understanding rather than knowledge. As such, 'reduces testing time' was insufficient, whereas
'reduces testing time due to less code to test' secured the mark.

Both marks of this question were secured by the majority of students. The most common reason
28. for dropped marks was giving more than just the subroutine’s name. For example,
ResetDataStructures was creditworthy, whereas ResetDataStructures() was not.

This question was the first that required changes to be made to the skeleton code. On the whole,
29. responses to this question were of a good quality, with most students securing most marks.

The most commonly dropped mark related to the requirement for new code to be at an
appropriate place within the subroutine. Validation had already been included to check that inputs
could be converted to integers. The new code, checking whether those integers related to
protected coordinates, should have been added after this validation code.

This question required additional validation to be added to the skeleton code. A value should not
30. be permitted in a cell if it already exists in the same row, column, or sub-grid. Most students
secured some marks on this question, but only a minority picked up all six. The marks relating to
the sub-grid were secured by fewer students than the marks relating to the row and column.

Determining whether a value already existed within the same row or column was a relatively
straightforward task. This could be accomplished using two simple loops. The most common way
of checking a sub-grid required a combination of the modulo operator and nested loops. Other
students opted for a nine-part selection structure, which was equally creditworthy.

This question required the addition of 'undo' functionality to the skeleton code. Design marks
31. were applicable to this question, so syntactically incorrect code could be credited. The majority of
students secured at least two of the three design marks.

Most students created the subroutine correctly, and were able to make a valid call to it from
elsewhere in the code. Beyond this, the majority of students conformed to one of two groups.
One group gained no further marks, and the other group secured all or most of the remaining
marks.

Marks dropped by more able students included replacement of a number with an empty string
rather than a space. Another common error was assuming that the number of 'undo' moves
would always be a single digit value. Were the user to enter -10, indicating ten 'undo' moves, this
would result in one 'undo' and an ignored zero.

Many vague answers were given for the difference between local and global variables.
47. Regardless of how the student’s chosen programming language requires local / global variables
to be declared, students need to be aware that a global variable is accessible to all parts of the
program, whereas a local variable is accessible only in the program block in which it was
declared. Many students’ answers were very vague as to the reasons for using local variables.
Some were able to state that memory used to store local variables is released when the
subroutine terminates, but very few mentioned that local variables make a subroutine
self-contained and therefore it is easier to re-use such subroutines in other programs.

GEMS Metropole School Page 233 of 236


This question was completed well by students with the majority of students achieving a high
48. mark. A lot of full mark answers were seen across all of the programming languages. A
significant number of students were not able to demonstrate their ability to convert the FOR loop
into the exact equivalent in their chosen programming language. A common mistake was to
misinterpret the starting and ending values for the loop counter. The pseudo-code clearly stated
that the loop counter started at 1. However, many responses were seen where the loop counter
started at 0, or did not use (Count – 1) as the last value. A few students also dropped marks by
not using the exact messages and identifiers given in the pseudo-code.

Most students completed the testing section well and provided clear screenshots of their code
working.

The majority of students recognised that the algorithm produced binary but, to gain the mark,
they needed to state that the conversion was from decimal to binary.

The majority of students secured both of the marks for this question. A few students copied
49. across more than just the identifier for each part and therefore did not gain the mark as it was not
clear which part of the copied code they believed the identifier to be.

The majority of students gained this mark.


50.
Many students’ answers were very vague as to the reasons for using exception handling in the
51. subroutine SetUpBoard. Answers that were given credit included stating that this would avoid a
program crash in case of file errors.

Less able students stated that it was the player’s pieces that would be contained in the
52. parameter. To earn this mark, a reference to the positions of player A’s pieces was required.

The hierarchy chart was attempted well by most students.


53.
Many responses just described the code without showing any understanding of the purpose of
54. using modular arithmetic to find odd and even numbers. The description of the programming
statements assigning the constant values SPACE needed to show understanding that these were
the squares that the game could use. Similarly, the squares being assigned the value UNUSED
were those that the game couldn’t use.

Very few responses provided clear explanations of what happens in the WHILE loop in
55. SelectMove. Many descriptions merely reworded the programming steps. An example of an
explanation gaining high marks was:

The user is asked to enter a Piece ID. The list of moves is searched sequentially for an
occurrence of the Piece ID entered until either the Piece ID is found or the end of ListOfMoves is
encountered. If the end of the list is encountered the user is asked again to enter the Piece ID.

(a) Task 1 required meaningful error messages to be displayed as well as the error code.
56.
Most students used either a series of IF statements or a CASE statement. Some responses
used a dictionary or a tuple. All these methods were given credit. However, meaningful
error messages were required. In particular, error code 3 needed to inform the user that a
number was required as input.

GEMS Metropole School Page 234 of 236


(b) Task 1 required students to change the subroutine ValidJump to jump over an opponent’s
piece.

The majority of students made the small change to the final IF statement from checking the
middle piece did not belong to the opponent to checking that it was the opponent’s. A
common mistake was to change the assignment of OppositePiecePlayer to be the same
as Player. This may result in jumping over the opponent’s piece, but it is poor
programming practice as it removes transparency of code. Player and
OppositePiecePlayer should never be the same value.

(c) Task 1 required the writing of a new subroutine to count the number of pieces a player had
on the board.

The majority of students produced sensible code for this task and credit was given for
designing the subroutine so that it could be called either with A or with B without duplicating
code. Some responses counted the pieces on the board rather than in the data structures A
and B. Both methods were given credit.

Task 2 required rewriting the PrintResult subroutine to output the winner and scores
using the amended rules.

The formula was given in the question but many students did not make use of the values
held in the A and B data structures for number of moves made and number of dames held.
A common error was to assume that the highest score wins, contrary to the information
given in the question. Some students did not output the scores or consider the possibility of
a draw. Both requirements were stated in the question.

(d) This question changed the rules of the game and allowed the player to take an opponent’s
piece. Some students were able to analyse the new requirements and that the
OpponentsPieces data structure now needed to be passed to the MoveDame subroutine, as
changes to this data structure now needed to be made.

Task 1 required new code for the MoveDame subroutine.

Many students secured some marks on this question. A common omission was not
checking that the piece to be removed was an opponent’s existing piece. Another common
error was to fail to update the opponent’s data structure with - 1 values in place of the
co-ordinates.

Some students struggled to complete the trace tables. The question clearly stated that the
58. pseudo-code described a method to test whether an integer is prime or not, yet some answers to
part a left the trace table showing that 5 was not prime, and some answers to part b left the trace
table showing that 25 was prime. Using a trace table to show how values change while iterating
through a loop needs practice. Many answers indicated little understanding of repeatedly
applying code until the condition(s) terminate the loop. Pseudo-code clearly shows what code is
part of a loop by ending with ENDWHILE or ENDFOR. Similarly, IF statements terminate with ENDIF.
Indentation is also used to help students see the logical flow of statements.

GEMS Metropole School Page 235 of 236


This question was completed well by students with the majority of students achieving a high
59. mark. A lot of full mark answers were seen across all of the programming languages. A common
mistake was to use real/float division instead of integer division. Some students did not
implement the IF ... ELSE IF ... statement, instead using two separate IF statements, this
type of solution was not given full credit. A few students also failed to gain marks by not using the
exact messages and identifiers given in the pseudo-code. A significant number of students were
not able to demonstrate their ability to convert the FOR loop into the exact equivalent in their
chosen programming language.

The majority of students secured both of the marks for this question. A few students copied
60. across more than just the identifier for each part and therefore did not gain the mark as it was not
clear which part of the copied code they believed the identifier to be.

GEMS Metropole School Page 236 of 236

You might also like