0% found this document useful (0 votes)
137 views

CSUK Writing Algorithms Separate GUIDE

This document provides a guide to writing algorithms. It covers topics such as outputs, inputs, variables, casting data types, random numbers, arithmetic operations, selection statements, iteration statements, string manipulation, subroutines, data structures, and file handling. The guide includes examples and practice questions for each topic.

Uploaded by

yxhk7wxf24
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
137 views

CSUK Writing Algorithms Separate GUIDE

This document provides a guide to writing algorithms. It covers topics such as outputs, inputs, variables, casting data types, random numbers, arithmetic operations, selection statements, iteration statements, string manipulation, subroutines, data structures, and file handling. The guide includes examples and practice questions for each topic.

Uploaded by

yxhk7wxf24
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 55

Computer Science UK Guide to Writing Algorithms

CSUK
Writing
Algorithms
Guide

KILGARRIFF Page 1
Guide to Writing Algorithms Computer Science UK

CONTENTS
1. Outputs, Inputs & Variables 3

2. Casting, Random Numbers & Arithmetic 6

3. Selection (IF-THEN-ELSE Statements) 10

4. Selection (CASE Select / SWITCH Statements) 14

5. Iterations 1 (COUNT Controlled (FOR LOOP)) 17

6. Iterations 2 (CONDITION Controlled (WHILE LOOP)) 21

7. Iterations 3 (CONDITION Controlled (DO UNTIL LOOP)) 3

8. String Manipulation 3

9. Subroutines 3

10. Data Structures 3

11. File Handling 3

12. Mixed Questions 3

Page 2 KILGARRIFF
Computer Science UK Guide to Writing Algorithms

1 Outputs, Inputs & Variables

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”)

Inputs and Variables


An input is where a program will ask the user to enter some data. When writing algorithms, we can demonstrate this
using an input() statement. And any data that we write inside the brackets will, be outputted to the screen for the
user.
But what is important to recognise is that if we wish our programs to store the inputted data, we must assign our input
statement to a variable.

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:

name = input(“What is your name? ”)


print(“Your name is:”)
print(name)

Algorithm Writing Guidance - Outputs, Inputs and Variables


Consider the following algorithm question:

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:

input(“Enter your name: ”)

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.

name = input(“Enter your name: ”)

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:

print(“The name ” + name + “ is a beautiful name”)

So, putting it all together, a solution to this question is:

name = input(“Enter your name: ”)


print(“The name ” + name + “ is a beautiful name”)

Practice Questions – Outputs, Inputs & Variables


Worked Example
Write an algorithm that will ask the user to enter their star sign, then output the sentence “Your star sign has been
recorded as *star_sign*”.
Input statement displays a message to user asking them to
Variable assigned to input statement to enter star sign and waits for input
store user’s input

star_sign = input(“Enter your star sign: ”)


print(“Your star sign has been recorded as ” + star_sign)
Page 4 KILGARRIFF
Computer Science UK Guide to Writing Algorithms

Print statement outputs a string (some text) joined to


the contents of the variable.

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

2 Casting, Random Numbers & Arithmetic

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.

1. The data ”22” is currently of type string


(recognised by the computer as keyboard symbols
and not a number)..
number1 = int(“22”) 2. The int() function casts the string into an integer

3. The casted data (now of type integer) is


assigned to the variable ‘number1’.

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)

Algorithm Writing Guidance - Casting, Random Numbers and Maths


Consider the following algorithm question:

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:

number1 = input(“Enter a number: ”)


number2 = input(“Enter another number: ”)

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:

number1 = input(“Enter a number: ”)


number2 = input(“Enter another number: ”)
number1 = int(number1)
number2 = int(number2)

What’s actually happening here is best understood by reading the statement from right to left:

1. The data inside number1 is currently assumed as a string.


2. The int() function casts the string into an integer

3. The casted data (now of type integer) is


reassigned to the variable ‘number1’. number1 = int(number1)
4. The variable ‘number1’ has effectively been
overwritten with data of the correct type.

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:

answer = number1 + number2

Finally, we complete point 3 by using a print() statement to output the contents of the variable containing the
answer.

print(answer)

So, putting it all together, a solution to this question is:

number1 = input(“Enter a number: ”)


KILGARRIFF
number2 = input(“Enter another number: ”) Page
7 7
number1 = int(number1)
Guide to Writing Algorithms Computer Science UK

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.

Variables assigned to input Input statements displays a message to user


statements to store user’s inputs. asking them to enter height, width, depth, waiting
height = input(“Enter the height: ”) for each input in turn.
width = input(“Enter the width: ”)
The casted data (now of type
integer) is reassigned to the
depth = input(“Enter the depth: ”) The data inside height, width depth, is of
variables height, width and height = int(height) string data type when inputted and so the
depth, in turn. These variables int() function casts each string value to an
have effectively been
width = int(width) integer type.
overwritten with data of the depth = int(depth)
correct type.
volume = height * width * depth The contents of height, width and depth
print(volume) are multiplied together and the result is
stored in a variable called ‘volume’.
Print statement outputs a string
(some text) joined to the contents
of the variable.

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

PRINT(“The square od “, num” is square .”)

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.")

num2 = INPUT("Please enter a second”)


if num2> num1:
break
else:
print("num2 must be greater than the num1.")
except ValueError:
print("Invalid input. Please enter a valid number.")
KILGARRIFF Page
9 9
Guide to Writing Algorithms Computer Science UK
random_number = (num1, num2)
print(f"A random number between (num1) and (num2) is:
(random_number)"

3 Selection (IF-THEN-ELSE Statements)

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

Selection and IF statements


Selection is a programming construct which allows a program to execute one line of code, from multiple possible
lines, depending on a condition.
For example, if we had an input statement where the user was asked to enter either the letter ‘y’ or ‘n’, storing their
input in a variable called answer we could then use an if-then-else statement to output one message if the letter
‘y’ was entered, but instead another message if the letter ‘n’ was entered:

answer = input(“Enter letter ‘y’ or ‘n’: ”)

if answer == "y" then


print("You entered the letter ‘y’")
elseif answer == "n" then
print("You entered the letter ‘n’")
else
print("You did not enter a ‘y’ or an ‘n’")
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:

number1 = input(“Enter a number: ”)


number2 = input(“Enter another number: ”)

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:

number1 = input(“Enter a number: ”)


number2 = input(“Enter another number: ”)
number1 = int(number1)
number2 = int(number2)

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:

if number1 > number2 then


print(str(number1) + “ is bigger than ” + str(number2))
elseif number1 < number2 then
print(str(number2) + “ is bigger than ” + str(number1))
else
print("The numbers you entered are equal")
endif

So, putting it all together, a solution to this question is:

number1 = input(“Enter a number: ”)


number2 = input(“Enter another number: ”)
KILGARRIFF number1 = int(number1) Page
11 11
number2 = int(number2)
Guide to Writing Algorithms Computer Science UK

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…

…with else to capture the scenario else …message to be outputted if number is


neither greater than or less than zero.
when number is neither greater than or
less than zero.
print("The numbers you entered is zero")
endif

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

4 Selection (CASE Select / SWITCH Statements)

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

Selection and Case Select / Switch Statements

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’.

Algorithm Writing Guidance – Case Select / Switch Statements


Consider the following algorithm question:

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.

number = input(“Enter number 1, 2 or 3”)


number = int(number)

For point two, we can demonstrate the logic of the case select / switch construct like so:

number = input(“Enter number 1, 2 or 3”)


number = int(number)

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.

number = input(“Enter number 1, 2 or 3”)


number = int(number)

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

Practice Questions - Case Select / Switch Statements


Worked Example
Write an algorithm, using a case select / switch statement, which asks the user what kind of web developer they wish
to be: ‘designer’, ‘frontend’ or ‘backend’. The program will output what language they should study to best help them
prepare.
Input statements displays a message to
Variable assigned to input statement,
user asking them to enter one word from
A switch statement is setup with to store user’s input
three
variable dev as the conditional.

dev = input(“designer, frontend or backend? ”) Page


KILGARRIFF
switch dev: 15 15
Guide to Writing Algorithms Computer Science UK

In the case of dev containing


‘designer’, the message
‘Learn CSS’ will be
If the user fails to enter
displayed…
either ‘designer’,
‘fronted’ or ‘backend’,
…in the case of dev
then an error message
containing ‘frontend’ the
will be displayed.
message ‘Learn JavaScript’
will be displayed…

…in the case of dev


containing ‘backend’ the
message ‘Learn PHP’ will be
displayed.

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.

Tip: x MOD 2 will divide x by 2, working out only


the remainder of the division.

5 Iterations 1 (Count Controlled (FOR LOOP))

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

The even numbers from 2 to 20 inclusive, will be outputted.

for i=10 to 0 step -1


print(i)
next i

The numbers from 10 to 0 inclusive (i.e. 10, 9, 8,…,2, 1, 0),


will be outputted.

Count Controlled Iteration (The FOR Loop)


An iteration is a programming construct which allows programs to repeatedly execute lines of code. Iterations are also
known as loops. There are two types of iteration. A count-controlled iteration is one which will allow a program to
repeatedly execute line(s) of code for a set number of times. A condition-controlled iteration is one which will allow a
program to repeatedly execute line(s) of code, whilst a condition (e.g. x == 3) is true.

In this section we will focus on a count-controlled iteration, known as a for loop.

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

…and the following would allow the program to count down:

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!”

Points 1, 2 and 3 require us to set up a for loop, with a custom ‘step’.

for i=10 to 1 step -1


code_to_be_execute
next i

Points 4 requires us to print out the stepper variable in each iteration.

for i=10 to 1 step -1


print(i)
next i

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:

for i=10 to 1 step -1


print(i)
next i
print(“Blast Off!”)

Practice Questions – FOR Loops


Worked Example

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

Why do we need to cast stepper variable i, to a string?

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).

6 Iterations 2 (Condition Controlled (WHILE LOOP))


Quick Reference

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

Count Controlled Iteration (The WHILE Loop)


As we learnt in the previous chapter, an iteration is a programming construct which allows programs to repeatedly
execute lines of code. A condition-controlled iteration is one which will allow a program to repeatedly execute line(s)
of code, whilst a condition (e.g. x == 3) is true.

In this section we will focus on a condition-controlled iteration, known as a while loop.

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.

Algorithm Writing Guidance – WHILE Loops


Consider the following algorithm question:

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.

Here is a final solution to the question:

x = 10
while x != 0
print(x)
x = x - 1
endwhile
print(“Blast Off!”)
Page 22 KILGARRIFF
Computer Science UK Guide to Writing Algorithms

Practice Questions – WHILE Loops


Worked Example
Write an algorithm, using a while loop, that will output the 10 times table.
A variable (which will be used as a counter) is
assigned the value of 1.
During each iteration, a print statement outputs:

1. The value of the counter variable (casted as a string), joined with…


A while loop is written, with the 2. The string “multiplied by 10 is ”, joined with…
condition x != 11. x = 1 3. The result of the counter variable multiplied by 10, cast as a string.

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

Why do we need to cast stepper variable i, to a string?

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.

Tip: x MOD 2 will divide x by 2, working out only


the remainder of the division.

7 Iterations 3 (Condition Controlled (DO UNTIL LOOP))

Quick Reference
Construct Setup Example
DO UNTIL loop do … do
(Condition-controlled) answer = input("Yes")
until … until answer == "Yes"

Count Controlled Iteration (The DO UNTIL Loop)


As we learnt in the previous chapters, an iteration is a programming construct which allows programs to repeatedly
execute lines of code and a condition-controlled iteration is one which will allow a program to repeatedly execute
line(s) of code, whilst a condition (e.g. x == 3) is true.

In this section we will focus on a condition-controlled iteration, known as a do until loop.

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.

Algorithm Writing Guidance – DO UNTIL Loops


Consider the following algorithm question:

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

Guide to Writing Algorithms Computer Science UK

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.

Here is a final solution to the question:

x = 10
do
print(x)
x = x - 1
until x == 0
print(“Blast Off!”)

Page 26 KILGARRIFF
Computer Science UK Guide to Writing Algorithms

Practice Questions – DO UNTIL Loops


Worked Example
Write an algorithm, using a do until loop, that will output the 10 times table.
A variable (which will be used as a counter) is
assigned the value of 1.
During each iteration, a print statement outputs:

1. The value of the counter variable (casted as a string), joined with…


2. The string “multiplied by 10 is ”, joined with…
x = 1 3. The result of the counter variable multiplied by 10, cast as a string.

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

Why do we need to cast stepper variable i, to a string?

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

Substrings .substring(x , i) resources = "ComputerScienceUK"


.left(i) resources.substring(3,5) returns "puter"
.right(i) resources.left(4) returns "Comp"
resources.right(3) returns "eUK"
x is starting index
i is number of characters
Index begins at 0
Concatenation + print(stringA + stringB)
print("Hello " + name)
Uppercase .upper resources = "ComputerScienceUK"
resources.upper gives "COMPUTERSCIENCEUK"

Lowercase .lower resources = "ComputerScienceUK"


resources.lower gives "computerscienceuk"

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)

Algorithm Writing Guidance – String Manipulation Methods


Consider the following algorithm question:

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.

Point 1 can be achieved with a single line, such as…

string = input(“Enter a string: ”)

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.

string = input(“Enter a string: ”)


KILGARRIFF Page
31 31
for i = 0 to string.length
… … … … … … …

Guide to Writing Algorithms Computer Science UK

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.

string = input(“Enter a string: ”)


for i = 0 to string.length
print(ASC(string[i]))
next i

For example, if string = ‘HELLO’, string[0] => H, string[1] => E, string[2] => L … and so on.

Practice Questions – String Manipulation Methods


Worked Example
Write an algorithm, that will output the first 4 characters of the string “I Love CS”.

A variable is assigned the string “I Love CS”. The substring method .left(4) is
applied to the variable.

The first 4 characters are


x = “I Love CS” therefore assigned to the variable
The variable subStris then
printed, outputting the first 4 subStr = x.left(4) subStr
characters of the inputted string. print(subStr)

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

procedure sum(num1, num2)


print(num1 + num2)
endprocedure
Calling a Procedure procedure(parameters) assessmentPass()
printAge(21)
sum(parameter1, parameter2)

Function function label(…) function cubed(x)


… cube = x * x * x
return … return cube
endfunction endfunction
Calling a Function function(parameters) print(cubed(4))
result = cubed(4)

Function calls should have a variable assigned to them if the returned


value is to be used in the main program.

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()

….the rest of the program code

There are two types of subroutine; procedures and functions.

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

procedure proc_123() function func_123()


Function Called to
Procedure Called to
#main x = 3 * 5 Run x = 3 * 5
Run #main
print(x) return x

proc_123() endprocedure endfunction


x = func_123()
No Values
Returned!
print(x) Value Being Returned & Stored in
Variable Assigned to Function Call
…the rest of the program code …the rest of the program code

Page 34 KILGARRIFF
Computer Science UK Guide to Writing Algorithms

Algorithm Writing Guidance – Procedures


Consider the following algorithm question:

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

Algorithm Writing Guidance – Functions


Consider the extremely similar algorithm question:

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

lengthOfWord = stringLengthFunc(“Computer Science”)

A quick note on Parameters and Arguments

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

Practice Questions – Subroutines


Worked Example
Write a function (including the function call), that will receive a parameter called ‘number’, (containing the argument
5), and return the received parameter’s square.

A function is created The function receives the


parameter called ‘number’.

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).

array table[…,…] = … array table[5,5]


Generates a 2D array with 5 subarrays each with 5 elements (indexed 0 to
4).

array animals = ["Pig", "Goat", "Cow"]


Arrays can be declared, already populated with values.
Assignment animals[…] = … animals[3] = "Sheep"
table[…,…] = … table[1,0] = "14"

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:

This means that it contains a single linear list (array) of items.


However, arrays can have multiple dimensions. What this means is that arrays can in fact contain, not just one array
of items, but an array of arrays of items.

one_d_array = [“bus”, “train”, “car”, “bicycle”]

For example, the following array is known as a two-dimensional array:

two_d_array = [ [“bus”, “train”, “car”] , [“plane”, “helicopter”, “glider”] ]

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.

One Dimensional Array Indexes


Here is an example of the indexes of items inside a one-dimensional array:

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!).

Two-Dimensional Array Indexes


Because two dimensional arrays effectively consist of ‘arrays inside an array’, the index of each item actually consists
of 2 values. The first value is the index of the array that it is contained within. The second value is the index of its own
position within that array.
Here is an example of the indexes of items inside a two-dimensional array:

0,0 0,1 0,2 1,0 1,1 1,2


two_d_array = [ [“bus”, “train”, “car”] , [“plane”, “helicopter”, “glider”] ]

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.

Declaring Empty Arrays


To declare an empty one-dimensional array, we need to write the word array, followed by the name we wish the array
to have, followed by the number of items we wish the array to hold (written inside square brackets):

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).

Declaring Pre-Populated Arrays


As said above, we can declare arrays with items already populated.
To declare a prepopulated one-dimensional array, we need to write the word array, followed by the name we wish the
array to have, followed by the data that the array holds (written inside square brackets):

array landBasedTransport = [“bus”, “train”, “car”, “bicycle”]

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.

array transport = [ [“bus”, “train”, “car”] , [“plane”, “helicopter”, “glider”] ]

Assigning Values into Arrays


To show the assignment of items into arrays, we simply need to state the array name and index in which the item is to
be placed.
For example:
furniture[5] = “chair”

…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).

Accessing Items in Arrays


We can access items in arrays, using the item’s index.
For example, in the array landBasedTransport = [“bus”, “train”, “car”, “bicycle”], we can use
landBasedTransport[3] to access the item ‘bicycle’.

And in the array transport = [[“bus”, “train”, “car”],[“plane”, “helicopter”, “glider”]], we


can use transport[0,2] to access the item ‘car’.

Algorithm Writing Guidance – Arrays


Consider the algorithm question:

Write an algorithm, which declares a two-dimensional array (called ‘animals’), with 3


subarrays, each with 3 elements, prepopulated with the following data:
cow pig sheep
elephant zebra giraffe
KILGARRIFF Page
41 41
rabbit gerbil guinea pig
Guide to Writing Algorithms Computer Science UK

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.

Point 1 can be achieved by writing the following array assignment line:

animals = [[“cow”, “pig”, “sheep”],[“elephant”, “zebra”, “giraffe”],[“rabbit”, “gerbil”, “guinea pig”]]

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!

animals = [[“cow”, “pig”, “sheep”],[“elephant”, “zebra”, “giraffe”],[“rabbit”, “gerbil”, “guinea pig”]]

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.

animals = [[“cow”, “pig”, “sheep”],[“elephant”, “zebra”, “giraffe”],[“rabbit”, “gerbil”, “guinea pig”]]

for i = 0 to (animals[2].length – 1)

print(animals[2,i])

next i

Practice Questions - Arrays


Worked Example
Write an algorithm that will declare a one-dimensional array, with 5 elements, then allow the user to populate the
array with 5 inputted strings.

A one-dimensional array with 5 elements is declared

array userStrings[5] A for loop is set up to


iterate 5 times
Within the loop, the user is asked to
enter a string, which is stored in a
for i = 0 to 4
variable called ‘string’.
string = input(“Enter a string: ”)
Each inputted string is assigned to the array, in
userStrings[i] = string the position/index which reflects the stepper
Stepper variable is then incremented
Page 42 by 1. value i in the loop. KILGARRIFF
next i
Computer Science UK Guide to Writing Algorithms

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.

Close .close() myFileHandler.close()


Read Line .readLine() myFileHandler.readLine() returns the next line in the file

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.

End of File .endOfFile() while NOT myFileHandler.endOfFile()


print(myFileHandler.readLine())
endwhile

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.

Creating a New File


We can demonstrate the creation of a new external file by writing newFile(), with the name of the file and its file
type, written within quotes, inside the brackets.
For example, newFile(“myNewFile.txt”) would demonstrate the creation of a text file, with the name
myNewFile.

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.

Reading a Line from a File


Once we have demonstrated the opening of a file, we can begin to show how our program will read the file using a
.readLine() method.
myNewFile.txt
For example, imagine we have a text file, which contains three lines of text, and have This is line one
opened the file in our program and assigned it to a file handler: myFileHandler =
open(“myNewFile.txt”) This is line two

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())

Writing a Line to a File


To demonstrate the writing of data to a file, we can use a .writeLine() method.

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.

Example Algorithm File Contents


(after algorithm is executed)
myNewFile.txt
name = “Anna”
favouriteColour = “green” Anna
myFileHandler = open(“myNewFile.txt”) green
myFileHandler.writeLine(name)
myFileHandler.writeLine(favouriteColour) The End
myFileHandler.writeLine(“The End”)

Checking if the Cursor is at the End of a File


Quite often, when we work with external files, we will not know how many lines of data the file will contain.
Thankfully most languages have a built-in method which can see if the file’s cursor is at the end of the file or not. This
means that we can create loops to read line after line of an external file and stop as soon as the cursor reaches the end
of the file.

The following algorithm can show the logic of such a scenario:

while NOT myFileHandler.endOfFile()


print(myFileHandler.readLine())
endwhile

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:

film = input(“Enter your favourite film: ”)

For point 2, we need to demonstrate the creating of a text file:

film = input(“Enter your favourite film: ”)


newFile(“favFilm.txt”)

For point 3, we will need to open the file and assign it to a file handler:

film = input(“Enter your favourite film: ”)


newFile(“favFilm.txt”)
myFileHandler = open(“favFilm.txt”)

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:

film = input(“Enter your favourite film: ”)


newFile(“favFilm.txt”)
myFileHandler = open(“favFilm.txt”)
myFileHandler.writeLine(film)

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:

film = input(“Enter your favourite film: ”)


newFile(“favFilm.txt”)
myFileHandler = open(“favFilm.txt”)
myFileHandler.writeLine(film)
myFileHandler.close()

Practice Questions – File Handling


Worked Example

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.

The file is opened and assigned to a file handler

A while loop is set to iterate while the


file handler is not at the end of the file. myFileHandler = open(“top5Films.txt”)
Within the loop, each line of the
while NOT myFileHandler.endOfFile() file is outputted, one line at a
time.
This identifies the end of print(myFileHandler.readLine())
the loop structure.

endwhile The connection to the file is


closed.
myFileHandler.close()

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]

…then add together each number contained in


the array and output the result.

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

You might also like