Tutorial 0

❓️

Common Pseudocode Tasks & FAQs

0478 IGCSE


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

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

1

Find Min, Max, Sum & Average of Inputs

Many IGCSE/O-Level 15 markers and some A-Level questions 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
DECLARE nums : ARRAY[1:5] OF INTEGER DECLARE min, max, sum, index : INTEGER DECLARE mean : REAL nums[1] <-- 6 nums[2] <-- 3 nums[3] <-- 8 nums[4] <-- 2 nums[5] <-- 5 min <-- nums[1] max <-- nums[1] FOR index <-- 1 TO 5 IF nums[index] < min THEN min <-- nums[index] ENDIF IF nums[index] > max THEN max <-- nums[index] ENDIF sum <-- sum + nums[index] NEXT index OUTPUT "Min: ", min OUTPUT "Max: ", max OUTPUT "Sum: ", sum OUTPUT "Mean: ", (sum / 5)

2

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

DECLARE min, max, sum, index, num, count : INTEGER DECLARE mean : REAL DECLARE isFirst : BOOLEAN isFirst <-- TRUE count <-- 0 REPEAT OUTPUT "Enter number or 0 to stop:" INPUT num IF num <> 0 THEN IF num < min OR isFirst = TRUE THEN min <-- num ENDIF IF num > max OR isFirst = TRUE THEN max <-- num ENDIF sum <-- sum + num count <-- count + 1 isFirst <-- FALSE ENDIF UNTIL num = 0 OUTPUT "Min: ", min OUTPUT "Max: ", max OUTPUT "Sum: ", sum OUTPUT "Count: ", count OUTPUT "Mean: ", (sum / count)

3

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:

  1. Initialise an index variable to point to first element in array
  2. Loop through array element-by-element
  3. If current element is the value we are searching for, then update flag/return TRUE if in a function etc
  4. If item hasn't been found after looping through all elements in the array, then we know the item doesn't exist
DECLARE nums : ARRAY[1:5] OF INTEGER DECLARE targetNumber, index : INTEGER DECLARE found : BOOLEAN nums[1] <-- 6 nums[2] <-- 3 nums[3] <-- 8 nums[4] <-- 2 nums[5] <-- 5 OUTPUT "Enter number to search for:" INPUT targetNumber index <-- 1 found <-- FALSE //loop to 5, since 5 elements in array WHILE found = FALSE AND index <= 5 DO IF nums[index] = targetNumber THEN found <-- TRUE ENDIF index <-- index + 1 ENDWHILE IF found = TRUE THEN OUTPUT targetNumber, " is in the array!" ELSE OUTPUT targetNumber, " is not in the array!" ENDIF

Note: we can also write this as a function, returning TRUE if we find the item, while returning FALSE is we have looped through the entire array and not found the item

DECLARE nums : ARRAY[1:5] OF INTEGER DECLARE targetNumber : INTEGER nums[1] <-- 6 nums[2] <-- 3 nums[3] <-- 8 nums[4] <-- 2 nums[5] <-- 5 OUTPUT "Enter number to search for:" INPUT targetNumber IF LinearSearch(nums, targetNumber) = TRUE THEN OUTPUT targetNumber, " is in the array!" ELSE OUTPUT targetNumber, " is not in the array!" ENDIF FUNCTION LinearSearch(arr : ARRAY OF INTEGER, toFind : INTEGER) RETURNS BOOLEAN DECLARE index : INTEGER FOR index <-- 1 TO 5 IF arr[index] = toFind THEN RETURN TRUE ENDIF NEXT index RETURN FALSE ENDFUNCTION

4

Bubble Sort

In order to sort an array in either ascending or descending order, we can use bubble sort:

  1. 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
  2. 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
  3. 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.

DECLARE arrayLength : INTEGER DECLARE nums : ARRAY[1:5] OF INTEGER DECLARE targetNumber : INTEGER arrayLength <-- 5 nums[1] <-- 6 nums[2] <-- 3 nums[3] <-- 8 nums[4] <-- 2 nums[5] <-- 5 //bubble sort DECLARE temp : INTEGER DECLARE isSorted : BOOLEAN DECLARE endIndex : INTEGER endIndex <-- arrayLength - 1 //if array has 5 elements, then loop to 4, since can't compare element 5 with element 6, as there is no element 6... isSorted <-- FALSE //assume unsorted by default WHILE isSorted = FALSE DO //loop while not sorted isSorted <-- TRUE //assume is sorted, at start of each pass over all pairs - if no swaps made, then loop will terminate after this iteration FOR index <-- 1 TO endIndex //compare current with next element - if wrong order, then swap IF nums[index] > nums[index + 1] THEN //swap, using temp variable as intermediate storage temp <-- nums[index] nums[index] <-- nums[index + 1] nums[index + 1] <-- temp //since at least 1 element is not in correct order, then we need to loop again to continue sorting/check isSorted <-- FALSE ENDIF NEXT index //rightmost element sorted on 1st loop, 2nd rightmost on 2nd loop etc - hence don't need to swap these already sorted elements endIndex <-- endIndex - 1 ENDWHILE //not bubble sort - just to output FOR index <-- 1 TO arrayLength OUTPUT nums[index] NEXT index

5

Round to n Decimal Places

We can 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

CONSTANT PI <-- 3.141592653589793 DECLARE decimalPlaces : INTEGER FOR decimalPlaces <-- 0 TO 15 OUTPUT decimalPlaces, ": ", ROUND(PI, decimalPlaces) NEXT decimalPlaces

6

Force Round Up or Down

We can use the ROUND function then add an offset of +/- 0.5 to round up or down to the nearest integer respectively

Let's look at an example - take a number like 7.0 - if we use ROUND(7.0, 0), that will be rounded to 7 - however, if we add 0.5, we effectively get ROUND(7.50, 0) which hence rounds up to 8

DECLARE n : REAL FOR n <-- 1 TO 2 STEP 0.01 OUTPUT "--- ", n, " ---" OUTPUT "Round: ", ROUND(n, 0) OUTPUT "Round Down: ", ROUND(n - 0.5, 0) OUTPUT "Round Up: ", ROUND(n + 0.5, 0) OUTPUT "" NEXT n

7

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

OUTPUT RANDOM() //real number 0-1 inclusive OUTPUT -10 + ROUND(RANDOM() * 20, 0) //-10 to 10 OUTPUT 5 + ROUND(RANDOM() * 5, 0) //5 to 10

8

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:

DECLARE index : INTEGER OUTPUT "--- Odd Numbers ---" FOR index <-- 1 TO 100 STEP 2 OUTPUT index NEXT index OUTPUT "--- 5x Table Numbers ---" FOR index <-- 0 TO 100 STEP 5 OUTPUT index NEXT index OUTPUT "--- Countdown 10-0 Numbers ---" FOR index <-- 10 TO 0 STEP -1 OUTPUT index NEXT index

9

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 SUBSTRING

DECLARE index : INTEGER DECLARE word : STRING word <-- "Supercalifragilisticexpialidocious" FOR index <-- 1 TO LENGTH(word) OUTPUT index, ": ", SUBSTRING(word, index, 1) NEXT index

10

Check if Character is Uppercase, Lowercase, Digit or Other

To check if a character is in a given range, we can use either IF or CASE statements

This works because it's simply the ASCII code of the characters that are compared - '0' = 48, 'A' = 65 and 'a' = 97

DECLARE c : CHAR c <-- 'T' IF c >= 'A' AND c <= 'Z' THEN OUTPUT c, " is uppercase" ELSE IF c >= 'a' AND c <= 'z' THEN OUTPUT c, " is lowercase" ELSE IF c >= '0' AND c <= '9' THEN OUTPUT c, " is a digit" ELSE OUTPUT c, " is a special character" ENDIF ENDIF ENDIF

11

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

DECLARE creditCardNumber : STRING OUTPUT "Please enter a FAKE credit card number of 16 digits:" INPUT creditCardNumber WHILE LENGTH(creditCardNumber) <> 16 DO OUTPUT "Not 16 digits - try again:" INPUT creditCardNumber ENDWHILE OUTPUT "Success!"

12

Range Check

Assume you have a pizza delivery business - customers should be able to order between 1 and 50 pizzas

DECLARE numPizzas : INTEGER OUTPUT "How many pizzas would you like to buy (1-50):" INPUT numPizzas WHILE numPizzas < 1 OR numPizzas > 50 DO OUTPUT numPizzas, " isn't in the range 1-50 - try again:" INPUT numPizzas ENDWHILE OUTPUT "Success!"

13

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
OUTPUT PasswordCheck("abcDef123#") OUTPUT PasswordCheck("AbcDef123#") FUNCTION PasswordCheck(pw : STRING) RETURNS BOOLEAN DECLARE index : INTEGER DECLARE currentChar : CHAR DECLARE hasLowercase, hasNumber, hasSpecialChar : BOOLEAN IF LENGTH(pw) < 8 THEN RETURN FALSE ENDIF currentChar <-- SUBSTRING(pw, 1, 1) IF currentChar < 'A' OR currentChar > 'Z' THEN RETURN FALSE ENDIF FOR index <-- 2 TO LENGTH(pw) currentChar <-- SUBSTRING(pw, index, 1) IF currentChar >= 'a' AND currentChar <= 'z' THEN hasLowercase <-- TRUE ELSE IF currentChar >= '0' AND currentChar <= '9' THEN hasNumber <-- TRUE ELSE IF currentChar < 'A' OR currentChar > 'Z' THEN hasSpecialChar <-- TRUE ENDIF ENDIF ENDIF NEXT index IF hasLowercase = TRUE AND hasNumber = TRUE AND hasSpecialChar = TRUE THEN RETURN TRUE ELSE RETURN FALSE ENDIF ENDFUNCTION

14

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

DECLARE num : INTEGER num <-- 5 IF MOD(num, 2) = 0 THEN OUTPUT num, " is even" ELSE OUTPUT num, " is odd" ENDIF

15

Check if Number is Integer

There are at least 3 ways of checking if a number is an integer or not

DECLARE num : REAL num <-- 5.1 OUTPUT "--- Checking ", num, " ---" OUTPUT num = ROUND(num, 0) OUTPUT DIV(num, 1) = num OUTPUT MOD(num, 1) = 0 num <-- 5 OUTPUT "--- Checking ", num, " ---" OUTPUT num = ROUND(num, 0) OUTPUT DIV(num, 1) = num OUTPUT MOD(num, 1) = 0

16

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

DECLARE grid : ARRAY[1:3, 1:3] OF INTEGER DECLARE row, col : INTEGER //looping through 2D array, populating/initialising array elements and outputting them FOR row <-- 1 TO 3 FOR col <-- 1 TO 3 grid[row, col] <-- ROUND(RANDOM() * 9, 0) OUTPUT row, ", ", col, ": ", grid[row, col] NEXT col NEXT row OUTPUT "" OUTPUT "---" OUTPUT "" DECLARE line : STRING //concatenating strings to output row on single line //note: contenation (&) operator is just for AS, so wouldn't be asked for IG - but some people just ask how to do this anyway FOR row <-- 1 TO 3 line <-- "" FOR col <-- 1 TO 3 line <-- line & grid[row, col] & ' ' NEXT col OUTPUT line NEXT row

17

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

DECLARE menuChoice : INTEGER REPEAT OUTPUT "Please enter a choice: 1) Do something... 2) Do something else... 3) Exit" INPUT menuChoice CASE OF menuChoice 1: CALL A() 2: CALL B() ENDCASE UNTIL menuChoice = 3 OUTPUT "Goodbye..." PROCEDURE A() OUTPUT "Procedure A called..." ENDPROCEDURE PROCEDURE B() OUTPUT "Procedure B called..." ENDPROCEDURE

18

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

CALL DisplayPaperDetails("0478") CALL DisplayPaperDetails("2210") CALL DisplayPaperDetails("9618") PROCEDURE DisplayPaperDetails(syllabusCode : STRING) DECLARE syllabusName : STRING DECLARE validSyllabus : BOOLEAN validSyllabus <-- FALSE IF syllabusCode = "0478" OR syllabusCode = "0984" THEN syllabusName <-- "IGCSE" validSyllabus <-- TRUE ELSE IF syllabusCode = "2210" THEN syllabusName <-- "O-Level" validSyllabus <-- TRUE ELSE OUTPUT syllabusCode, " is an unknown syllabus" ENDIF ENDIF IF validSyllabus = TRUE THEN OUTPUT "--- Computer Science | ", syllabusCode, " | ", syllabusName, " ---" OUTPUT "Paper 1: 1h 45m, Theory, 75 Marks" OUTPUT "Paper 2: 1h 45m, Programming, 75 Marks" ENDIF ENDPROCEDURE

19

Functions

Like procedures, functions are groups of code that can be used at different points throughout the program

There are two differences, however:

  1. Functions have to return a value
  2. 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
DECLARE n : INTEGER FOR n <-- 1 TO 100 IF isSquareNumber(n) THEN OUTPUT "🟢 ", n, " is square" ELSE OUTPUT "🔴 ", n, " is not square" ENDIF NEXT n FUNCTION isSquareNumber(num : INTEGER) RETURNS BOOLEAN DECLARE temp : REAL temp <-- num ^ 0.5 RETURN temp = ROUND(temp, 0) ENDFUNCTION

20

Reading from Files

For IGCSE/O-Level, you should only have to read a single line of a file - if they ask you to read multiple lines of a file, they will tell you the number of lines to read/that the file contains

For example, Jokes.txt contains 36 lines, hence the following code will read and output all 36 lines

Note how we are first required to open the file in read mode and close it after use too

DECLARE lineNum : INTEGER DECLARE line : STRING OPENFILE Jokes.txt FOR READ FOR lineNum <-- 1 TO 36 READFILE Jokes.txt, line OUTPUT line NEXT lineNum CLOSEFILE Jokes.txt

21

Writing to Files

Suppose we want to keep writing names of students in your class to a file, until the user enters nothing

DECLARE classmate : STRING OPENFILE Students.txt FOR WRITE REPEAT OUTPUT "Enter classmate's name:" INPUT classmate IF classmate <> "" THEN WRITEFILE Students.txt, classmate ENDIF UNTIL classmate = "" CLOSEFILE Students.txt