Download as pdf or txt
Download as pdf or txt
You are on page 1of 73

Licenced to: mhighmore@shsg.org.

Downloaded: January 24, 2024

CSUK’s
Algorithm Writing Guide
& Workbook
With OCR’s Exam Reference Language Support
Licenced to: mhighmore@shsg.org. Downloaded: January 24, 2024
ComputerScienceUK.com CSUK:Teacher

Contents
Introduction ................................................................................................................................................................................................ 4
Who is this workbook for?..................................................................................................................................................................... 4
OCR’s ERL & Other Exam Boards? ...................................................................................................................................................... 4
Outputs, Inputs and Variables ................................................................................................................................................................. 5
Outputs.................................................................................................................................................................................................... 5
Inputs and Variables ............................................................................................................................................................................. 5
Algorithm Writing Guidance - Outputs, Inputs and Variables ....................................................................................................... 6
Practice Questions – Outputs, Inputs & Variables ........................................................................................................................... 7
Casting, Random Numbers & Arithmetic .............................................................................................................................................. 8
Casting .................................................................................................................................................................................................... 8
Random Numbers ................................................................................................................................................................................. 8
Algorithm Writing Guidance - Casting, Random Numbers and Maths ....................................................................................... 9
Practice Questions - Casting, Random Numbers and Maths ..................................................................................................... 11
Selection (if-then-else statements) ....................................................................................................................................................... 12
Selection and IF statements .............................................................................................................................................................. 12
Algorithm Writing Guidance – if-then-else Statements ........................................................................................................... 13
Practice Questions - if-then-else Statements............................................................................................................................. 15
Selection (Case Select / Switch statements) ...................................................................................................................................... 16
Selection and Case Select / Switch Statements ........................................................................................................................... 16
Algorithm Writing Guidance – Case Select / Switch Statements ............................................................................................... 17
Practice Questions - Case Select / Switch Statements ................................................................................................................ 18
Iterations 1 (Count Controlled (FOR LOOP)) ....................................................................................................................................... 19
Count Controlled Iteration (The FOR Loop).................................................................................................................................... 19
Algorithm Writing Guidance – FOR Loops ...................................................................................................................................... 21
Practice Questions – FOR Loops ....................................................................................................................................................... 22
Iterations 2 (Condition Controlled (WHILE LOOP)) ............................................................................................................................. 23
Count Controlled Iteration (The WHILE Loop) ................................................................................................................................ 23
Algorithm Writing Guidance – WHILE Loops ................................................................................................................................... 24
Practice Questions – WHILE Loops.................................................................................................................................................... 26
Iterations 3 (Condition Controlled (DO UNTIL LOOP)) ....................................................................................................................... 27
Count Controlled Iteration (The DO UNTIL Loop) .......................................................................................................................... 27
Algorithm Writing Guidance – DO UNTIL Loops ............................................................................................................................. 28
Practice Questions – DO UNTIL Loops .............................................................................................................................................. 30
String Manipulation .................................................................................................................................................................................. 31
String Manipulation ............................................................................................................................................................................. 31
String Length .................................................................................................................................................................................... 31
Substrings .......................................................................................................................................................................................... 32
Concatenation ............................................................................................................................................................................... 32
Uppercase ....................................................................................................................................................................................... 33
Lowercase........................................................................................................................................................................................ 33
ASCII Conversion............................................................................................................................................................................. 33
ASC() ................................................................................................................................................................................................. 33
CHR() ................................................................................................................................................................................................. 33
Algorithm Writing Guidance – String Manipulation Methods ...................................................................................................... 34

Computer Science UK Membership Site Licence: Do not share outside of your centre 2
Licenced to: mhighmore@shsg.org. Downloaded: January 24, 2024
ComputerScienceUK.com CSUK:Teacher

Practice Questions – String Manipulation Methods ...................................................................................................................... 35


Subroutines ................................................................................................................................................................................................ 36
Subroutines ........................................................................................................................................................................................... 36
Procedures ....................................................................................................................................................................................... 37
Functions .......................................................................................................................................................................................... 37
Algorithm Writing Guidance – Procedures ..................................................................................................................................... 38
Algorithm Writing Guidance – Functions ........................................................................................................................................ 39
A quick note on Parameters and Arguments ........................................................................................................................... 40
Practice Questions – Subroutines ..................................................................................................................................................... 41
Data Structures ......................................................................................................................................................................................... 42
Arrays ..................................................................................................................................................................................................... 42
Dimensions ....................................................................................................................................................................................... 42
Array Indexes ................................................................................................................................................................................... 43
Declaring Arrays .............................................................................................................................................................................. 43
Declaring Empty Arrays ................................................................................................................................................................. 43
Declaring Pre-Populated Arrays .................................................................................................................................................. 44
Assigning Values into Arrays.......................................................................................................................................................... 44
Accessing Items in Arrays .............................................................................................................................................................. 44
Algorithm Writing Guidance – Arrays .............................................................................................................................................. 45
Practice Questions - Arrays ................................................................................................................................................................ 46
File Handling ............................................................................................................................................................................................. 47
File Handling ......................................................................................................................................................................................... 47
Creating a New File........................................................................................................................................................................ 47
Opening a File ................................................................................................................................................................................. 47
Reading a Line from a File ............................................................................................................................................................ 48
Writing a Line to a File .................................................................................................................................................................... 48
Checking if the Cursor is at the End of a File ............................................................................................................................. 49
Closing a File .................................................................................................................................................................................... 49
Algorithm Writing Guidance – File Handling .................................................................................................................................. 50
Practice Questions – File Handling ................................................................................................................................................... 52
Mixed Questions ....................................................................................................................................................................................... 53
Answers ...................................................................................................................................................................................................... 58
Outputs, Inputs and Variables – Answers ........................................................................................................................................ 58
Casting, Random Numbers and Maths - Answers......................................................................................................................... 59
if-then-else Statements - Answers ................................................................................................................................................ 60
Case Select / Switch Statements - Answers ................................................................................................................................... 61
FOR Loops - Answers ........................................................................................................................................................................... 62
WHILE Loops - Answers ....................................................................................................................................................................... 63
DO UNTIL Loops - Answers .................................................................................................................................................................. 64
String Manipulation Methods - Answers .......................................................................................................................................... 65
Subroutines - Answers ......................................................................................................................................................................... 66
Arrays - Answers ................................................................................................................................................................................... 67
File Handling - Answers ....................................................................................................................................................................... 68
Mixed Questions - Answers ................................................................................................................................................................ 69

Computer Science UK Membership Site Licence: Do not share outside of your centre 3
Licenced to: mhighmore@shsg.org. Downloaded: January 24, 2024
ComputerScienceUK.com CSUK:Teacher

Introduction

Algorithm writing can feel very daunting for a number of reasons. Not only are you required to
understand how programs are structured and organised, you also need to be able to understand
the problems in question, and understand how to break these problems down, so that logical
steps can be identified, to help build a solution.

But fear not, because this workbook has been designed to remedy these issues!

The chapters in this workbook introduce you to generic programming constructs, individually, so
that you can focus on mastering the ability to form algorithmic solutions using these constructs in
isolation, before being introduced to others.

And only after you have looked at each construct in isolation, will you begin to experience
questions which require combinations of these constructs, at which point you will have had the
prior success and built enough confidence, to tackle them.

Ultimately, when it comes to algorithm writing, the more you practice, the easier it becomes! And
this is made easier still, if you regularly practice your programming skills in the language that you’re
studying!

Who is this workbook for?

The following workbook is designed to support all students studying Computer Science at GCSE
(and A-Level), across all UK exam boards.

Algorithm writing is a major aspect of all CS courses, whether it’s directly examined in written
examinations, or indirectly examined in project planning, and as such this workbook will be
invaluable to all regardless of the exam board they are studying.

OCR’s ERL & Other Exam Boards?

If examples are provided in OCR’s ERL, is this workbook therefore not suitable for those studying
other exam boards?

Regardless of the exam board being studied, this workbook is designed to help students
understand generic programming constructs, develop skills in decomposition and write well
organised and well-structured algorithmic solutions.

At the end of the day, the OCR Exam Reference Language is not a real language and as such
can be considered to be pseudocode.

Using OCR’s ERL as the basis for the construction of example algorithms in this workbook, provides
consistency when demonstrating logical solutions.

Depending on the exam board being studied and how teachers wish to use this workbook,
getting students to follow the provided syntax ‘verbatim’, is not necessarily important.

Computer Science UK Membership Site Licence: Do not share outside of your centre 4
Licenced to: mhighmore@shsg.org. Downloaded: January 24, 2024
ComputerScienceUK.com CSUK:Teacher

Outputs, Inputs and 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)

Computer Science UK Membership Site Licence: Do not share outside of your centre 5
Licenced to: mhighmore@shsg.org. Downloaded: January 24, 2024
ComputerScienceUK.com CSUK:Teacher

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

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

Computer Science UK Membership Site Licence: Do not share outside of your centre 6
Licenced to: mhighmore@shsg.org. Downloaded: January 24, 2024
ComputerScienceUK.com CSUK:Teacher

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
Variable assigned to input asking them to enter star sign and waits for input
statement to store user’s input

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


print(“Your star sign has been recorded as ” + star_sign)

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 their favourite colour, then
outputs the sentence “Your favourite
colour is *colour*” (where *colour* is
the inputted string).

Question 2 Algorithm
Write an algorithm that asks the user to
enter their first name, middle name
and surname, stores each input in
separate variables, then outputs the
user’s full name.

Question 3 Algorithm
Write an algorithm that asks the user to
enter their house name/number, street
name, town and postcode, then
outputs the user’s full address back to
the screen.

Computer Science UK Membership Site Licence: Do not share outside of your centre 7
Licenced to: mhighmore@shsg.org. Downloaded: January 24, 2024
ComputerScienceUK.com CSUK:Teacher

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)

Computer Science UK Membership Site Licence: Do not share outside of your centre 8
Licenced to: mhighmore@shsg.org. Downloaded: January 24, 2024
ComputerScienceUK.com CSUK:Teacher

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.

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

Computer Science UK Membership Site Licence: Do not share outside of your centre 9
Licenced to: mhighmore@shsg.org. Downloaded: January 24, 2024
ComputerScienceUK.com CSUK:Teacher

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


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

Computer Science UK Membership Site Licence: Do not share outside of your centre 10
Licenced to: mhighmore@shsg.org. Downloaded: January 24, 2024
ComputerScienceUK.com CSUK:Teacher

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


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

Question 1 Algorithm
Write an algorithm that requests a
number from the user and outputs its
square.

Question 2 Algorithm
Write an algorithm that will ask the user
to enter their weekly pocket money,
their weekly spend on their phone,
their weekly spend on snacks and then
outputs the money that they have left.

Question 3 Algorithm
Write an algorithm that will ask the user
for two numbers and will then output a
random number within the range of
the two inputted values.

Computer Science UK Membership Site Licence: Do not share outside of your centre 11
Licenced to: mhighmore@shsg.org. Downloaded: January 24, 2024
ComputerScienceUK.com CSUK:Teacher

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.

Computer Science UK Membership Site Licence: Do not share outside of your centre 12
Licenced to: mhighmore@shsg.org. Downloaded: January 24, 2024
ComputerScienceUK.com CSUK:Teacher

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

Computer Science UK Membership Site Licence: Do not share outside of your centre 13
Licenced to: mhighmore@shsg.org. Downloaded: January 24, 2024
ComputerScienceUK.com CSUK:Teacher

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

number1 = input(“Enter a number: ”)


number2 = input(“Enter another number: ”)
number1 = int(number1)
number2 = int(number2)
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

Computer Science UK Membership Site Licence: Do not share outside of your centre 14
Licenced to: mhighmore@shsg.org. Downloaded: January 24, 2024
ComputerScienceUK.com CSUK:Teacher

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 Input statements displays a message to user
statement to store user’s input asking them to enter a number
The data inside number is
The casted data (now of of string data type when
type integer) is reassigned to inputted and so the int()
the variable ‘number’. number = input(“Enter a number: ”) function casts value to an
integer type
number = int(number)
An if-then-else statement is used
to first check if inputted number
if number > 0 then Message to be outputted if
is greater than zero… print(str(number) + “ is greater than zero”) number is greater than zero…

…then check if inputted number


elseif number < 0 then …message to be outputted if
is less than zero… print(str(number) + “ is less than zero”) number is less than zero…

…with else to capture the


else …message to be outputted if
scenario when number is neither print("The numbers you entered is zero") number is neither greater than or
greater than or less than zero. endif less than zero.

Question 1 Algorithm
Write an algorithm that will ask the user
to enter their age. If the entered age is
less than 67, the message “You cannot
retire yet” is outputted, else the
message “Happy retirement!” is
outputted.

Question 2 Algorithm
Write an algorithm that will ask the user
if they are feeling ok. If the user enters
‘yes’, the message ‘glad to hear it’ is
outputted. If the user enters ‘no’, the
message ‘sorry to hear that’ is
outputted. If neither ‘yes’ or ‘no’ is
inputted, an appropriate error
message is outputted.

Question 3 Algorithm
Write an algorithm that asks the user to
enter a number. If the number is even,
it will output a message stating this
fact. Else it will output a message
stating that the inputted number is
odd.
Tip: x MOD 2 will divide x by 2, working out
only the remainder of the division.

Computer Science UK Membership Site Licence: Do not share outside of your centre 15
Licenced to: mhighmore@shsg.org. Downloaded: January 24, 2024
ComputerScienceUK.com CSUK:Teacher

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

Computer Science UK Membership Site Licence: Do not share outside of your centre 16
Licenced to: mhighmore@shsg.org. Downloaded: January 24, 2024
ComputerScienceUK.com CSUK:Teacher

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 from 1 to 3, and output one of three facts, depending on the number entered.

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

Computer Science UK Membership Site Licence: Do not share outside of your centre 17
Licenced to: mhighmore@shsg.org. Downloaded: January 24, 2024
ComputerScienceUK.com CSUK:Teacher

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
Variable assigned to input
message to user asking them to
statement, to store user’s input
A switch statement is setup enter one word from three
with variable dev as the
conditional. dev = input(“designer, frontend or backend? ”)
switch dev:
In the case of dev
case “designer”:
containing ‘designer’, print(“Learn CSS”)
the message ‘Learn
case “frontend”: If the user fails to
CSS’ will be displayed… enter either
print(“Learn JavaScript”) ‘designer’, ‘fronted’
…in the case of dev case “backend”: or ‘backend’, then
containing ‘frontend’
print(“Learn PHP”) an error message
the message ‘Learn
will be displayed.
JavaScript’ will be default:
displayed…
print(“You didn’t enter correctly!”)
…in the case of dev endswitch
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.

Computer Science UK Membership Site Licence: Do not share outside of your centre 18
Licenced to: mhighmore@shsg.org. Downloaded: January 24, 2024
ComputerScienceUK.com CSUK:Teacher

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

for … to … step … “I’m Iterating” will be outputted 20 times, i.e. 0-19


next … inclusive.

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
print(“This is loop number ” + i) This is loop number 4
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

Computer Science UK Membership Site Licence: Do not share outside of your centre 19
Licenced to: mhighmore@shsg.org. Downloaded: January 24, 2024
ComputerScienceUK.com CSUK:Teacher

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
print(“This is loop number ” + i) This is loop number 8
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
for i=10 to 0 step -1 This is loop number 8
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

Computer Science UK Membership Site Licence: Do not share outside of your centre 20
Licenced to: mhighmore@shsg.org. Downloaded: January 24, 2024
ComputerScienceUK.com CSUK:Teacher

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

Computer Science UK Membership Site Licence: Do not share outside of your centre 21
Licenced to: mhighmore@shsg.org. Downloaded: January 24, 2024
ComputerScienceUK.com CSUK:Teacher

Practice Questions – FOR Loops


Worked Example

Write an algorithm, using a for loop, that will output the 10 times table.
A for loop is started with the stepper During each iteration, a print statement outputs:
variable 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).

Computer Science UK Membership Site Licence: Do not share outside of your centre 22
Licenced to: mhighmore@shsg.org. Downloaded: January 24, 2024
ComputerScienceUK.com CSUK:Teacher

Iterations 2 (Condition Controlled (WHILE LOOP))

Quick Reference

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.

Computer Science UK Membership Site Licence: Do not share outside of your centre 23
Licenced to: mhighmore@shsg.org. Downloaded: January 24, 2024
ComputerScienceUK.com CSUK:Teacher

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:

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.

Computer Science UK Membership Site Licence: Do not share outside of your centre 24
Licenced to: mhighmore@shsg.org. Downloaded: January 24, 2024
ComputerScienceUK.com CSUK:Teacher

Here is a final solution to the question:

x = 10
while x != 0
print(x)
x = x - 1
endwhile
print(“Blast Off!”)

Computer Science UK Membership Site Licence: Do not share outside of your centre 25
Licenced to: mhighmore@shsg.org. Downloaded: January 24, 2024
ComputerScienceUK.com CSUK:Teacher

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 2. The string “multiplied by 10 is ”, joined with…
the condition x != 11.
x = 1 3. The result of the counter variable multiplied by 10, cast as a string.

Therefore, all the while x while x != 11 Then, the value of counter variable x is reduced by 1.
doesn’t 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 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 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.

Computer Science UK Membership Site Licence: Do not share outside of your centre 26
Licenced to: mhighmore@shsg.org. Downloaded: January 24, 2024
ComputerScienceUK.com CSUK:Teacher

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.

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.

Computer Science UK Membership Site Licence: Do not share outside of your centre 27
Licenced to: mhighmore@shsg.org. Downloaded: January 24, 2024
ComputerScienceUK.com CSUK:Teacher

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
do
x = x – 1
until x == 0

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.

Computer Science UK Membership Site Licence: Do not share outside of your centre 28
Licenced to: mhighmore@shsg.org. Downloaded: January 24, 2024
ComputerScienceUK.com CSUK:Teacher

Here is a final solution to the question:

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

Computer Science UK Membership Site Licence: Do not share outside of your centre 29
Licenced to: mhighmore@shsg.org. Downloaded: January 24, 2024
ComputerScienceUK.com CSUK:Teacher

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, do Then, the value of counter variable x is reduced by 1.


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

Computer Science UK Membership Site Licence: Do not share outside of your centre 30
Licenced to: mhighmore@shsg.org. Downloaded: January 24, 2024
ComputerScienceUK.com CSUK:Teacher

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"

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)

Computer Science UK Membership Site Licence: Do not share outside of your centre 31
Licenced to: mhighmore@shsg.org. Downloaded: January 24, 2024
ComputerScienceUK.com CSUK:Teacher

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) ceUK
print(subStr)

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)

Computer Science UK Membership Site Licence: Do not share outside of your centre 32
Licenced to: mhighmore@shsg.org. Downloaded: January 24, 2024
ComputerScienceUK.com CSUK:Teacher

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)

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)

Computer Science UK Membership Site Licence: Do not share outside of your centre 33
Licenced to: mhighmore@shsg.org. Downloaded: January 24, 2024
ComputerScienceUK.com CSUK:Teacher

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


for i = 0 to string.length
… … … … … … …
next i

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.

Computer Science UK Membership Site Licence: Do not share outside of your centre 34
Licenced to: mhighmore@shsg.org. Downloaded: January 24, 2024
ComputerScienceUK.com CSUK:Teacher

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.

x = “I Love CS” The first 4 characters are


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

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

Computer Science UK Membership Site Licence: Do not share outside of your centre 35
Licenced to: mhighmore@shsg.org. Downloaded: January 24, 2024
ComputerScienceUK.com CSUK:Teacher

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.

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.

Computer Science UK Membership Site Licence: Do not share outside of your centre 36
Licenced to: mhighmore@shsg.org. Downloaded: January 24, 2024
ComputerScienceUK.com CSUK:Teacher

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

#main x = 3 * 5 x = 3 * 5
#main
print(x) return x

proc_123() endprocedure endfunction


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

Computer Science UK Membership Site Licence: Do not share outside of your centre 37
Licenced to: mhighmore@shsg.org. Downloaded: January 24, 2024
ComputerScienceUK.com CSUK:Teacher

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

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

Computer Science UK Membership Site Licence: Do not share outside of your centre 38
Licenced to: mhighmore@shsg.org. Downloaded: January 24, 2024
ComputerScienceUK.com CSUK:Teacher

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)
return word.length
endfunction

Computer Science UK Membership Site Licence: Do not share outside of your centre 39
Licenced to: mhighmore@shsg.org. Downloaded: January 24, 2024
ComputerScienceUK.com CSUK:Teacher

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.

Computer Science UK Membership Site Licence: Do not share outside of your centre 40
Licenced to: mhighmore@shsg.org. Downloaded: January 24, 2024
ComputerScienceUK.com CSUK:Teacher

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 The function squares the
return number*number received parameter and
structure is
completed returns the result
endfunction
The function call is assigned
the variable ‘answer’ to store As requested, the
the returned value. algorithm also contains
answer = square(5) the function call, 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’.

Computer Science UK Membership Site Licence: Do not share outside of your centre 41
Licenced to: mhighmore@shsg.org. Downloaded: January 24, 2024
ComputerScienceUK.com CSUK:Teacher

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.

Computer Science UK Membership Site Licence: Do not share outside of your centre 42
Licenced to: mhighmore@shsg.org. Downloaded: January 24, 2024
ComputerScienceUK.com CSUK:Teacher

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]

Computer Science UK Membership Site Licence: Do not share outside of your centre 43
Licenced to: mhighmore@shsg.org. Downloaded: January 24, 2024
ComputerScienceUK.com CSUK:Teacher

In these examples:

- The one-dimension array will store 3 items (indexed 0–2).


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

Computer Science UK Membership Site Licence: Do not share outside of your centre 44
Licenced to: mhighmore@shsg.org. Downloaded: January 24, 2024
ComputerScienceUK.com CSUK:Teacher

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
rabbit gerbil guinea pig

Using a loop, output each animal contained inside the 3rd sub array.

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 3rd 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

Computer Science UK Membership Site Licence: Do not share outside of your centre 45
Licenced to: mhighmore@shsg.org. Downloaded: January 24, 2024
ComputerScienceUK.com CSUK:Teacher

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 for i = 0 to 4
to enter a string, which is stored
in a variable called ‘string’.
string = input(“Enter a string: ”)
userStrings[i] = string Each inputted string is assigned to the
Stepper variable is then array, in the position/index which reflects
incremented by 1. the stepper value i in the loop.
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.

Computer Science UK Membership Site Licence: Do not share outside of your centre 46
Licenced to: mhighmore@shsg.org. Downloaded: January 24, 2024
ComputerScienceUK.com CSUK:Teacher

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

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.

Computer Science UK Membership Site Licence: Do not share outside of your centre 47
Licenced to: mhighmore@shsg.org. Downloaded: January 24, 2024
ComputerScienceUK.com CSUK:Teacher

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 This is line one
text, and have 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 This is the last line!
of the 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.

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

Computer Science UK Membership Site Licence: Do not share outside of your centre 48
Licenced to: mhighmore@shsg.org. Downloaded: January 24, 2024
ComputerScienceUK.com CSUK:Teacher

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

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

Computer Science UK Membership Site Licence: Do not share outside of your centre 49
Licenced to: mhighmore@shsg.org. Downloaded: January 24, 2024
ComputerScienceUK.com CSUK:Teacher

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)

Computer Science UK Membership Site Licence: Do not share outside of your centre 50
Licenced to: mhighmore@shsg.org. Downloaded: January 24, 2024
ComputerScienceUK.com CSUK:Teacher

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

Computer Science UK Membership Site Licence: Do not share outside of your centre 51
Licenced to: mhighmore@shsg.org. Downloaded: January 24, 2024
ComputerScienceUK.com CSUK:Teacher

Practice Questions – File Handling


Worked Example

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 myFileHandler = open(“top5Films.txt”)
of the file.
Within the loop, each line
while NOT myFileHandler.endOfFile() of the file is outputted, one
line at a time.
This identifies the end print(myFileHandler.readLine())
of 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.

Computer Science UK Membership Site Licence: Do not share outside of your centre 52
Licenced to: mhighmore@shsg.org. Downloaded: January 24, 2024
ComputerScienceUK.com CSUK:Teacher

Mixed Questions

Question 1 Algorithm
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.

Computer Science UK Membership Site Licence: Do not share outside of your centre 53
Licenced to: mhighmore@shsg.org. Downloaded: January 24, 2024
ComputerScienceUK.com CSUK:Teacher

Question 4 Algorithm
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.

Computer Science UK Membership Site Licence: Do not share outside of your centre 54
Licenced to: mhighmore@shsg.org. Downloaded: January 24, 2024
ComputerScienceUK.com CSUK:Teacher

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.

Computer Science UK Membership Site Licence: Do not share outside of your centre 55
Licenced to: mhighmore@shsg.org. Downloaded: January 24, 2024
ComputerScienceUK.com CSUK:Teacher

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.

Computer Science UK Membership Site Licence: Do not share outside of your centre 56
Licenced to: mhighmore@shsg.org. Downloaded: January 24, 2024
ComputerScienceUK.com CSUK:Teacher

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.

Computer Science UK Membership Site Licence: Do not share outside of your centre 57
Licenced to: mhighmore@shsg.org. Downloaded: January 24, 2024
ComputerScienceUK.com CSUK:Teacher

Answers

Outputs, Inputs and Variables – Answers

Question 1 Algorithm
Write an algorithm that asks the user to
enter their favourite colour, then colour = input(“Enter your favourite colour: ”)
outputs the sentence “Your favourite print(“Your favourite colour is ” + colour)
colour is *colour*” (where *colour* is
the inputted string).

Question 2 Algorithm
Write an algorithm that asks the user to
enter their first name, middle name firstName = input(“Enter your first name: ”)
and surname, stores each input in middleName = input(“Enter your middle name: ”)
surname = input(“Enter your surname: ”)
separate variables, then outputs the
print(firstName + “ ” + middleName + “ ” + surname)
user’s full name.

Question 3 Algorithm
Write an algorithm that asks the user to
enter their house name/number, street house = input(“Enter your house name / number: ”)
street = input(“Enter your street: ”)
name, town and postcode, then
town = input(“Enter your town: ”)
outputs the user’s full address back to postCode = input(“Enter your post code: ”)
the screen. print(house)
print(street)
print(town)
print(postCode)

Computer Science UK Membership Site Licence: Do not share outside of your centre 58
Licenced to: mhighmore@shsg.org. Downloaded: January 24, 2024
ComputerScienceUK.com CSUK:Teacher

Casting, Random Numbers and Maths - Answers

Question 1 Algorithm
Write an algorithm that requests a
number from the user and outputs its number = input(“Enter a number to be squared: ”)
square. number = int(number)
print(number * number)

Question 2 Algorithm
Write an algorithm that will ask the user
to enter their weekly pocket money, pmoney = int(input(“Enter weekly pocket money: ”))
phone = int(input(“Enter weekly phone spend: ”))
their weekly spend on their phone,
snack = int(input(“Enter weekly snack spend: ”))
their weekly spend on snacks and then result = pmoney – phone – snack
outputs the money that they have left. print(result)

Question 3 Algorithm
Write an algorithm that will ask the user
for two numbers and will then output a number1 = input(“Enter first number: ”)
number2 = input(“Enter second number: ”)
random number within the range of
number1 = int(number1)
the two inputted values. number2 = int(number2)
randomNumber = random(number1,number2)
print(randomNumber)

Computer Science UK Membership Site Licence: Do not share outside of your centre 59
Licenced to: mhighmore@shsg.org. Downloaded: January 24, 2024
ComputerScienceUK.com CSUK:Teacher

if-then-else Statements - Answers

Question 1 Algorithm
Write an algorithm that will ask the user age = input(“Enter your age: ”)
to enter their age. If the entered age is age = int(age)
less than 67, the message “You cannot if age < 67 then
retire yet” is outputted, else the print(“You cannot retire yet”)
message “Happy retirement!” is else
outputted. print("Happy retirement!")
endif

Question 2 Algorithm
Write an algorithm that will ask the user feeling = input(“Are you feeling ok? ”)
if they are feeling ok. If the user enters if feeling == ‘yes’ then
‘yes’, the message ‘glad to hear it’ is print(“Glad to hear it”)
outputted. If the user enters ‘no’, the elseif feeling == ‘no’ then
message ‘sorry to hear that’ is print(“Sorry to hear that”)
outputted. If neither ‘yes’ or ‘no’ is else
inputted, an appropriate error print("You didn’t enter ‘yes’ or ‘no’")
message is outputted. endif

Question 3 Algorithm
Write an algorithm that asks the user to number = input(“Enter a number: ”)
enter a number. If the number is even, number = int(number)
it will output a message stating this if (number MOD 2) == 0 then
fact. Else it will output a message print(“The number entered is even”)
stating that the inputted number is else
odd. print("The number entered is odd")
Tip: x MOD 2 will divide x by 2, working out endif
only the remainder of the division.

Computer Science UK Membership Site Licence: Do not share outside of your centre 60
Licenced to: mhighmore@shsg.org. Downloaded: January 24, 2024
ComputerScienceUK.com CSUK:Teacher

Case Select / Switch Statements - Answers

Question 1 Algorithm
Write an algorithm, using a case select
/ switch statement, that will ask the answer = input(“Do you like programming? ”)
switch answer:
user if they like programming. The
case “yes”:
program will output the message print(“Great news!”)
“Great news!” if they enter ‘yes’, and case “no”:
output the message “You probably print(“You probably need more practice then”)
need more practice then!”, if they default:
enter ‘no’. A default case will execute print(“You didn’t enter ‘yes’ or ‘no’!”)
if neither ‘yes’ or ‘no’ is entered. endswitch

Question 2 Algorithm
Write an algorithm, using a case select
/ switch statement, that will generate a number = random(1,3)
switch number:
random number from 1-3, and output
case 1:
“Yes” (if 1 is generated), “No” (if 2 is print(“Yes”)
generated) or “Maybe” (if 3 is case 2:
generated). The program’s aim is to print(“No”)
mimic a Magic-8-Ball, but with fewer case 3:
statements. print(“Maybe”)
endswitch

Question 3 Algorithm
Write an algorithm, using a case select
/ switch statement, that will ask the number = input(“Enter a number”)
number = int(number)
user to enter a number and will
remainder = number MOD 2
respond by stating if the inputted
number was even or odd. switch remainder:
case 0:
Tip: x MOD 2 will divide x by 2, working out print(“Your number is even”)
only the remainder of the division. default:
print(“Your number is odd”)
endswitch

Computer Science UK Membership Site Licence: Do not share outside of your centre 61
Licenced to: mhighmore@shsg.org. Downloaded: January 24, 2024
ComputerScienceUK.com CSUK:Teacher

FOR Loops - Answers

Question 1 Algorithm
Write an algorithm with a for loop that
will output the numbers from 1 to 100 for i=1 to 100
inclusive. print(i)
next i

Question 2 Algorithm
Write an algorithm with a for loop that
will output only the even numbers from for i=2 to 100 step 2
1-100 inclusive. print(i)
next i

Question 3 Algorithm
Write an algorithm with a for loop that number = input(“Enter a timestable number: ”)
number = int(number)
will ask the user which multiplications
table they want to be displayed (by for i=1 to 10
print(str(number) + “X” + str(i) + “=” + str(i*number))
requesting that an integer is entered) next i
and outputs the requested
multiplications table in the form of:
5x1=5
5 x 2 = 10 …etc (if 5 were the inputted
value).

Computer Science UK Membership Site Licence: Do not share outside of your centre 62
Licenced to: mhighmore@shsg.org. Downloaded: January 24, 2024
ComputerScienceUK.com CSUK:Teacher

WHILE Loops - Answers

Question 1 Algorithm
Write an algorithm with a while loop password = input(“Enter password: ”)
that will repeatedly ask the user to
enter a password, and will only stop while password != “pa55w0rd”
when the password pa55w0rd is print(“Incorrect, try again.”)
entered. password = input(“Enter password: ”)
endwhile

print(“Access Granted”)

Question 2 Algorithm
Write an algorithm with a while loop number = input(“Enter a number: ”)
that will continually ask the user to number = int(number)
enter a number and will only stop
when they enter the number 10. while number != 10
number = input(“Enter a number: ”)
number = int(number)
endwhile

Question 3 Algorithm
Write an algorithm with a while loop number = input(“Enter a number: ”)
that will repeatedly ask the user to number = int(number)
enter a number and will only stop
when the number they enter is even. while (number MOD 2) != 0
number = input(“Enter a number: ”)
Tip: x MOD 2 will divide x by 2, working out number = int(number)
only the remainder of the division. endwhile

Computer Science UK Membership Site Licence: Do not share outside of your centre 63
Licenced to: mhighmore@shsg.org. Downloaded: January 24, 2024
ComputerScienceUK.com CSUK:Teacher

DO UNTIL Loops - Answers

Question 1 Algorithm
Write an algorithm with a do-until loop
that will repeatedly ask the user to number = 0
enter a number and will only stop do
when the user enters the integer 5. number = input(“Enter a number: ”)
number = int(number)
until number == 5

Question 2 Algorithm
Write an algorithm with a do-until loop
that will output all numbers from 1 to number = 1
100, and then stop. do
print(number)
number = number + 1
until number == 101

Question 3 Algorithm
Write an algorithm with a do-until loop
that will repeatedly ask the user to do
enter a password, and will only stop password = input(“Enter password: ”)
when the password pa55w0rd is until password == “pa55w0rd”
entered.
print(“Access Granted”)

Computer Science UK Membership Site Licence: Do not share outside of your centre 64
Licenced to: mhighmore@shsg.org. Downloaded: January 24, 2024
ComputerScienceUK.com CSUK:Teacher

String Manipulation Methods - Answers

Question 1 Algorithm
Write an algorithm that will ask the user
to enter a word and output the word = input(“Enter a word: ”)
inputted word with all characters in newStr = word.upper
uppercase. print(newStr)

Question 2 Algorithm
Write an algorithm that will ask the user
to enter their name and output a name = input(“Enter your name: ”)
resulting username consisting of the username = name.left(2) + “1234”
first 2 letters of the inputted name and print(username)
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 word = input(“Enter a word: ”)
character of the word on separate
lines. for i = 0 to (word.length – 1)
print(word[i])
next i

Computer Science UK Membership Site Licence: Do not share outside of your centre 65
Licenced to: mhighmore@shsg.org. Downloaded: January 24, 2024
ComputerScienceUK.com CSUK:Teacher

Subroutines - Answers

Question 1 Algorithm
Write a procedure that receives a
parameter containing an integer, and procedure posOrNeg(number)
outputs one of two messages. If the if number >= 0 then
received value is positive (zero or print(“positive”)
greater), the message ‘positive’ is else
outputted, otherwise the message print(“negative”)
‘negative’ is outputted. endif
endprocedure

Question 2 Algorithm
Write a function (including the function
call) that receives a parameter function firstChar(word)
containing a string and returns only the return word.left(1)
first character of the received string. endfunction

character = firstChar(“Some String”)

Question 3 Algorithm
Write a function (including the function function containZ(word)
call) that receives a parameter message = “Does not contain the letter ‘z’”
containing a string and returns for i = 0 to (word.length – 1)
“Contains the letter ‘z’” if the string if word[i] == “Z” then
contains a ‘z’, but returns “Does not message = “Contains the letter ‘z’”
contain the letter ‘z’” if the string does endif
not contain a ‘z’. next i
return message
endfunction

character = containZ(“Zebra”)

Computer Science UK Membership Site Licence: Do not share outside of your centre 66
Licenced to: mhighmore@shsg.org. Downloaded: January 24, 2024
ComputerScienceUK.com CSUK:Teacher

Arrays - Answers

Question 1 Algorithm
Write an algorithm that will declare a
animals = [“cow”, “pig”, “sheep”, “elephant”, “zebra”]
one-dimensional array, prepopulated
with the names of 5 animals. Then use for i = 0 to (animals.length – 1)
a loop to output each item of the list. print(animals[i])
next i

Question 2 Algorithm
Write an algorithm that will declare a
two-dimensional array, prepopulated letters = [[“a”,“b”,“c”,“d”,“e”], [“z”,“y”,“x”,“w”,“v”]]
with 10 letters (5 in each subarray) and for i = 0 to (letters.length – 1)
then output the 3rd letter in each print(letters[i,2])
subarray. next i

Question 3 Algorithm
Write an algorithm that will declare an
empty two-dimensional array array userFilms[5,5]
containing 5 sub-arrays, each with 5 for i = 0 to (userFilms.length – 1)
elements, then allow the user to for j = 0 to (userFilms[i].length – 1)
populate the subarrays with film film = input(“Enter a film: ”)
names. userFilms[i,j] = film
next j
next i

Computer Science UK Membership Site Licence: Do not share outside of your centre 67
Licenced to: mhighmore@shsg.org. Downloaded: January 24, 2024
ComputerScienceUK.com CSUK:Teacher

File Handling - Answers

Question 1 Algorithm
Write an algorithm that will create a
text file called ‘myFile.txt’, open the newFile(“myFile.txt”)
file, then write the string ‘This is the first myFileHandler = open(“myFile.txt”)
line’ to the text file, before closing it. myFileHandler.writeLine(“This is the first line”)
myFileHandler.close()

Question 2 Algorithm
Write an algorithm that will open a text
file called ‘HighScore.txt’ (which myFileHandler = open(“HighScore.txt”)
contains a list of high scores in print(myFileHandler.readLine())
descending order) and output the top myFileHandler.close()
score (first line).

Question 3 Algorithm
Write an algorithm that will open a text
file called “examFeedback.txt”, read myFileHandler = open(“examFeedback.txt”)
and output the entire contents of the while NOT myFileHandler.endOfFile()
text file, then ask the user to enter a print(myFileHandler.readLine())
comment and write this to the end of endwhile
the file, before closing it. comment = input(“Enter your comment”)
myFileHandler.writeLine(comment)
myFileHandler.close()

Computer Science UK Membership Site Licence: Do not share outside of your centre 68
Licenced to: mhighmore@shsg.org. Downloaded: January 24, 2024
ComputerScienceUK.com CSUK:Teacher

Mixed Questions - Answers

Question 1 Algorithm
Write an algorithm that will ask the user
side1 = int(input(“Enter the first side’s length”))
to enter the lengths of a triangle’s 3 side2 = int(input(“Enter the second side’s length”))
sides and the output whether the side3 = int(input(“Enter the third side’s length”))
if (side1==side2) AND (side2==side3) AND (side1==side3) then
triangle is equilateral, isosceles or print(“Equilateral”)
scalene. elseif (side1==side2) OR (side2==side3) OR (side1==side3) then
print(“Isosceles”)
else
print(“Scalene”)
endif

Question 2 Algorithm
In a frisbee making factory, a worker
hours = int(input(“How many hours worked today? ”))
gets paid £10 per hour, plus £5 for frisbees = int(input(“How many frisbees made today? ”))
every frisbee made in addition to the hoursPay = hours * 10
if frisbees > 100 then
first 100. Write an algorithm that will frisbeePay = (frisbees – 100) * 5
accept the hours worked and frisbees pay = frisbeePay + hoursPay
print(pay)
made, for a given day and work out else
(and output) the worker’s pay for the print(hoursPay)
day. endif

Question 3 Algorithm
Write an algorithm that will declare the
array scores = [2,5,12,8,3,25,21,6]
following 1D array: total = 0

for i=0 to (scores.length – 1)


scores = [2,5,12,8,3,25,21,6] total = total + scores[i]
next i
…then add together each number print(total)
contained in the array and output the
result.

Computer Science UK Membership Site Licence: Do not share outside of your centre 69
Licenced to: mhighmore@shsg.org. Downloaded: January 24, 2024
ComputerScienceUK.com CSUK:Teacher

Question 4 Algorithm
Write an algorithm that will ask the user
numberOfIntegers = int(input(“How many integers will you enter?”))
how many integers they wish to enter, total = 0
then allow the user to enter the
for i=1 to numberOfIntegers
integers and output the mean of the number = int(input(“Enter a number: ”))
entered integers. total = total + number
next i

mean = total / numberOfIntegers

print(mean)

Question 5 Algorithm
A user wishes to add a series of names
numberOfNames = int(input(“How many integers will you enter?”))
to a text file. Write an algorithm that
will ask the user how many names they newFile(“myFile.txt”)
myFileHandler = open(“myFile.txt”)
wish to enter, then ask the user to enter
these names, writing each one to a for i=1 to numberOfNames
name = input(“Enter a name: ”)
text file. myFileHandler.writeLine(name)
next i

myFileHandler.close()

Question 6 Algorithm
Write an algorithm that first declares
array points = [[2,5,12,8],[3,25,21,6]]
the following 2D array: teamA = 0
points = [[2,5,12,8],[3,25,21,6]] teamB = 0
The array contains the points scored by for i=0 to (points.length – 1)
Team A (first subarray) and Team B for j=0 to (points[i].length – 1)
(second subarray). if i == 0 then
teamA = teamA + points[i,j]
The algorithm is to calculate and elseif i == 1 then
output the points total of each team teamB = teamB + points[i,j]
and state which team won. endif
next j
next i

if teamA > teamB then


print(“Team A Won!”)
elseif teamA < teamB then
print(“Team B Won!”)
else
print(“It was a draw!”)
endif

Computer Science UK Membership Site Licence: Do not share outside of your centre 70
Licenced to: mhighmore@shsg.org. Downloaded: January 24, 2024
ComputerScienceUK.com CSUK:Teacher

Question 7 Algorithm
Write an algorithm that will ask the user
function cubeMe(n)
to enter a number and store it in a return n*n*n
variable. Then, this value is to be endfunction

passed to a function that will cube the number = int(input(“Enter a number: ”))
input and return it back to the main result = cubeMe(number)
print(result)
program for outputting.

Question 8 Algorithm
A text file, contains a list of test results,
total = 0
with each result on its own line of the lineCount = 0
file. myFileHandler = open(“testResults.txt”)
Write an algorithm that will open and while NOT myFileHandler.endOfFile()
read the text file, calculating the total = total + int(myFileHandler.readLine())
lineCount = lineCount + 1
mean of these test results. endwhile
The algorithm will complete by
outputting the calculated mean. mean = total / lineCount
print(mean)

Question 9 Algorithm
Write an algorithm that will first pick a
number = random(1,100)
number between 1 and 100, then ask guess = 0
the user to guess the number. Each
while number != guess
time the user guesses, the algorithm will guess = int(input(“Enter your guess”))
inform the user whether or not their if guess < number then
print(“Your guess was too low!”)
guess was higher or lower than the elseif guess > number then
chosen number, until they guess print(“Your guess was too high!”)
correctly. else
print(“You guessed correctly!”)

Computer Science UK Membership Site Licence: Do not share outside of your centre 71
Licenced to: mhighmore@shsg.org. Downloaded: January 24, 2024
ComputerScienceUK.com CSUK:Teacher

Question 10 Algorithm
Write an algorithm that will ask the user
word = input(“Enter a word: ”)
to enter a word, convert it to lower word = word.lower
case and encrypt the word using a
array newWord[word.length]
Caesar Cipher with a left shift of 1. The
encrypted word will be outputted for i=0 to (word.length – 1)
asciiCode = ASC(word[i])
following the encryption. if asciiCode == 97 then
asciiCode = 122
else
asciiCode = asciiCode – 1
newWord[i] = CHR(asciiCode)
next i

for i=0 to (newWord.length – 1)


print(newWord[i])
next i

Question 11 Algorithm
Write an algorithm that will ask the user
password = input(“Enter a password: ”)
to enter a password between 6 and 12
characters long. The algorithm will while (password.length > 12) OR (password.length < 6) then
print(“Incorrect length! Try again!”)
reject passwords with lengths outside password = input(“Enter a password: ”)
of this character range and request endwhile
the password again. A suitable print(“Password Accepted!”)
message will be displayed when an
acceptable password is entered.

Question 12 Algorithm
Write an algorithm that will ask the user
procedure future(year)
to enter a year (e.g. 2022), pass this year = year + 100
year to a procedure, that will output print(year)
endprocedure
what the year will be in 100 years’
time. year = int(input(“Enter a year: ”))
future(year)

Computer Science UK Membership Site Licence: Do not share outside of your centre 72
Licenced to: mhighmore@shsg.org. Downloaded: January 24, 2024
ComputerScienceUK.com CSUK:Teacher

Question 13 Algorithm
Write an algorithm that will accept
function findASCII(char)
only a single character, pass the chrCode = ASC(char)
character to a function, which will return chrCode
endfunction
convert the character to its equivalent
ASCII code, returning the code back character = input(“Enter a character: ”)
to the main program for outputting. while (character.length > 1)
print(“You didn’t enter a single character! Try again!”)
character = input(“Enter a character: ”)
endwhile

code = findASCII(character)
print(code)

Question 14 Algorithm
Write a procedure that will receive a
procedure traversal2D(arr)
two-dimensional array, traverse the for i = 0 to (arr.length – 1)
array, outputting each item that it for j = 0 to (arr[i].length – 1)
print(arr[i,j])
finds, one after the other. next j
next i
endprocedure

traversal2D(arr)

Computer Science UK Membership Site Licence: Do not share outside of your centre 73

You might also like