Computer Science 9618/42 — October/November 2022
Cambridge A-Level · Practical · worked solutions for every part, with the mark scheme
Topics Programming Paradigms (Procedural and Object-oriented) · Algorithms and Abstract Data Types · File Processing and Exception Handling · Recursion
A computer program is needed to store jobs in order of priority. Each job has a job number (for example, 123) and a priority from 1 to 10, with 1 being the highest priority and 10 the lowest.
The program stores the jobs in a global 2D array.
The pseudocode declaration for the array is:
DECLARE Jobs : ARRAY[0:99, 0:1] OF INTEGER
For example:
Jobs[0, 0]stores the job number of the first job.Jobs[0, 1]stores the priority of the first job.
The global variable, NumberOfJobs, stores the number of jobs currently in the array.
Write program code to declare the global 2D array Jobs and the global variable NumberOfJobs.
Save your program as Question1_N22.
Copy and paste the program code into part 1(a) in the evidence document.
Answer
Jobs = [[0 for Column in range(2)] for Row in range(100)]
NumberOfJobs = 0
See program code
Background Concept
In Paper 4, a 2D array in pseudocode is usually implemented in Python using a list of lists. Here, ARRAY[0:99, 0:1] OF INTEGER means 100 rows and 2 columns. Each row stores one job record:
- column
0= job number - column
1= priority
A global variable is one that can be accessed throughout the program. NumberOfJobs is used to keep track of how many rows are currently filled with valid data.
Understanding the Question
You are not being asked to write any processing yet. You only need to create:
- a global 2D structure called
Jobs - a global variable called
NumberOfJobs
The structure must be large enough for 100 jobs, and each job needs exactly 2 integer positions.
Approach
Use a nested list:
- the outer list gives the 100 rows
- each inner list gives the 2 columns
Then create NumberOfJobs and set it to 0, because at the start there are no jobs stored.
Step-by-Step Reasoning
Jobs = [[0 for Column in range(2)] for Row in range(100)]
range(100)creates 100 rows.range(2)creates 2 columns in each row.- Every element is initially set to
0. - This gives a structure equivalent to the required 2D integer array.
NumberOfJobs = 0
- This means no jobs have been stored yet.
- Later, when a job is added, this variable will increase.
Even though part (b) later changes every element to -1, it is still correct here to declare the array with initial values such as 0, because part (a) is only about declaration.
Key Takeaways
- A pseudocode 2D array can be represented in Python as a list of lists.
- The first dimension is the number of rows; the second is the number of columns.
- A separate counter variable is often used to track how many entries are valid.
Common Mistakes
- Creating the wrong size array, such as 99 rows instead of 100.
- Forgetting that there are 2 columns per job.
- Not declaring
NumberOfJobsat all. - Using a one-dimensional list instead of a two-dimensional structure.
Things to Be Careful About
Jobs[0][0]is the first job number andJobs[0][1]is its priority, so each row must contain exactly two values.- Avoid
Jobs = [[0, 0]] * 100in teaching contexts, because it creates repeated references to the same inner list; a list comprehension is safer. - Keep the identifier names exactly as required:
JobsandNumberOfJobs.
The procedure Initialise() stores –1 in each of the array elements and assigns 0 to NumberOfJobs.
Write program code for the procedure Initialise().
Save your program.
Copy and paste the program code into part 1(b) in the evidence document.
Answer
def Initialise():
global Jobs, NumberOfJobs
for Row in range(100):
for Column in range(2):
Jobs[Row][Column] = -1
NumberOfJobs = 0
See program code
Background Concept
Initialisation means putting a data structure into a known starting state before the rest of the program uses it. For arrays, this often means assigning a default value to every element. For counters, it usually means setting them back to zero.
Because Jobs is two-dimensional, every cell must be visited. That is why nested loops are needed:
- outer loop for rows
- inner loop for columns
Understanding the Question
The question tells you exactly what Initialise() must do:
- store
-1in every element of theJobsarray - assign
0toNumberOfJobs
So this is not just resetting the count; it is also clearing all stored job numbers and priorities.
Approach
Write a procedure named Initialise() that:
- accesses the global array and global counter
- loops through all 100 rows
- loops through both columns in each row
- stores
-1in each position - resets
NumberOfJobsto0
Step-by-Step Reasoning
def Initialise():
- Defines the procedure with the exact required name.
global Jobs, NumberOfJobs
- The procedure changes global data, so it should explicitly refer to the global variables.
for Row in range(100):
- Visits rows
0to99.
for Column in range(2):
- Visits columns
0and1.
Jobs[Row][Column] = -1
- Places
-1in every cell. - After both loops finish, all 200 array elements have been cleared.
NumberOfJobs = 0
- Resets the count of valid jobs.
- This is essential, because even if the array is cleared, the program must also know that no jobs are currently stored.
Key Takeaways
- Initialisation puts program data into a predictable starting state.
- A 2D array needs nested loops if every element must be processed.
- Resetting the counter is just as important as clearing the data values.
Common Mistakes
- Only setting one row or one column to
-1. - Forgetting to reset
NumberOfJobs. - Writing one loop instead of nested loops.
- Using the wrong loop bounds, such as
range(99)orrange(1, 100).
Things to Be Careful About
- The valid row indices are
0to99, sorange(100)is correct. - The valid column indices are
0and1, sorange(2)is correct. - Do not set
NumberOfJobsinside the loops; it should be reset once after clearing the array. - In Python, changing a global scalar such as
NumberOfJobsinside a procedure needs theglobaldeclaration.
The procedure AddJob():
- takes a job number and priority as parameters
- stores the job in the next free array element
- outputs ‘Added’ if the job was successfully stored in the array
- outputs ‘Not added’ if the job was not successfully stored in the array.
Write program code for the procedure AddJob().
Save your program.
Copy and paste the program code into part 1(c) in the evidence document.
Answer
def AddJob(JobNumber, Priority):
global Jobs, NumberOfJobs
if NumberOfJobs < 100:
Jobs[NumberOfJobs][0] = JobNumber
Jobs[NumberOfJobs][1] = Priority
NumberOfJobs += 1
print('Added')
else:
print('Not added')
See program code
Background Concept
When data is stored in an array using a counter, the next free position is usually the position indicated by the counter. After storing the new item, the counter is increased.
This is a common pattern:
- check there is space
- store the new data
- update the count
- report success or failure
Because the array has 100 rows, the program must not try to store data once NumberOfJobs reaches 100.
Understanding the Question
AddJob() must do four things:
- receive a job number and a priority as parameters
- store them in the next free row of
Jobs - print
Addedif successful - print
Not addedif the array is full
The important phrase is “next free array element”. That tells you to use NumberOfJobs as the row index.
Approach
Use an if statement:
- if
NumberOfJobs < 100, there is room - write the job number into column
0 - write the priority into column
1 - increase
NumberOfJobs - print
Added
Otherwise, print Not added.
Step-by-Step Reasoning
def AddJob(JobNumber, Priority):
- The procedure takes exactly the two required parameters.
global Jobs, NumberOfJobs
- The procedure needs to change the main program's data.
if NumberOfJobs < 100:
- Valid rows go from
0to99. - So if 100 jobs are already stored, there is no free row left.
Jobs[NumberOfJobs][0] = JobNumber
- Stores the job number in the first column of the next free row.
Jobs[NumberOfJobs][1] = Priority
- Stores the matching priority in the second column of the same row.
- Keeping both pieces of data in the same row is essential.
NumberOfJobs += 1
- The row is now occupied, so the number of valid jobs increases by 1.
print('Added')
- Confirms success.
else: / print('Not added')
- This handles the full-array case.
Key Takeaways
- A counter often points to the next free array position.
- Always check bounds before storing into a fixed-size array.
- Related values must be stored in the same row so the record stays together.
Common Mistakes
- Using
<= 100instead of< 100, which allows an invalid row index. - Incrementing
NumberOfJobsbefore storing, which skips row 0. - Storing the job number and priority in different rows.
- Printing
Addedeven when the array is full.
Things to Be Careful About
- The array size is 100 rows, so the last valid insert position is row
99. NumberOfJobsis the count of used rows, not the last used index.- Keep the column positions correct:
0for job number,1for priority. - In Python, remember that updating
NumberOfJobsinside the procedure requiresglobal NumberOfJobs.
The main program should call the procedure Initialise() and then use the AddJob() procedure to store the following jobs in the order given:
| Job number | Priority |
|---|---|
| 12 | 10 |
| 526 | 9 |
| 33 | 8 |
| 12 | 9 |
| 78 | 1 |
Write program code for the main program and perform the tasks described.
Save your program.
Copy and paste the program code into part 1(d) in the evidence document.
Answer
Initialise()
AddJob(12, 10)
AddJob(526, 9)
AddJob(33, 8)
AddJob(12, 9)
AddJob(78, 1)
See program code
Background Concept
The main program controls the sequence in which procedures are called. In a procedural program, correctness often depends on calling routines in the right order.
Here, Initialise() must run before adding jobs, otherwise the array and counter may contain old values.
Understanding the Question
You must write the main program code to:
- call
Initialise() - add five jobs
- use the exact job numbers and priorities given
- keep the exact order shown in the table
The order matters because the jobs are first stored in that sequence, and later the sort uses those stored records.
Approach
This is just a series of procedure calls:
- first clear the array
- then call
AddJob()once for each row in the table
Each call passes two values:
- the job number
- the priority
Step-by-Step Reasoning
Initialise()
- Clears the array and sets
NumberOfJobsto0.
AddJob(12, 10)
- Stores job number
12with priority10.
AddJob(526, 9)
- Stores the next job.
AddJob(33, 8)
- Stores the third job.
AddJob(12, 9)
- Stores another job number
12; duplicate job numbers are not forbidden by the question.
AddJob(78, 1)
- Stores the final job.
Because all five calls are within the 100-job limit, each one will print Added.
Key Takeaways
- The main program often just sequences procedure calls.
- Use the exact data given in the question.
- Do not change the order unless the task explicitly says to.
Common Mistakes
- Forgetting to call
Initialise()first. - Putting the jobs in a different order.
- Swapping job number and priority in a call.
- Missing one of the five
AddJob()calls.
Things to Be Careful About
AddJob(12, 10)means job number12, priority10, not the other way around.- There are two jobs with job number
12; that is allowed here. - This part does not yet sort or print the final array. It only initialises and adds the jobs.
When a new job has been added, the array is sorted into ascending numerical order of priority using an insertion sort.
Write program code for the procedure InsertionSort() to sort the data into ascending numerical order of priority.
Save your program.
Copy and paste the program code into part 1(e) in the evidence document.
Answer
def InsertionSort():
global Jobs, NumberOfJobs
for Count in range(1, NumberOfJobs):
CurrentJob = Jobs[Count][0]
CurrentPriority = Jobs[Count][1]
Pointer = Count - 1
while Pointer >= 0 and Jobs[Pointer][1] > CurrentPriority:
Jobs[Pointer + 1][0] = Jobs[Pointer][0]
Jobs[Pointer + 1][1] = Jobs[Pointer][1]
Pointer -= 1
Jobs[Pointer + 1][0] = CurrentJob
Jobs[Pointer + 1][1] = CurrentPriority
See program code
Background Concept
Insertion sort builds a sorted section of the array from left to right. At each step:
- take the next item
- compare it with items before it
- shift larger items right
- insert the item into the gap
In this question, each row is a record containing two linked values:
- job number
- priority
So you are not sorting single numbers. You are sorting records based on the priority field, which is in column 1. Whenever a row moves, both fields must move together.
Understanding the Question
The array must be sorted into ascending numerical order of priority:
- smaller priority number comes first
- so priority
1is before8,9, or10
The phrase “using an insertion sort” means you must code that algorithm, not use Python's built-in sorting methods.
Also, only the jobs currently stored should be sorted. The rest of the array contains unused values such as -1 and must not be included.
Approach
Use standard insertion sort over rows 0 to NumberOfJobs - 1:
- start at row
1 - save that row's job number and priority
- move left while earlier priorities are larger
- shift rows right to make space
- insert the saved row
The key comparison is Jobs[Pointer][1] > CurrentPriority because column 1 is the priority column.
Step-by-Step Reasoning
for Count in range(1, NumberOfJobs):
- The first row by itself is already considered sorted.
- So insertion sort begins at the second stored row.
- Using
NumberOfJobsensures only valid jobs are sorted.
CurrentJob = Jobs[Count][0]
CurrentPriority = Jobs[Count][1]
- Save the full record currently being inserted.
- You need both values, not just the priority.
Pointer = Count - 1
- Start comparing with the row immediately before the current one.
while Pointer >= 0 and Jobs[Pointer][1] > CurrentPriority:
- Move left while earlier priorities are larger.
- Because the sort is ascending, larger priorities must shift right.
- Using
>rather than>=makes the sort stable, so equal priorities stay in their original order.
Jobs[Pointer + 1][0] = Jobs[Pointer][0]
Jobs[Pointer + 1][1] = Jobs[Pointer][1]
- Shift the whole row one place to the right.
- This is vital: the job number must stay attached to its priority.
Pointer -= 1
- Continue checking earlier rows.
After the loop ends, the correct insertion position is Pointer + 1.
Jobs[Pointer + 1][0] = CurrentJob
Jobs[Pointer + 1][1] = CurrentPriority
- Place the saved record into the gap.
Key Takeaways
- Insertion sort works by inserting one item at a time into an already sorted section.
- When sorting records, move the entire record, not just the key field.
- Limit processing to the used portion of the array with
NumberOfJobs.
Common Mistakes
- Sorting all 100 rows instead of only the used rows.
- Comparing the job number instead of the priority.
- Moving only the priority and leaving the job number behind.
- Using Python's built-in sort instead of coding insertion sort.
- Getting the sort direction wrong and producing descending order.
Things to Be Careful About
- The key field is
Jobs[row][1], notJobs[row][0]. - If you include unused
-1rows in the sort, they will move to the front and corrupt the result. - Keep
CurrentJobandCurrentPrioritytogether throughout the insertion. - Using
>rather than>=preserves the order of equal priorities, which matches the expected output here.
The procedure PrintArray() outputs each job number and priority on a line, for example:
123 priority 1
39 priority 3
120 priority 7
Write program code for the procedure PrintArray().
Save your program.
Copy and paste the program code into part 1(f) in the evidence document.
Answer
def PrintArray():
for Count in range(NumberOfJobs):
print(f'{Jobs[Count][0]} priority {Jobs[Count][1]}')
See program code
Background Concept
Output routines often loop through stored records and print selected fields in a required format. When an array is only partly full, the loop must stop at the current number of valid records, not at the physical size of the array.
Understanding the Question
PrintArray() must output each stored job on its own line in this form:
jobNumber priority priorityValue
For example:
123 priority 1
So the procedure must print:
- the job number from column
0 - the word
priority - the priority from column
1
for every stored job.
Approach
Use a loop from 0 to NumberOfJobs - 1 and print one formatted line per row.
Do not print all 100 rows, because most of them are unused.
Step-by-Step Reasoning
def PrintArray():
- Defines the required procedure.
for Count in range(NumberOfJobs):
- Loops over just the valid rows.
- If 5 jobs have been stored, this gives rows
0to4.
print(f'{Jobs[Count][0]} priority {Jobs[Count][1]}')
Jobs[Count][0]is the job number.Jobs[Count][1]is the priority.- The literal word
priorityis placed between them to match the required output format.
Key Takeaways
- Use the logical size of the data (
NumberOfJobs), not the maximum capacity. - Output formatting matters in Paper 4.
- Each row in the 2D array represents one complete job record.
Common Mistakes
- Looping through all 100 rows and printing unused
-1values. - Printing the columns in the wrong order.
- Printing the Python list itself, such as
[12, 10], instead of the required format. - Omitting the word
priority.
Things to Be Careful About
- The line format must match the question example closely.
range(NumberOfJobs)is correct because Python stops before the upper bound.- If the array has not been sorted yet,
PrintArray()will print jobs in insertion order, not priority order.
The main program needs to sort the array and then output the contents of the array.
Amend the main program by writing program code to call procedures InsertionSort() and PrintArray().
Save your program.
Copy and paste the program code into part 1(g)(i) in the evidence document.
Answer
InsertionSort()
PrintArray()
See program code
Background Concept
A main program often coordinates different procedures, with each one doing one specific task. The sequence matters: if you print before you sort, the output will show the original insertion order rather than the required sorted order.
Understanding the Question
This part says the main program now needs to:
- sort the array
- output the contents
So you must add calls to the two procedures already written:
InsertionSort()PrintArray()
Approach
Add the procedure calls after all five AddJob() calls in the main program. The correct order is:
- call
InsertionSort()first - call
PrintArray()second
Step-by-Step Reasoning
InsertionSort()
- Reorders the stored jobs by ascending priority.
PrintArray()
- Outputs the jobs in their new sorted order.
If these lines are placed after the AddJob() calls, the final display will show the sorted list.
Key Takeaways
- Procedure calls in the main program control the order of operations.
- Sorting must happen before printing if sorted output is required.
- Reusing previously written procedures keeps the program modular.
Common Mistakes
- Calling
PrintArray()beforeInsertionSort(). - Forgetting one of the two procedure calls.
- Placing the calls before all the jobs have been added.
Things to Be Careful About
- This part is an amendment, so these lines belong in the main program, not inside another procedure.
- The procedure names must match exactly:
InsertionSort()andPrintArray().
Test your program.
Take a screenshot of the output.
Copy and paste the screenshot into part 1(g)(ii) in the evidence document.
Answer
Using the five AddJob() calls from part (d), the console output is:
Added
Added
Added
Added
Added
78 priority 1
33 priority 8
526 priority 9
12 priority 9
12 priority 10
See expected console output
Background Concept
To predict console output, you follow the program in execution order and record every print statement. In this program there are two sources of output:
AddJob()printsAddedorNot addedPrintArray()prints each stored job after sorting
Because the data is sorted by ascending priority, the smallest priority number appears first.
Understanding the Question
You are testing the finished program after:
- initialising the array
- adding five jobs
- sorting the stored jobs by priority
- printing the sorted array
The task is effectively asking for the output that should appear on screen so it can be compared with the screenshot.
Approach
Work through the program in order:
- each
AddJob()succeeds, so each printsAdded InsertionSort()orders the five stored rows by priority ascendingPrintArray()outputs the sorted rows one per line
Step-by-Step Reasoning
The five jobs are added in this order:
(12, 10)(526, 9)(33, 8)(12, 9)(78, 1)
Since the array has space, all five insertions succeed. So the first five output lines are:
AddedAddedAddedAddedAdded
Now sort by priority ascending:
- priority
1-> job78 - priority
8-> job33 - priority
9-> job526 - priority
9-> job12 - priority
10-> job12
So the sorted records are:
78 priority 133 priority 8526 priority 912 priority 912 priority 10
Notice the two jobs with priority 9 stay in the same relative order they were added. That is consistent with insertion sort when the comparison uses > rather than >=.
Key Takeaways
- Test output is produced by following every output statement in sequence.
- For this program, successful insertion produces five
Addedlines. - Sorting by ascending priority places the smallest priority number first.
Common Mistakes
- Forgetting the five
Addedlines and only writing the final sorted list. - Sorting in descending order by mistake.
- Reversing the two priority-9 jobs.
- Printing unsorted insertion order instead of sorted order.
Things to Be Careful About
- The output contains 10 lines in total: 5 status lines and 5 job lines.
- The format must match exactly, especially the word
priority. - Equal priorities can keep their original order if the insertion sort is coded stably, which matches the expected output shown.
The rest of this paper
2 more questions- Q2Programming Paradigms (Procedural and Object-oriented) · File Processing and Exception Handling · Algorithms and Abstract Data Types31M
- Q3Algorithms and Abstract Data Types · Programming Paradigms (Procedural and Object-oriented) · Recursion21M