Tutorial 0
❓️
Common Pseudocode Tasks & FAQs
9618 A-Level
There are many common tasks you will have to complete in exams - this page is essentially a repository of many of these key tasks you are expected to be able to perform for AS & A2 9618
If there is something else you'd like me to add to this page, please contact me
More details for specific aspects of pseudocode you have to know can be found on the tutorials pages
You should also ensure you are familiar with the built-in library modules provided in the pseudocode module insert too
1
Input into an Array
Often, we are required to ask the user to input data into an array
This is fairly simple to do - simply loop over all elements in the array and input at that particular index
In the example below, the user is asked to select their football team - both positions and players - this team sheet is then output to the user at the end
2
Find Min, Max, Sum & Average of Inputs
Although more common for IG 15 markers, some A-Level questions also require us to calculate the minimum, maximum, sum and mean of all numbers in an array
Looking at the code below, note:
- We assign min & max as being the first element - this is since, e.g. if giving min a huge default value, then if all values happened to be larger than this, we would think the min was this default value we initially assigned it - same for max, if we chose a small/negative initial value, but the real values all happened to be less than it
- We then loop through all elements in the array
- Min: if the current element is smaller than the current minimum, then set this current element as the new minimum
- Max: if the current element is bigger than the current maximum, then set this current element as the new maximum
- Sum: add each element to the sum
- Mean: divide the sum by the number of elements
- Note: in this example, we could have also assigned sum to be the first element, then started our loop from element 2
3
Find Min, Max, Sum & Average of Inputs
The code is effectively the same as that above, but here we should ideally assign the first input to be the min/max/sum - we could do this by having the first input before the loop, then only looping from 2 to n, or we could have a Boolean value (flag) representing whether we have got the first input yet
4
Linear Search
Often we want to search to see whether a specific value exists in an array - we can use linear search to do that:
- Initialise an index variable to point to first element in array
- Loop through array element-by-element
- If current element is the value we are searching for, then update flag/return TRUE if in a function etc
- If item hasn't been found after looping through all elements in the array, then we know the item doesn't exist
Note: we can also write this as a function, returning TRUE if we find the item, while returning FALSE if we have looped through the entire array and not found the item
5
1D Bubble Sort
In order to sort an array in either ascending or descending order, we can use bubble sort:
- Assume array is unsorted and loop to the n-1 position (e.g. 1 to 4, if 5 elements) in the array on the first iteration
- Compare elements pair by pair - if in the wrong order (i.e. if current element bigger than next element for ascending order...or current element smaller than next for descending order), then swap them by making use of a temporary variable
- If elements are not sorted after looping over all pairs, then go back to the start
More detailed comments can be seen in the code
Note: when we swap, we need the temporary variable - this is since if we do a <-- b, both variables now have the same value at this point - b <-- a will be redundant - hence why we need to move one value into a temporary variable before we update it, then assign this temporary variable value to the other variable. Drawing a picture with arrows representing the assignments between 3 variables can help with understanding.
Note: to sort in descending order, simply change the > in the IF statement to a <
2D Bubble Sort
The logic for 2D bubble sort is the same as for 1D bubble sort - the only difference is that we need to swap each column individually inside the IF statement
6
Round to n Decimal Places
For IG/O-Level, we could use the ROUND function to round to a given number of decimal places, where the 2nd parameter is the number of decimal places to round to
Unfortunately, for A-Level we don't have that function and, as you can see, the approach below is a bit tricky, so it's unlikely they will ask it, however, I will include this example too, in case people are curious/want to round in any of their own code without using the IG function
Let's walkthrough an example Custom_ROUND(123.456, 2) to see how it works
- Since we are rounding to 2 decimal places, we first want to move the decimal place 2 places to the right - 10 ** decimalPlaces will cause tenPower to be assigned the value 100
- Multiplying 123.456 * 100 = 12345.6
- We then have to add 0.5, giving us 12346.1 as we have seen before to correctly round either up or down (since INT simply truncates the values after the decimal point - i.e. rounding down for positive numbers)
- INT(12346.1) will evaluate to 12346
- Finally, 12346 / 100 = 123.46
7
Force Round Up or Down
Since INT truncates positive numbers (effectively rounding down), then unlike IG where we needed to subtract 0.5 like ROUND(x - 0.5, 0) to round down (floor), in AS, we can simply use INT as is
If we want to always round up (ceiling), we can just +1 to the argument we are passing into the INT function
8
Generate Random Number in a Range
Returns a real number between 0-1 inclusive
Note: we can multiply and add an offset to generate a random number within a range as shown below
The offset should be the lower bound of our range - then we should multiply our random value by the range. For example, if we want a random number between -10 and 10, the smallest number in the range is -10 and the range is 20
If we want to make this an integer, we will have to use ROUND
9
For Loop - Custom & Negative Step
By default, when we create a for loop, there is an implied step of 1 - i.e. the for loop variable increments by 1 each iteration of the loop
We can change this via the STEP keyword as shown below:
10
Loop Through Characters in a String
We can create a simple for loop from 1 to the length of the string, then get the current character with MID
11
Check if Character is Uppercase, Lowercase, Digit or Other
To check if a character is in a given range, we can either:
- Use the ASC function to get the character's ASCII code, then check which range it falls within (e.g. 65 to 90 for uppercase etc...)
- Directly compare the character with other characters - e.g 'b' > 'a' AND 'b' <= 'z' will evaluate to TRUE, since 'b' has the ASCII code 98, 'a' is 97, 'z' is 122
Remember the following ASCII codes, since sometimes they're not given in exams:
- '0' = 48
- 'A' = 65
- 'a' = 97
As shown below, since we have a finite integer range, we can use either CASE or nested IF statements to determine the character type - it's up to you
12
Length Check
Suppose customers should enter their credit card number - for this simple example, let's assume all should be 16 digits
Note: for credit card/telephone numbers, we often want to store them as strings, not integers - this is so leading zeros aren't remove, so that additional characters can be allowed in telephone numbers such as +(123) 456-789 etc
13
Range Check
Assume you have a pizza delivery business - customers should be able to order between 1 and 50 pizzas
14
Format Check
The specific code for a format check will depend on the format you are checking - let's say for our example, a password has to:
- Start with an uppercase letter
- Be at least 8 characters
- Contain at least 1 lowercase character, number and special character
- Can't start and end with the same character
15
Odd or Even
We can simply MOD by 2 - if the answer is 0, the number is even, if the answer is 1, it's odd
This same logic can be used to check if a number is a multiple of anything - for example, if MOD(n, 5) = 0, then n would be a multiple of 5
16
Check if Number is Integer
There are at least 3 ways of checking if a number is an integer or not
17
Declare, Populate & Output 2D Array
Note: we usually loop through a 2D array with rows being the outer loop, the columns being the inner loop - this effectively loops left to right, top to bottom - the same way books in many languages like English are read
18
Display Menu
To display a menu, we can simply output a list of options along with a "rogue value" to stop the program - we loop until that rogue value is entered
19
Procedures
A reminder - a procedure is a group of code we can use (call) via the CALL keyword - we can optionally have parameters which will have different arguments on different calls of the procedure, hence modifying the behaviour of that particular procedure call - like below, where we call the same procedure with 3 different syllabus codes
20
Functions
Like procedures, functions are groups of code that can be used at different points throughout the program
There are two differences, however:
- Functions have to return a value
- We don't need the CALL keyword when calling a function - since we can use the function directly in another statement or expression like output, an if statement, calculation etc
21
Reading from Files
The file Jokes.txt contains 36 lines. We continue looping while the end of file (EOF) hasn't been reached - note that READFILE will read the next line of the file
Note how we are first required to open the file in read mode and close it after use too - forgetting to close the file will lose you marks in the exam, so try not to forget! The site will give you a warning if you did forget too
22
Writing to Files
Suppose we want to keep writing names of students in your class to a file, until the user enters nothing
Note: opening a file in WRITE mode will overwrite (delete the old contents) of an existing file with that name, if one exists
23
Appending to Files
Sometimes we might want to write to an existing file - to do that, we simply open the file in APPEND mode
Note how we still use WRITEFILE when appending - a keyword like APPENDFILE doesn't exist in the syllabus
Content will be written to the end of an existing file - see the next example for writing data at an arbitrary point in a file
24
Inserting to File at Arbitrary Position
While appending is useful, it is limited in that data is always written at the end - sometimes we might want to write at a different position though
Consider a list of programming languages stored alphabetically - when inserting, we would want to insert the new language at the correct position
The approach is as follows
- Open the existing file in READ mode and create a new file in WRITE mode
- Read all lines and check if we have reached the point to insert:
- - if we haven't, then write the existing line to the new file
- - if we have, write the new line to insert to the new file, followed by the current line we have just read
- Write the remaining lines from the original file to the new file
25
Checking if String is a Palindrome
One approach used to check if a string is a palindrome (the same in reverse order) is to create a new string that is the reversed version of the original string and checking it is equal to the original (e.g. by looping through in reverse order or concatenating character by character...or looping through in ascending order of character index, but prepending the current character) - this approach does work, but is less efficient in terms of both time and memory
Instead, we will go with an 'in place' approach (i.e. without creating a copy of the data) - the way we can do that is as follows:
- Create a character index that represents the offset from the start (left) and end (right) of the string - initialise this index to 1
- i.e. we will be comparing the first and last characters, the 2nd and 2nd last, the 3rd and 3rd last etc
- If any of the pairs don't match, then return FALSE
- Think of an example with an even number of characters like noon and a odd example like level - in the first example, we compare "n" with "n", then "o" with "o"...while in the 2nd example we can compare the "l"'s, then the "e"'s - we don't have to compare the remaining middle "v" character, since by virtue of it being a single character, it is a palindrome of itself. This is why the number of comparisons we have to do is the integer division of the string length divided by 2
26
Extract Characters from Fixed-Format String
Often there will be questions where we have to use the string functions LEFT, RIGHT, MID and LENGTH to extract specific parts of a string
Consider data in the following format:
[4 character student ID][variable length student name][3 letter subject code]
An example could be: "inewIsaac NewtonPHY"
We could then extract each part using the following code - note how since 7 characters are fixed in length (4 + 3), then we can use that to calculate that the name must be the total string length minus 7
27
Convert Minutes to Hours & Minutes
In recent exam papers, there have been a lot of date/time questions - it's recommended to attempt all the past paper questions and see the solutions, but something that has been asked a few times is to convert a given number of minutes like 200 into the number of hours and minutes it represents
We could do this by working out how many whole hours can be made from 200 minutes (in this case, 3 hours = 180 minutes), then subtracting 180 minutes, giving us 20 minutes remaining
It's actually possible to do it even more simply, by using just DIV and MOD
28
Implementing Existing Functions Yourself
Sometimes exams ask you to implement existing Cambridge pseudocode functions yourself - we will just look at 1 here, though you can also try to implement others too
For this example, let's try to convert a string (using the English alphabet) to uppercase, without using TO_UPPER
We can do this by:
- Declaring a variable to store out new uppercase string (and others for the current position & current char)
- Looping through each character in the original string
- If the current character is lowercase, you can convert it to uppercase by subtracting 32 from it's ASCII value, then converting that resulting integer into a character using CHR - this works since the ASCII codes for uppercase English characters are 32 less than their corresponding lowercase equivalent. Concatenate this new character with the new string
- If the current character isn't lowercase, then just concatenate this character with the new string - in effect, making no change
29
Factorial
To calculate factorial, we can use either an iterative or recursive approach - since recursion is an A2 topic, then just the iterative approach will be expected
Note how we can start the loop from 2, since doing 1 * 1 is redundant - if an argument of 0 or 1 is entered, max will be less than the starting index, hence the loop body will never be entered
For simplicity, it's not handled here, but you could output an error message and return -1 or something if a negative value is passed in
30
Fibonacci
This has never actually come up in a past paper - though it's a famous series, common programming task and could potentially come up in a future paper, so I will include it anyway