CSUK Writing Algorithms Separate GUIDE
CSUK Writing Algorithms Separate GUIDE
CSUK
Writing
Algorithms
Guide
KILGARRIFF Page 1
Guide to Writing Algorithms Computer Science UK
CONTENTS
1. Outputs, Inputs & Variables 3
8. String Manipulation 3
9. Subroutines 3
Page 2 KILGARRIFF
Computer Science UK Guide to Writing Algorithms
Quick Reference
Construct Setup Example
Variables
Assignment = x = 10
name = “Sam”
Constants const const pi = 3.14
Global Variables global global surname = Smith
Input/Output
Input input(…) name = input(“Enter your name”)
Output print(…) print(“Your name is ” + name)
Outputs
An output is where a program will display some information on the screen for the user. When writing algorithms, we
can demonstrate an output using a print() statement. The data that we enter inside the brackets will be outputted to
the screen.
For example, if we wished to write an algorithm for a program that outputs the statement “Hello World” to the screen,
we could write:
print(“Hello World”)
What is a variable?
A variable is a named location in memory, which can store data whilst the program is running. In other words, it’s a
word which represents a place that can store a single item of data that is assigned to it.
So, if we wished to write an algorithm for a program that asks the user for their name, stores the inputted name and
outputs both a ‘hardcoded’ message and the contents of the variable, we could write:
Write an algorithm which will ask the user to enter their name, and then respond with the
statement: ”The name *name* is a beautiful name”.
KILGARRIFF Page 3
Guide to Writing Algorithms Computer Science UK
Let’s begin by breaking down the question to understand what it wants us to do.
Ultimately, there are two parts to this algorithm question:
1. User to enter name
2. Sentence (including inputted name) to be outputted.
Point 1, requires us to write an input statement. This can be achieved by the following:
This line represents the displaying of the text ‘Enter your name’ on the screen and waiting for a user’s response.
However, because point 2 requires the inputted name to be outputted, we need to have a way to store the input, so that
it can be later outputted. We can demonstrate this by assigning a variable to the input() statement. In the example
below, we have assigned a variable called name to the input() statement.
Now let’s focus on point 2. This part of the question requires that we output some text (which has the data type known
as ‘string’) along with the contents of a variable. The print() statement can allow us to output, and the + operator
can allow us to join together strings and variables. We must remember to write strings with quotes and variables
without. Here is an example:
Question 1 Algorithm
Write an algorithm that asks the user to enter Favcolour=INPUT (“Please enter your fav colour”)
their favourite colour, then outputs the Print (“Your fav colour is “, favcolour)
sentence “Your favourite colour is *colour*”
(where *colour* is the inputted string).
Question 2 Algorithm
Write an algorithm that asks the user to enter Firstname=INPUT(“Please enter your first name:”)
their first name, middle name and surname, Midname=input(“Please enter your middle name:”)
stores each input in separate variables, then Surname=INPUT(“Please enter your surname:”)
outputs the user’s full name.
PRINT(“Your full name is “firstname,middlename,surname”)
Question 3 Algorithm
Write an algorithm that asks the user to enter House=INPUT(“Please enter your house name or number:”)
their house name/number, street name, town Street= INPUT (“Please enter your street name:”)
and postcode, then outputs the user’s full Town=INPUT(“Please enter your town:”)
address back to the screen. Postcode=INPUT(“Please enter your postcode:”)
PRINT( “House,Street,Town,Postcode”)
KILGARRIFF Page 5
Guide to Writing Algorithms Computer Science UK
Quick Reference
Construct Setup Example
Casting str() str(10)
int() int(“10”)
float() float(“3.14”)
real() real(“3.14”)
bool() bool(“False”)
Random number random(_,_) number = random(1 , 8)
number = random(1.0 , 12.0)
Casting
Before we go any further, we need to learn about casting.
So that data can be processed correctly, programs need to know what type of data they are working with. For example,
strings (which can be a long collection of keyboard characters) are stored and processed differently in computer
systems, compared to integers (whole number). As such, we need to let our programs know what type of data is to be
held in variables, so that their data can be handled correctly. This is done by casting data of one type to another. And
when writing algorithms, we can demonstrate this using an int() function.
Random Numbers
Random numbers can often be generated in programming languages using a built-in function. When writing
algorithms we can demonstrate creating random numbers using the following pseudocode random(x,y) where x and
y can be two integers (or decimal numbers) between which the random number is to be generated.
For example, the following would produce and output a variable, which could contain either the number 1, 2 or 3,
each time the program is run:
answer = random(1,3)
print(answer)
Write an algorithm which will ask the user to enter two whole numbers, add them together,
then output the result.
Page 6 KILGARRIFF
Computer Science UK Guide to Writing Algorithms
As before, let’s begin by breaking this question down into its component parts. A quick analysis will find that there
are three parts to this algorithm question:
1. User to enter 2 numbers
2. Program to add the numbers
3. Program to output the result
Point 1, requires us to write 2 input statements. And as we learnt in the last section, we need to ensure that each input
is stored and so we must assign each statement with a variable. This can be achieved by the following:
Because we need our program to work with integers, we will need to cast the data stored in number1 and number2, to
integers. This can be achieved by the following:
What’s actually happening here is best understood by reading the statement from right to left:
Now that we have the correct type of data in our variables, we are ready to complete point 2 of the question and add
them together. We can achieve this by using the ‘+’ operator (like we would in maths), and assigning the answer to a
variable. Remember though that in programming we assign values from right to left and so our calculation would be
presented as:
Finally, we complete point 3 by using a print() statement to output the contents of the variable containing the
answer.
print(answer)
Page 8 KILGARRIFF
Computer Science UK Guide to Writing Algorithms
Practice Questions - Casting, Random Numbers and Maths
Worked Example
Write an algorithm that will find the volume of a box by asking the user to enter the length, width and depth of the
box, multiplying the dimensions and outputting the volume.
Question 1 Algorithm
Write an algorithm that requests a number num = Imput(“Please enter a number.”)
from the user and outputs its square.
square = num*num
Question 2 Algorithm
Write an algorithm that will ask the user to weeklyPocketMoney = INPUT(“Please enter your
enter their weekly pocket money, their weekly weeklypocketmoney:”)
spend on their phone, their weekly spend on weeklyPhoneSpend= INPUT(“Please enter your weekly phone
snacks and then outputs the money that they spend:”)
have left. weeklySnackSnackSpend= INPUT(“Please enter your weekly
snack spend:”)
moneyLeft = weeklyPocketMoney-weeklyPhoneSpend-
weeklySnackSpend
PRINT(“Money left is”, moneyleft)
Question 3 Algorithm
Write an algorithm that will ask the user for import random
two numbers and will then output a random
number within the range of the two inputted num1= INPUT ("Please enter a number”))
values. except ValueError:
print("Invalid input. Please enter a valid number.")
Quick Reference
Construct Setup Example
Selection
if-then-else if … then if answer == "a" then
elseif … then print("Apple")
else elseif answer == "b" then
endif print("Banana")
else
print("Incorrect input")
endif
When writing if-then-else statements in the pseudocode above, notice how the keyword then finishes each if
and elseif statement (the condition), notice how there is no keyword then after the else statement and notice how
the if-then-else statement completes with keyword endif. By writing these key words we can ensure that our
algorithms are well structured and easy to follow.
Page 10 KILGARRIFF
Computer Science UK Guide to Writing Algorithms
Algorithm Writing Guidance – if-then-else Statements
Consider the following algorithm question:
Write an algorithm which will ask the user to enter two whole numbers, work out which one is
bigger and output a message to state which number was the biggest (or a message stating
that the inputted numbers where the same).
As before, let’s begin by breaking this question down into its component parts. A quick analysis will find that there
are arguably 3 parts to this algorithm question:
1. User to enter 2 numbers
2. Program to see if first number is bigger, smaller or the same as the second number
3. Program to output 1 of 3 messages depending on the above.
Point 1, requires us to write 2 input statements. And as we learnt in the last section, we need to ensure that each input
is stored and so we must assign each statement with a variable. This can be achieved by the following:
Because we need our program to work with integers, we will need to cast the data stored in number1 and number2, to
integers. This can be achieved by the following:
Point 2 requires that the program makes a decision based on the two numbers entered, so we need an if-then-else
statement to compare the two inputted values, working out if the first number is bigger, smaller or the same as the
second number.
Point 3 requires that one of three different messages are displayed to the user, depending on the conditions being
checked.
Both points can be achieved with the following:
Page 12 KILGARRIFF
Computer Science UK Guide to Writing Algorithms
Practice Questions - if-then-else Statements
Worked Example
Write an algorithm that will ask the user to enter a number and output a message which states whether the entered
number was greater than zero, less than zero or equal to zero.
Variable assigned to input statement to Input statements displays a message to user asking them to
store user’s input enter a number
The data inside number is of
The casted data (now of type string data type when inputted
integer) is reassigned to the and so the int() function casts
variable ‘number’. number = input(“Enter a number: ”) value to an integer type
number = int(number)
An if-then-else statement is used to first
check if inputted number is greater if number > 0 then Message to be outputted if number is
than zero… print(str(number) + “ is greater than zero”) greater than zero…
…then check if inputted number is less elseif number < 0 then …message to be outputted if number is
than zero… print(str(number) + “ is less than zero”) less than zero…
Question 1 Algorithm
Write an algorithm that will ask the user to age = INT(INPUT("Please enter your age: "))
enter their age. If the entered age is less than if age < 67:
67, the message “You cannot retire yet” is PRINT("You cannot retire yet.")
outputted, else the message “Happy ELSE:
retirement!” is outputted. PRINT("Happy retirement!")
Question 2 Algorithm
Write an algorithm that will ask the user if they user_response = INPUT("Are you feeling okay? (yes/no):
are feeling ok. If the user enters ‘yes’, the ").lower()
message ‘glad to hear it’ is outputted. If the
user enters ‘no’, the message ‘sorry to hear IF user_response == 'yes':
that’ is outputted. If neither ‘yes’ or ‘no’ is PRINT("Glad to hear it!")
inputted, an appropriate error message is ELIF user_response == 'no':
outputted. PRINT("Sorry to hear that.")
ELSE:
PRINT("Invalid response. Please enter 'yes' or 'no'.")
Question 3 Algorithm
Write an algorithm that asks the user to enter a PRINT("Enter a number:")
number. If the number is even, it will output a number = INT(INPUT()) # Read input as an integer
message stating this fact. Else it will output a remainder = number % 2
message stating that the inputted number is IF remainder == 0:
odd. PRINT("The entered number is even.")
Tip: x MOD 2 will divide x by 2, working out only ELSE:
the remainder of the division. PRINT("The entered number is odd.")
KILGARRIFF Page
13 13
Guide to Writing Algorithms Computer Science UK
Quick Reference
Construct Setup Example
Selection
CASE SELECT or switch … : switch month:
SWITCH case … : case "Jan":
case … : print("January")
default: case "Feb":
endswitch print("February")
default:
print("Not a valid month")
endswitch
As we learnt in the last section, ‘selection’ is a programming construct which allows a program to execute one line of
code, from multiple possible lines, depending on a condition. We learnt how this can be achieved using an ‘if-then-
else’ statement. However, there is also another way of achieving the same.
A case select/switch statement works by in a very similar way in that they will check the condition of a variable. The
major difference is the structure of the construct.
switch day:
case "Sat":
print("Saturday")
case "Sun":
print("Sunday")
default:
print("Weekday")
endswitch
In the example case select/switch statement above, the contents of the variable day is first checked. If the variable
contains the string ‘Sat’, a print() statement will be executed, outputting the string ‘Saturday’. If the variable
instead contains the string ‘Sun’, a print() statement will be executed, outputting the string ‘Sunday’. And if the
variable doesn’t contain either ‘Sat’ or ‘Sun’, it will default to a print() statement which will output the string
‘Weekday’.
Write an algorithm, using a case select / switch statement, which will ask the user to enter a
number
Page 14from 1 to 3, and output one of three facts, depending on the number entered. KILGARRIFF
Computer Science UK Guide to Writing Algorithms
As before, let’s begin by breaking this question down into its component parts. A quick analysis will find that there
are arguably 3 parts to this algorithm question:
1) User to enter a number, input cast to integer and stored in variable
2) Case select / switch construct to be created, to output a fact for each number
3) Default case to catch erroneous input (number not in range of 1-3)
We can demonstrate the logic for point one by writing an input() statement, assigning the input to a variable and
casting the value of that variable to an integer type.
For point two, we can demonstrate the logic of the case select / switch construct like so:
switch number:
case 1:
print("Crocodiles cannot stick out their tongue.")
case 2:
print("A shrimp's heart is in its head.")
case 3:
print("It’s impossible to touch your ear with your elbow.")
endswitch
For point three, we need to add a default case, so that if the previous cases are not selected, there is a message to let
the user know why the program didn’t respond with a fact.
switch number:
case 1:
print("Crocodiles cannot stick out their tongue.")
case 2:
print("A shrimp's heart is in its head.")
case 3:
print("It’s impossible to touch your ear with your elbow.")
default:
print("You didn’t enter 1, 2 or 3")
endswitch
Question 1 Algorithm
Write an algorithm, using a case select / switch
statement, that will ask the user if they like
programming. The program will output the
message “Great news!” if they enter ‘yes’, and
output the message “You probably need more
practice then!”, if they enter ‘no’. A default
case will execute if neither ‘yes’ or ‘no’ is
entered.
Question 2 Algorithm
Write an algorithm, using a case select / switch
statement, that will generate a random number
from 1-3, and output “Yes” (if 1 is generated),
“No” (if 2 is generated) or “Maybe” (if 3 is
generated). The program’s aim is to mimic a
Magic-8-Ball, but with fewer statements.
Question 3 Algorithm
Write an algorithm, using a case select / switch
statement, that will ask the user to enter a
number and will respond by stating if the
inputted number was even or odd.
Quick Reference
Construct Setup Example
FOR loop for … to … for i=0 to 19
(Count-controlled) next … print("I’m Iterating")
next i
Page 16 KILGARRIFF
Computer Science UK Guide to Writing Algorithms
for … to … step … “I’m Iterating” will be outputted 20 times, i.e. 0-19 inclusive.
next …
for i=2 to 20 step 2
print(i)
next i
We begin a for loop by assigning a stepper variable a starting and ending number, so that the program can count the
correct number of times it is to repeatedly execute lines of code. Then indented underneath, we write our code which
is to be executed inside the loop. Then we complete the construct with a next statement, to tell the program to
increment the count by 1. An example of this can be seen below:
Algorithm Output
This is loop number 0
This is loop number 1
for i=0 to 10 This is loop number 2
This is loop number 3
This is loop number 4
print(“This is loop number ” + i) This is loop number 5
This is loop number 6
next i This is loop number 7
This is loop number 8
This is loop number 9
This is loop number 10
KILGARRIFF Page
17 17
Guide to Writing Algorithms Computer Science UK
If we wish to increment (or decrement) by a different number after each loop, we can add in a step value.
For example, the following would allow the program to count in twos:
Algorithm Output
This is loop number 0
This is loop number 2
for i=0 to 10 step 2 This is loop number 4
This is loop number 6
This is loop number 8
print(“This is loop number ” + i) This is loop number 10
next i
Algorithm Output
This is loop number 10
This is loop number 9
This is loop number 8
for i=10 to 0 step -1 This is loop number 7
This is loop number 6
print(“This is loop number ” + i) This is loop number 5
This is loop number 4
next i This is loop number 3
This is loop number 2
This is loop number 1
This is loop number 0
Page 18 KILGARRIFF
Computer Science UK Guide to Writing Algorithms
Algorithm Writing Guidance – FOR Loops
Consider the following algorithm question:
Write an algorithm, using a FOR loop, which will display a countdown from 10 to 1, then
complete with the output “Blast Off!”.
As before, let’s begin by breaking this question down into its component parts. A quick analysis will find that there
are arguably 5 things to consider in this algorithm:
1. A for loop will be required in order to iterate for a set number of times
2. The stepper variable will need to decrement by 1 on each loop
3. The stepper variable will need to start at value 10 and stop at 1
4. A print statement will be required in each loop, outputting the stepper variable value
5. An additional print statement will be required after the loop to output the string “Blast Off!”
Finally, point 5 requires that a final print statement to output “Blast Off!”, once the loop has ended. Here is a final
solution to the question:
KILGARRIFF Page
19 19
Guide to Writing Algorithms Computer Science UK
Write an algorithm, using a for loop, that will output the 10 times table.
A for loop is started with the stepper variable During each iteration, a print statement outputs:
starting at 1, counting to 10. 1. The value of the stepper variable (casted as a string), joined with…
2. The string “multiplied by 10 is ”, joined with…
3. The result of the stepper variable multiplied by 10, cast as a string.
for i=1 to 10
Stepper variable is then
incremented by 1. print(str(i) + “multiplied by 10 is ” + str(i*10))
next i
The reason for str(i) and str(i*10) is so that we can use the + operator in the print statement to concatenate the values to the sentence. If we didn’t, the program would try to add
numbers to strings and this would cause an error. So, we must cast the integer values to strings so that the + operator can simply join the strings together.
Question 1 Algorithm
Write an algorithm with a for loop that will
output the numbers from 1 to 100 inclusive.
Question 2 Algorithm
Write an algorithm with a for loop that will
output only the even numbers from 1-100
inclusive.
Question 3 Algorithm
Write an algorithm with a for loop that will
ask the user which multiplications table they
want to be displayed (by requesting that an
integer is entered) and outputs the requested
multiplications table in the form of:
5x1=5
5 x 2 = 10 …etc (if 5 were the inputted value).
Page 20 KILGARRIFF
Computer Science UK Guide to Writing Algorithms
Construct Setup Example
WHILE loop while … while answer != "Yes"
(Condition-controlled) answer = input("Please enter ‘Yes’")
endwhile endwhile
We begin a while loop by writing a condition statement. If the statement is TRUE, the loop will be entered and its
contents executed.
x = 10
while x == 10
print(“Loop in progress”)
endwhile
In the example above, the variable x has been assigned the value 10. Underneath, we have a while loop which looks
to evaluate whether or not x is equal to 10. Clearly this is true and so the loop is entered and the string ‘Loop in
progress’ is outputted. We then go back to the start of the loop and check/evaluate the condition again. As x is still 10,
the loop is entered and the string ‘Loop in progress’ is outputted again. This process repeats and because, in this
example, the value of x will not change, the loop will continue to iterate.
Write an algorithm, using a WHILE loop, which will display a countdown from 10 to 1, then
complete with the output “Blast Off!”.
As before, let’s begin by breaking this question down into its component parts. A quick analysis will find that there
are arguably 4 things to consider in this algorithm:
KILGARRIFF Page
21 21
Guide to Writing Algorithms Computer Science UK
1. A while loop will be required in order to iterate, with a condition statement that can allow the loop to stop
after 10 iterations…
2. …the variable in the condition statement will need to change so that the loop stops after 10 iterations
3. A print statement will be required in each loop, outputting the countdown
4. An additional print statement will be required after the loop to output the string “Blast Off!”
Points 1 and 2, need a little bit of thought. Ultimately, we need this loop to only iterate 10 times and so we need to
ensure that we can alter the variable which is evaluated inside the condition statement, so that after 10 loops, the
condition is no longer true.
x = 10
while x != 0
x = x - 1
endwhile
In the code example above, we have achieved this aim. Variable x is initialised with the value 10. Next, the while
loop checks to see if x doesn’t equal 0, which it doesn’t, and so the loop is entered. Inside the loop, we reduce the
value contained inside x by 1. We return to the start of the loop and again we check to see if x doesn’t equal 0, which
it still doesn’t (i.e. 9 doesn’t equal 0). The loop is entered again and x is reduced by 1. This process continues until x
becomes 0, at which time, the loop is forced to end.
To finish this algorithm, we just need to add in our two print statements.
Point 3 requires that we output the countdown and so this print statement needs to be inside the loop, outputting the
value of x each time.
Point 4 requires that we output the statement ‘Blast Off!’ once the countdown has ended and so this print statement
needs to be after the loop.
x = 10
while x != 0
print(x)
x = x - 1
endwhile
print(“Blast Off!”)
Page 22 KILGARRIFF
Computer Science UK Guide to Writing Algorithms
Therefore, all the while x doesn’t while x != 11 Then, the value of counter variable x is reduced by 1.
contain 11, the loop will be
entered.
print(str(x) + “multiplied by 10 is ” + str(x*10))
x = x + 1
endwhile
The reason for str(x) and str(x*10) is so that we can use the + operator in the print statement to concatenate the values to the sentence. If we didn’t, the program would try to add
KILGARRIFF
numbers to strings and this would cause an error. So, we must cast the integer values to strings so that the + operator can simply join the strings together. Page
23 23
Guide to Writing Algorithms Computer Science UK
Question 1 Algorithm
Write an algorithm with a while loop that will
repeatedly ask the user to enter a password,
and will only stop when the password
pa55w0rd is entered.
Question 2 Algorithm
Write an algorithm with a while loop that will
continually ask the user to enter a number and
will only stop when they enter the number 10.
Question 3 Algorithm
Write an algorithm with a while loop that will
repeatedly ask the user to enter a number and
will only stop when the number they enter is
even.
Quick Reference
Construct Setup Example
DO UNTIL loop do … do
(Condition-controlled) answer = input("Yes")
until … until answer == "Yes"
Page 24 KILGARRIFF
Computer Science UK Guide to Writing Algorithms
Before we look at how its set up, it is important to recognise a major difference between this condition-controlled loop
and the while loop.
As we saw in the last chapter, the while loop will begin by checking a conditional statement and only if the statement
is true, will the loop be entered. Therefore, a while loop may never be entered.
A do until loop has its conditional statement at the end of the loop. Therefore, this type of loop will always execute
at least once, before checking the conditional statement to see if it should loop again.
We begin a do until loop by writing the key word do. Then indented underneath, we write the code of our loop.
Then at the end of this code structure, we write a condition statement after the key word until. If the statement is
false, the loop will be repeated, otherwise it will stop.
x = 10
do
print(“Loop in progress”)
until x == 10
In the example above, the variable x has been assigned the value 10. Underneath, we have a DO UNTIL loop which
will be entered and the string ‘Loop in progress’ will be outputted. Then the loop will look to evaluate whether or not
x is equal to 10. Clearly this is true and so the loop will stop.
Write an algorithm, using a DO UNTIL loop, which will display a countdown from 10 to 1, then
complete with the output “Blast Off!”.
As before, let’s begin by breaking this question down into its component parts. A quick analysis will find that there
are arguably 4 things to consider in this algorithm:
1. A do until loop will be required in order to iterate, with a condition statement that can allow the loop to
stop after 10 iterations…
2. …the variable in the condition statement will need to change so that the loop stops after 10 iterations
3. A print statement will be required in each loop, outputting the countdown
4. An additional print statement will be required after the loop to output the string “Blast Off!”
Points 1 and 2, need a little bit of thought. Ultimately, we need this loop to only iterate 10 times and so we need to
ensure that we can alter the variable which is evaluated inside the condition statement, so that after 10 loops, the
condition is no longer true.
x = 10
KILGARRIFF Page
25 25
do
x = x – 1
In the code example above, we have achieved this aim. Variable x is initialised with the value 10. Next, a do until
loop is entered, where we reduce the value contained inside x by 1. Then the loop checks to see if x is equal to 0.
After the first iteration, x will of course equal 9, and so the condition statement will evaluate to false, forcing the loop
to repeat. This process will continue until x does becomes 0, at which time, the loop will end.
To finish this algorithm, we just need to add in our two print statements.
Point 3 requires that we output the countdown and so this print statement needs to be inside the loop, outputting the
value of x each time.
Point 4 requires that we output the statement ‘Blast Off!’ once the countdown has ended and so this print statement
needs to be after the loop.
x = 10
do
print(x)
x = x - 1
until x == 0
print(“Blast Off!”)
Page 26 KILGARRIFF
Computer Science UK Guide to Writing Algorithms
A do until loop is written, which do Then, the value of counter variable x is reduced by 1.
completes with the condition until
x == 10. print(str(x) + “multiplied by 10 is ” + str(x*10))
Therefore, until x equals 10, the
loop will repeat. x = x + 1
until x == 11
The reason for str(x) and str(x*10) is so that we can use the + operator in the print statement to concatenate the values to the sentence. If we didn’t, the program would try to add
numbers to strings and this would cause an error. So, we must cast the integer values to strings so that the + operator can simply join the strings together.
Question 1 Algorithm
KILGARRIFF Page
27 27
Guide to Writing Algorithms Computer Science UK
Write an algorithm with a do-until loop that
will repeatedly ask the user to enter a number
and will only stop when the user enters the
integer 5.
Question 2 Algorithm
Write an algorithm with a do-until loop that
will output all numbers from 1 to 100, and then
stop.
Question 3 Algorithm
Write an algorithm with a do-until loop that
will repeatedly ask the user to enter a
password, and will only stop when the
password pa55w0rd is entered.
8 String Manipulation
Quick Reference
Construct Setup Example
String Length .length resources = "ComputerScienceUK"
resources.length gives the value 17
Page 28 KILGARRIFF
Computer Science UK Guide to Writing Algorithms
ASCII Conversion ASC(…) ASC(B) returns 66 (numerical)
CHR(…) CHR(98) returns ‘b’ (char)
String Manipulation
Most programming languages have many useful built-in string manipulation methods, which help programmers carry
out a number of operations on strings. For example, there is a built-in method to convert a string to uppercase, and
another to count how many characters a string consists of.
Let’s take a closer look at some.
String Length
Imagine we have a variable that is assigned the string ‘ComputerScienceUK’.
If we used the .length method on the variable, it will find the number of characters in the string.
var = “ComputerScienceUK”
numberOfCharacters = var.length 18
print(numberOfCharacters)
Substrings
A substring is a subsection of a string. There are several methods that can allow us to access subsections of strings.
If we used the .substring(2,4) method on a variable, it will return 4 characters in a string, starting from the
character at index 2. Remember, the index of the first character is zero!
var = “ComputerScienceUK”
subStr = var.substring(2,4) mput
print(subStr)
If we used the .left(4) method on a variable, it will return 4 characters in a string starting from the left-most
character.
var = “ComputerScienceUK”
subStr = var.left(4) Comp
print(subStr)
If we used the .right(4) method on a variable, it will return 4 characters in a string starting from the right-most
character.
var = “ComputerScienceUK”
subStr = var.right(4)
print(subStr)
KILGARRIFF Page
29 29
Guide to Writing Algorithms Computer Science UK
ceUK
Concatenation
Concatenation is the joining together of strings and we use the ‘+’ operator to achieve this.
For example, we can use the + operator to join the string assigned to a variable and another non-assigned string, to
form a new string like so…
var = “ComputerScience”
newStr = var + “UK” ComputerScienceUK
print(newStr)
In order to use this ‘+’ operator, we must remember that if a variable contains a non-string type, for example an
integer, the variable must be cast to a string type in order for the concatenation to work. The reason for this is that if
we don’t, the program will view the ‘+’ operator as an addition and will be unable to ‘add’ a number to a string,
resulting in an error.
var = 123
newStr = str(var) + “ComputerScienceUK” 123ComputerScienceUK
print(newStr)
Uppercase
Sometimes we may wish to quickly convert all characters of a string to uppercase. Thankfully, there is a method for
this process.
For example, we can use the .upper method to achieve this.
var = “ComputerScienceUK”
newStr = var.upper COMPUTERSCIENCEUK
print(newStr)
Lowercase
Similarly, we may wish to quickly convert all characters of a string to lowercase and there is a method for this process
too.
For example, we can use the .lower method to achieve this.
var = “ComputerScienceUK”
computerscienceuk
newStr = var.lower
print(newStr)
Page 30 KILGARRIFF
Computer Science UK Guide to Writing Algorithms
ASCII Conversion
Every character that we might find on a keyboard has its own, unique character code, which is simply a number. For
example, the character ‘A’ has the character code 65 and its lowercase equivalent ‘a’ has the character code 97.
There are two inbuilt methods which allow us to find out:
1. a given character’s code (ASC(A))
2. the character of a given code (CHR(65))
ASC()
If we wanted to find the character code of the character ‘b’, we could carry out the following:
chrCode = ASC(b)
98
print(chrCode)
CHR()
If we wanted to find the character which has the character code 100, we could carry out the following:
character = CHR(100)
d
print(character)
Write an algorithm, which will request a string from the user, then output the character codes
of each character from the inputted string.
As before, let’s begin by breaking this question down into its component parts. A quick analysis will find that there
are arguably 4 things to consider in this algorithm:
1. An input statement will be required, assigned to a variable, for the inputted string
2. We will need to use the .length method to find the number of characters in the string
3. We will then be able to use that number in a FOR loop, so that it iterates the same number of times as there
are characters in the string
4. During each iteration, we will need to use the FOR loop’s stepper variable to access each character in the
string and then apply this to the ASC() method in order to find the characters’ code.
Points 2 and 3 can be achieved together. Below you can see that we have added a for loop where the stepper variable
will start at zero and count up to the number of characters there are in the string.
Finally, for point 4 we can add a print statement, which will contain the ASC() method. And contained inside the
ASC() method we can use the stepper variable to access each character of the string in turn.
For example, if string = ‘HELLO’, string[0] => H, string[1] => E, string[2] => L … and so on.
A variable is assigned the string “I Love CS”. The substring method .left(4) is
applied to the variable.
Question 1 Algorithm
Write an algorithm that will ask the user to
enter a word and output the inputted word with
all characters in uppercase.
Question 2 Algorithm
Page 32 KILGARRIFF
Computer Science UK Guide to Writing Algorithms
Write an algorithm that will ask the user to
enter their name and output a resulting
username consisting of the first 2 letters of the
inputted name and the number 1234.
For example, if they entered their name as
Jason, their username would be Ja1234.
Question 3 Algorithm
Write an algorithm that will ask the user to
enter a word and output each character of the
word on separate lines.
9 Subroutines
Quick Reference
Construct Setup Example
Subroutines
Procedure procedure label(…) procedure assessmentPass()
endprocedure print("You passed your test!")
endprocedure
procedure printAge(age)
print(age)
endprocedure
KILGARRIFF Page
33 33
Guide to Writing Algorithms Computer Science UK
Subroutines
A subroutine is a block of code, that has been given a unique name and that will only execute (be run) when it is
called to do so.
The diagram below attempts to demonstrate this. The subroutine named ‘timestable’, is only executed after it has been
called. When it is called, the main program pauses whilst the subroutine runs. Then, after the subroutine has finished
executing its code, the main program resumes.
#Subroutine:
procedure timestable()
for x = 0 to 10
#Main Program: print(str(x) + “times 10 is” + str(x*10))
endprocedure
print(“Welcome to the 10 Times Table”)
timestable()
Procedures
The example subroutine shown above was that of a procedure. A procedure is a subroutine that when called, will
execute its code but any data that it generates is not passed back to the main program.
Functions
A function is also a subroutine, but when a function is called and executes its code, it will complete by passing a value
(or set of values) back to the main program, where it will be collected by an accepting variable (or data structure).
Procedure Function
#procedure #function
Page 34 KILGARRIFF
Computer Science UK Guide to Writing Algorithms
Write a procedure, which will receive a string as an argument stored inside a parameter called
word, then output the number of characters that the string contains.
As before, let’s begin by breaking this question down into its component parts. A quick analysis will find that there
are arguably 4 things to consider in this particular algorithm:
1. Set up the code structure for a procedure
2. Add the parameter word to the procedure’s brackets
3. Use the .length method to find the string’s length
4. Use a print() statement to output the string’s length
We can achieve point one by typing the word procedure, followed by a suitable name for the procedure, completing
the structure with ‘endprocedure’:
procedure stringLengthPro()
…
endprocedure
For point two, we simply need to add the name of the parameter into the procedure’s parentheses (brackets):
procedure stringLengthPro(word)
…
endprocedure
KILGARRIFF Page
35 35
Guide to Writing Algorithms Computer Science UK
And for points three and four, we just need to apply the .length method to the received parameter and print() out
the result, which can actually be done in one line of code:
procedure stringLengthPro(word)
print(word.length)
endprocedure
Write a function, which will receive a string as an argument stored inside a parameter called
word, then return the number of characters that the string contains.
As before, let’s begin by breaking this question down into its component parts. A quick analysis will find that there
are arguably 4 things to consider in this particular algorithm:
1. Set up the code structure for a function
2. Add the parameter word to the function’s brackets
3. Use the .length method to find the string’s length
4. Use a return statement to return the string’s length
We can achieve point one by typing the word function, followed by a suitable name for the function, completing the
structure with the ‘endfunction’:
function stringLengthFunc()
…
endfunction
For point two, we simply need to add the name of the parameter into the function’s parentheses (brackets):
function stringLengthFunc(word)
…
endfunction
And for points three and four, we just need to apply the .length method to the received parameter and return the
result, which can actually be done in one line of code:
function stringLengthFunc(word)
Page 36 KILGARRIFF
return word.length
Computer Science UK Guide to Writing Algorithms
If we were to be asked to also write the ‘function call’, from the main program code, we would need to ensure that we
assign the function call to a variable so that it can receive the returned value:
function stringLengthFunc(word)
return word.length
endfunction
When we write subroutines, values will often be passed into them, so that they can be processed in some way.
The name of the variable that receives the value that is passed in, is called a parameter. In the example above, word is
the parameter.
The value that is passed into the variable, is called an argument. In the example above, ‘Computer Science’ is the
argument.
KILGARRIFF Page
37 37
Guide to Writing Algorithms Computer Science UK
function square(number)
The function squares the received
The function structure return number*number parameter and returns the result
is completed
endfunction
The function call is assigned the
variable ‘answer’ to store the As requested, the algorithm
returned value. also contains the function call,
answer = square(5) with 5 as the passed argument.
Question 1 Algorithm
Write a procedure that receives a parameter
containing an integer, and outputs one of two
messages. If the received value is positive
(zero or greater), the message ‘positive’ is
outputted, otherwise the message ‘negative’ is
outputted.
Question 2 Algorithm
Write a function (including the function call)
that receives a parameter containing a string
and returns only the first character of the
received string.
Question 3 Algorithm
Write a function (including the function call)
that receives a parameter containing a string
and returns “Contains the letter ‘z’” if the
string contains a ‘z’, but returns “Does not
contain the letter ‘z’” if the string does not
contain a ‘z’.
Page 38 KILGARRIFF
Computer Science UK Guide to Writing Algorithms
10 Data Structures
Quick Reference
Construct Setup Example
Arrays
Declaration array animals[…] array animals[10]
Generates a 1D array with 10 elements (indexed 0 to 9).
Arrays are 0 indexed (e.g.: first element will have the index ‘zero’)
Arrays only store a single data type (e.g.: all strings or all integers, but not a mixture)
Arrays
Arrays are data structures. Unlike variables, which can store a single item of data under a single identifier (name), an
array can store multiple items of data (of the same type), under a single identifier (name).
For example:
a_variable = “bus”
an_array = [“bus”, “train”, “car”, “bicycle”]
Dimensions
The following array is known as a one-dimensional array:
As you can see, this array contains an array of arrays. The first array contains types of land-based transport and the
second contains types of air-based transport, with both arrays being stored in an array themselves.
KILGARRIFF Page
39 39
Guide to Writing Algorithms Computer Science UK
Array Indexes
Each item of an array is given an index, which really just means a position number. What is important to recognise is
that array indexes often begin at zero. This means that the first item of an array is given the position number 0, the
second item given the position number 1 and so on.
0
1 2 3
| |
one_d_array = [“bus”, “train”, “car”, “bicycle”]
The item at index 2 is ‘car’ because it is at position 3 (but we start counting from zero!).
The item at index 1,2 is therefore ‘glider’, because ‘glider’ is contained within the second array (which has the index
1) and is the 3rd item in that array (which has the index 2).
Declaring Arrays
When we use arrays in our algorithms, we will first need to declare them. What this means is that before we starting
working with them, we will first need to set them up with a name and size (number of items that it is to hold).
We can declare empty arrays or we can declare arrays populated with data.
array landBasedTransport[3]
Similarly, to declare an empty two-dimensional array, we do the same, but with two values in the square brackets. The
first sets how many arrays the two-dimensional array will hold and the second sets how many items each sub array
will hold:
array transport[2,3]
In these examples:
- The one-dimension array will store 3 items (indexed 0–2).
Page 40 KILGARRIFF
Computer Science UK Guide to Writing Algorithms
- The two-dimensional array will store 6 items, in two arrays (indexed 0-1) that can each store 3 items (indexed
0-2).
If the data is to be of type string, we will need to make sure we contain each string inside quotes. If the data is to be of
another type, for example an integer, we must not use quotes.
To declare a prepopulated two-dimensional array, we do the same, but the data will be contained inside subarrays of
the array.
…would assign the value “chair” into a one-dimensional array called ‘furniture’, at index 5 (which would be the sixth
position of the array).
Similarly:
cities[1,4] = “Exeter”
…would assign the value “Exeter” into a two-dimensional array called ‘cities’, at index 1,4 (which would be position
5 of the second of the array’s subarrays).
As before, let’s begin by breaking this question down into its component parts. This problem has arguably 3 main
parts to it:
1) Create two-dimensional array with provided data.
2) Set up a loop, which will iterate only for the number of items in the 3rd sub array.
3) Access each item in the 3rd sub array and output it.
For point 2, we need to create a for loop, but we need it to only iterate for the number of items in the 3 rd sub array.
To find this we can use the string manipulation method .length on the 3rd sub array, which will return the number of
elements that the sub array contains. However, we must subtract this number by 1, because the index of an array
begins at zero! As the subarray contains 3 items, we need the for loop’s stepper variable i to count 0, 1, 2…the
indexes for each of the 3 items!
for i = 0 to (animals[2].length – 1)
… … … … … … …
next i
Finally, for point 3, we can use the stepper variable i to access each element in the 3rd sub array, along with a
print() statement to output the value.
for i = 0 to (animals[2].length – 1)
print(animals[2,i])
next i
Question 1 Algorithm
Write an algorithm that will declare a one-
dimensional array, prepopulated with the
names of 5 animals. Then use a loop to output
each item of the list.
Question 2 Algorithm
Write an algorithm that will declare a two-
dimensional array, prepopulated with 10 letters
(5 in each subarray) and then output the 3rd
letter in each subarray.
Question 3 Algorithm
Write an algorithm that will declare an empty
two-dimensional array containing 5 sub-arrays,
each with 5 elements, then allow the user to
populate the subarrays with film names.
11 File Handling
Quick Reference
Construct Setup Example
Create a New File newFile() newFile("myFile.txt")
This simply creates a new text file called "myFile". The file still needs to be
opened using the open() statement (see below).
Open open(…) myFileHandler = open("myFile.txt")
When opening a file, it must be assigned to a file handler.
KILGARRIFF Page
43 43
Guide to Writing Algorithms Computer Science UK
Write Line .writeLine(…) myFileHandler.writeLine("Some Text")
The line will be written to the end of the file.
File Handling
File handling involves the reading from and writing to a file, that is external to the program. When programs store data
in variables and arrays, the data itself is actually store in the RAM, which is volatile and as such, when the program
closes, the data is lost.
It is therefore often required that our programs write data to an external file, so that when the program is closed and
reopened again at a later date, the saved data can be retrieved.
When writing algorithms, we can demonstrate the logic for this in the following ways.
Opening a File
In order for programs to begin working with an external file, they will first need to open the file. This can be
demonstrated in our algorithms by writing open(), with the name of the file and its file type, written within quotes,
inside the brackets.
But what is important here is that we assign a file handler to this process!
For example, myFileHandler = open(“myNewFile.txt”) would demonstrate the opening of the text file, with
the name myNewFile, inside the program, assigning it to a file handler called ‘myFileHandler’.
You can think of a file handler as a data structure, which keeps track of how the file is being used by the program. For
example, as the file is being read by the program, the file handler will keep track of where the program has read up to,
using a cursor.
If we write myFileHandler.readLine(), this will demonstrate the reading of the This is the last line!
next line of the file. So, if used immediately after opening the file, it will be the first line
of the file that is read. If repeated, the next line will be read, and so on.
Remember that there will be an invisible cursor which will track where the file has been read up to. .readLine()
will read the next line that follows the current position of the cursor, and will move the cursor on to the end of that line
after it is read by the program.
Page 44 KILGARRIFF
Computer Science UK Guide to Writing Algorithms
File Example Algorithm Output
This is line one
myFileHandler = open(“myNewFile.txt”) This is line two
print(myFileHandler.readLine()) This is the last line!
print(myFileHandler.readLine())
print(myFileHandler.readLine())
For example, imagine we have some data that we want to write to a file. Once we have opened the file in our program
and assigned it to a file handler myFileHandler = open(“myNewFile.txt”) we can write
myFileHandler.writeLine() and place either a hardcoded string or a variable in the brackets, to have the data
written to the open file.
KILGARRIFF Page
45 45
Guide to Writing Algorithms Computer Science UK
Closing a File
Once we have finished working with an external file, it is sensible to close the connection to the file. This can be
achieved by appending a .close() method to the end of the file handler. The final line of the following algorithm
demonstrates this:
myFileHandler = open(“myNewFile.txt”)
print(myFileHandler.readLine())
myFileHandler.close()
Page 46 KILGARRIFF
Computer Science UK Guide to Writing Algorithms
Algorithm Writing Guidance – File Handling
Consider the algorithm question:
Write an algorithm, which will ask the user to enter their favourite film and write the inputted
information to a text file.
As before, let’s begin by breaking this question down into its component parts. This problem has arguably 5 main
parts to it:
1) Ask the user to input data and store in a variable
2) Create a text file
3) Open the text file and assign a file handler
4) Write the variable contents to the file
5) Close the file
For point one, we will need a simply input() statement and assign to it a variable to store the input:
For point 3, we will need to open the file and assign it to a file handler:
We are now in a position to carry out point 4 which is to write the contents of the variable ‘film’ to the file, which can
be demonstrated like this:
KILGARRIFF Page
47 47
Guide to Writing Algorithms Computer Science UK
Finally, we can complete the final step (point 5) and close the connection to the file:
Page 48 KILGARRIFF
Computer Science UK Guide to Writing Algorithms
Write an algorithm that will open a text file called “top5Films.txt”, read and output the contents of the text file, in its
entirety.
Question 1 Algorithm
Write an algorithm that will create a text file
called ‘myFile.txt’, open the file, then write the
string ‘This is the first line’ to the text file,
before closing it.
Question 2 Algorithm
Write an algorithm that will open a text file
called ‘HighScore.txt’ (which contains a list of
high scores in descending order) and output the
top score (first line).
Question 3 Algorithm
Write an algorithm that will open a text file
called “examFeedback.txt”, read and output
the entire contents of the text file, then ask the
user to enter a comment and write this to the
end of the file, before closing it.
12 Mixed Questions
Question 1 Algorithm
KILGARRIFF Page
49 49
Guide to Writing Algorithms Computer Science UK
Write an algorithm that will ask the user to
enter the lengths of a triangle’s 3 sides and the
output whether the triangle is equilateral,
isosceles or scalene.
Question 2 Algorithm
In a frisbee making factory, a worker gets paid
£10 per hour, plus £5 for every frisbee made in
addition to the first 100. Write an algorithm
that will accept the hours worked and frisbees
made, for a given day and work out (and
output) the worker’s pay for the day.
Question 3 Algorithm
Write an algorithm that will declare the
following 1D array:
scores = [2,5,12,8,3,25,21,6]
Question 4 Algorithm
Page 50 KILGARRIFF
Computer Science UK Guide to Writing Algorithms
Write an algorithm that will ask the user how
many integers they wish to enter, then allow
the user to enter the integers and output the
mean of the entered integers.
Question 5 Algorithm
A user wishes to add a series of names to a text
file. Write an algorithm that will ask the user
how many names they wish to enter, then ask
the user to enter these names, writing each one
to a text file.
Question 6 Algorithm
Write an algorithm that first declares the
following 2D array:
points = [[2,5,12,8],[3,25,21,6]]
The array contains the points scored by Team A
(first subarray) and Team B (second subarray).
The algorithm is to calculate and output the
points total of each team and state which team
won.
KILGARRIFF Page
51 51
Guide to Writing Algorithms Computer Science UK
Question 7 Algorithm
Write an algorithm that will ask the user to
enter a number and store it in a variable. Then,
this value is to be passed to a function that will
cube the input and return it back to the main
program for outputting.
Question 8 Algorithm
A text file, contains a list of test results, with
each result on its own line of the file.
Write an algorithm that will open and read the
text file, calculating the mean of these test
results.
The algorithm will complete by outputting the
calculated mean.
Question 9 Algorithm
Write an algorithm that will first pick a
number between 1 and 100, then ask the user
to guess the number. Each time the user
guesses, the algorithm will inform the user
whether or not their guess was higher or lower
than the chosen number, until they guess
correctly.
Page 52 KILGARRIFF
Computer Science UK Guide to Writing Algorithms
Question 10 Algorithm
Write an algorithm that will ask the user to
enter a word, convert it to lower case and
encrypt the word using a Caesar Cipher with a
left shift of 1. The encrypted word will be
outputted following the encryption.
Question 11 Algorithm
Write an algorithm that will ask the user to
enter a password between 6 and 12 characters
long. The algorithm will reject passwords with
lengths outside of this character range and
request the password again. A suitable
message will be displayed when an acceptable
password is entered.
Question 12 Algorithm
Write an algorithm that will ask the user to
enter a year (e.g. 2022), pass this year to a
procedure, that will output what the year will
be in 100 years’ time.
KILGARRIFF Page
53 53
Guide to Writing Algorithms Computer Science UK
Question 13 Algorithm
Write an algorithm that will accept only a
single character, pass the character to a
function, which will convert the character to its
equivalent ASCII code, returning the code
back to the main program for outputting.
Question 14 Algorithm
Write a procedure that will receive a two-
dimensional array, traverse the array,
outputting each item that it finds, one after the
other.
Page 54 KILGARRIFF
Computer Science UK Guide to Writing Algorithms
NOTES
KILGARRIFF Page
55 55