Tutorial 9

🧮

Functions & Procedures - Built-in

9618 A-Level


Cambridge A-Level 9618 pseudocode comes with many built-in modules (functions or procedures) - for A-Level, the built-in modules are all functions, though custom modules can be created too which we will see in the next tutorial

Many students get confused about the difference between a function a procedure - the difference should be fairly easy to understand with practice (next tutorial :)), but is also outlined briefly below:

  • Functions will return a value that can be used to assign, in a calculation, a condition, output statement etc
  • Procedures won't return a value - we can output data inside the procedure, but the procedure itself won't evaluate to an answer

The built-in function categories for A-Level are:

Note: functions change slightly over the years. Make sure to check the function insert in the exam

String Functions

1

LENGTH

Returns the number of characters in a string

Parameters:

  1. [STRING] - the string to get the length from
OUTPUT LENGTH("Pseudocode") OUTPUT LENGTH("hello") = LENGTH("world")

2

LEFT

Returns a given number of characters starting from the left of the string

Parameters:

  1. [STRING] - the string to extract the characters from
  2. [INTEGER] - the number of characters to get
OUTPUT LEFT("Pseudocode", 6)

3

MID

Gets a part of a string, starting from a given index position and containing a given number of characters

Parameters:

  1. [STRING] - the string to extract the substring from
  2. [INTEGER] - the starting position of the substring
  3. [INTEGER] - the number of characters to get
DECLARE s : STRING s <-- "pseudocode.pro" OUTPUT MID(s, 1, 6) OUTPUT MID(s, 7, 4) OUTPUT MID(s, 12, 3)

4

RIGHT

Returns the rightmost n characters of a string. Note: the characters will still be returned in left to right order

Parameters:

  1. [STRING] - the string to extract the characters from
  2. [INTEGER] - the number of characters to get
OUTPUT RIGHT("Pseudocode", 4)

5

TO_LOWER

Converts a string to lowercase

Parameters:

  1. [STRING] - the string to convert to lowercase
OUTPUT TO_LOWER("CLAUDE SHANNON")

6

TO_UPPER

Converts a string to uppercase

Parameters:

  1. [STRING] - the string to convert to uppercase
OUTPUT TO_UPPER("charles babbage")

7

LCASE

Converts a character to lowercase

Parameters:

  1. [CHAR] - the character to convert to lowercase
OUTPUT LCASE('A')

8

UCASE

Converts a character to uppercase

Parameters:

  1. [CHAR] - the character to convert to uppercase
OUTPUT UCASE('a')

9

NUM_TO_STR

Converts an INTEGER or REAL to a STRING

Parameters:

  1. [INTEGER | REAL] - the number to convert to a string
OUTPUT NUM_TO_STR(123.456) OUTPUT NUM_TO_STR(7 * 42)

10

STR_TO_NUM

Converts a STRING to an INTEGER or REAL

Parameters:

  1. [STRING] - the string to convert to a numeric value
OUTPUT STR_TO_NUM("123.456") OUTPUT STR_TO_NUM("987")

11

IS_NUM

Returns whether a given string is numeric

Parameters:

  1. [STRING] - the string to check if numeric
OUTPUT IS_NUM("-123.456") OUTPUT IS_NUM("13579") OUTPUT IS_NUM("abc")

12

ASC

Returns the ASCII code for a given character.

Note: the site extends this to allow full Unicode support for non-Latin characters, emojis, symbols etc

Parameters:

  1. [CHAR] - the character to get the ASCII code of
OUTPUT ASC('0') OUTPUT ASC('A') OUTPUT ASC('a')

13

CHR

Returns the character represented by a given ASCII code

Note: the site extends this to allow full Unicode support for non-Latin characters, emojis, symbols etc

Parameters:

  1. [INTEGER] - the ASCII code to convert to a character
OUTPUT CHR(48) OUTPUT CHR(65) OUTPUT CHR(97)

Numeric Functions

14

INT

Returns the integer part of a number after removing the value after the decimal point

Parameters:

  1. [REAL] - the real number to extract the integer part from
DECLARE x : REAL x <-- 5.6 OUTPUT INT(x) OUTPUT INT(x + 0.5) //round up OUTPUT INT(x - 0.5) //round down

15

RAND

Returns a random real number in the range 0 to max (not inclusive of max)

Parameters:

  1. [REAL] - the maximum number to generate (exclusive)
OUTPUT RAND(10) // 0 TO 10 (not exclusive) OUTPUT RAND(10) - 5 // -5 TO 5 (not exclusive) OUTPUT RAND(50) + 50 // 50 TO 100 (not exclusive) OUTPUT INT(RAND(50)) + 50 // 50 TO 99

Date Functions

16

DAY

Returns the day value from a date

Parameters:

  1. [DATE] - the date to extract the day value part from
OUTPUT DAY(26/02/2025)

17

MONTH

Returns the month value from a date

Parameters:

  1. [DATE] - the date to extract the month value part from
OUTPUT MONTH(26/02/2025)

18

YEAR

Returns the year value from a date

Parameters:

  1. [DATE] - the date to extract the year value part from
OUTPUT YEAR(26/02/2025)

19

DAYINDEX

Returns the day index of the week where Sunday = 1, Monday = 2...Saturday = 7

Parameters:

  1. [DATE] - the date to extract the day index from
OUTPUT DAYINDEX(26/02/2025) //=4 (Wednesday)

20

SETDATE

Returns a date object with values corresponding to the day, month and year parameters

Parameters:

  1. [INTEGER] - the day value
  2. [INTEGER] - the month value
  3. [INTEGER] - the year value
DECLARE tutorialCreated : DATE tutorialCreated <-- SETDATE(26, 2, 2025) OUTPUT tutorialCreated

21

TODAY

Returns a date object representing the current day

Note: on older papers, this was called NOW() - check the insert if requiring this function in your exam

OUTPUT TODAY()

File Functions

Note: other file handling operations use keywords, not functions - OPENFILE, WRITEFILE, READFILE. And for A2, SEEK, GETRECORD, PUTRECORD

22

EOF (End of File)

Returns whether there are any more file contents left to read

Parameters:

  1. [STRING | FILE] - the file to check if the end of file has been reached. Can be specified with or without quotes

Note: we often use EOF within a WHILE loop to read all lines from a file, as shown below:

CONSTANT filename = "test.txt" DECLARE line : STRING DECLARE index : INTEGER OPENFILE filename FOR WRITE FOR index <-- 1 TO 5 WRITEFILE filename, "hello " & NUM_TO_STR(index) NEXT index CLOSEFILE filename WHILE NOT EOF(filename) DO READFILE filename, line OUTPUT line ENDWHILE

23

Generate IDs

Create a program can generate 8-character alphanumeric IDs - all characters should be equally likely. An example ID could be "T3nA8x1g"

DECLARE id : STRING DECLARE index, randNum : INTEGER id ← "" FOR index ← 1 TO 8 randNum ← INT(RAND(62)) IF randNum < 10 THEN id ← id & CHR(48 + randNum) ELSE IF randNum < 36 THEN id ← id & CHR(55 + randNum) ELSE id ← id & CHR(61 + randNum) ENDIF ENDIF NEXT index OUTPUT id

24

Email Greeting

Create a program that asks for a user to enter their first name then last name - the program will then output the following: "Dear SURNAME, firstname" is uppercase and lowercase respectively

DECLARE firstname, lastname : STRING OUTPUT "Enter your first name:" INPUT firstname OUTPUT "Enter your last name:" INPUT lastname OUTPUT "Dear ", TO_UPPER(lastname), ", ", TO_LOWER(firstname)

25

AbCdE

Create a program outputs the whole alphabet in alternating case - the output should be on a single line

DECLARE alphabet : STRING DECLARE currentIsUpper : BOOLEAN DECLARE charCode : INTEGER alphabet ← "" currentIsUpper ← TRUE FOR charCode ← 65 TO 90 IF currentIsUpper THEN alphabet ← alphabet & CHR(charCode) ELSE alphabet ← alphabet & CHR(charCode + 32) ENDIF currentIsUpper ← NOT currentIsUpper NEXT charCode OUTPUT alphabet

26

Work Usernames

Work usernames will be in the form of: [1 char for first name].[variable chars for last name].[3 digits] - examples could include: W.Rooney.005, C.Ronaldo.007, P.Scholes.001

You should create a program that can extract and assign each of these 3 parts to a variable. Note: the number should be assigned to a numeric variable, since we might want to do comparisons - e.g. finding who was the first employee

DECLARE firstInitial : CHAR DECLARE lastname, username : STRING DECLARE employeeNum : INTEGER username ← "W.Rooney.005" firstInitial ← LEFT(username, 1) lastname ← MID(username, 3, LENGTH(username) - 6) employeeNum ← STR_TO_NUM(RIGHT(username, 3)) OUTPUT "Initial: ", firstInitial OUTPUT "Last name: ", lastname OUTPUT "Num: ", employeeNum

27

Number of Digits

Ask the user to enter an integer, then output how many digits that number has

DECLARE num : INTEGER OUTPUT "Enter a whole number:" INPUT num OUTPUT num, " has ", LENGTH(NUM_TO_STR(num)), " digits"

28

ASCII Quiz

Create a program that generates a random alphanumeric character, asks the user to guess its ASCII code, then tells them if they were right or wrong

DECLARE validChars : STRING DECLARE randNum, userGuess : INTEGER DECLARE charToGuess : CHAR validChars ← "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789" randNum ← 1 + INT(RAND(LENGTH(validChars))) charToGuess ← MID(validChars, randNum, 1) OUTPUT "What is the ASCII code of '", charToGuess, "'?" INPUT userGuess IF userGuess = ASC(charToGuess) THEN OUTPUT "Correct!" ELSE OUTPUT "Unlucky - the correct answer was ", ASC(charToGuess) ENDIF

29

Random Distribution

Create a program generates 100,000 random integers from 1-10, then outputs a count of how many of each number was generated. You should ensure that an approximately equal distribution of all numbers is achieved

DECLARE numCounts : ARRAY[1:10] OF INTEGER DECLARE index, randNum : INTEGER FOR index ← 1 TO 100000 randNum ← 1 + INT(RAND(10)) numCounts[randNum] ← numCounts[randNum] + 1 NEXT index FOR index ← 1 TO 10 OUTPUT index, ": ", numCounts[index] NEXT index

30

Email Greeting

Create a program converts the current date into a full text date - i.e. 26/02/2025 would become "Wednesday 26th, February 2025"

DECLARE dayNames : ARRAY[1:7] OF STRING DECLARE monthNames : ARRAY[1:12] OF STRING DECLARE currentDate : DATE DECLARE dateStr : STRING dayNames ← ["Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"] monthNames ← ["January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"] currentDate ← TODAY() dateStr ← dayNames[DAYINDEX(currentDate)] & " " & NUM_TO_STR(DAY(currentDate)) CASE OF DAY(currentDate) 1, 21, 31: dateStr ← dateStr & "st" 2, 22: dateStr ← dateStr & "nd" 3, 23: dateStr ← dateStr & "rd" OTHERWISE: dateStr ← dateStr & "th" ENDCASE dateStr ← dateStr & ", " & monthNames[MONTH(currentDate)] & " " & NUM_TO_STR(YEAR(currentDate)) OUTPUT "Today is: ", dateStr

Extension: can you output this information for every day in the year? (you can choose to ignore leap years if you want - or see this leap year challenge

31

CS Quote File

Create a program that can read the following file, then output the data in the form: [quote] - [person]

Note how the lines are in pairs - Alan Turing said the first quote, Grace Hopper said the next and so on. You can assume that there is a valid quote for each person

CONSTANT filename = "CSQuotes.txt" DECLARE person, quote : STRING OPENFILE filename FOR READ WHILE NOT EOF(filename) DO READFILE filename, person READFILE filename, quote OUTPUT quote, " - ", person ENDWHILE CLOSEFILE filename

32

Vowels to Upper

Create a program that asks the user to enter a string, then converts all the vowels to uppercase and everything else to lowercase - i.e. "hello world" would become "hEllO wOrld"

DECLARE origStr, newStr : STRING DECLARE currentChar : CHAR DECLARE index : INTEGER OUTPUT "Enter some words:" INPUT origStr origStr ← TO_LOWER(origStr) newStr ← "" FOR index ← 1 TO LENGTH(origStr) currentChar ← MID(origStr, index, 1) CASE OF currentChar 'a', 'e', 'i', 'o', 'u': newStr ← newStr & UCASE(currentChar) OTHERWISE: newStr ← newStr & LCASE(currentChar) ENDCASE NEXT index OUTPUT newStr