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
Returns the leftmost x characters from ThisString.
Example:
LEFT("ABCDEFGH", 3) returns "ABC"
RIGHT Function
Returns the rightmost x characters from ThisString.
Example:
RIGHT("ABCDEFGH", 3) returns "FGH"
MID Function
Returns a string of length y starting at position x from ThisString.
Example:
MID("ABCDEFGH", 2, 3) returns "BCD"
LENGTH Function
Returns the integer value representing the length of ThisString.
Example:
LENGTH("Happy Days") returns 10
Case Conversion Functions
TO_UPPER Function
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
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.
Type Conversion Functions
NUM_TO_STR Function
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
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
Returns TRUE if ThisString represents a valid numeric value. <datatype> may be CHAR or STRING.
Example:
IS_NUM("-12.36") returns TRUE
ASCII Functions
Returns an integer value (the ASCII value) of character ThisChar.
Example:
ASC('A') returns 65, ASC('B') returns 66, etc.
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:
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:
- What does LEFT("Programming", 3) return?
- What does RIGHT("Programming", 4) return?
- What does MID("Programming", 4, 5) return?
- What does LENGTH("Programming") return?
- What does TO_UPPER("Hello World!") return?
- What does ASC('m') return? (ASCII of 'm' is 109)
- What does CHR(72) return? (72 is ASCII for 'H')
Solution:
- LEFT("Programming", 3): Returns "Pro"
- RIGHT("Programming", 4): Returns "ming"
- MID("Programming", 4, 5): Returns "gramm" (starts at position 4, takes 5 characters)
- LENGTH("Programming"): Returns 11
- TO_UPPER("Hello World!"): Returns "HELLO WORLD!"
- ASC('m'): Returns 109 (ASCII value of lowercase 'm')
- CHR(72): Returns 'H' (character with ASCII value 72)
Check Your Understanding: String & Character Functions
1. What does the MID function do and what are its parameters? [2 marks]
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"
2. When would IS_NUM return FALSE? [2 marks]
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
3. What is the difference between ASC and CHR functions? [2 marks]
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
4. Why would TO_UPPER("Error 803") return "ERROR 803" and not "ERROR 803"? [1 mark]
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.
5. What error would occur if you tried LEFT(123, 2)? [2 marks]
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"
6. What is the result of RIGHT("Hello" & " " & "World", 5)? [2 marks]
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
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
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
RAND Function
Real-Life Example: Shopping Cart Calculations
In an e-commerce system, numeric functions are used to calculate prices, taxes, and discounts:
Built-in numeric functions simplify common calculations in real-world applications.
Activity 2: Numeric Function Practice
Evaluate the following expressions:
- What does INT(15.999) return?
- What does INT(-3.7) return?
- If RAND(50) returns a value, what is the range of possible values?
- What does NUM_TO_STR(INT(12.75)) return?
- What does STR_TO_NUM("100") + 25 return?
- Write an expression to get a random integer between 0 and 99 inclusive.
Solution:
- INT(15.999): Returns 15 (truncates, doesn't round)
- INT(-3.7): Returns -3 (truncates toward zero)
- RAND(50) range: Returns a real number ≥ 0 and < 50 (0.0 to 49.999...)
- NUM_TO_STR(INT(12.75)): INT(12.75) = 12, then NUM_TO_STR(12) = "12"
- STR_TO_NUM("100") + 25: STR_TO_NUM("100") = 100, then 100 + 25 = 125
- 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
Returns the current day number from ThisDate.
Example:
DAY(04/10/2003) returns 4
MONTH Function
Returns the current month number from ThisDate.
Example:
MONTH(04/10/2003) returns 10
YEAR Function
Returns the current year number from ThisDate.
Example:
YEAR(04/10/2003) returns 2003
Special Date Functions
DAYINDEX Function
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
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
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.
Real-Life Example: Age Calculator
Date functions are commonly used to calculate ages, determine due dates, and schedule events:
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
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:
Real-Life Example: Reading Student Records
EOF is essential when reading data from files, such as student records or configuration files:
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.
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:
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
1. Explain the purpose of built-in functions and give three benefits of using them. [5 marks]
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
2. What are the three string extraction functions and how do they differ? [6 marks]
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
3. Write pseudocode to validate a user's email address format. Check it contains "@" and at least one "." after the "@". [6 marks]
Marking Scheme & Answer
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.
4. Explain the difference between INT, RAND, MOD, and DIV with examples. [8 marks]
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
5. What will the following expressions evaluate to? [6 marks]
a) LEFT("Computer Science", 8)
b) ASC('a') - ASC('A')
c) DAYINDEX(25/12/2023) (25th Dec 2023 is a Monday)
d) 15 MOD 4
e) INT(9.9)
f) "Hello" & " " & "World"
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"
6. When would the EOF function generate an error? [2 marks]
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.
7. Write pseudocode to extract the domain name from an email address. [5 marks]
Example: From "john@example.com", extract "example.com"
Marking Scheme & Answer
Alternative solution: Could also use MID: domain ← MID(email, atPosition + 1, LENGTH(email) - atPosition)
8. Explain the difference between TO_UPPER and TO_LOWER functions. When would you use each? [4 marks]
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.
9. What is wrong with this expression: LEFT(1234, 2)? How would you fix it? [3 marks]
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.
10. Write pseudocode to calculate how many days until a person's next birthday. [7 marks]
Assume you have functions: TODAY(), SETDATE(), DAY(), MONTH(), YEAR()
Marking Scheme & Answer
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.