Topic 8 · Programming
Operators, library routines, and strings
Arithmetic operators, MOD and DIV, ROUND and RANDOM, and string handling with LENGTH, SUBSTRING, UCASE, and LCASE.
Arithmetic operators
| Operator | Meaning | Example | Result |
|---|---|---|---|
+ | add | 7 + 2 | 9 |
- | subtract | 7 - 2 | 5 |
* | multiply | 7 * 2 | 14 |
/ | divide | 7 / 2 | 3.5 |
^ | raise to the power | 7 ^ 2 | 49 |
MOD(7, 2) | remainder after division | MOD(7, 2) | 1 |
DIV(7, 2) | whole number division | DIV(7, 2) | 3 |
MOD and DIV
DIV gives how many whole times one number goes into another, and MOD gives what is left over. Together they split a number apart.
A common use: a number is even when MOD(Number, 2) = 0. Another: turning minutes into hours and minutes.
DECLARE TotalMinutes : INTEGER
INPUT TotalMinutes
OUTPUT DIV(TotalMinutes, 60), " hours and ", MOD(TotalMinutes, 60), " minutes"ROUND and RANDOM
ROUND(Value, Places) rounds a real number to a number of decimal places. RANDOM() returns a random number from 0 to 1, which you can scale up.
DECLARE Price : REAL
Price <- 19.987
OUTPUT ROUND(Price, 2)
OUTPUT "Random whole number from 0 to 100: ", ROUND(RANDOM() * 100, 0)Strings are numbered characters
A string is a sequence of characters. In Cambridge pseudocode the first character is at position 1. Click a character to see its position.
| 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 |
|---|---|---|---|---|---|---|---|
String handling
| Routine | Returns | Example with "Computer" | Result |
|---|---|---|---|
LENGTH(S) | The number of characters | LENGTH(Word) | 8 |
SUBSTRING(S, Start, Length) | Part of the string | SUBSTRING(Word, 4, 3) | "put" |
UCASE(S) | The string in upper case | UCASE(Word) | "COMPUTER" |
LCASE(S) | The string in lower case | LCASE(Word) | "computer" |
DECLARE FirstName : STRING
DECLARE LastName : STRING
DECLARE Username : STRING
INPUT FirstName
INPUT LastName
Username <- LCASE(SUBSTRING(FirstName, 1, 1)) & LCASE(LastName)
OUTPUT "Your username is ", Username
OUTPUT "It has ", LENGTH(Username), " characters"Exam tip. & joins (concatenates) two strings: "Ada" & "Lovelace" gives "AdaLovelace".
Key terms
- MOD
- Gives the remainder after integer division.
- DIV
- Gives the whole-number result of a division.
- Library routine
- A ready-made subroutine provided by the language, such as ROUND or RANDOM.
- Concatenation
- Joining strings together.
Check yourself
What are MOD(23, 5) and DIV(23, 5)?Show answer
MOD = 3, DIV = 4 (23 = 4 × 5 + 3).
What is SUBSTRING("Keyboard", 4, 5)?Show answer
"board".
Write a condition that is TRUE when N is a multiple of 3.Show answer
MOD(N, 3) = 0.