F

11.1 Built-in Functions

Understanding and using pre-defined functions for string manipulation, character handling, numeric operations, date processing, and file operations

Learning Objectives

By the end of this lesson, you will be able to:

  • Understand what built-in functions are and why they are useful
  • Use string functions (LEFT, RIGHT, MID, LENGTH) to manipulate text data
  • Apply character functions (TO_UPPER, TO_LOWER, ASC, CHR) for case conversion and ASCII operations
  • Convert between numeric and string types using NUM_TO_STR and STR_TO_NUM
  • Use numeric functions (INT, RAND) for mathematical operations
  • Work with date functions (DAY, MONTH, YEAR, DAYINDEX, SETDATE, TODAY)
  • Check end of file using the EOF function
  • Apply operators (&, AND, OR, NOT, MOD, DIV) correctly
  • Understand the benefits of using built-in functions in programming
  • Evaluate expressions containing multiple built-in functions

Key Terms

Built-in Function

A pre-defined function in a programming language that is always available for use

String Function

A function that operates on string data (text)

Character Function

A function that operates on single characters or converts string case

ASCII Value

A numeric code that represents a character in computer memory

Parameter

Data passed to a function that it needs to perform its task

Return Value

The result that a function produces and sends back

Concatenation

Joining two or more strings together end-to-end

Operator

A symbol that performs an operation on values (e.g., +, -, AND, OR)

Case Sensitive

When uppercase and lowercase letters are treated as different characters

Integer Division (DIV)

Division that returns only the whole number quotient (no remainder)

Modulo (MOD)

An operation that returns the remainder of a division

Date Function

A function that works with date values (day, month, year)

String and Character Functions

Programming languages have built-in functions for manipulating strings and characters. These functions save time and make code more reliable.

Important: Error Generation

An error will be generated if:

  • A function call is not properly formed
  • The parameters are of an incorrect type
  • The parameters have an incorrect value

Example: Calling LEFT("Hello", "two") would generate an error because the second parameter should be an INTEGER, not a STRING.

String Manipulation Functions

LEFT Function

LEFT(ThisString : STRING, x : INTEGER) RETURNS STRING

Returns the leftmost x characters from ThisString.

Example:

LEFT("ABCDEFGH", 3) returns "ABC"

LEFT("ABCDEFGH", 3)
A
B
C
D
E
F
G
H
1
2
3
4
5
6
7
8
"ABC"

RIGHT Function

RIGHT(ThisString : STRING, x : INTEGER) RETURNS STRING

Returns the rightmost x characters from ThisString.

Example:

RIGHT("ABCDEFGH", 3) returns "FGH"

RIGHT("ABCDEFGH", 3)
A
B
C
D
E
F
G
H
1
2
3
4
5
6
7
8
"FGH"

MID Function

MID(ThisString : STRING, x : INTEGER, y : INTEGER) RETURNS STRING

Returns a string of length y starting at position x from ThisString.

Example:

MID("ABCDEFGH", 2, 3) returns "BCD"

MID("ABCDEFGH", 2, 3)
A
B
C
D
E
F
G
H
1
2
3
4
5
6
7
8
"BCD"

LENGTH Function

LENGTH(ThisString : STRING) RETURNS INTEGER

Returns the integer value representing the length of ThisString.

Example:

LENGTH("Happy Days") returns 10

LENGTH("Happy Days")
"H a p p y   D a y s"
10
characters

Case Conversion Functions

TO_UPPER Function

TO_UPPER(x : <datatype>) RETURNS <datatype>

Returns an object of type <datatype> formed by converting all characters of x to upper case. <datatype> may be CHAR or STRING.

Examples:
  • TO_UPPER("Error 803") returns "ERROR 803"
  • TO_UPPER('a') returns 'A'

TO_LOWER Function

TO_LOWER(x : <datatype>) RETURNS <datatype>

Returns an object of type <datatype> formed by converting all characters of x to lower case. <datatype> may be CHAR or STRING.

Examples:
  • TO_LOWER("JIM 803") returns "jim 803"
  • TO_LOWER('W') returns 'w'

String Functions Visualizer

Enter a string and select a function to see how it works. Watch the visualization to understand what each function does.

LEFT("Computer Science", 5)
"Compu"

Type Conversion Functions

NUM_TO_STR Function

NUM_TO_STR(x : <datatype1>) RETURNS <datatype2>

Returns a string representation of a numeric value. <datatype1> may be REAL or INTEGER, <datatype2> may be CHAR or STRING.

Example:

NUM_TO_STR(87.5) returns "87.5"

STR_TO_NUM Function

STR_TO_NUM(x : <datatype1>) RETURNS <datatype2>

Returns a numeric representation of a string. <datatype1> may be CHAR or STRING, <datatype2> may be REAL or INTEGER.

Example:

STR_TO_NUM("23.45") returns 23.45

IS_NUM Function

IS_NUM(ThisString : <datatype>) RETURNS BOOLEAN

Returns TRUE if ThisString represents a valid numeric value. <datatype> may be CHAR or STRING.

Example:

IS_NUM("-12.36") returns TRUE

ASCII Functions

ASC(ThisChar : CHAR) RETURNS INTEGER

Returns an integer value (the ASCII value) of character ThisChar.

Example:

ASC('A') returns 65, ASC('B') returns 66, etc.

CHR(x : INTEGER) RETURNS CHAR

Returns the character whose integer value (the ASCII value) is x.

Example:

CHR(65) returns 'A', CHR(66) returns 'B', etc.

Important Notes about Strings and Characters

  • A string of length 1 may be either of type CHAR or STRING
  • A CHAR may be assigned to, or concatenated with, a STRING
  • A STRING of length greater than 1 cannot be assigned to a CHAR
Examples:
  • myChar ← 'A' is valid (CHAR)
  • myString ← "A" is also valid (STRING of length 1)
  • myString ← "Hello" & '!' is valid (CHAR concatenated with STRING)
  • myChar ← "Hello" would generate an ERROR (STRING too long for CHAR)

Real-Life Example: User Registration Form

When users register on a website, built-in functions are used to validate and format their input:

// Example pseudocode for user registration validation
username ← "jOhN_dOe123"
email ← "JOHN@EXAMPLE.COM"
birthDate ← "15/03/2005"
// Format username: capitalize first letter, rest lowercase
formattedUsername ← TO_UPPER(LEFT(username, 1)) & TO_LOWER(RIGHT(username, LENGTH(username)-1))
// Result: "John_doe123"
// Format email to lowercase
formattedEmail ← TO_LOWER(email)
// Result: "john@example.com"
// Extract year from birth date
birthYear ← STR_TO_NUM(RIGHT(birthDate, 4))
// Result: 2005
// Check if username contains at least 3 letters
letterCount ← 0
FOR i ← 1 TO LENGTH(username)
IF ASC(MID(username, i, 1)) >= 65 AND ASC(MID(username, i, 1)) <= 90 OR
   ASC(MID(username, i, 1)) >= 97 AND ASC(MID(username, i, 1)) <= 122
THEN letterCount ← letterCount + 1
ENDIF
END FOR
// Result: letterCount would be 7 for "jOhN_dOe123"

Built-in functions make it easy to validate, format, and extract information from user input without writing complex code.

Activity 1: String Function Practice

Evaluate the following expressions. Use the string "Programming" for questions 1-4:

  1. What does LEFT("Programming", 3) return?
  2. What does RIGHT("Programming", 4) return?
  3. What does MID("Programming", 4, 5) return?
  4. What does LENGTH("Programming") return?
  5. What does TO_UPPER("Hello World!") return?
  6. What does ASC('m') return? (ASCII of 'm' is 109)
  7. What does CHR(72) return? (72 is ASCII for 'H')
Solution:
  1. LEFT("Programming", 3): Returns "Pro"
  2. RIGHT("Programming", 4): Returns "ming"
  3. MID("Programming", 4, 5): Returns "gramm" (starts at position 4, takes 5 characters)
  4. LENGTH("Programming"): Returns 11
  5. TO_UPPER("Hello World!"): Returns "HELLO WORLD!"
  6. ASC('m'): Returns 109 (ASCII value of lowercase 'm')
  7. CHR(72): Returns 'H' (character with ASCII value 72)

Check Your Understanding: String & Character Functions

Answer
  • [1 mark] MID function returns a substring from a string
  • [1 mark] Parameters: ThisString (STRING), x (INTEGER - starting position), y (INTEGER - length to extract)
  • [Additional] Example: MID("ABCDEFGH", 2, 3) returns "BCD"
Answer
  • [1 mark] When the string contains non-numeric characters (except decimal point and minus sign at start)
  • [1 mark] When the string is not a valid number format (e.g., "12.34.56", "AB123", "12-34")
  • [Additional] Examples: IS_NUM("123abc") returns FALSE, IS_NUM("12.3.4") returns FALSE
Answer
  • [1 mark] ASC takes a character and returns its ASCII code (integer)
  • [1 mark] CHR takes an ASCII code (integer) and returns the corresponding character
  • [Additional] They are inverse functions: CHR(ASC('A')) returns 'A', ASC(CHR(65)) returns 65
Answer
  • [1 mark] Numbers and spaces don't have uppercase/lowercase versions, so they remain unchanged
  • [Additional] TO_UPPER only affects alphabetic characters (A-Z, a-z). Digits, spaces, and punctuation stay the same.
Answer
  • [1 mark] Type error - LEFT expects a STRING as first parameter
  • [1 mark] 123 is an INTEGER, not a STRING
  • [Additional] To fix: Use NUM_TO_STR first: LEFT(NUM_TO_STR(123), 2) would return "12"
Answer
  • [1 mark] First evaluate concatenation: "Hello" & " " & "World" = "Hello World"
  • [1 mark] RIGHT("Hello World", 5) returns "World"
  • [Additional] The & operator joins strings before RIGHT function extracts last 5 characters

Numeric Functions

Numeric functions perform mathematical operations. They are useful for calculations, rounding, and generating random numbers.

Integer and Random Functions

INT Function

INT(x : REAL) RETURNS INTEGER

Returns the integer part of x (truncates decimal part without rounding).

Example:

INT(27.5415) returns 27

Important:

INT function truncates (removes decimal part) rather than rounds. INT(27.999) returns 27, not 28.

RAND Function

RAND(x : INTEGER) RETURNS REAL

Returns a real number in the range 0 to x (not inclusive of x).

Example:

RAND(87) may return 35.43

Important:

RAND returns a value less than x, not less than or equal to x. RAND(10) can return 0.0 to 9.999..., but never 10.0.

Numeric Functions Visualizer

Experiment with numeric functions. See how INT truncates decimals and RAND generates random numbers.

INT Function
INT(27.5415)
27
RAND Function
RAND(87)
35.43

Real-Life Example: Shopping Cart Calculations

In an e-commerce system, numeric functions are used to calculate prices, taxes, and discounts:

// Example pseudocode for shopping cart calculations
price ← 24.99
quantity ← 3
taxRate ← 0.20 // 20% tax
// Calculate subtotal (price × quantity)
subtotal ← price * quantity
// Result: 74.97
// Calculate tax (subtotal × taxRate)
tax ← subtotal * taxRate
// Result: 14.994
// Round down to nearest whole currency unit (no cents)
taxWhole ← INT(tax)
// Result: 14 (truncates 14.994 to 14)
// Generate order ID with random component
orderID ← "ORD" & NUM_TO_STR(INT(RAND(10000)))
// Example: "ORD" & "3542" = "ORD3542"
// Display formatted price
displayPrice ← "$" & NUM_TO_STR(price)
// Result: "$24.99"

Built-in numeric functions simplify common calculations in real-world applications.

Activity 2: Numeric Function Practice

Evaluate the following expressions:

  1. What does INT(15.999) return?
  2. What does INT(-3.7) return?
  3. If RAND(50) returns a value, what is the range of possible values?
  4. What does NUM_TO_STR(INT(12.75)) return?
  5. What does STR_TO_NUM("100") + 25 return?
  6. Write an expression to get a random integer between 0 and 99 inclusive.
Solution:
  1. INT(15.999): Returns 15 (truncates, doesn't round)
  2. INT(-3.7): Returns -3 (truncates toward zero)
  3. RAND(50) range: Returns a real number ≥ 0 and < 50 (0.0 to 49.999...)
  4. NUM_TO_STR(INT(12.75)): INT(12.75) = 12, then NUM_TO_STR(12) = "12"
  5. STR_TO_NUM("100") + 25: STR_TO_NUM("100") = 100, then 100 + 25 = 125
  6. Random integer 0-99: INT(RAND(100)) or for inclusive 0-100: INT(RAND(101))

Date Functions

Date functions work with dates. The date format is assumed to be DD/MM/YYYY unless otherwise stated.

Important: Date Format

All date functions assume the format DD/MM/YYYY (Day/Month/Year) unless otherwise specified.

Example: 04/10/2003 means 4th October 2003, not 10th April 2003.

Date Extraction Functions

DAY Function

DAY(ThisDate : DATE) RETURNS INTEGER

Returns the current day number from ThisDate.

Example:

DAY(04/10/2003) returns 4

MONTH Function

MONTH(ThisDate : DATE) RETURNS INTEGER

Returns the current month number from ThisDate.

Example:

MONTH(04/10/2003) returns 10

YEAR Function

YEAR(ThisDate : DATE) RETURNS INTEGER

Returns the current year number from ThisDate.

Example:

YEAR(04/10/2003) returns 2003

Special Date Functions

DAYINDEX Function

DAYINDEX(ThisDate : DATE) RETURNS INTEGER

Returns the day index number from ThisDate where Sunday = 1, Monday = 2, Tuesday = 3, etc.

Example:

DAYINDEX(09/05/2023) returns 3 (Tuesday)

Day Index Values:
  • Sunday = 1
  • Monday = 2
  • Tuesday = 3
  • Wednesday = 4
  • Thursday = 5
  • Friday = 6
  • Saturday = 7

SETDATE and TODAY Functions

SETDATE(Day, Month, Year : INTEGER) RETURNS DATE

Returns a value of type DATE with the value of <Day>/<Month>/<Year>.

Example:

SETDATE(26, 10, 2003) returns a date corresponding to 26/10/2003

TODAY() RETURNS DATE

Returns a value of type DATE corresponding to the current date.

Example:

If today is 15th May 2023, TODAY() returns 15/05/2023

Date Functions Visualizer

Experiment with date functions. Enter a date and see how different functions extract information from it.

09/05/2023
DAY(09/05/2023)
9

Real-Life Example: Age Calculator

Date functions are commonly used to calculate ages, determine due dates, and schedule events:

// Example pseudocode for age calculator
birthDate ← 15/03/2005
currentDate ← TODAY() // Assume today is 10/05/2023
// Extract year, month, and day components
birthYear ← YEAR(birthDate) // 2005
birthMonth ← MONTH(birthDate) // 3
birthDay ← DAY(birthDate) // 15
currentYear ← YEAR(currentDate) // 2023
currentMonth ← MONTH(currentDate) // 5
currentDay ← DAY(currentDate) // 10
// Calculate age in years
ageYears ← currentYear - birthYear // 2023 - 2005 = 18
// Adjust if birthday hasn't occurred yet this year
IF currentMonth < birthMonth OR (currentMonth = birthMonth AND currentDay < birthDay)
THEN ageYears ← ageYears - 1
ENDIF
// Since March (3) < May (5) is false, and days 10 < 15 is true but months not equal, age stays 18
// Calculate days until next birthday
nextBirthday ← SETDATE(birthDay, birthMonth, currentYear)
// Creates 15/03/2023
IF nextBirthday < currentDate THEN
nextBirthday ← SETDATE(birthDay, birthMonth, currentYear + 1)
// Birthday already passed this year, set to next year
ENDIF
// In this case: 15/03/2023 < 10/05/2023 is true, so set to 15/03/2024

Date functions make it easy to work with dates for birthdays, appointments, schedules, and age calculations.

Text File Functions

Text file functions help work with files. The EOF function is particularly important for reading files correctly.

EOF Function

EOF(FileName : STRING) RETURNS BOOLEAN

Returns TRUE if there are no more lines to be read from file FileName.

Important:

The function will generate an error if the file is not already open in READ mode.

Typical Usage:
OPENFILE "data.txt" FOR READ
WHILE NOT EOF("data.txt")
READFILE "data.txt", lineData
// Process lineData
END WHILE
CLOSEFILE "data.txt"

Real-Life Example: Reading Student Records

EOF is essential when reading data from files, such as student records or configuration files:

// Example pseudocode for reading student records
studentCount ← 0
totalMarks ← 0
OPENFILE "students.txt" FOR READ
WHILE NOT EOF("students.txt")
READFILE "students.txt", studentRecord
// Assume format: "Name,Mark" e.g., "John Smith,85"
// Extract name and mark
commaPos ← 0
FOR i ← 1 TO LENGTH(studentRecord)
IF MID(studentRecord, i, 1) = "," THEN
commaPos ← i
EXIT FOR
END IF
END FOR
studentName ← LEFT(studentRecord, commaPos - 1)
studentMark ← STR_TO_NUM(RIGHT(studentRecord, LENGTH(studentRecord) - commaPos))
studentCount ← studentCount + 1
totalMarks ← totalMarks + studentMark
END WHILE
CLOSEFILE "students.txt"
// Calculate average
IF studentCount > 0 THEN
averageMark ← totalMarks / studentCount
ELSE
averageMark ← 0
END IF

The EOF function ensures we read all records in the file without trying to read past the end, which would cause an error.

Operators

Operators perform operations on values. An error will be generated if an operator is used with a value or values of an incorrect type.

Type Errors with Operators

Using an operator with incorrect data types will generate an error:

  • "Hello" + "World" - ERROR: + is for numbers, use & for string concatenation
  • 5 AND "True" - ERROR: AND expects Boolean values, not INTEGER and STRING
  • 10 MOD "3" - ERROR: MOD expects numbers, not INTEGER and STRING

Operator Reference Table

Operator Description Example Evaluates to
& Concatenates (joins) two strings. May also be used to concatenate a CHAR with a STRING "Summer" & " " & "Pudding" "Summer Pudding"
AND Performs a logical AND on two Boolean values TRUE AND FALSE FALSE
OR Performs a logical OR on two Boolean values TRUE OR FALSE TRUE
NOT Performs a logical NOT on a Boolean value NOT TRUE FALSE
MOD Finds the remainder when one number is divided by another 10 MOD 3 1
DIV Finds the quotient when one number is divided by another (integer division) 10 DIV 3 3

Comparison Operators

Comparison operators are used to compare two items of the same type. They evaluate to TRUE if the condition is true, otherwise evaluate to FALSE.

Notes about comparison operators:
  • May be used to compare types REAL and INTEGER
  • May be used to compare types CHAR and STRING
  • Case sensitive when used to compare types CHAR or STRING
  • Cannot be used to compare two records
Examples:
  • "Program" = "program" evaluates to FALSE (case sensitive)
  • Count = 4 evaluates to TRUE when variable Count contains the value 4

Operator Visualizer

Experiment with different operators. See how they work with different data types.

"Hello" & "World"
"HelloWorld"

Benefits of Built-in Functions

Complex Operations Made Simple

Allows the use of functions that would be difficult to code from scratch

Extensively Tested

They (should) have been more extensively tested, reducing time to test your code

Development Efficiency

Reduce the time to write code by using pre-built, reliable functions

Real-Life Example: Password Validation

Built-in functions and operators are often combined to validate complex rules, such as password requirements:

// Example pseudocode for password validation
password ← "Secret123!"
hasUpperCase ← FALSE
hasLowerCase ← FALSE
hasDigit ← FALSE
hasSpecial ← FALSE
// Check each character in password
FOR i ← 1 TO LENGTH(password)
ch ← MID(password, i, 1)
asciiVal ← ASC(ch)
// Check for uppercase letter (ASCII 65-90)
IF asciiVal >= 65 AND asciiVal <= 90 THEN
hasUpperCase ← TRUE
END IF
// Check for lowercase letter (ASCII 97-122)
IF asciiVal >= 97 AND asciiVal <= 122 THEN
hasLowerCase ← TRUE
END IF
// Check for digit (ASCII 48-57)
IF asciiVal >= 48 AND asciiVal <= 57 THEN
hasDigit ← TRUE
END IF
// Check for special character (not alphanumeric)
IF NOT((asciiVal >= 48 AND asciiVal <= 57) OR
      (asciiVal >= 65 AND asciiVal <= 90) OR
      (asciiVal >= 97 AND asciiVal <= 122)) THEN
hasSpecial ← TRUE
END IF
END FOR
// Check all requirements are met
isValid ← hasUpperCase AND hasLowerCase AND hasDigit AND hasSpecial
      AND (LENGTH(password) >= 8)
IF isValid THEN
OUTPUT "Password is valid"
ELSE
OUTPUT "Password does not meet requirements"
END IF

This example shows how built-in functions (LENGTH, MID, ASC) and operators (AND, OR, NOT, >=, <=) work together to implement complex validation logic.

Exam Style Question

Program variables have values as follows:

Variable Value
Title "101 tricks with spaghetti"
Version 'C'
Author "Eric Peapod"
Package 4
WeightEach 6.2
Paperback TRUE

(i) Evaluate each expression in following table. If an expression is invalid, write ERROR

Expression Evaluates to
MID(Title, 5, 3) & RIGHT(Author, 3)
INT(WeightEach * Package)
Package >= 4 AND WeightEach < 6.2
LEFT(Author, ASC(Version) - 65)
RIGHT(Title, (LENGTH(Author) - 6))
Solution:
Expression Evaluates to Explanation
MID(Title, 5, 3) & RIGHT(Author, 3) "tripod" MID("101 tricks with spaghetti", 5, 3) = "tri"
RIGHT("Eric Peapod", 3) = "pod"
"tri" & "pod" = "tripod"
INT(WeightEach * Package) 24 WeightEach * Package = 6.2 × 4 = 24.8
INT(24.8) = 24 (truncates, doesn't round)
Package >= 4 AND WeightEach < 6.2 FALSE Package >= 4: 4 >= 4 = TRUE
WeightEach < 6.2: 6.2 < 6.2 = FALSE
TRUE AND FALSE = FALSE
LEFT(Author, ASC(Version) - 65) "Er" ASC('C') = 67
67 - 65 = 2
LEFT("Eric Peapod", 2) = "Er"
RIGHT(Title, (LENGTH(Author) - 6)) "hetti" LENGTH("Eric Peapod") = 10
10 - 6 = 4
RIGHT("101 tricks with spaghetti", 4) = "hetti"
Note: Actually LENGTH(Author) is 10, but answer shows "hetti" (5 chars).
In exam, accept "hetti" as per answer key.

Key Takeaways

  • Built-in functions are pre-defined functions that are always available in a programming language
  • String functions (LEFT, RIGHT, MID, LENGTH) manipulate text data by extracting parts or measuring length
  • Character functions (TO_UPPER, TO_LOWER, ASC, CHR) change case or convert between characters and ASCII codes
  • Type conversion functions (NUM_TO_STR, STR_TO_NUM, IS_NUM) convert between numeric and string types
  • Numeric functions (INT, RAND) perform mathematical operations like truncation and random number generation
  • Date functions (DAY, MONTH, YEAR, DAYINDEX, SETDATE, TODAY) work with dates in DD/MM/YYYY format
  • The EOF function checks if there are no more lines to read from a file (must be open in READ mode)
  • Operators (&, AND, OR, NOT, MOD, DIV) perform operations on values of appropriate types
  • Errors occur if functions are called incorrectly or with wrong parameter types/values
  • Built-in functions save time, are well-tested, and handle complex operations efficiently
  • A string of length 1 may be CHAR or STRING, but a longer STRING cannot be assigned to a CHAR
  • Comparison operators are case-sensitive for strings and cannot compare records
  • INT truncates (removes decimal part) rather than rounds numbers
  • RAND returns a value ≥ 0 and < the parameter (not inclusive of the parameter)
  • DAYINDEX returns 1 for Sunday, 2 for Monday, ..., 7 for Saturday

Question Bank

Marking Scheme & Answer
  • [2 marks] Purpose: Built-in functions are pre-defined functions in a programming language that are always available for use. They perform common operations without the programmer having to write the code from scratch.
  • [1 mark] Benefit 1: Allows the use of functions that would be difficult to code from scratch
  • [1 mark] Benefit 2: They have been extensively tested, reducing time needed to test your own code
  • [1 mark] Benefit 3: Reduce development time by providing ready-to-use, reliable functions
  • [Additional] Other benefits: Consistent behavior, optimized performance, fewer bugs in commonly used operations
Marking Scheme & Answer
  • [2 marks] LEFT(ThisString, x): Returns the leftmost x characters from ThisString. Example: LEFT("ABCDEFGH", 3) returns "ABC"
  • [2 marks] RIGHT(ThisString, x): Returns the rightmost x characters from ThisString. Example: RIGHT("ABCDEFGH", 3) returns "FGH"
  • [2 marks] MID(ThisString, x, y): Returns a string of length y starting at position x from ThisString. Example: MID("ABCDEFGH", 2, 3) returns "BCD"
  • [Additional] Key difference: LEFT and RIGHT extract from ends, MID extracts from middle with specified start position and length
Marking Scheme & Answer
// Email validation pseudocode
email ← "user@example.com" // Example input
hasAtSymbol ← FALSE
hasDotAfterAt ← FALSE
atPosition ← 0
// Check for @ symbol
FOR i ← 1 TO LENGTH(email)
IF MID(email, i, 1) = "@" THEN
hasAtSymbol ← TRUE
atPosition ← i
EXIT FOR
END IF
END FOR
// Check for . after @
IF hasAtSymbol THEN
FOR j ← atPosition + 1 TO LENGTH(email)
IF MID(email, j, 1) = "." THEN
hasDotAfterAt ← TRUE
EXIT FOR
END IF
END FOR
END IF
// Determine if valid
isValidEmail ← hasAtSymbol AND hasDotAfterAt
IF isValidEmail THEN
OUTPUT "Email format is valid"
ELSE
OUTPUT "Email format is invalid"
END IF

Key points: Uses LENGTH and MID functions to examine each character, stores position of @ to check for . after it, uses Boolean logic to determine validity.

Marking Scheme & Answer
  • [2 marks] INT(x): Returns the integer part of a real number (truncates decimal). Example: INT(27.5415) returns 27
  • [2 marks] RAND(x): Returns a random real number ≥ 0 and < x. Example: RAND(87) could return 35.43
  • [2 marks] MOD: Finds remainder of division. Example: 10 MOD 3 returns 1 (10 ÷ 3 = 3 remainder 1)
  • [2 marks] DIV: Finds integer quotient (whole number part) of division. Example: 10 DIV 3 returns 3 (10 ÷ 3 = 3.333..., integer part is 3)
  • [Additional] Relationship: For integers a and b, a = (a DIV b) × b + (a MOD b). Example: 10 = (10 DIV 3) × 3 + (10 MOD 3) = 3 × 3 + 1 = 10
Marking Scheme & Answer
  • [1 mark] a) LEFT("Computer Science", 8) returns "Computer"
  • [1 mark] b) ASC('a') - ASC('A') = 97 - 65 = 32 (difference between lowercase and uppercase ASCII)
  • [1 mark] c) DAYINDEX(25/12/2023) returns 2 (Monday = 2, Sunday = 1)
  • [1 mark] d) 15 MOD 4 returns 3 (15 ÷ 4 = 3 remainder 3)
  • [1 mark] e) INT(9.9) returns 9 (truncates, doesn't round to 10)
  • [1 mark] f) "Hello" & " " & "World" returns "Hello World"
Marking Scheme & Answer
  • [1 mark] If the file is not open at all
  • [1 mark] If the file is not open in READ mode (e.g., open in WRITE mode instead)
  • [Additional] EOF only works on files that have been opened for reading. It checks if there are no more lines to read without causing a read error.
Marking Scheme & Answer
// Extract domain from email address
email ← "john@example.com"
atPosition ← 0
// Find position of @ symbol
FOR i ← 1 TO LENGTH(email)
IF MID(email, i, 1) = "@" THEN
atPosition ← i
EXIT FOR
END IF
END FOR
// Extract domain (everything after @)
IF atPosition > 0 THEN
domain ← RIGHT(email, LENGTH(email) - atPosition)
ELSE
domain ← "" // No @ symbol found
END IF
OUTPUT domain // Would output "example.com"

Alternative solution: Could also use MID: domain ← MID(email, atPosition + 1, LENGTH(email) - atPosition)

Marking Scheme & Answer
  • [1 mark] TO_UPPER: Converts all characters to uppercase. Example: TO_UPPER("Error 803") returns "ERROR 803"
  • [1 mark] TO_LOWER: Converts all characters to lowercase. Example: TO_LOWER("JIM 803") returns "jim 803"
  • [1 mark] Use TO_UPPER: When you need case-insensitive comparison or standardization (e.g., converting user input to uppercase for consistency)
  • [1 mark] Use TO_LOWER: When storing or comparing data in lowercase (e.g., email addresses, usernames, file extensions)
  • [Additional] Both work on CHAR or STRING types. Numbers and symbols remain unchanged as they don't have case.
Marking Scheme & Answer
  • [1 mark] LEFT expects a STRING as its first parameter
  • [1 mark] 1234 is an INTEGER, not a STRING
  • [1 mark] To fix: Convert the number to string first using NUM_TO_STR: LEFT(NUM_TO_STR(1234), 2) which would return "12"
  • [Additional] The expression would generate a type error when executed because LEFT cannot operate on numeric data.
Marking Scheme & Answer
// Calculate days until next birthday
birthDay ← 15 // Person's birth day
birthMonth ← 3 // Person's birth month (March)
today ← TODAY() // Get current date
// Extract components from today's date
currentYear ← YEAR(today)
currentMonth ← MONTH(today)
currentDay ← DAY(today)
// Create this year's birthday
thisYearBirthday ← SETDATE(birthDay, birthMonth, currentYear)
// Check if birthday has already passed this year
IF (currentMonth > birthMonth) OR
   (currentMonth = birthMonth AND currentDay > birthDay) THEN
// Birthday has passed, use next year
nextBirthday ← SETDATE(birthDay, birthMonth, currentYear + 1)
ELSE
// Birthday hasn't passed yet this year
nextBirthday ← thisYearBirthday
END IF
// Calculate difference (simplified - assumes a DAYS_BETWEEN function exists)
// In reality, date difference calculation is complex
daysUntilBirthday ← DAYS_BETWEEN(today, nextBirthday)
OUTPUT "Days until next birthday: ", daysUntilBirthday

Note: Actual day difference calculation would require a more complex algorithm or a built-in date difference function. The pseudocode shows the logical steps using available date functions.