Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
0% found this document useful (0 votes)
44 views

igcse_compsci_2ed_python_sol

The document is a programming book for Cambridge IGCSE™ & O Level Computer Science, covering topics such as Python programming, variables, arithmetic operators, algorithm design, and GUI applications. It includes practice tasks, challenge tasks, and end-of-chapter tasks with sample code and pseudocode solutions. The book emphasizes the importance of using correct identifiers in pseudocode and provides guidance on assessment preparation and algorithm design tools.

Uploaded by

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

igcse_compsci_2ed_python_sol

The document is a programming book for Cambridge IGCSE™ & O Level Computer Science, covering topics such as Python programming, variables, arithmetic operators, algorithm design, and GUI applications. It includes practice tasks, challenge tasks, and end-of-chapter tasks with sample code and pseudocode solutions. The book emphasizes the importance of using correct identifiers in pseudocode and provides guidance on assessment preparation and algorithm design tools.

Uploaded by

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

CAMBRIDGE IGCSE™ & O LEVEL COMPUTER SCIENCE: PROGRAMMING BOOK

Sample answers have been written by the authors. In examinations, the way marks are awarded may be different. References to
assessment and/or assessment preparation are the publisher’s interpretation of the syllabus requirements and may not fully reflect
the approach of Cambridge Assessment International Education.
A note about identifiers in pseudocode: The identifiers, which include variable, procedure and function names, given in exam
questions will be in mixed upper case, for example, NumberOfPlayers. When using pseudocode to answer questions you must
use the exact same variable name for any variables given in the question. When you are creating your own variable names in your
pseudocode answers, it is quite normal to use the syntax that is used in your preferred programming language, for example in
Python, number_of_players. You must ensure that your algorithm is correct and unambiguous and that the identifiers chosen are
consistent throughout your solution.

Solutions
Chapter 1: Python 3
Practice tasks
1.1 (Answer provided in text.)

1.2 (Answer provided in text.)

1.3 (Answer provided in text.)

Challenge tasks
1.1 # two_inputs.py
first = input('What is your first name? ')
last = input('What is your last name? ')
print('Hi', first, last)

1.2 # triangle.py
from turtle import *

forward(100)
right(120)
forward(100)
right(120)
forward(100)

1
CAMBRIDGE IGCSE™ & O LEVEL COMPUTER SCIENCE: PROGRAMMING BOOK

Skills focus questions


1.1 1 Lines 6 to 12 would look like this:
turtle.forward(100)
turtle.right(90)
turtle.forward(100)
turtle.right(90)
turtle.forward(100)
turtle.right(90)
turtle.forward(100)

End-of-chapter tasks
1 age = input('What is your age? ')
name = input('What is your name? ')
print('Hi ' + name + '. You are ' + age + '.')

2 from turtle import *

forward(100)
left(90)
forward(50)
left(45)
forward(70)
left(90)
forward(70)
left(45)
forward(50)
hideturtle()

3 from turtle import *

forward(100)
left(72)
forward(100)
left(72)
forward(100)
left(72)
forward(100)
left(72)
forward(100)

2
CAMBRIDGE IGCSE™ & O LEVEL COMPUTER SCIENCE: PROGRAMMING BOOK

Chapter 2: Variables and arithmetic operators


Practice tasks
2.1 c is a float data type.

2.2 # remainder_machine.py

# Request and store user input


number1 = int(input('Please insert first number: '))
number2 = int(input('Please insert second number: '))

remainder = number1 % number2

# Display the value held in the variable remainder


print('The answer is', remainder)

# End nicely by waiting for the user to press the return key.
input('\n\nPress RETURN to finish.')

2.3 # square.py
from turtle import *

# Request and store user input


d = int(input('Length of side of square: '))

forward(d)
right(90)
forward(d)
right(90)
forward(d)
right(90)
forward(d)

Challenge tasks
2.1 # sphere.py

# Request and store user input


diameter = int(input('Diameter of sphere: '))
r = diameter / 2

volume = (4 /3) * 3.1415 * r**3

# Display the value held in the variable volume


print('The volume of your sphere is', volume)

# End nicely by waiting for the user to press the return key.
input('\n\nPress RETURN to finish.')

3
CAMBRIDGE IGCSE™ & O LEVEL COMPUTER SCIENCE: PROGRAMMING BOOK

2.2 # grass_seed.py

# Request and store user input


length = int(input('Length of lawn: '))
width = int(input('Width of lawn: '))

seed_mass = length * width * 50

# Display the value held in the variable seed_mass


print('You need ' , seed_mass , 'g of grass seed.' )

# End nicely by waiting for the user to press the return key.
input('\n\nPress RETURN to finish.')

2.3 # hexagons.py
from turtle import *

# Request and store user input


d = int(input('Length of side of hexagon: '))

forward(d)
right(60)
forward(d)
right(60)
forward(d)
right(60)
forward(d)
right(60)
forward(d)
right(60)
forward(d)

End-of-chapter tasks
1 # dice.py
import random

# Get random number


my_random_number = random.randint(1,6)

# Output the random number


print(my_random_number)

2 # time.py
time24 = float (input('Provide the time in the form 18.25: '))
if time24 < 13.0:
print(time24) # The input is in the correct format
else:
print(round(time24 - 12, 2))

4
CAMBRIDGE IGCSE™ & O LEVEL COMPUTER SCIENCE: PROGRAMMING BOOK

3 a 
# triangle.py
from turtle import *

s = int(input('side length: '))

forward(s)
left(120)
forward(s)
left(120)
forward(s)

b 
# isosceles.py
from turtle import *

s = int(input('side length: '))


A = int(input('base angle: '))

left(180-A)
forward(s)
left(2*A)
forward(s)
right(180-A)
goto(0,0)

Chapter 3: Algorithm design tools


Practice tasks
3.1 a Logic flow arrows that point back to an earlier process in the algorithm.

b The diamond symbol is used to indicate selection.

c Logic flow arrows are used to show sequence within an algorithm.

3.2 3

5
CAMBRIDGE IGCSE™ & O LEVEL COMPUTER SCIENCE: PROGRAMMING BOOK

3.3
START

INPUT
number1
number2

answer ← number1 + number2

OUTPUT
answer

STOP

3.4 fullname  ''


INPUT firstname
INPUT lastname
fullname  firstname + lastname
OUTPUT fullname

Chapter 4: Subroutines
Practice tasks
4.1 a 11 b 11

4.2 # square.py
from turtle import *

def square(side_length):
forward(side_length)
right(90)
forward(side_length)
right(90)
forward(side_length)
right(90)
forward(side_length)

square(100)

6
CAMBRIDGE IGCSE™ & O LEVEL COMPUTER SCIENCE: PROGRAMMING BOOK

4.3 # number_squared.py

def number_squared(number):
return number * number

print(number_squared(2))

4.4 # highest_number.py

def highest(number1, number2):


if number1 > number2:
return number1
else:
return number2

print(highest(4, 2))

4.5 # password_number.py

def check_passcode(passcode):
if passcode > 999 and passcode <10000:
return 'PASS'
else:
return 'FAIL'

print(check_passcode(1413))

4.6 # circle.py

def circle_properties(radius):
circumference = 2 * 3.142 * radius
area = 3.142 * radius * radius

return circumference, area

c,a = circle_properties(50)
print('Circumference:', c, '\nArea:', a)

4.7 # global_name.py

name = 'Jon Jones'

def edit_name(new_name):
global name
name = new_name
return name

new = input('What is your correct name? ')


print(edit_name(new))

7
CAMBRIDGE IGCSE™ & O LEVEL COMPUTER SCIENCE: PROGRAMMING BOOK

4.8 a 
import turtle module

PROCEDURE draw_star
forward(50)
right(144)
forward(50)
right(144)
forward(50)
right(144)
forward(50)
right(144)
forward(50)
ENDPROCEDURE

CALL draw_star

b # star.py
from turtle import *

def draw_star():
forward(50)
fight(144)
forward(50)
right(144)
forward(50)
right(144)
forward(50)
right(144)
forward(50)

draw_star()

Challenge tasks
4.1 # flower.py
from turtle import *

circle(50)
right(72)
circle(50)
right(72)
circle(50)
right(72)
circle(50)
right(72)
circle(50)

8
CAMBRIDGE IGCSE™ & O LEVEL COMPUTER SCIENCE: PROGRAMMING BOOK

4.2 # circle2.py

def circle_properties(radius):
circumference = 2 * 3.142 * radius
area = 3.142 * radius * radius
return circumference, area

r = int(input('What is the radius of the circle? '))


c,a = circle_properties(r)
print('Circumference:', c, '\nArea:', a)

Skills focus questions


4.1 1 Global variable: player_score; Local variable: result

2 The function is going to change the value of the global variable so player_score must be
re-declared with the global keyword. This acts as a warning to the programmer that their
function is going to alter the value of a variable that is outside the scope of the function and
so that the programmer can be sure that this is what is intended.

3 The keyword global is not required if the function is just accessing the value of the variable
and not altering it.

End-of-chapter tasks
1 A pseudocode solution:

FUNCTION time
mins  seconds // 60
secs  seconds % 60
RETURN mins, secs
ENDFUNCTION

time_in_seconds  190
m,s  time(time_in_seconds)
OUTPUT m, s

A Python solution:

def time(seconds):
mins = seconds // 60
secs = seconds % 60
return mins, secs

time_in_seconds = 190
m,s = time(time_in_seconds)
print(m, 'minutes', s, 'seconds')

9
CAMBRIDGE IGCSE™ & O LEVEL COMPUTER SCIENCE: PROGRAMMING BOOK

2 A pseudocode solution:

FUNCTION to_mph(kph)
mph  kph / 1.60934
RETURN mph
ENDFUNCTION

speed_kph  80
OUTPUT to_mph(speed_kph)

A Python solution:

def to_mph(kph):
mph = kph / 1.60934
return mph

speed_kph = 80
print(to_mph(speed_kph))

3 A pseudocode solution:

import turtle module

PROCEDURE square
forward(100)
right(90)
forward(100)
right(90)
forward(100)
right(90)
forward(100)
right(90)
ENDPROCEDURE

CALL square
right(60)
CALL square
right(60)
CALL square
right(60)
CALL square
right(60)
CALL square
right(60)
CALL square

A Python solution:

from turtle import *

def square():
forward(100)

10
CAMBRIDGE IGCSE™ & O LEVEL COMPUTER SCIENCE: PROGRAMMING BOOK

right(90)
forward(100)
right(90)
forward(100)
right(90)
forward(100)
right(90)
square()
right(60)
square()
right(60)
square()
right(60)
square()
right(60)
square()
right(60)
square()

4 A pseudocode solution:

FUNCTION paint(height, width)


litres  (height * width) / 8
tins  ROUND UP litres / 5
return litres, tins
ENDFUNCTION

h  10
w  8.3
l,t  paint(h,w)
OUTPUT l, t

A Python solution:

from math import *

def paint(height, width):


litres = (height * width) / 8
tins = ceil(litres / 5)
return litres, tins

h = 10
w = 8.3
l,t = paint(h,w)
print('litres:', l, '\ntins:', int(t))

11
CAMBRIDGE IGCSE™ & O LEVEL COMPUTER SCIENCE: PROGRAMMING BOOK

Chapter 5: GUI applications


Practice tasks
5.1 This task asks you to add the code for each widget one at a time but here is an example program with all the
widgets added:
# Import everything required from the tkinter module
from tkinter import *

# Create the main tkinter window


window = Tk()
window.title('My Application')

# A text entry box with a label


Label(window, text='Name:').grid(row=0, column=0)

my_text_box = Entry(window, width=15)


my_text_box.grid(row=0, column=1)

# Two frames
frame1 = Frame(window,height=20,width=100,bg='green')
frame1.grid(row=1, column=0)
frame2 = Frame(window,height=20,width=100,bg='red')
frame2.grid(row=1, column=1)

# A drop-down menu
options = (1,2,3)
my_variable_object = IntVar() # access the value with .get()
my_variable_object.set('choose:')
my_dropdown = OptionMenu(window, my_variable_object, *options)
my_dropdown.grid()

# Enter the main event loop


window.mainloop()

5.2 a sticky=W

b sticky=E

c There are only two letters that need changing in Code snippet 5.6, which are highlighted below.
# Add two radiobutton widgets
# Use optional sticky argument to align left
radio1 = Radiobutton(window, text='Female', variable=gender,
value='female')
radio1.grid(row=2, column=0, sticky=E)
radio1.select() # pre-selects this this radiobutton for the user

12
CAMBRIDGE IGCSE™ & O LEVEL COMPUTER SCIENCE: PROGRAMMING BOOK

radio2 = Radiobutton(
window, text='Male', variable=gender,
value='male')
radio2.grid(row=3, column=0, sticky=E)

# Enter the main event loop


window.mainloop()

5.3 # drop-down.py
from tkinter import *

def change_text():
my_label.config(text=my_variable_object.get())

# Create the main tkinter window


window = Tk()
window.title('My Application')
# Add an empty tkinter label widget
my_label = Label(window, width=20, height=1, text='')
my_label.grid(row=0, column=0)

# Add a tkinter button widget


my_button = Button(window, text='Submit', width=10,
command=change_text)
my_button.grid(row=1, column=0)

# Add a drop-down menu


options = ('Female','Male')
my_variable_object = StringVar() # access the value with .get()
my_variable_object.set('choose:')
my_dropdown = OptionMenu(window, my_variable_object, *options)
my_dropdown.grid()

# Enter the main event loop


window.mainloop()

Challenge tasks
5.1 # two-way-converter.py
from tkinter import *

def to_mph():
if kph_textbox.get() != '': # Not essential
kph = float(kph_textbox.get())
mph = kph / 1.60934
mph_textbox.delete(0, END)
mph_textbox.insert(END, mph)

def to_kph():
if mph_textbox.get() != '': # Not essential
mph = float(mph_textbox.get())

13
CAMBRIDGE IGCSE™ & O LEVEL COMPUTER SCIENCE: PROGRAMMING BOOK

kph = mph * 1.60934


kph_textbox.delete(0, END)
kph_textbox.insert(END, kph)

# Create the main tkinter window


window = Tk()
window.title('Speed Converter')

# Add a frame
button_frame = Frame(window, height=4, width=4)
button_frame.grid(row=1, column=1)

# Add two tkinter label widgets


label1 = Label(window, width=5, height=1, text='mph')
label1.grid(row=0, column=0)

label2 = Label(window, width=5, height=1, text='kph')


label2.grid(row=0, column=2)

# Add two textboxes


mph_textbox = Entry(window, width=10)
mph_textbox.grid(row=1, column=0, sticky=W)

kph_textbox = Entry(window, width=10)


kph_textbox.grid(row=1, column=2, sticky=W)

# Add two tkinter button widgets


button1 = Button(button_frame, text='-->', width=4, command=to_kph)
button1.grid(row=0, column=0)

button2 = Button(button_frame, text='<--', width=4, command=to_mph)


button2.grid(row=1, column=0)

# Enter the main event loop


window.mainloop()

End-of-chapter tasks
1 from tkinter import *

def change_text1():
my_label.config(text='Hello World')

def change_text2():
my_label.config(text='Bye Bye')

# Create the main tkinter window


window = Tk()
window.title('My Application')

14
CAMBRIDGE IGCSE™ & O LEVEL COMPUTER SCIENCE: PROGRAMMING BOOK

# Add an empty tkinter label widget and place it in a grid layout


my_label = Label(window, width=20, height=1, text='')
my_label.grid(row=0, column=0)

# Add tkinter button widgets, place it in the grid layout


# and attach the functions
my_button1 = Button(window, text='Say Hi', width=10, command=change_text1)
my_button1.grid(row=1, column=0)
my_button2 = Button(window, text='Say Bye', width=10, command=change_text2)
my_button2.grid(row=1, column=1)

# Enter the main event loop


window.mainloop()

2 from tkinter import *

def change_text1():
my_label.config(text='Hello World')

def change_text2():
my_label.config(text='Bye Bye')

# Create the main tkinter window


window = Tk()
window.title('My Application')

# Add an empty tkinter label widget and place it in a grid layout


my_label = Label(window, width=20, height=1, text='')
my_label.grid(row=0, column=0)
# Add tkinter button widgets, place it in the grid layout
# and attach the functions
my_button1 = Button(window, text='Say Hi', width=10, command=change_text1)
my_button1.grid(row=1, column=0)
my_button2 = Button(window, text='Say Bye', width=10, command=change_text2)
my_button2.grid(row=2, column=0)

# Enter the main event loop


window.mainloop()

3 from tkinter import *

# Functions called by clicking my_button:


def change_text1():
my_label.config(text='1')

def change_text2():
my_label.config(text='2')

def change_text3():
my_label.config(text='3')

15
CAMBRIDGE IGCSE™ & O LEVEL COMPUTER SCIENCE: PROGRAMMING BOOK

def change_text4():
my_label.config(text='4')

def change_text5():
my_label.config(text='5')

def change_text6():
my_label.config(text='6')

def change_text7():
my_label.config(text='7')

def change_text8():
my_label.config(text='8')

def change_text9():
my_label.config(text='9')

# Create the main tkinter window


window = Tk()
window.title('My App')

# Add a frame
frame1 = Frame(window, height=20, width=60)
frame1.grid(row=1, column=0)

# Add an empty tkinter label widget and place it in a grid layout


my_label = Label(window, width=15, height=1, text='')
my_label.grid(row=0, column=0)

# Add tkinter button widgets, place it in the grid layout


# and attach the functions
my_button1 = Button(frame1, text='1', width=2, command=change_text1)
my_button1.grid(row=0, column=0)
my_button2 = Button(frame1, text='2', width=2, command=change_text2)
my_button2.grid(row=0, column=1)
my_button3 = Button(frame1, text='3', width=2, command=change_text3)
my_button3.grid(row=0, column=2)
my_button4 = Button(frame1, text='4', width=2, command=change_text4)
my_button4.grid(row=1, column=0)
my_button5 = Button(frame1, text='5', width=2, command=change_text5)
my_button5.grid(row=1, column=1)
my_button6 = Button(frame1, text='6', width=2, command=change_text6)
my_button6.grid(row=1, column=2)
my_button7 = Button(frame1, text='7', width=2, command=change_text7)
my_button7.grid(row=2, column=0)
my_button8 = Button(frame1, text='8', width=2, command=change_text8)
my_button8.grid(row=2, column=1)
my_button9 = Button(frame1, text='9', width=2, command=change_text9)
my_button9.grid(row=2, column=2)

16
CAMBRIDGE IGCSE™ & O LEVEL COMPUTER SCIENCE: PROGRAMMING BOOK

# Enter the main event loop


window.mainloop()

4 See answer from Practice task 5.1 for the structure.

Chapter 6: Sequence and strings


Practice tasks
6.1 Speed = 12 kilometres per hour

Distance = 15 miles

Time = Distance / Speed

(The Speed and Distance must be assigned values before Time can be calculated. Be aware that
kilometres and miles are different distances.)

6.2 The flowchart does not indicate what units are being used for distance and speed or what units the
journey time should be given in.

6.3 a A pseudocode algorithm:


INPUT length

OUTPUT move forward length


OUTPUT turn left 120
OUTPUT move forward length
OUTPUT turn left 120
OUTPUT move forward length

b A Python solution:
from turtle import *

length = int(input('Input the side length in pixels: '))

forward(length)
left(120)
forward(length)
left(120)
forward(length)

6.4 a Here are three possibilities:


print('Hello', 'Hello', 'Hello')
print('Hello ' + 'Hello ' + 'Hello')
print('Hello '*3) # This solution has an extra space at the end.

b Here are two possibilities:


print('Please enter your "firstname": ')
input('Please enter your "firstname": ')

17
CAMBRIDGE IGCSE™ & O LEVEL COMPUTER SCIENCE: PROGRAMMING BOOK

c Here are three possibilities:


print('20 / 5 = 4')
print('20 / 5 =', 4)
print('20 / 5 =', int(20/5))

6.5 a Pseudocode: LOWER(my_string)


Python: my_string.lower()

b Pseudocode: UPPER(my_string)
Python: my_string.upper()

c Pseudocode: SUBSTRING(my_string, 3, 11)


Python: my_string[3:14] or my_string[3:]

d Pseudocode: UPPER(SUBSTRING(my_string, 0, 5))


Python: my_string[0:5].upper() or my_string[:5].upper()

e Pseudocode: LENGTH(my_string)
Python: len(my_string)

Challenge tasks
6.1 a A Python solution:
distance = int(input('Distance between airports in km: '))
speed = int(input('Speed of aircraft in km/hr: '))

journey_time = distance / speed

print(journey_time, 'hours')

b It is unclear how the journey time should be output. Hours to decimal places is what was
chosen but hours and minutes would have been better. Or perhaps the answer was only
required to the nearest hour.

6.2 In the input() function, it is intended that three strings are joined. As a+b is not a string it
cannot be joined to other strings. Here is a solution to the problem:
confirm = input('Is the sum of your two numbers ' + str(a+b) + '?')

End-of-chapter tasks
1 a is used for showing inputs and outputs in algorithms.

b is used for general processes in algorithms such as calculations or assigning values to
variables.
c is used to show termination of the algorithm - either START or STOP.

2 my_string = str(5*2)

18
CAMBRIDGE IGCSE™ & O LEVEL COMPUTER SCIENCE: PROGRAMMING BOOK

3 a A pseudocode and flowchart algorithm:


START
INPUT name
INPUT time1
INPUT time2
INPUT time3
INPUT time4 INPUT name,
INPUT time5 time1, time2, time3,
average  (time1 + time2 + time3 + time4 time4, time5
+ time5) / 5
pb  MINIMUM(time1, time2, time3, time4,
time5)
average ←
OUTPUT '
Hi', name, 'Here are your 100m (time1 + time2 + time3 + time4 + time5) / 5
    statistics:' pb ←
OUTPUT 
'Your average 100m time is', minimum(time1, time2, time3, time4, time5)
    average, 's'
OUTPUT 'Your PB is', pb, 's'

b A Python solution:
OUTPUT
name = input('Your name: ') name,
time1 = float(input('First 100m time: ')) average, pb
time2 = float(input('Second 100m time: '))
time3 = float(input('Third 100m time: '))
time4 = float(input('Fourth 100m time: '))
time5 = float(input('Fifth 100m time: ')) STOP

average = (
time1 + time2 + time3 + time4 + time5) / 5
average = round(average, 2)
pb = min(time1, time2, time3, time4, time5)

print('Hi ' + name + ', Here are your 100m statistics:')


print('Your average 100m time is ' + str(average) + 's')
print('Your PB is ' + str(pb) + 's')
Note that the round() function is required because division of decimal numbers sometimes results in
answers that are stored with many decimal places.

19
CAMBRIDGE IGCSE™ & O LEVEL COMPUTER SCIENCE: PROGRAMMING BOOK

Chapter 7: Selection
Practice tasks
7.1 discount = 0.5

ticket_price = float(input('Enter full ticket price: £'))


child = input('Is this for a child? y/n: ')

if child == 'y':
ticket_price = ticket_price * discount

print('The price you pay is £' + str(ticket_price))

7.2 Python uses the equals sign as the assignment operator instead of the  symbol that is used
in pseudocode. This means Python cannot use a single equals sign for the “is equal to” logical
operator and so uses two equals signs instead.

7.3 a The output will be ‘First’.

b The following line of code will need to be changed:


if number2 > number1:
to
if number2 >= number1:
number2 >= number 1

You would change the diamond in the algorithm to:

number2 >= number1

7.4 a A pseudocode and flowchart algorithm:


INPUT number1, number2

IF number2 = number1
THEN
OUTPUT 'Match'
ELSE
OUTPUT 'No match'
ENDIF

20
CAMBRIDGE IGCSE™ & O LEVEL COMPUTER SCIENCE: PROGRAMMING BOOK

START

INPUT
number1
number2

FALSE TRUE
OUTPUT number2 = OUTPUT
"No Match" number1 "Match"

STOP

b A Python solution:
number1 = int(input('Enter first number: '))
number2 = int(input('Enter second number: '))

if number2 == number1:
print('Match')
else:
print('No Match')

7.5 a A pseudocode and flowchart algorithm:


INPUT number1, number2

IF number2 > number1 * 2


THEN
OUTPUT 'Too Large'
ELSE
OUTPUT 'Acceptable'
ENDIF

21
CAMBRIDGE IGCSE™ & O LEVEL COMPUTER SCIENCE: PROGRAMMING BOOK

START

INPUT
number1
number2

FALSE TRUE
OUTPUT number2 > OUTPUT
"Acceptable" number1 * 2 "Too Large"

STOP

b A Python solution:
number1 = int(input('Enter first number: '))
number2 = int(input('Enter second number: '))
if number2 > number1 * 2:
print('Too Large')
else:
print('Acceptable')

22
CAMBRIDGE IGCSE™ & O LEVEL COMPUTER SCIENCE: PROGRAMMING BOOK

7.6 a A pseudocode and flowchart algorithm:


INPUT number1, number2

IF number1 MOD number2 = 0


THEN
OUTPUT 'Factor'
ELSE
OUTPUT 'Not a Factor'
ENDIF

START

INPUT
number1
number2

FALSE TRUE
OUTPUT number1 MOD OUTPUT
"Not a Factor" number2 = 0 "Factor"

STOP

b A Python solution:
number1 = int(input('Enter first number: '))
number2 = int(input('Enter second number: '))

if number1 % number2 == 0:
print('Factor')
else:
print('Not a Factor')

23
CAMBRIDGE IGCSE™ & O LEVEL COMPUTER SCIENCE: PROGRAMMING BOOK

7.7
START

INPUT
number1
number2

number2 = TRUE
OUTPUT
number1 'Same'

FALSE

TRUE
number2 > OUTPUT
number1 'Second'

FALSE

number2 < TRUE


OUTPUT
number1 'First'

FALSE

STOP

24
CAMBRIDGE IGCSE™ & O LEVEL COMPUTER SCIENCE: PROGRAMMING BOOK

7.8 a A flowchart and pseudocode algorithm:

START

INPUT
full_price
age

TRUE
age >= 18 final_price ← full_price

FALSE

TRUE
age >= 15 final_price ← full_price * 0.8

FALSE

FALSE TRUE
final_price ← 0 age >= 4 final_price ← full_price * 0.6

OUTPUT
final_price

STOP

25
CAMBRIDGE IGCSE™ & O LEVEL COMPUTER SCIENCE: PROGRAMMING BOOK

INPUT full_price
INPUT age

IF age >= 18
THEN
final_price  full_price
ELSE
IF Age >=15
THEN
final_price  full_price * 0.8
ELSE
IF Age >=4
THEN
final_price  full_price * 0.6
ELSE
final_price  0
ENDIF
ENDIF
ENDIF

OUTPUT final_price

b A Python solution:
full_price = float(input('Enter full ticket price: £'))
age = int(input('Enter passenger age: '))

if age >= 18:


final_price = full_price
else:
if age >= 15:
final_price = full_price * 0.8
else:
if age >= 4:
final_price = full_price * 0.6
else:
final_price = 0.0

print('Price: £' + str(round(final_price, 2)))

26
27
7.9 a

ENDCASE
CASE month

OTHERWISE
INPUT LOWER(month)

'may': OUTPUT 31

entered a month.'
'july': OUTPUT 31
'june': OUTPUT 30
'april': OUTPUT 30
'march': OUTPUT 31

'august': OUTPUT 31
START

OUTPUT 'You have not


'october': OUTPUT 31
'january': OUTPUT 31

'december': OUTPUT 31
'november': OUTPUT 30
'february': OUTPUT 28

'september': OUTPUT 30
A pseudocode and flowchart algorithm:

INPUT
LOWER(month)

FALSE FALSE FALSE FALSE FALSE FALSE


month = month = month = month = month = month =
'january' 'february' 'march' 'april' 'may' 'june'
TRUE TRUE TRUE TRUE TRUE TRUE

OUTPUT OUTPUT OUTPUT OUTPUT OUTPUT OUTPUT


31 28 31 30 31 30

FALSE FALSE FALSE FALSE FALSE FALSE


month = month = month = month = month = month =
'december' 'november' 'october' 'september' 'august' 'july'
CAMBRIDGE IGCSE™ & O LEVEL COMPUTER SCIENCE: PROGRAMMING BOOK

TRUE TRUE TRUE TRUE TRUE TRUE


OUTPUT OUTPUT OUTPUT OUTPUT OUTPUT OUTPUT OUTPUT
'Not a month' 31 30 31 30 31 31

STOP
CAMBRIDGE IGCSE™ & O LEVEL COMPUTER SCIENCE: PROGRAMMING BOOK

b A Python solution:
month = input('Enter a month: ').lower()

if month == 'january':
print(31)
elif month == 'february':
print(28)
elif month == 'march':
print(31)
elif month == 'april':
print(30)
elif month == 'may':
print(31)
elif month == 'june':
print(30)
elif month == 'july':
print(31)
elif month == 'august':
print(31)
elif month == 'september':
print(30)
elif month == 'october':
print(31)
elif month == 'november':
print(30)
elif month == 'december':
print(31)
else:
print('You have not entered a month.')
A GUI application will have the same logic as the text-based solution given. There are two ways of
obtaining the month data from users in a GUI version of this application:

i Use a textbox – where the input needs to be handled exactly as above.

ii Use a drop-down menu – which is the better solution as the user cannot enter any
unexpected data.

28
CAMBRIDGE IGCSE™ & O LEVEL COMPUTER SCIENCE: PROGRAMMING BOOK

7.10 a A pseudocode and flowchart algorithm:


START
INPUT Year

IF Year MOD 4 = 0
THEN
IF Year MOD 100 = 0 INPUT
THEN year
IF Year MOD 400 = 0
THEN
OUTPUT "Leap Year"
ELSE
OUTPUT "Normal Year" FALSE
year MOD 4 OUTPUT
ENDIF
=0 'Normal year'
ELSE
OUTPUT "Leap Year"
ENDIF TRUE
ELSE
OUTPUT "Normal Year"
ENDIF FALSE
year MOD 100 OUTPUT
=0 'Leap year'

TRUE

FALSE
year MOD 400 OUTPUT
=0 'Normal year'

TRUE

OUTPUT
'Leap year'

b A Python solution:
year = int(input(
'In what year
were you STOP
born?'))

if year % 4 == 0:
if year % 100 == 0:
if year % 400 == 0:
p
rint('The year is a leap year and has 366 days')
else:
p
rint('The year is not a leap year and has 365 days')
else:
p
rint('The year is a leap year and has 366 days')
else:
print('The year is not a leap year and has 365 days')

29
CAMBRIDGE IGCSE™ & O LEVEL COMPUTER SCIENCE: PROGRAMMING BOOK

7.11 year = int(input('In what year were you born?'))

if (year % 4 == 0 and year % 100 != 0) or year % 400 == 0:


print('The year is a leap year and has 366 days')
else:
print('The year is not a leap year and has 365 days')

Challenge tasks
7.1 Even though there is no ELSE in the pseudocode algorithm, the consequence of a False answer to
the IF clause is that the program carries on:

START

discount ← 0.5

INPUT
ticket_price
child

TRUE ticket_price ←
child = y
ticket_price * discount

FALSE

OUTPUT
ticket_price

STOP

30
CAMBRIDGE IGCSE™ & O LEVEL COMPUTER SCIENCE: PROGRAMMING BOOK

7.2 As the logic does not change, below is one example of the Python code for a GUI application.
The logic for the other two can be taken from the previous tasks.
from tkinter import *

def is_factor():
number1 = int(number1_textbox.get())
number2 = int(number2_textbox.get())
if number1 % number2 == 0:
label_ans.config(text='Factor')
else:
label_ans.config(text='Not a Factor')

def clear():
number1_textbox.delete(0, END)
number2_textbox.delete(0, END)
label_ans.config(text='')

# Create the main tkinter window


window = Tk()
window.title('Factor?')

# Add tkinter label widgets


label_ans = Label(window, width=10, height=1, text='')
label_ans.grid(row=3, column=1, sticky=W)

label1 = Label(window, width=10, height=1, text='number1:')


label1.grid(row=0, column=0, sticky=E)

label2 = Label(window, width=10, height=1, text='number2:')


label2.grid(row=1, column=0, sticky=E)

label3 = Label(window, width=5, height=1, text='Output:')


label3.grid(row=3, column=0, sticky=E)

# Add two textboxes


number1_textbox = Entry(window, width=10)
number1_textbox.grid(row=0, column=1, sticky=W)

number2_textbox = Entry(window, width=10)


number2_textbox.grid(row=1, column=1, sticky=W)

# Add two tkinter button widgets


button1 = Button(window, text='Submit', width=8, command=is_factor)
button1.grid(row=2, column=0)

31
CAMBRIDGE IGCSE™ & O LEVEL COMPUTER SCIENCE: PROGRAMMING BOOK

button2 = Button(window, text='Clear', width=6, command=clear)


button2.grid(row=2, column=1)

# Enter the main event loop


window.mainloop()

7.3 a An if ... elif ... else construct is not as efficient as a CASE statement because
all of the conditions prior to the one that returns True have to be tested. The rest are then
skipped. This makes it just as efficient as a nested if solution. CASE statements are more
efficient than this because they jump straight to the condition that returns True. This is
because they do not actually run any tests. The separate cases are in fact indexed locations
in memory.

b CASE statements are limited to evaluating the output from a single variable. An if ...
elif ... else construct is more flexible because it can have different test conditions at
each new elif clause.

End-of-chapter tasks
1 a A pseudocode and flowchart algorithm:
INPUT number1, number2, number3

IF number1 = number2 OR number1 = number3 OR number2 = number3


THEN
OUTPUT 'Error: match found'
ELSE
IF number1 > number2 and number1 > number3
THEN
OUTPUT number1
ELSE
IF number2 > number3
THEN
OUTPUT number2
ELSE
OUTPUT number3
ENDIF
ENDIF
ENDIF

32
CAMBRIDGE IGCSE™ & O LEVEL COMPUTER SCIENCE: PROGRAMMING BOOK

START

INPUT
number1
number2
number3

number1 = number2
OR TRUE
number1 = number3 OUTPUT
OR 'Error: match'
number2 = number3

number1 > number2 TRUE


AND OUTPUT
number1 > number3 number1

TRUE
number2 > number3 OUTPUT
number2

OUTPUT STOP
number3

33
CAMBRIDGE IGCSE™ & O LEVEL COMPUTER SCIENCE: PROGRAMMING BOOK

b A text-based nested if solution:


number1 = int(input('Enter number1: '))
number2 = int(input('Enter number2: '))
number3 = int(input('Enter number3: '))

if number1 == number2 or number1 == number3 or number2 == number3:


print('Error: match found')
else:
if number1 > number2 and number1 > number3:
print(number1)
else:
if number2 > number3:
print(number2)
else:
print(number3)

c A text-based else if solution:


number1 = int(input('Enter number1: '))
number2 = int(input('Enter number2: '))
number3 = int(input('Enter number3: '))

if number1 == number2 or number1 == number3 or number2 == number3:


print('Error: match found')
elif number1 > number2 and number1 > number3:
print(number1)
elif number2 > number3:
print(number2)
else:
print(number3)

34
CAMBRIDGE IGCSE™ & O LEVEL COMPUTER SCIENCE: PROGRAMMING BOOK

2 a A pseudocode and flowchart algorithm:


INPUT destination
INPUT ticket_class // 'b' or 'e'
INPUT return_ticket // 'y' or 'n'
INPUT meal // 'y' or 'n'

IF destination = 'Edinburgh'
THEN
IF ticket_class = 'b'
THEN
IF return_ticket = 'y'
THEN
cost  '£178'
ELSE
cost  '£87'
ENDIF
ELSE // economy
IF return_ticket = 'y'
THEN
IF meal = 'y'
THEN
cost  '£70'
ELSE
cost  '£52'
ENDIF
ELSE // single
IF meal = 'y'
THEN
cost  '£44'
ELSE
cost  '£32'
ENDIF
ENDIF
ENDIF
ELSE // Going to Cardiff
IF ticket_class = 'b'
THEN
IF return_ticket = 'y
THEN
cost  '£138'
ELSE
cost  '£72'
ENDIF
ELSE // economy
IF return_ticket = 'y'
THEN
IF meal = 'y'
THEN
cost  '£68'

35
CAMBRIDGE IGCSE™ & O LEVEL COMPUTER SCIENCE: PROGRAMMING BOOK

ELSE
cost  '£50'
ENDIF
ELSE // single
IF meal = 'y'
THEN
cost  '£48'
ELSE
cost  '£36'
ENDIF
ENDIF
ENDIF
ENDIF

OUTPUT cost

36
37
b
START
cost ← '£68' cost ← '£50' cost ← '£48' cost ← '£36'

INPUT
destination
ticket_class TRUE FALSE TRUE FALSE
return_ticket meal = 'y' meal = 'y'

A text-based solution:
meal

TRUE

FALSE FALSE
destination = 'Edinburgh' return_ticket = 'y'
cost ← '£87'

FALSE TRUE

meal = input('Meal? [y/n]: ')


FALSE

TRUE TRUE FALSE


return_ticket = 'y' ticket_class = 'b' ticket_class = 'b' return_ticket = 'y' cost ← '£72'

destination = input('Destination: ')


TRUE FALSE TRUE

cost ← '£138'
cost ← '£178' FALSE
return_ticket = 'y'

return_ticket = input('Return ticket? [y/n]: ')


TRUE

ticket_class = input('Business or Economy? [b/e]: ')


TRUE FALSE TRUE FALSE OUTPUT
meal = 'y' meal = 'y' cost
CAMBRIDGE IGCSE™ & O LEVEL COMPUTER SCIENCE: PROGRAMMING BOOK

STOP
cost ← '£70' cost ← '£52' cost ← '£44' cost ← '£32'
CAMBRIDGE IGCSE™ & O LEVEL COMPUTER SCIENCE: PROGRAMMING BOOK

if destination == 'Edinburgh':
if ticket_class == 'b':
if return_ticket == 'y':
cost = '£178'
else:
cost = '£87'
else: # economy
if return_ticket == 'y':
if meal == 'y':
cost = '£70'
else:
cost = '£52'
else: # single
if meal == 'y':
cost = '£44'
else:
cost = '£32'
else: # Going to Cardiff
if ticket_class == 'b':
if return_ticket == 'y':
cost = '£138'
else:
cost = '£72'
else: # economy
if return_ticket == 'y':
if meal == 'y':
cost = '£68'
else:
cost = '£50'
else: # single
if meal == 'y':
cost = '£48'
else:
cost = '£36'

print(cost)

c A GUI solution will have the same logic as the above solution but a relatively simple
interface. It will have one output in either a label or a textbox widget and four places for user
input. To ensure no errors in inputs, this GUI could use four sets of radio buttons.
An equally good solution would be four drop-down menus.

38
CAMBRIDGE IGCSE™ & O LEVEL COMPUTER SCIENCE: PROGRAMMING BOOK

Chapter 8: Iteration
Practice tasks
8.1 from turtle import *

for _ in range(6):
forward(100)
left(60)

8.2 from turtle import *

for _ in range(6):
for _ in range(4):
forward(100)
left(90)
left(60)

8.3 a A pseudocode and flowchart algorithm:


INPUT number

FOR i  1 TO number
OUTPUT i*i
NEXT

START

INPUT
number

i←1

TRUE
i > number

i←i+1 FALSE

OUTPUT
i*i
STOP

39
CAMBRIDGE IGCSE™ & O LEVEL COMPUTER SCIENCE: PROGRAMMING BOOK

b A text-based solution:
number = int(input('Input an integer: '))

for i in range(1, number+1):


print(i*i)

8.4 a A pseudocode and flowchart algorithm:


bit_values  ''
INPUT num
bit_value  1

FOR i  1 TO num
bit_values  bit_values + STRING(bit_value) + ', '
bit_value  bit_value * 2
NEXT

// Remove the last comma and space:


bit_values  SUBSTRING(bit_values, 0, LENGTH(bit_values)-2)
print(bit_values)

START

bit_values ← ''
bit_value ← 1

INPUT
num

OUTPUT
TRUE
i > number bit_values with ', '
removed from end
i←i+1 FALSE

bit_values ← bit_values + bit_value +', '


STOP
bit_value ← bit_value * 2

b A text-based solution:
bit_values = ''
num = int(input('Input an integer: '))
bit_value = 1

40
CAMBRIDGE IGCSE™ & O LEVEL COMPUTER SCIENCE: PROGRAMMING BOOK

for _ in range(num):
bit_values = bit_values + str(bit_value) + ', '
bit_value = bit_value * 2

# Remove the last comma and space:


bit_values = bit_values[0:-2]

print(bit_values)

8.5 a A flowchart algorithm:

START

sentence ← ''

INPUT
word

FALSE OUTPUT
word != 'end'
sentence

TRUE

sentence ← sentence + word + ' '

INPUT
STOP
word

b A text-based solution:
sentence = ''

word = input('Enter your word: ')

while word != 'end':


sentence = sentence + word + ' '
word = input('Enter your word: ')

print(sentence)

c Student testing

41
CAMBRIDGE IGCSE™ & O LEVEL COMPUTER SCIENCE: PROGRAMMING BOOK

8.6 a A pseudocode and flowchart algorithm:


INPUT num
total  num

count  1
WHILE num != -1 AND count < 20 DO
INPUT num
total  total + num
count  count + 1
ENDWHILE

average  total / count


OUTPUT average

START

INPUT
num

total ← num
count ← 1

num != –1 FALSE
AND average ← total / count
count < 20

TRUE

INPUT OUTPUT
num average

total ← total + num


STOP
count ← count +1

42
CAMBRIDGE IGCSE™ & O LEVEL COMPUTER SCIENCE: PROGRAMMING BOOK

b A text-based solution:
num = int(input('Enter an integer: '))
total = num

count = 1
while num != -1 and count < 20:
num = int(input('Enter an integer: '))
total = total + num
count = count + 1

average = total / count


print(average)

8.7 a A pseudocode and flowchart algorithm:


REPEAT
INPUT password1
INPUT password2
IF password1 != password2 OR LENGTH(password1) < 11
THEN
OUTPUT 'Error!'
ENDIF
UNTIL password1 = password2 AND LENGTH(password1) > 10

OUTPUT 'Password accepted'

START

INPUT
password1
password2

OUTPUT STOP
'Error!'

password1 = password2
FALSE TRUE OUTPUT
AND
LENGTH(password1) > 10 'Password accepted'

43
CAMBRIDGE IGCSE™ & O LEVEL COMPUTER SCIENCE: PROGRAMMING BOOK

b A text-based solution:

Here is a Python implementation of the REPEAT...UNTIL algorithm:


while True:
password1 = input('Input your password: ')
password2 = input('Input your password again: ')
if password1 != password2 or len(password1) < 11:
print('Error!')
if password1 == password2 and len(password1) > 10:
break

print('Password accepted')

It is interesting to compare the above solution with a normal while loop program:
password1 = input('Input your password: ')
password2 = input('Input your password again: ')

while password1 != password2 or len(password1) < 11:


print('Error!')
password1 = input('Input your password: ')
password2 = input('Input your password again: ')

print('Password accepted')

Both solutions involve repeated code although if we were not trying to implement the pseudocode so
literally the first version could actually be written:
while True:
password1 = input('Input your password: ')
password2 = input('Input your password again: ')
if password1 != password2 or len(password1) < 11:
print('Error!')
else:
break

print('Password accepted')

8.8 a A text-based solution for Code snippet 8.18:


total = 0
number = int(input('Input a number: '))

while number != -1:


total = total + number
number = int(input('Input a number: '))

print(total)

44
CAMBRIDGE IGCSE™ & O LEVEL COMPUTER SCIENCE: PROGRAMMING BOOK

b A text-based solution Code snippet 8.19:


total = 0

while True:
number = int(input('Input a number: '))
total = total + number
if number == -1:
break
total = total + 1

print(total)

c Student testing

Challenge task
8.1 #nonsense_sentences_gui.py
from tkinter import *
sentence = ''

def submit_word():
global sentence
word = my_text_entry_box.get()

if word != 'end':
sentence = sentence + word + ' '
my_text_entry_box.delete(0, END)
else:
output_label.config(text=sentence)

# Add GUI
# Create the main tkinter window
window = Tk()
window.title('Nonsense Sentences')

# Add widgets
frame1 = Frame(window, height=1, width=45)
frame1.grid(row=0, column=0)

label1 = Label(frame1, width=15, height=1, text=' Enter word:',


anchor="w")
label1.grid(row=0, column=0, sticky=W)

my_text_entry_box = Entry(frame1, width=15)


my_text_entry_box.grid(row=0, column=1)

my_button = Button(frame1, text='Submit', width=15, command=submit_word)


my_button.grid(row=0, column=2)

45
CAMBRIDGE IGCSE™ & O LEVEL COMPUTER SCIENCE: PROGRAMMING BOOK

label2 = Label(
window, width=45, height=2, text='\nNonsense sentence:',
anchor="w")
label2.grid(row=1, column=0)

output_label = Label(
window, width=45, height=1, text='', anchor="w",
fg='blue')
output_label.grid(row=2, column=0)

# Enter the main event loop


window.mainloop()

Skills focus questions


8.1 1 WHILE

The loop is used to total a series of inputs until a negative value is input. The input value must be
checked before the loop runs to avoid including the negative value in the total. The WHILE
loop would be most appropriate as it checks the condition before the loop runs.
INPUT Value
WHILE Value >= 0
Total  Total + Value
INPUT Value
ENDWHILE

2 REPEAT...UNTIL

The process requires that a total is maintained of the values input. There will always be at least
one input in this process, even if that input itself is large enough to stop the process and halt any
other inputs. Checking at the end of each input would be most appropriate.
REPEAT
INPUT Value
Total  Total + Value
UNTIL Total > 1000

3 Either WHILE or REPEAT...UNTIL

It would be important to check the username and password before allowing access to the system.
The WHILE loop would check that the values input matched system records before allowing
access. If the first input failed, an error message could be generated including a prompt to
try again.
INPUT Username, Password
WHILE Username != SystemUserName AND Password != SystemPassword
OUTPUT 'Access Rejected, re-enter Username and password'
INPUT Username and Password
ENDWHILE
// Run System Access Code

46
CAMBRIDGE IGCSE™ & O LEVEL COMPUTER SCIENCE: PROGRAMMING BOOK

The REPEAT...UNTIL could also be used to achieve a similar result, but would require the use of an
IF statement to include the error message.
REPEAT
INPUT Username and Password
IF Username != SystemUserName OR Password != SystemPassword
THEN
OUTPUT 'Access Rejected, re-enter Username and password'
ENDIF
UNTIL Username = SystemUserName AND Password = SystemPassword
// Run System Access Code

End-of-chapter tasks
1 a Count-controlled FOR loop.

The user will need to input 25 scores. As the number of iterations is known, a count-controlled loop
would be appropriate.

b Condition-controlled WHILE or REPEAT...UNTIL loop.

The number of recordings required is unknown. A condition-controlled loop set to stop when the input
value is 20 would be appropriate.

c FOR or WHILE or REPEAT...UNTIL

There are 200 runners so it could be expected that 200 values will need to be input. Using this logic,
a count controlled FOR loop would be appropriate. However, what would happen if a runner fails
to complete the race? Is a time recorded for them? Using a FOR loop would force the input of 200
values. It might be more appropriate to use a condition-controlled loop. The condition could be set so
a negative number would end the input sequence. This would allow the input of times only for those
runners who complete the marathon.

Both methods could be appropriate and the task would need to be better defined before a final decision
could be made.

d Condition-controlled WHILE or REPEAT...UNTIL loop.

It is unlikely that the cinema will know how many people are going to watch the film. The number of
ages being input into the system will also be unknown. A condition-controlled loop would seem to be
the most appropriate as the input could be ended when the last ticket is bought. The condition could be
set so a negative number would end the input sequence. As it is not possible to have a negative age this
would seem an appropriate condition. It might also be appropriate to end the input when tickets for all
available seats have been sold. This could be a second condition.

47
CAMBRIDGE IGCSE™ & O LEVEL COMPUTER SCIENCE: PROGRAMMING BOOK

2 a A pseudocode and flowchart algorithm:


START
INPUT num

OUTPUT 'The factors of', num, 'are:'


FOR counter  1 TO num
IF num MOD counter = 0 INPUT
THEN num
OUTPUT counter
ENDIF
NEXT
OUTPUT
b A text-based solution: 'The factors of ' + num + 'are: '

num = int(input(
'Enter an
integer: '))
print('The factors of', num, 'are:') counter ← 1

for counter in range(1, num+1):


if num % counter == 0:
print(counter)
counter > TRUE
num STOP

counter ←
FALSE
counter + 1

FALSE num MOD


counter = 0

TRUE

OUTPUT
counter

3 
from turtle import *

sides = int(input('Enter the number of sides: '))


angle = 360 / sides

for _ in range(sides):
forward(100)
left(angle)

48
CAMBRIDGE IGCSE™ & O LEVEL COMPUTER SCIENCE: PROGRAMMING BOOK

4 A pseudocode and flowchart algorithm:

START

INPUT
num1
num2

OUTPUT
'The factors of ' + num1 +
'and ' + num2 + 'are: '

largest ← maximum(num1, num2)


counter ← 1

counter > TRUE


STOP
largest

counter ← FALSE
counter + 1

FALSE num1 MOD counter = 0


AND
num 2 MOD counter = 0

TRUE

OUTPUT
counter

A pseudocode algorithm:
INPUT num1
INPUT num2

OUTPUT 'The factors of', num1, 'and',


num2, 'are: '

//Find largest:
largest  num1
IF num2 > num1
THEN
largest  num2
ENDIF

49
CAMBRIDGE IGCSE™ & O LEVEL COMPUTER SCIENCE: PROGRAMMING BOOK

FOR counter  1 TO largest


IF num1 MOD counter = 0

AND num2 MOD counter = 0
THEN
OUTPUT counter
ENDIF
NEXT
A text-based solution:
num1 = int(input('Enter an integer: '))
num2 = int(input('Enter another integer: '))
print('The common factors of', num1, 'and', num2, 'are:')

# Find largest, could also use


Python's max() function:
largest = num1
if num2 > num1:
largest = num2

#Search for common factors


for counter in range(1, largest+1):
if num1 % counter == 0 and num2 % counter == 0:
print(counter)

5 a A pseudocode and flowchart algorithm:


INPUT num
a  0
b  1
series  '0, 1, '

FOR counter  1 TO num-2


temp  a
a  b
b  a + temp
series  series + str(b) + ', '
counter  counter + 1
NEXT

// Remove comma and space from end:


series  SUBSTRING(series, 0, num*3 - 2]

OUTPUT series

50
CAMBRIDGE IGCSE™ & O LEVEL COMPUTER SCIENCE: PROGRAMMING BOOK

START

INPUT
num
STOP

a←0
b←1
series ← '0, 1, ' OUTPUT
series

counter > TRUE series ← SUBSTRING(series, 0, num*3 – 2]


num - 2

counter ← FALSE
counter + 1
temp ← a
a←b
b ← a + temp
series ← series + b + ', '

b A text-based solution:
num = int(input('Enter an integer: '))
a = 0
b = 1
series = '0, 1, '

for counter in range(num-2):


temp = a
a = b
b = a + temp
series = series + str(b) + ', '
counter = counter + 1

# Remove comma and space from end:


series = series[0:-2]
print(series)

51
CAMBRIDGE IGCSE™ & O LEVEL COMPUTER SCIENCE: PROGRAMMING BOOK

Chapter 9: System design


Practice tasks
9.1
Weather App

Input location Output forecast

New town Saved town Map Table

9.2 Other solutions include:


• The IF statement could determine the highest number input before the calculation of total.
Both must remain within the loop but the order of completion is not important.
• The FOR loop could have been written as FOR counter = 0 TO 99; this would still iterate
100 times.
• It would have been possible to use a WHILE or REPEAT...UNTIL loop. Although a FOR
loop is an efficient solution to a scenario where the number of iterations is known, any loop
can be written to perform a similar role. Remember that in a FOR loop, the NEXT statement
automatically increments the loop counter; WHILE and REPEAT...UNTIL loops do not
automatically increment the loop counter so code to do this would need to be included in the
program.

9.3 a A structure diagram for the system:

Average pages in
a library book

Initialise global Process Average


Process Average
variables Until num_pages < 0

INPUT total ← count ← average ← OUTPUT


total ← 0
num_pages total + num_pages count + 1 total/count average

52
CAMBRIDGE IGCSE™ & O LEVEL COMPUTER SCIENCE: PROGRAMMING BOOK

b A flowchart for the system:

START

total ← 0
count ← 0

INPUT
num_pages

FALSE OUTPUT
num_pages
>0 average

count ←
count + 1 TRUE

total ← total + num_pages

INPUT
num_pages STOP

c A pseudocode algorithm for the system:


total  0
INPUT num_pages

count  0
WHILE num_pages > 0 DO
total  total + num_pages
INPUT num_pages
count  count + 1
ENDWHILE

average  total / num_books

OUTPUT 'Average number of pages:', average

53
CAMBRIDGE IGCSE™ & O LEVEL COMPUTER SCIENCE: PROGRAMMING BOOK

d A Python implementation of the algorithm:


total = 0
num_pages = int(input('Total pages: '))

count = 0
while num_pages > 0:
total = total + num_pages
num_pages = int(input('Total pages: '))
count = count + 1

average = total / count

print('Average number of pages:', average)

Challenge tasks
9.1 The design shown below assumes that when a weather station sends in their monthly figures that this is all
the data that they have. If the data for some of the days is missing this is because no measurements were
taken. The proposed system will estimate values for the missing days.

Collect
rainfall data

Request Check if data Calculate Output all data


Store data
data complete national for the month
average

Use data Estimate OUTPUT OUTPUT


as sent missing data for national
each station average

(The circles in two of the boxes indicate that they are alternatives.)

54
CAMBRIDGE IGCSE™ & O LEVEL COMPUTER SCIENCE: PROGRAMMING BOOK

9.2 A flowchart algorithm:

START

total ← 0
count ← 0

INPUT
daily_rainfall

FALSE
daily_rainfall OUTPUT
>= 0 total

count ←
count +1 TRUE

total ← total +daily_rainfall

INPUT
daily_rainfall STOP

A Python solution:
total = 0

daily_rainfall = float(input('Rainfall to 0.1mm: '))

while daily_rainfall >= 0:


total = total + daily_rainfall
daily_rainfall = float(input('Rainfall to 0.1mm: '))

print("This month's total recorded rainfall: ", total)

55
CAMBRIDGE IGCSE™ & O LEVEL COMPUTER SCIENCE: PROGRAMMING BOOK

End-of-chapter tasks
1 total  0

INPUT monthly_rainfall

count  0
WHILE monthly_rainfall >= 0 DO
total  total + monthly_rainfall
INPUT monthly_rainfall
count = count + 1
ENDWHILE

average  total / count

OUTPUT 'Number of stations:', count


OUTPUT "This month's national average rainfall:", average

A Python implementation of the algorithm:


total = 0

monthly_rainfall = float(input('Rainfall to 0.1mm: '))

count = 0
while monthly_rainfall >= 0:
total = total + monthly_rainfall
monthly_rainfall = float(input('Rainfall to 0.1mm: '))
count = count + 1
average = total / count

print("Number of stations: ", count)


print("This month's national average rainfall: ", average)

56
CAMBRIDGE IGCSE™ & O LEVEL COMPUTER SCIENCE: PROGRAMMING BOOK

2 a Here is a flowchart for the text-based solution:

START

score ← 0
hit ← 0

INPUT
hit

FALSE
OUTPUT
hit != – 1
score

TRUE

INPUT
hit

score ← score + hit STOP

and here is a Python implementation:


score = 0
hit = 0

while hit != -1:


hit = int(input('Mole! '))
score = score + hit

# Remove final -1 from score:


score = score + 1

print('Your score is: ', score)

57
CAMBRIDGE IGCSE™ & O LEVEL COMPUTER SCIENCE: PROGRAMMING BOOK

b Here is a GUI test program:


from tkinter import *

score = 0

def hit():
global score
score = score + 1
label_ans.config(text='')

def finish():
global score
label_ans.config(text=score)
score = 0

# Create the main tkinter window


window = Tk()
window.title('Whack a mole')

# Add two tkinter label widgets


label_ans = Label(window, width=6, height=1, text='')
label_ans.grid(row=1, column=2, sticky=W)

label_score = Label(window, width=6, height=1, text='Score:')


label_score.grid(row=1, column=0, sticky=W)

# Add two tkinter button widgets


button1 = Button(window, text='MOLE', width=8, height=4, command=hit)
button1.grid(row=0, column=1)

button2 = Button(window, text='Finish', width=8, command=finish)


button2.grid(row=2, column=1)

# Enter the main event loop


window.mainloop()

c Optional (no solution provided).

58
CAMBRIDGE IGCSE™ & O LEVEL COMPUTER SCIENCE: PROGRAMMING BOOK

3 a A structure diagram for the system:

Draw a house

IMPORT PROCEDURE: PROCEDURE:


Build house
turtle module draw_rectangle draw_triangle

INPUT process INPUT process


CALL Move turtle
height, width rectangle x1, y1, x2, y2, x3, y3 triangle
rectangle X 3 Lift and
triangle X 1 lower pen

b A flowchart for the system:

START START
START
draw_rectangle draw_triangle

CALL
draw_rectangle(300, 200) parameter: height parameters: x1, y1
draw_triangle(0, 200, 300, 200, 150, 300) parameter: width parameters: x2, y2
parameters: x3, y3

goto(40, 70)
pendown
left(90)
forward(width) goto(x1, y1)
left(90) pendown
forward(height) goto(x2, y2)
CALL left(90) goto(x3, y3)
draw_rectangle(100, 80) forward(width) goto(x1, y1)
left(90) penup
forward(height)
penup
goto(180, 0)
left(90)
STOP
draw_triangle
STOP
CALL draw_rectangle
draw_rectangle(80, 150)

hide turtle()

STOP

59
CAMBRIDGE IGCSE™ & O LEVEL COMPUTER SCIENCE: PROGRAMMING BOOK

A pseudocode algorithm for the system:


import turtle module

PROCEDURE draw_rectangle(height, width)


pendown
forward(width)
left(90)
forward(height)
left(90)
forward(width)
left(90)
forward(height)
penup
ENDPROCEDURE

PROCEDURE draw_triangle(x1,y1,x2,y2,x3,y3)
goto(x1,y1)
pendown
goto(x2,y2)
goto(x3,y3)
goto(x1,y1)
penup
ENDPROCEDURE

// Draw House
draw_rectangle(300,200)
draw_triangle(0,200,300,200,150,300)
goto(40,70)
left(90)
draw_rectangle(100,80)
goto(180,0)
left(90)
draw_rectangle(80,150)
hideturtle()

c A Python implementation of the algorithm:


import turtle as t
# Drawing functions that all start by putting
# the pen down and ending by lifting the pen.
def draw_rectangle(width, height):
t.pendown()
t.forward(width)
t.left(90)
t.forward(height)
t.left(90)
t.forward(width)
t.left(90)
t.forward(height)
t.penup()

60
CAMBRIDGE IGCSE™ & O LEVEL COMPUTER SCIENCE: PROGRAMMING BOOK

def draw_triangle(x1,y1,x2,y2,x3,y3):
t.goto(x1,y1)
t.pendown()
t.goto(x2,y2)
t.goto(x3,y3)
t.goto(x1,y1)
t.penup()

# Draw House
draw_rectangle(300,200)
draw_triangle(0,200,300,200,150,300)
t.goto(40,70)
t.left(90)
draw_rectangle(100,80)
t.goto(180,0)
t.left(90)
draw_rectangle(80,150)
t.hideturtle()

Chapter 10: Arrays


Practice tasks
10.1 task = [None] * 4

def input_data():
data_item = int(input('Enter an integer: '))
index = int(input('Enter an index from 0 to 3: '))
task[index] = data_item

def output_data():
index = int(input('Enter an index from 0 to 3: '))
print(task[index])

### Main (with some unnecessary menu functionality)


print('Welcome to this application.')

choice = '0'
while choice != '3':
choice = input('''
Menu:
1. Input data
2. Output data
3. Finish

Choose 1, 2 or 3: ''')

if choice == '3':

61
CAMBRIDGE IGCSE™ & O LEVEL COMPUTER SCIENCE: PROGRAMMING BOOK

print('Thanks for using this application.')


else:
while (choice != '1' and choice != '2'):
choice = input('Enter 1, 2 or 3: ')

if choice == '1':
input_data()
else:
output_data()

input('Press any key to continue.')

10.2 W
 hen the program ends the values in the arrays are lost. This means that every time the program
is started the values have to be re-entered.

10.3 a A flowchart for the system:

START

names ← ['Albert', 'Beck', 'Caro,' 'Dimpna', 'Eli', 'Filiz']

INPUT
number

OUTPUT
names[number–1]

STOP

A pseudocode algorithm for the system:


names  ['Albert', 'Beck', 'Caro', 'Dimpna', 'Eli', 'Filiz']
INPUT number
OUTPUT names[number-1]

62
CAMBRIDGE IGCSE™ & O LEVEL COMPUTER SCIENCE: PROGRAMMING BOOK

b A Python implementation:
names = ['Albert', 'Beck', 'Caro', 'Dimpna', 'Eli', 'Filiz']
number = int(input('Enter a number between from 1 to 6: '))
print(names[number-1])

10.4 a A flowchart for the system with the array numbered from 1 to 6:

START

names ← ['Albert', 'Beck', 'Caro,' 'Dimpna', 'Eli', 'Filiz']

found ← FALSE
i←1

INPUT
name

TRUE found = FALSE


i=7
FALSE

FALSE TRUE
i←i+1

OUTPUT
FALSE name = STOP
'No match.'
names[i]

TRUE

OUTPUT
'Name found.'

found ← TRUE

63
CAMBRIDGE IGCSE™ & O LEVEL COMPUTER SCIENCE: PROGRAMMING BOOK

A pseudocode algorithm for the system:


names  ['Albert', 'Beck', 'Caro', 'Dimpna', 'Eli', 'Filiz']
found  FALSE

INPUT name
// Perform search
FOR i  1 TO 6
IF name = names[i]
THEN
OUTPUT 'Name found.'
found = TRUE
ENDIF
NEXT

IF found = FALSE
THEN
OUTPUT 'No match.'
ENDIF

b A Python implementation where the array is numbered from 0 to 5:


names = ['Albert', 'Beck', 'Caro', 'Dimpna', 'Eli', 'Filiz']
found = False

name = input('Enter a name: ')

# Perform search
for i in range(6):
if name == names[i]:
print('Name found.')
found = True

if found == False:
print('No match.')

64
CAMBRIDGE IGCSE™ & O LEVEL COMPUTER SCIENCE: PROGRAMMING BOOK

10.5 A flowchart for the system:

START

names ← ['Albert', 'Beck', 'Caro,' 'Beck', 'Caro', 'Beck']

found ← FALSE
i←1

INPUT
name

TRUE found = FALSE


i=7
FALSE

FALSE TRUE
i←i+1

OUTPUT
FALSE name = STOP
'No match.'
names[i]

TRUE

OUTPUT
'Name found at' + i

found ← TRUE

A pseudocode algorithm for the system:


names  ['Albert', 'Beck', 'Caro', 'Beck', 'Caro', 'Beck']
found  FALSE

INPUT name
// Perform search
FOR i  1 TO 6
IF name = names[i]

65
CAMBRIDGE IGCSE™ & O LEVEL COMPUTER SCIENCE: PROGRAMMING BOOK

THEN
OUTPUT 'Name found at location: ' + i
found = TRUE
ENDIF
NEXT

IF found = FALSE
THEN
OUTPUT 'No match found.'
ENDIF
A Python implementation:
names = ['Albert', 'Beck', 'Caro', 'Beck', 'Caro', 'Beck']
found = False

name = input('Enter a name: ')

# Perform search
for i in range(6):
if name == names[i]:
print('Name found at location: ', i)
found = True

if found == False:
print('No match found.')

10.6 def search():


# Initialise list to be searched
letters = ['a','b','c','d','e','f']

found = False
user_letter = input('Enter the character to search for: ')

counter = 0
# Perform search of letters
while counter < len(letters) and found == False:
if user_letter == letters[counter]:
found = True
counter = counter + 1

if found == True:
print('Match found.')
else:
print('No match.')

# Call function
search()

66
CAMBRIDGE IGCSE™ & O LEVEL COMPUTER SCIENCE: PROGRAMMING BOOK

10.7 a A pseudocode algorithm:


// Initialise arrays:
BabyID  ['B2003', 'B2004', 'B2005']
gender  ['Male', 'Female', 'Female']
weight  [3.5, 3.34, 3.62]
blood_group  ['O Neg', 'A Pos', 'O Pos']

// Implement the algorithm:


INPUT search_ID

FOR i  0 TO 3
IF search_ID = BabyID[i]
THEN
OUTPUT gender[i], weight[i], blood_group[i]
ENDIF
NEXT

b A Python implementation:
# Initialise arrays:
BabyID = ['B2003', 'B2004', 'B2005']
gender = ['Male', 'Female', 'Female']
weight = [3.5, 3.34, 3.62]
blood_group = ['O Neg', 'A Pos', 'O Pos']

# Implement the algorithm:


search_ID = input("Please enter the baby's ID: ")

for i in range(0,3):
if search_ID == BabyID[i]:
p
rint(gender[i] + ' ' + str(weight[i]) + 'kg ' + blood_group[i])

10.8 a–b
# In arrays the weights have to be
# stored in strings but with Python lists
# this is unnecessary.

# Initialise 2D array:
baby_data = [['B2003', 'Male', '3.5' , 'O Neg'],
['B2004', 'Female', '3.34', 'A Pos'],
['B2005', 'Female', '3.62', 'O Pos']]

# Implement the algorithm:


search_ID = input("Please enter the baby's ID: ")

for i in range(0,3):
if search_ID == baby_data[i][0]:
print(baby_data[i][1] + ' ' + baby_data[i][2]
+ 'kg ' + baby_data[i][3])

67
CAMBRIDGE IGCSE™ & O LEVEL COMPUTER SCIENCE: PROGRAMMING BOOK

Challenge tasks
10.1 A text-based Python solution:
# Initialise arrays:
BabyID = ['B2003', 'B2004', 'B2005']
gender = ['Male', 'Female', 'Female']
weight = [3.5, 3.34, 3.62]
blood_group = ['O Neg', 'A Pos', 'O Pos']

# Implement the algorithm:


search_gender = input('Gender: ')
total = 0

print(search_gender, 'baby IDs:')


for i in range(3):
total = total + weight[i]
if search_gender == gender[i]:
print(BabyID[i])

average = round(total / len(BabyID), 2)


print('Average weight of all babies: ' + str(average) + 'kg')

10.2 #
 Initialise 2D array:
baby_data = [['B2003', 'B2004', 'B2005'],
['Male', 'Female', 'Female'],
['3.5', '3.34', '3.62'],
['O Neg', 'A Pos', 'O Pos']]

# Implement the algorithm:


search_gender = input('Gender: ')
total = 0

print(search_gender, 'baby IDs:')


for i in range(3):
total = total + float(baby_data[2][i])
if search_gender == baby_data[1][i]:
print(baby_data[0][i])

average = round(total / len(baby_data[0]), 2)


print('Average weight of all babies: ' + str(average) + 'kg')

Skills focus questions


10.1 1 Pass 2:

Compare values 0 and 1: [2,1,4,3,5,6] becomes [1,2,4,3,5,6]

Compare values 1 and 2: [1,2,4,3,5,6] becomes [1,2,4,3,5,6]

Compare values 2 and 3: [1,2,4,3,5,6] becomes [1,2,3,4,5,6]

68
CAMBRIDGE IGCSE™ & O LEVEL COMPUTER SCIENCE: PROGRAMMING BOOK

2 Three passes would be required:

Pass 1:

[7,2,4,1] becomes [2,4,1,7]

Pass 2:

[2,4,1,7] becomes [2,1,4,7]

Pass 3:

[2,1,4,7] becomes [1,2,4,7]

End-of-chapter tasks
1 a A pseudocode algorithm:
numbers  [17, 103, 36, 42, 85, 3, 64, 98, 55, 11]
total  0
largest  0
smallest  1000000

PROCEDURE input_data()
INPUT data_item
INPUT index // From 0 to LENGTH(numbers)-1
numbers[index]  data_item
ENDPROCEDURE
PROCEDURE output_data():
global total
global largest
global smallest
FOR i  0 TO LENGTH(numbers)-1
total  total + numbers[i]
IF numbers[i] > largest
THEN
largest  numbers[i]
ENDIF
IF numbers[i] < smallest
THEN
smallest  numbers[i]
ENDIF
NEXT

average  total / LENGTH(numbers)


OUTPUT total, largest, smallest, average
ENDPROCEDURE

// Main program
choice  '0'
WHILE choice != '3' DO
choice  INPUT '1', '2' or '3'

69
CAMBRIDGE IGCSE™ & O LEVEL COMPUTER SCIENCE: PROGRAMMING BOOK

IF choice = '3'
THEN
OUTPUT 'Thanks for using this application.'
ELSE
WHILE (choice != '1' and choice != '2') DO
choice  INPUT INPUT '1', '2' or '3'
ENDWHILE

IF choice = '1'
THEN
input_data()
ELSE
output_data()
ENDIF
input('\nPress any key to continue.')
ENDWHILE
ENDWHILE

b Since the loop has to loop through every number to find the total of them, we cannot
optimise it any further.

c A Python implementation:
numbers = [17, 103, 36, 42, 85, 3, 64, 98, 55, 11]
total = 0
largest = 0
smallest = 1000000

def input_data():
data_item = int(input('Enter an integer: '))
index = int(input(
'Enter an index from 0 to ' +
str(len(numbers)-1) + ': '))
numbers[index] = data_item

def output_data():
global total
global largest
global smallest
for i in range(len(numbers)):
total = total + numbers[i]
if numbers[i] > largest:
largest = numbers[i]
if numbers[i] < smallest:
smallest = numbers[i]

average = total / len(numbers)


print('\nTotal:', total)
print('Largest:', largest)
print('Smallest:', smallest)
print('Average:', average)

70
CAMBRIDGE IGCSE™ & O LEVEL COMPUTER SCIENCE: PROGRAMMING BOOK

# Main program
choice = '0'
while choice != '3':
choice = input('''
Menu:
1. Input data
2. Output data
3. Finish

Choose 1, 2 or 3: ''')

if choice == '3':
print('\nThanks for using this application.')
else:
while (choice != '1' and choice != '2'):
choice = input('Enter 1, 2 or 3: ')

if choice == '1':
input_data()
else:
output_data()

input('\nPress any key to continue.')

2 a A turtle answer:
# rainbow.py
from turtle import *

pensize(50)
line_length = 20
colours = ['Red', 'Orange', 'Yellow', 'Blue', 'Green', 'Indigo', 'Violet']

for i in range(7):
pencolor(colours[i])
forward(line_length)
right(72)
line_length = line_length + 15

b A turtle answer:
# rainbow.py
from turtle import *

pensize(50)
line_length = 20
colours = ['Red', 'Orange', 'Yellow', 'Blue', 'Green', 'Indigo', 'Violet']

for i in range(14):
if i < 7:
pencolor(colours[i])
forward(line_length)

71
CAMBRIDGE IGCSE™ & O LEVEL COMPUTER SCIENCE: PROGRAMMING BOOK

right(72)
line_length = line_length + 15
else:
pencolor(colours[i-7])
forward(line_length)
right(72)
line_length = line_length + 15

c A turtle answer:
# rainbow.py
from turtle import *
import random
pensize(50)
line_length = 20
colours = ['Red', 'Orange', 'Yellow', 'Blue', 'Green', 'Indigo', 'Violet']
for i in range(10):
pencolor(random.choice(colours))
forward(line_length)
right(72)
line_length = line_length + 15

3 a A pseudocode algorithm:
nums[0:5] OF Integer
// Gather the data and enter it in the array:
FOR i  0 TO 5
INPUT num
nums[i]  num
NEXT
IF nums[0] = nums[5] AND nums[1] = nums[4] AND nums[2] = nums[3]
THEN
OUTPUT 'Palindrome'
ELSE
OUTPUT 'Nothing special'
ENDIF

b A Python implementation:
nums = [None]*6
# Gather the data and enter it in the array:
for i in range(6):
num = int(input('Enter a digit: '))
nums[i] = num
if nums[0] == nums[5] and nums[1] == nums[4] and nums[2] == nums[3]:
print('Palindrome')
else:
print('Nothing special')

72
CAMBRIDGE IGCSE™ & O LEVEL COMPUTER SCIENCE: PROGRAMMING BOOK

4 Here is the pseudocode for three functions that could be used in your program. They then just
need to be called by a menu system. An example is shown in the Python code below.
// Initialise arrays:
Type  ['Cat', 'Dog', 'Dog', 'Parrot']
Colour  ['White', 'Black & White', 'Grey', 'Blue & Red']
Min_age  [5, 12, 1, 8]
Breed  ['Persian', 'Husky', 'Poodle', 'Macaw']
length  len(Type)

PROCEDURE get_data()
INPUT pet_type
FOR i  0 TO length - 1
IF pet_type = Type[i]
THEN
OUTPUT Colour[i], Breed[i], Min_age[i]
ENDIF
NEXT
ENDPROCEDURE

PROCEDURE get_suitable()
INPUT age
FOR i  0 TO length - 1
IF age >= Min_age[i]
THEN
OUTPUT Colour[i], Breed[i], Type[i]
ENDIF
NEXT
ENDPROCEDURE

PROCEDURE get_suitable_advanced()
INPUT pet_type
INPUT age
FOR i  0 TO length - 1
IF pet_type = Type[i] and age >= Min_age[i]
THEN
OUTPUT Colour[i], Breed[i], Type[i]
ENDIF
NEXT
ENDPROCEDURE

// Main program provides a suitable menu (e.g. see Python below)


A Python implementation:
# Initialise arrays:
Type = ['Cat', 'Dog', 'Dog', 'Parrot']
Colour = ['White', 'B&W', 'Grey', 'Blue & Red']
Min_age = [5, 12, 1, 8]
Breed = ['Persian', 'Husky', 'Poodle', 'Macaw']
length = len(Type)

73
CAMBRIDGE IGCSE™ & O LEVEL COMPUTER SCIENCE: PROGRAMMING BOOK

def get_data():
pet_type = input('Animal type: ')
for i in range(length):
if pet_type == Type[i]:
print(Colour[i], Breed[i], 'suitable for children over',
Min_age[i])

def get_suitable():
age = int(input('Youngest pet owner age (if adult enter 18): '))
for i in range(length):
if age >= Min_age[i]:
print(Colour[i], Breed[i], Type[i])

def get_suitable_advanced():
pet_type = input('Animal type: ')
age = int(input('Youngest pet owner age (if adult enter 18): '))
for i in range(length):
if pet_type == Type[i] and age >= Min_age[i]:
print(Colour[i], Breed[i], Type[i])

# Main program
choice = '0'
while choice != '4':
choice = input('''
Menu:
1. Find data about an animal type
2. Find pets based on owner age
3. Find pets based on owner age and pet type
4. Finish

Choose 1, 2, 3 or 4: ''')

if choice == '4':
print('\nThanks for using this application.')
break
else:
while (choice != '1' and choice != '2' and choice != '3'):
choice = input('Enter 1, 2, 3 or 4: ')

if choice == '1':
get_data()
elif choice == '2':
get_suitable()
else:
get_suitable_advanced()

input('\nPress any key to continue.')

74
CAMBRIDGE IGCSE™ & O LEVEL COMPUTER SCIENCE: PROGRAMMING BOOK

5 Here is the pseudocode for the three functions that could be used in your program.
// Initialise 2D array:
pets  [['Cat', 'Dog', 'Dog', 'Parrot'],
['White', 'B&W', 'Grey', 'Blue & Red'],
['5', '12', '1', '8'],
['Persian', 'Husky', 'Poodle', 'Macaw']]
length  len(pets[0])
PROCEDURE get_data()
INPUT pet_type
FOR i  0 TO length - 1
IF pet_type = pets[0][i]
THEN
OUTPUT pets[1][i], pets[3][i], pets[2][i]
ENDIF
NEXT
ENDPROCEDURE
PROCEDURE get_suitable()
INPUT age
FOR i  0 TO length - 1
IF age >= pets[2][i]
THEN
OUTPUT pets[1][i], pets[3][i], pets[0][i]
ENDIF
NEXT
ENDPROCEDURE

PROCEDURE get_suitable_advanced()
INPUT pet_type
INPUT age
FOR i  0 TO length - 1
IF pet_type = pets[0][i] and age >= pets[2][i]
THEN
OUTPUT pets[1][i], pets[3][i], pets[0][i]
ENDIF
NEXT
ENDPROCEDURE

// Main program provides a suitable menu (e.g. see Python below)


The Python implementation shown below leaves out the menu system as this is exactly the same as the
program in task 4.
# Initialise arrays:
pets = [
['Cat', 'Dog', 'Dog', 'Parrot'],
['White', 'B&W', 'Grey', 'Blue & Red'],
['5', '12', '1', '8'],
['Persian', 'Husky', 'Poodle', 'Macaw']]

length = len(pets[0])

75
CAMBRIDGE IGCSE™ & O LEVEL COMPUTER SCIENCE: PROGRAMMING BOOK

def get_data():
pet_type = input('Animal type: ')
for i in range(length):
if pet_type == pets[0][i]:
p
rint(pets[1][i], pets[3][i], 'suitable for children over',
pets[2][i])
def get_suitable():
age = int(input('Youngest pet owner age (if adult enter 18): '))
for i in range(length):
if age >= int(pets[2][i]):
print(pets[1][i], pets[3][i], pets[0][i])

def get_suitable_advanced():
pet_type = input('Animal type: ')
age = int(input('Youngest pet owner age (if adult enter 18): '))
for i in range(length):
if pet_type == pets[0][i] and age >= int(pets[2][i]):
print(pets[1][i], pets[3][i], pets[0][i])

Chapter 11: Checking inputs


Practice tasks
11.1 a A pseudocode implementation: A flowchart algorithm:
INPUT last_name
START
WHILE last_name = '' DO
OUTPUT 'Error.'
INPUT last_name
ENDWHILE INPUT
last_name
// program continues

b A Python implementation:
last_name = input('Enter your lastname:')
TRUE OUTPUT
while last_name == '': last_name
'Error.'
print('Error.') =''
last_name = input('Enter your lastname:')
FALSE
# program continues

Continue with
program

76
CAMBRIDGE IGCSE™ & O LEVEL COMPUTER SCIENCE: PROGRAMMING BOOK

11.2 a A flowchart algorithm:

START

INPUT
month

month = ''
OR TRUE OUTPUT
month > 12
'Error.'
OR
month < 1

FALSE

Continue with
program

A pseudocode implementation:
INPUT month

WHILE month = '' OR month > 12 OR month < 1 DO


OUTPUT 'Error.'
INPUT month
ENDWHILE

// program continues

b A Python implementation:

The while loop tests for no entry as well as the range 1 to 12. It is therefore best not to cast
the input into an integer until the conditions for the while loop have been met, otherwise
errors will be thrown when an empty is string is entered as input.
month = input('Month? [Enter 1 to 12]: ')

while month == '' or int(month) > 12 or int(month) < 1:


print('Error.')
month = input('Month? [Enter 1 to 12]: ')

# program continues

77
CAMBRIDGE IGCSE™ & O LEVEL COMPUTER SCIENCE: PROGRAMMING BOOK

11.3 A pseudocode algorithm:


INPUT password
WHILE LENGTH(password) < 6 DO
OUTPUT 'Error'
INPUT password START
ENDWHILE

// Program continues

11.4 a A flowchart algorithm:


INPUT
A pseudocode implementation: month

INPUT month

WHILE month IS NOT an INTEGER DO


OUTPUT 'Error.'
INPUT month month TRUE
IS NOT OUTPUT
ENDWHILE 'Error.'
integer
// program continues
FALSE
b A Python implementation:
month = input('Enter Month: ')
Continue with
while True: program
try:
int(month)
break
except: START
month = input('Please enter
month as an integer:')

# program continues
INPUT
11.5 a A flowchart algorithm: date

A pseudocode implementation:
INPUT date

WHILE date IS NOT in format yyyy/mm/dd DO date


OUTPUT Error message in format FALSE OUTPUT
INPUT date yyyy/mm/dd 'Error.'
ENDWHILE

// Continue with program TRUE

Continue with
program

78
CAMBRIDGE IGCSE™ & O LEVEL COMPUTER SCIENCE: PROGRAMMING BOOK

b A Python implementation:
from datetime import datetime

def validate_date(d):
while True:
try:
return datetime.strptime
(d, '%Y/%m/%d')
except:
d = input('Date must be in the format yyyy/mm/dd: ')

date = input('Please enter a date: ')


date = validate_date(date)

# Program continues

11.6 A pseudocode implementation:


multiplier  1
total  0

// Input an ISBN-13 number as a string


INPUT isbn

// Obtain the 13th digit


check_digit  INTEGER(isbn[12])

// Iterate through the first 12 digits of the ISBN number


FOR i  0 TO 11
total  total + (INTEGER(isbn[i]) * multiplier)
IF multiplier = 1
THEN
multiplier  3
ELSE
multiplier  1
ENDIF
NEXT

remainder  total MOD 10

IF (10 – remainder) = check_digit


THEN
OUTPUT 'ISBN valid'
ELSE
OUTPUT 'Invalid ISBN number'
ENDIF

79
CAMBRIDGE IGCSE™ & O LEVEL COMPUTER SCIENCE: PROGRAMMING BOOK

Challenge tasks
11.1 a A flowchart algorithm:

START

INPUT
first_name

first_name =''
OR TRUE OUTPUT
just_letters(first_name) 'Error.'
= FALSE

FALSE

Continue with
program

A pseudocode implementation:
FUNCTION just_letters(word)
letters  ['a','b','c','d','e','f','g','h','i','j','k','l','m',
'n','o','p','q','r','s','t','u','v','w','x','y','z']

// Put lowercase letters into an "array" called chars:


chars  ARRAY(LOWER(word))

// Loop through each character checking it is


// in letters and keeping track of this:
correct_counter  0
FOR i  0 TO LENGTH(chars)-1
FOR j  0 TO LENGTH(letters)-1
IF chars[i] = letters[j]
THEN
correct_counter  correct_counter + 1
ENDIF
NEXT
NEXT
IF correct_counter = len(chars)
THEN
RETURN TRUE
ELSE

80
CAMBRIDGE IGCSE™ & O LEVEL COMPUTER SCIENCE: PROGRAMMING BOOK

RETURN FALSE
ENDIF
ENDFUNCTION

INPUT first_name

WHILE first_name = '' OR just_letters(first_name) = False DO


OUTPUT 'Error.'
INPUT first_name
ENDWHILE
// program continues

81
CAMBRIDGE IGCSE™ & O LEVEL COMPUTER SCIENCE: PROGRAMMING BOOK

START
just_letters(word)

letters ← ['a','b','c','d','e','f','g','h',
'i','j','k','l','m','n','o','p','q','r','s',
't','u','v','w','x','y','z']
chars ← ARRAY(LOWER(word))

RETURN
correct_counter ← 0 TRUE
i←0
j←0
TRUE

i= TRUE correct_counter = STOP


LENGTH(chars)
LENGTH(chars) just_letters(word)

i ← i +1 FALSE
FALSE

TRUE j= RETURN
LENGTH(letters) FALSE

FALSE
j ← j +1

chars[i] FALSE
=
letters[j]

TRUE

correct_counter ←
counter_correct + 1

b A Python implementation:
def just_letters(word):
letters = ['a','b','c','d','e','f','g',
'h','i','j','k','l','m','n',
'o','p','q','r','s','t','u',
'v','w','x','y','z']

# Put lowercase letters into an "array" called chars:


chars = list(word.lower())

82
CAMBRIDGE IGCSE™ & O LEVEL COMPUTER SCIENCE: PROGRAMMING BOOK

#Loop through each character checking it is


# in letters and keeping track of this:
correct_counter = 0
for i in range(len(chars)):
for j in range(len(letters)):
if chars[i] == letters[j]:
correct_counter = correct_counter + 1
if correct_counter == len(chars):
return True
else:
return False

first_name = input('Enter your first name: ')


while first_name == '' or just_letters(first_name) == False:
print('Error.')
first_name = input('Enter your first name: ')

# program continues

83
CAMBRIDGE IGCSE™ & O LEVEL COMPUTER SCIENCE: PROGRAMMING BOOK

11.2 a A flowchart algorithm:

START
is_a_day(d)

days ← ['monday', 'tuesday', 'wednesday',


'thursday', 'friday', 'saturday', 'sunday']

i←0

TRUE
RETURN
i=7
FALSE

FALSE

i ← i +1 STOP
is_a_day(d)

FALSE lower(d) TRUE


RETURN
=
TRUE
days[i]

84
CAMBRIDGE IGCSE™ & O LEVEL COMPUTER SCIENCE: PROGRAMMING BOOK

A pseudocode implementation:
FUNCTION is_a_day(d)
days  ['monday', 'tuesday', 'wednesday', 'thursday',
'friday', 'saturday', 'sunday']
FOR i  0 TO 6
IF LOWER(d) = days[i]
THEN
RETURN TRUE
ENDIF
RETURN FALSE
ENDFUNCTION

INPUT day

WHILE is_a_day(day) = False DO


OUTPUT 'Error.'
INPUT day
ENDWHILE

// program continues

b Below is a Python implementation that iterates through an array to check that the input matches one
of the items in it. There are a number of ways of doing this. By doing it this way there is no need to
test for the presence of an empty string because that does not exist in the array.
def is_a_day(d):
days = ['monday', 'tuesday', 'wednesday', 'thursday',
'friday', 'saturday', 'sunday']
for i in range(7):
if d.lower() == days[i]:
return True
return False

day = input('Day? [Enter Monday, Tuesday, etc.]: ')

while is_a_day(day) == False:


print('Error.')
day = input('Day? [Enter Monday, Tuesday, etc.]: ')

# program continues

85
CAMBRIDGE IGCSE™ & O LEVEL COMPUTER SCIENCE: PROGRAMMING BOOK

Of course using Python’s list tools, this could have been achieved without iterating through the list like this:
days = ['monday', 'tuesday', 'wednesday', 'thursday',
'friday', 'saturday', 'sunday']

day = input('Day? [Enter Monday, Tuesday, etc.]: ').lower()

while day not in days:


print('Error.')
day = input('Day? [Enter Monday, Tuesday, etc.]: ')

# program continues

11.3 a A flowchart algorithm:

START

INPUT
p

LENGTH(p) < 6
OR
TRUE OUTPUT
contains_letter(p) = FALSE
OR 'Error.'
contains_number(p)
= FALSE

FALSE

Continue with
program

86
CAMBRIDGE IGCSE™ & O LEVEL COMPUTER SCIENCE: PROGRAMMING BOOK

START
contains_letter(password)

letters ← ['a','b','c','d','e','f','g','h',
'i','j','k','l','m','n','o','p','q','r','s',
't','u','v','w','x','y','z']
pw ← ARRAY(password)

i←0
j←0

TRUE RETURN
i = LENGTH(pw)
FALSE

i ← i +1 FALSE

TRUE
j = LENGTH(letters)

FALSE
j ← j +1

LOWER(pw[i]) FALSE
=
letters[j]

TRUE

RETURN STOP
TRUE contains_letter(password)

87
CAMBRIDGE IGCSE™ & O LEVEL COMPUTER SCIENCE: PROGRAMMING BOOK

START
contains_number(password)

numbers ← ['0','1','2','3','4','5','6','7','8','9']
pw ← ARRAY(password)

i←0
j←0

TRUE RETURN
i = LENGTH(pw)
FALSE

i ← i +1 FALSE

TRUE j=
LENGTH(numbers)

FALSE
j ← j +1

pw[i] FALSE
=
numbers[j]

TRUE

RETURN STOP
TRUE contains_number(password)

88
CAMBRIDGE IGCSE™ & O LEVEL COMPUTER SCIENCE: PROGRAMMING BOOK

A pseudocode implementation:
FUNCTION contains_letter(password)
letters  ['a','b','c','d','e','f','g',
'h','i','j','k','l','m','n',
'o','p','q','r','s','t','u',
'v','w','x','y','z']
// Create an array from letters in password
pw  ARRAY(password)
FOR i  0 TO LENGTH(pw)-1
FOR j  0 TO LENGTH(letters)-1
IF LOWER(pw[i]) = letters[j]
THEN
RETURN TRUE
ENDIF
NEXT
NEXT
RETURN FALSE
ENDFUNCTION

FUNCTION contains_number(password):
numbers  ['0','1','2','3','4','5','6','7','8','9']
pw  ARRAY(password)
FOR i  0 TO LENGTH(pw)-1
FOR j  TO LENGTH(numbers)-1
IF pw[i] = numbers[j]
THEN
RETURN TRUE
ENDIF
NEXT
NEXT
RETURN FALSE
ENDFUNCTION

INPUT p

WHILE LENGTH(p) < 6 OR contains_letter(p) = FALSE


OR contains_number(p) = False DO
OUTPUT 'Error'
INPUT p
ENDWHILE

// Program continues

b A Python implementation:
def contains_letter(password):
letters = ['a','b','c','d','e','f','g',
'h','i','j','k','l','m','n',
'o','p','q','r','s','t','u',
'v','w','x','y','z']

89
CAMBRIDGE IGCSE™ & O LEVEL COMPUTER SCIENCE: PROGRAMMING BOOK

pw = list(password)
for i in range(len(pw)):
for j in range(len(letters)):
if pw[i].lower() == letters[j]:
return True
return False

def contains_number(password):
numbers = ['0','1','2','3','4','5','6','7','8','9']
pw = list(password)
for i in range(len(pw)):
for j in range(len(numbers)):
if pw[i] == numbers[j]:
return True
return False

p = input('Enter password: ')


while len(p) < 6 or contains_letter(p) == False
or contains_number(p) == False:
print('Error')
password = input('Your password must have six or more characters
including one letter and one number: ')

# Program continues
The above program can be made more efficient by doing both tests in one function and inside one set
of nested loops rather than separately. This will make the code harder to read and debug. The function
will also be less flexible because then they cannot be used elsewhere in the program separately, should
this be needed. Again there is a simpler way of writing these two functions in Python:
def contains_letter(password):
letters = 'abcdefghijklmnopqrstuvwxyz'
for i in range(len(password)):
if password[i].lower() in letters:
return True
break
return False

def contains_number(password):
numbers = '1234567890'
for i in range(len(password)):
if password[i] in numbers:
return True
break
return False

90
CAMBRIDGE IGCSE™ & O LEVEL COMPUTER SCIENCE: PROGRAMMING BOOK

11.4 a A flowchart algorithm:

START

INPUT
day

day > 31 TRUE


OR OUTPUT
day < 1 'Error.'

FALSE

Continue with
program

A pseudocode implementation:
INPUT day

WHILE day > 31 OR day < 1 DO


OUTPUT 'Error'
INPUT day
ENDWHILE

// program continues

b A Python implementation:
day = input('Enter day of month: ')

while True:
try:
while int(day) > 31 or int(day) <1:
day = input('Enter a number from 1 to 31: ')
break
except:
day = input('Not an integer. Please enter month as an integer: ')
# program continues

91
CAMBRIDGE IGCSE™ & O LEVEL COMPUTER SCIENCE: PROGRAMMING BOOK

11.5 a A flowchart algorithm:

START

INPUT
fn

fn = ''
OR
just_letters(fn) = FALSE TRUE OUTPUT
OR 'Error.'
begins_capital(fn)
= FALSE

FALSE

Continue with
program

START
begins_capital(word)

RETURN FALSE word[0] is TRUE RETURN


FALSE uppercase TRUE

STOP
begins_capital(word)

92
CAMBRIDGE IGCSE™ & O LEVEL COMPUTER SCIENCE: PROGRAMMING BOOK

START
just_letters(word)

letters ← ['a','b','c','d','e','f','g','h','i','j','k','l',
'm','n','o','p','q','r','s','t','u','v','w','x','y','z',"'",'-']

chars ← ARRAY(LOWER(word)

RETURN
correct_counter ← 0 TRUE
i←0
j←0
TRUE

i= TRUE correct_counter = STOP


LENGTH(chars)
LENGTH(chars) just_letters(word)

i ← i +1 FALSE
FALSE

j=
TRUE RETURN
LENGTH(letters)
FALSE

FALSE
j ← j +1

chars[i] FALSE
=
letters[j]

TRUE

correct_counter ←
counter_correct + 1

93
CAMBRIDGE IGCSE™ & O LEVEL COMPUTER SCIENCE: PROGRAMMING BOOK

A pseudocode implementation that is an adaptation of the solution in Challenge task 11.1:


FUNCTION just_letters(word)
letters  ['a','b','c','d','e','f','g',
'h','i','j','k','l','m','n',
'o','p','q','r','s','t','u',
'v','w','x','y','z',"'",'-']

// Put lowercase letters into an "array" called chars:


chars  ARRAY(LOWER(word)

// Loop through each character checking it is


// in letters and keeping track of this:
correct_counter  0
FOR i  0 TO LENGTH(chars)-1
FOR j  0 TO LENGTH(letters)-1
IF chars[i] = letters[j]
THEN
correct_counter  correct_counter + 1
ENDIF
NEXT
NEXT
IF correct_counter = len(chars)
THEN
RETURN TRUE
ELSE
RETURN FALSE
ENDIF
ENDFUNCTION

FUNCTION begins_capital(word)
IF word[0] is uppercase
THEN
RETURN TRUE
ELSE
RETURN FALSE
ENDIF
ENDFUNCTION

INPUT fn

WHILE fn = '' OR just_letters(fn) = FALSE


OR begins_capital(fn) = False DO
OUTPUT 'Error.'
INPUT fn
ENDWHILE

// program continues

94
CAMBRIDGE IGCSE™ & O LEVEL COMPUTER SCIENCE: PROGRAMMING BOOK

b A Python implementation that is an adaptation of the solution in Challenge task 11.1:


def just_letters(word):
letters = ['a','b','c','d','e','f','g',
'h','i','j','k','l','m','n',
'o','p','q','r','s','t','u',
'v','w','x','y','z',"'",'-']

# Put lowercase letters into an "array" called chars:


chars = list(word.lower())

#Loop through each character checking it is


# in letters and keeping track of this:
correct_counter = 0
for i in range(len(chars)):
for j in range(len(letters)):
if chars[i] == letters[j]:
correct_counter = correct_counter + 1
if correct_counter == len(chars):
return True
else:
return False

def begins_capital(word):
if word[0].isupper():
return True
else:
return False

fn= input('Enter your first name: ')

while fn == '' o
r just_letters(fn) == False
or begins_capital(fn) == False:
print('Error.')
fn= input('Enter your first name: ')

# program continues
As this is an Extension Challenge task, we can look a little more at style. Look at this bit of code:
if correct_counter == len(chars):
return True
else:
return False
This follows the IF...ELSE structure we have learnt in Chapter 7 but we can write this in a much
shorter (and more correct) way. The double equals symbol is a Boolean operator so it is already
returning True or False to the IF clause. This means that we can replace all the above code with:
return correct_counter == len(chars)

95
CAMBRIDGE IGCSE™ & O LEVEL COMPUTER SCIENCE: PROGRAMMING BOOK

In the same way, we do not need to evaluate


or just_letters(fn) == False
in our final while condition; we can just write:
or not just_letters(fn)
Our program can thus be written more elegantly. In the example below I have implemented this better
practice and shortened the code further by taking advantage of Python’s ability to iterate through strings.
def just_letters(word):
letters = "abcdefghijklmnopqrstuvwxyz'-"

# Put lowercase letters into an "array" called chars:


chars = list(word.lower())

#Loop through each character checking it is


# in letters and keeping track of this:
correct_counter = 0
for i in range(len(chars)):
if chars[i] in letters:
correct_counter = correct_counter + 1
return correct_counter == len(chars)

def begins_capital(word):
return word[0].isupper()

fn = input('Enter your first name: ')

while fn == '' or not just_letters(fn) or not begins_capital(fn):


print('Error')
fn = input('Enter your first name: ')

# Program continues

96
CAMBRIDGE IGCSE™ & O LEVEL COMPUTER SCIENCE: PROGRAMMING BOOK

11.6 a A flowchart algorithm:

START

odds ← 3 * (barcode[0] + barcode[2] + barcode[4] + barcode[6])


evens ← (barcode[1] + barcode[3] + barcode[5])
checkdigit ← (odds + evens) MOD 10

OUTPUT FALSE checkdigit = TRUE OUTPUT


'invalid' barcode[7] 'valid'

STOP

A pseudocode implementation:
odds  3 * (barcode[0] + barcode[2] + barcode[4] + barcode[6])
evens  (barcode[1] + barcode[3] + barcode[5])
checkdigit  (odds + evens) % 10

IF checkdigit = barcode[7]
THEN
OUTPUT 'valid'
ELSE
OUTPUT 'invalid'
ENDIF

b A Python implementation:
# test data
barcode = [3, 4, 7, 8, 6, 6, 2, 2]

# main program
odds = 3 * (barcode[0] + barcode[2] + barcode[4] + barcode[6])
evens = (barcode[1] + barcode[3] + barcode[5])
checkdigit = (odds + evens) % 10

if checkdigit == barcode[7]:
print('valid')
else:
print('invalid')

97
CAMBRIDGE IGCSE™ & O LEVEL COMPUTER SCIENCE: PROGRAMMING BOOK

Skills focus questions


11.1 1 A presence check and a length check.

2 onceuponatime – is a well-known phrase.


G30graPHY – is too short and difficult to remember.
lemonvansgreetflu – is made of an unrelated list of words and so a good password.
theclockswerestrikingthirteen – is a well-known quote from George Orwell’s 1984 novel.

End-of-chapter tasks
1 A Python text-based solution:
def valid_user(u, p):
# validate username
letters = ['a','b','c','d','e','f','g',
'h','i','j','k','l','m','n',
'o','p','q','r','s','t','u',
'v','w','x','y','z','-']

# Put letters from username into an "array" called chars:


chars = list(u)

#Loop through each character checking it is


# in letters and keeping track of this:
correct_counter = 0
for i in range(len(chars)):
for j in range(len(letters)):
if chars[i] == letters[j]:
correct_counter = correct_counter + 1
break
if correct_counter != len(chars):
return False

# validate password
if len(p) != 7:
return False
if p[0] != 'P':
return False
if int(p[1:7]) > 999999:
return False
if int(p[1:7]) < 100000:
return False

# If the logic flow gets this far:


return True

98
CAMBRIDGE IGCSE™ & O LEVEL COMPUTER SCIENCE: PROGRAMMING BOOK

# test function:
username = input('Username: ')
password = input('Password: ')
print(valid_user(username, password))

2 a A flowchart algorithm:

START

INPUT
username
password

valid_user(username, TRUE
password) = True

FALSE

OUTPUT Continue with


'Error.' program

valid_user(username, TRUE
password) = TRUE

FALSE

OUTPUT
'Locked Out.'

99
CAMBRIDGE IGCSE™ & O LEVEL COMPUTER SCIENCE: PROGRAMMING BOOK

START STOP
valid_user(u, p) valid_user(u, p)

letters ← ['a','b','c','d','e','f','g','h','i','j','k','l',
'm','n','o','p','q','r','s','t','u','v','w','x','y','z','-'] FALSE
correct_counter = RETURN
chars ← ARRAY(u) FALSE
LENGTH(chars)

i←0
TRUE
j←0
correct_counter ← 0

FALSE
RETURN
LENGTH(p) FALSE
=7
i= TRUE
LENGTH(chars)
TRUE

i ← i +1 FALSE FALSE
RETURN
(p)[0] = 'P' FALSE
j=
TRUE
LENGTH(letters) TRUE

FALSE INTEGER FALSE


j ← j +1 (SUBSTRING RETURN
(p, 1, 6)) FALSE
chars[i] FALSE > 999999
=
letters[j]
TRUE

TRUE

correct_counter ← INTEGER FALSE


counter_correct + 1 (SUBSTRING RETURN
(p, 1, 6)) FALSE
< 100000

TRUE
RETURN
TRUE

100
CAMBRIDGE IGCSE™ & O LEVEL COMPUTER SCIENCE: PROGRAMMING BOOK

A pseudocode implementation:
IMPORT sys

FUNCTION valid_user(u, p)
// validate username
letters  ['a','b','c','d','e','f','g',
'h','i','j','k','l','m','n',
'o','p','q','r','s','t','u',
'v','w','x','y','z','-']

// Put letters from username into an "array" called chars:


chars  list(u)

// Loop through each character checking it is


// in letters and keeping track of this:
correct_counter  0
FOR i  0 TO LENGTH(chars) - 1
FOR j  0 TO LENGTH(letters)-1
IF chars[i] = letters[j]
THEN
correct_counter  correct_counter + 1
ENDIF
NEXT j
NEXT i
IF correct_counter != LENGTH(chars)
THEN
RETURN FALSE
ENDIF

// validate password
IF LENGTH(p) != 7
THEN
RETURN FALSE
ENDIF
IF p[0] != 'P'
THEN
RETURN FALSE
ENDIF
IF int(p[1:7]) > 999999
THEN
RETURN FALSE
ENDIF
IF int(p[1:7]) < 100000
THEN
RETURN FALSE
ENDIF

// If the logic flow gets this far:


RETURN TRUE
ENDFUNCTION

101
CAMBRIDGE IGCSE™ & O LEVEL COMPUTER SCIENCE: PROGRAMMING BOOK

INPUT username
INPUT password

IF valid_user(username, password) = False


THEN
OUTPUT 'Error. Please try again.'
INPUT username
INPUT password
ELSE
OUTPUT 'Welcome.'
sys.EXIT
ENDIF
IF valid_user(username, password) = False
THEN
OUTPUT 'Locked Out'
ELSE
OUTPUT 'Welcome.'
ENDIF

b A text-based Python implementation:


import sys

def valid_user(u, p):


# the code for this function is the same as in last task
# (Question 1).

username = input('Username: ')


password = input('Password: ')

if valid_user(username, password) == False:


print('Error. Please try again.')
username = input('Username: ')
password = input('Password: ')
else:
print('Welcome.')
sys.exit()
if valid_user(username, password) == False:
print('Locked Out')
else:
print('Welcome.')

Chapter 12: Testing


Practice tasks
12.1 a Syntax error
b Runtime error
c Logical error

102
CAMBRIDGE IGCSE™ & O LEVEL COMPUTER SCIENCE: PROGRAMMING BOOK

12.2 x y w Output Comments


0 0 0 Initialisation values of the variables.
60 15 0 The new values are input.
x is reduced by 15, w is incremented by 1.
45 15 1 Loop returns to the WHILE condition check.
As x > y, loop runs.
x is reduced by 15, w is incremented by 1.
30 15 2 Loop returns to the WHILE condition check.
As x > y, loop runs.
x is reduced by 15, w is incremented by 1.
15 15 3 Loop returns to the WHILE condition check.
As x = y, loop exits.
3 The value in w is output.

The output is incorrect as 60 quotient 15 = 4. The error is in the last iteration – the loop
condition should read WHILE x >= y.

12.3 a The aim of the flowchart is to return a5. Use of trace tables with different input values can
help to determine the purpose of unfamiliar programs.

b The flowchart is following the structure of a REPEAT. . .UNTIL loop.

12.4 a The value passed to tins is correctly cast to an Integer as you cannot have a fraction of a tin
of paint. The system makes use of simple division to calculate the number of tins of paint
required; the resultant number is then rounded to an Integer. In some of your test cases, you
should have found that this results in the number of tins being rounded down. In test cases
where rounding area / coverage produces results with the decimal part of the answer being
0.5 or more, this is not a problem. Rounding down, though, will result in not having enough
paint to complete the job.

b To resolve the problem, the number of tins calculated needs to be rounded up. This could be
achieved in pseudocode by using a ROUND UP command. In Python this could be solved
by importing the math library and using the ceil() function:
>>> 4.9 * 0.5
2.45
>>> int(4.9 * 0.5)
2
>>> import math
>>> math.ceil(4.9 * 0.5)
3

103
CAMBRIDGE IGCSE™ & O LEVEL COMPUTER SCIENCE: PROGRAMMING BOOK

12.5 a
 and b Appropriate data types and input validation with boundary data mentioned when
appropriate.

Data Item Data Type Input Validation


• Presence check – cannot be a null value.
• It might be appropriate to reject certain characters, for
Name String example, a $ symbol. But as this is a children’s address
book it is possible that the child would record a
nickname of their friend which might include symbols.
Current Date • None required because the system will pass the value
Date correctly.
(from system)
• Format check – to ensure the value input number is in
the expected format.
• Type check – to ensure the value input is a valid date.
• Range check – it would be reasonable to have a range
check. But it would be difficult to decide on specific
Date of Birth dates as the date on which the friend is entered into
Date the app cannot be known. The range limit for earliest
(When friend
date could be set to reject a date more than 100 years
enters data)
in the past. It is possible to link the app to the current
system date and reject dates in the future.
• You might consider a presence check – but what
happens if the child does not know the friend’s date
of birth. Enforcing a presence check would mean the
friend could not be entered into the app
Age Integer • None required as this is an output not an input.

c Invalid and boundary data that could be used as test data:

Test Area Tested Data to use Expected Outcome


1 Invalid data Leave name Input rejected and error message
Input empty “Enter a Value” generated.
Presence check on Name
2 Invalid Data Mon/10/2001
Format check on Date of Birth
Input rejected and error message
(Assuming the set format is 1/3/05
“Not correct Format” generated.
dd/mm/yyyy.)
22-12-2007
3 Invalid Data 51/21/2007 Input rejected and error message
Type check on Date of Birth “Not a correct date” generated.

(continued)

104
CAMBRIDGE IGCSE™ & O LEVEL COMPUTER SCIENCE: PROGRAMMING BOOK

Test Area Tested Data to use Expected Outcome


4 Invalid Data 10/10/1870 Input rejected and error message
“Date to early” generated.
Range check on Date of Birth
(Assuming the range is set as
01/01/1900 and the current Input rejected and error message
date.) 10/05/2070 “Date in future” generated.
5 Boundary Data 01/01/1900 Input accepted.
Range check on Date of Birth
Minimum value
(Assuming the minimum range 31/12/1899 Input rejected and error message
is set as 01/01/1900.) “Date to early” generated.
6 Boundary Data The current Input accepted.
system date
Range check on Date of Birth
Maximum value
Tomorrow’s
(Assuming the maximum system date Input rejected and error message
range is set as todays date.) “Date in future” generated.
7 Invalid Data
Presence check on Date of Leave date
Input rejected and error message
Birth of birth Input
“Enter a Value” generated.
empty
(Only when entered as a
search input.)

You might be surprised to see the older age being used to test the minimum end of the range check for
date of birth. Remember the older you are the earlier your date of birth.

Challenge tasks
12.1 a x y counter Output Comments
−1 Initialisation values of the variables.
15 5 −1 The new values are input.
x is reduced by y, counter is incremented by 1.
10 5 0 Loop returns to the WHILE condition check.
As x > −1, loop runs.
x is reduced by y, counter is incremented by 1.
5 5 1 Loop returns to the WHILE condition check.
As x > −1, loop runs.
x is reduced by y, counter is incremented by 1.
0 5 2 Loop returns to the WHILE condition check.
As x > −1, loop runs.
(continued)

105
CAMBRIDGE IGCSE™ & O LEVEL COMPUTER SCIENCE: PROGRAMMING BOOK

x y counter Output Comments


x is reduced by y, counter is incremented by 1.
-5 5 3 Loop returns to the WHILE condition check.
As x > −1, loop exits.
3 The value in counter is output.

b x y counter Output Comments


−1 Initialisation values of the variables.
18 4 −1 The new values are input.
x is reduced by y, counter is incremented by 1.
14 4 0 Loop returns to the WHILE condition check.
As x > −1, loop runs.
x is reduced by y, counter is incremented by 1.
10 4 1 Loop returns to the WHILE condition check.
As x > −1, loop runs.
x is reduced by y, counter is incremented by 1.
6 4 2 Loop returns to the WHILE condition check.
As x > −1, loop runs.
x is reduced by y, counter is incremented by 1.
2 4 3 Loop returns to the WHILE condition check.
As x > −1, loop runs.
x is reduced by y, counter is incremented by 1.
−2 4 4 Loop returns to the WHILE condition check.
As x > −1, loop exits.
4 The value in counter is output.

12.2 a x y w Output Comments


17 6 The new values are input.
17 6 6 w is assigned the value of y.
x is reduced by y, w is increased by y.
11 6 12 Loop returns to the WHILE condition check.
As x > 0, loop runs.
x is reduced by y, w is increased by y.
5 6 18 Loop returns to the WHILE condition check.
As x > 0, loop runs.
x is reduced by y, w is increased by y.
-1 6 24 Loop returns to the WHILE condition check.
As x < 0, loop exits.
24 The value in w is output.
(continued)

106
CAMBRIDGE IGCSE™ & O LEVEL COMPUTER SCIENCE: PROGRAMMING BOOK

b x y w Output Comments
18 6 The new values are input.
18 6 6 w is assigned the value of y.
x is reduced by y, w is increased by y.
12 6 12 Loop returns to the WHILE condition check.
As x > 0, loop runs.
x is reduced by y, w is increased by y.
6 6 18 Loop returns to the WHILE condition check.
As x > 0, loop runs.
x is reduced by y, w is increased by y.
0 6 24 Loop returns to the WHILE condition check.
As x = 0, loop runs.
-6 6 30 As x < 0, loop exits.
30 The value in w is output.

End-of-chapter tasks
1 a Alpha testing – the game has not been completed or distributed at this point.

b Beta testing – the weather app has been completed and is now being distributed to selected
testers before being deployed to the public.

2 a Runtime error

b Syntax error

c Logical error

3 a Runtime errors can be detected by the IDE when the program is run or compiled. The IDE
will display error messages and often highlight the line where the problem occurs. This may
be enough for the programmer to fix the problem straight away. Alternatively, there may be a
need to consult the official language documentation to find out what is the required syntax in
this situation.

b Syntax errors are usually visible before a program is run or compiled in the IDE. “Pretty
text” or “syntax highlighting” is a feature found in all programming IDEs. A programmer
can often spot mistakes by looking out for where this goes wrong. For example, when many
lines of code are green in IDLE this indicates that a speech mark has been missed off the end
of a string. On other occasions the syntax errors may be small but will be highlighted by the
IDE when the programmer tries to run or compile it. An error message will also be given to
indicate what the problem is.

c Logical errors can be found by producing trace tables, running the IDE debugger and
stepping through a program to see what values are held in each variable at each line of the
program; by running tests with boundary, incorrect, and invalid data sets to see whether the
expected output is produced and by alpha and beta testing. Fixing the errors needs careful
thought but is often easier than finding them. Once a fix has been applied another set of tests
will need to be run.

107
CAMBRIDGE IGCSE™ & O LEVEL COMPUTER SCIENCE: PROGRAMMING BOOK

4 Error Explanation / Correction


small  0 As all the numbers input are between 1 and 99.
Initialising small to zero will mean it will always be less
than the value of the numbers input and therefore
never change.
To correct, either initialise small to a number larger
than 99:
small  99
or assign the first input value to small:
INPUT Number
small  number
IF number > 0 OR number < 100 Using OR as a logical operator to connect the criteria
will mean the condition will accept any input value.
To correct change the logical operator to AND:
IF number > 0 AND number < 100
IF number > 0 OR number < 100 The required input range is 1 to 100. Setting the
criteria to <100 will reject the number 100.
To correct change the comparison to less than or
equals (<=):
WHILE number > 0 AND number <= 100
IF number > 0 OR number < 100 The required input range is 1 to 100. Setting the
criteria to >0 will accept any decimal inputs above 0
but less than 1.0.
To correct change the comparison to greater than or
equals to 1 (>=1):
IF number >=1 AND number <= 100
IF number > large This code assigns the value in the variable large to the
THEN variable number. This is the wrong way around as large
number  large will remain unaltered as 0.
To correct swap the assignment:
large  number
OUTPUT average The average is printed within the loop. This means as
ENDWHILE each value is input the newly calculated average will
be output. The task required outputs to be made when
the sequence had completed.
To correct move the OUTPUT after the loop ends:
ENDWHILE
OUTPUT average
(continued)

108
CAMBRIDGE IGCSE™ & O LEVEL COMPUTER SCIENCE: PROGRAMMING BOOK

Error Explanation / Correction


INPUT number The counter is incorrectly incremented. As it is
counter  counter + 1 incremented after the input within the loop it will count
the final input of −1 used to end the sequence.
To correct increment put counter before the input is
made:
counter  counter + 1
INPUT number
OUTPUT 'small' Because small is in speech marks the program will read
it as a string. The system will output the word ‘small’
not the value held in the variable small.
To correct remove the speech marks:
OUTPUT small

5 A Python implementation of the algorithm from the corrected pseudocode in task 4 is shown
here:
large = 0
total = 0
counter = 0

number = int(input('Number: '))


small = number

while number != -1:


if number >= 1 and number <= 100:
if number < small:
small = number
if number > large:
large = number
total = total + number
counter = counter + 1
number = int(input('Number: '))
average = total / counter
else:
print('Out of range - enter number')
number = int(input('Number: '))

print('Average:', average)
print('Smallest:', small)
print('Largest:', large)

109
CAMBRIDGE IGCSE™ & O LEVEL COMPUTER SCIENCE: PROGRAMMING BOOK

Chapter 13: Files and databases


Practice tasks
13.1 a–c Answers provided in the text.

13.2 a A pseudocode solution:


tuesday_array = ARRAY[4, 4, 8, 10, 14, 17, 19,
20, 20, 19, 17, 16, 14]

temp_text  ''
FOR i  0 TO 12
temp_text  temp_text + STRING(tuesday_array[i]) + ','
NEXT

//Remove last comma:


temp_text  temp_text[0:25]

tuesday  OPEN 'tuesday.txt'


WRITE temp_text TO tuesday

CLOSE tuesday

b A Python solution:
# tuesday.py
tuesday_list = [4, 4, 8, 10, 14, 17, 19, 20, 20, 19, 17, 16, 14]

temp_text = ''
for i in tuesday_list:
temp_text = temp_text + str(i) + ','
temp_text = temp_text[0:-1]

tuesday = open('tuesday.txt', 'w')


tuesday.write(temp_text)

tuesday.close()
To check this script has done what is expected, open the created tuesday.txt file in a text
editor and see what is in it.

110
CAMBRIDGE IGCSE™ & O LEVEL COMPUTER SCIENCE: PROGRAMMING BOOK

13.3 ‘Player alias’ could be used as the primary key for this database table. It is the only other field to have a
set of unique values.

13.4 Only ‘Invisibility Cloak’ is a Boolean field.

13.5 The query required is:


SELECT * FROM Book;
When run you should see:
+------------------------------------------------------------+
| BookID | Title | Author | Year |
+------------------------------------------------------------+
| 1 | The Hobbit | Tolkien | 1937 |
| 2 | The Fellowship of the Ring | Tolkien | 1954 |
| 3 | The Two Towers | Tolkien | 1954 |
| 4 | The Return of the King | Tolkien | 1955 |
| 5 | The Little Prince | Saint-Exupêry | 1943 |
| 6 | Flight to Arras | Saint-Exupêry | 1942 |
| 7 | Nineteen Eighty-Four | Orwell | 1949 |
| 8 | Animal Farm | Orwell | 1945 |
+------------------------------------------------------------+

13.6 T
 here are no variables in database_tool.py that are written to a file or database so everything is reset
after quitting. As you have only learnt how to query a database at the moment (rather than write to
one) the database contents are also unchanged.

13.7 a 
SELECT * FROM Book
ORDER BY Year ASC;

b 
SELECT Title FROM Book
WHERE Author = 'Orwell'
ORDER BY Title ASC;

c 
SELECT Title, Author FROM Book
ORDER BY Year ASC;

d 
SELECT Title, Author, Year FROM Book
ORDER BY Author ASC, Title ASC;

e 
SELECT Author, Title, Year FROM Book
ORDER BY Year DESC;

f 
SELECT Title FROM Book
WHERE Year > 1940 AND Year < 1950
ORDER BY Year ASC;

111
CAMBRIDGE IGCSE™ & O LEVEL COMPUTER SCIENCE: PROGRAMMING BOOK

13.8 a SELECT SUM(Speed) FROM Character;

b 
SELECT SUM(Strength) FROM Character
WHERE Sprite = 'Giant';

c 
SELECT COUNT(Strength) FROM Character
WHERE Sprite = 'Elf';

13.9 a Follow the instructions.

b If all went well in part a, the file trees.db should be found in the same folder as
database_tool.py.

c This is just an instruction to check everything is OK.

13.10 a Follow the instructions.

b Follow the instructions.

c Click on the List Tables button.

13.11 a Follow the instructions.

b Follow the instructions.

c Show every record and field in the selected table.

d Follow the instructions.

Challenge tasks
13.1 # names.py
name = open('name.txt', 'r')
names = name.read().split()

print('First name:', names[0])


print('Second name:', names[1])

name.close()

13.2 S
 ELECT SUM(Speed), SUM(Strength) FROM Character
WHERE Sprite = 'Giant';

112
CAMBRIDGE IGCSE™ & O LEVEL COMPUTER SCIENCE: PROGRAMMING BOOK

End-of-chapter tasks
1 a A pseudocode solution:
date  OPEN birthday.txt
WRITE '25th May 2009' TO date

date  OPEN birthday.txt


OUTPUT 'I was born on ' + READ date

CLOSE date

b A Python solution:
date = open('birthday.txt', 'w')
date.write('25th May 2009')
date = open('birthday.txt', 'r')
print('I was born on ', date.read())
date.close()

2 a A pseudocode solution:
PROCEDURE update_leaderboard(name)
leader  OPEN leader.txt
WRITE name TO leader
CLOSE leader
ENDPROCEDURE

b A Python solution:
def update_leaderboard(name):
leader = open('leader.txt', 'w')
leader.write(name)
leader.close()

# Test
my_name = input('Name: ')
update_leaderboard(my_name)

After running this program and entering your name a file called leader.txt should appear in the same
folder as the Python file.

3 a A pseudocode solution:
PROCEDURE get_leader()
file  OPEN leader.txt
leader  READ file
OUTPUT "Today's leader is:" + leader
CLOSE file
ENDPROCEDURE

CALL get_leader()

113
CAMBRIDGE IGCSE™ & O LEVEL COMPUTER SCIENCE: PROGRAMMING BOOK

b A Python solution:
def get_leader():
file = open('leader.txt', 'r')
leader = file.read()
print("Today's leader is:", leader)
file.close()
get_leader()

4 a Follow the instructions.

b SELECT * FROM Character;

5 a Follow the instructions.

b 
SELECT * FROM Character
WHERE Sprite = 'Giant';

6 a Follow the instructions.

b SELECT Player_alias, Speed, Strength FROM Character;

7 a Follow the instructions.

b 
SELECT COUNT(Title) FROM Book
WHERE Author = 'Orwell';

Chapter 14:
Programming scenario task
End-of-chapter tasks
1 A pseudocode solution:
// Initialise global variables
player1_score  0
player2_score  0
// Game function
FUNCTION play RETURNS INTEGER
score  0
FOR i 1 TO 10
IF INPUT('Guess a number from 1 to 10: ')) = rand_num()
THEN
score  score +1
ENDIF
NEXT i
RETURN score
ENDFUNCTION

114
CAMBRIDGE IGCSE™ & O LEVEL COMPUTER SCIENCE: PROGRAMMING BOOK

// Player 1 turn
OUTPUT 'Player 1, Are you ready?'
player1_score  play()
OUTPUT 'You scored', player1_score
// Player 2 turn
OUTPUT 'Player 2, Are you ready?'
player2_score  play()
OUTPUT 'You scored', player2_score
// Output results
IF player1_score > player2_score
THEN
OUTPUT 'Player 1 is the winner!'
ELSE
IF player1_score = player2_score
THEN
OUTPUT 'The game is a draw!'
ELSE
OUTPUT 'Player 2 is the winner!'
ENDIF
ENDIF
A Python solution:
from random import *

# Initialise global variables


player1_score = 0
player2_score = 0

# Game function
def play():
score = 0
for i in range(10):
i
f int(input('Guess a number from 1 to 10: ')) == randint(1,10):
score = score +1
return score

# Main program
# Player 1 turn
print('\n Player 1, Are you ready?')
player1_score = play()
print('You scored', player1_score)

# Player 2 turn
print('\n Player 2, Are you ready?')
player2_score = play()
print('You scored', player2_score)

# Leave a line and output the result


print()
if player1_score > player2_score:
print('Player 1 is the winner!')

115
CAMBRIDGE IGCSE™ & O LEVEL COMPUTER SCIENCE: PROGRAMMING BOOK

elif player1_score == player2_score:


print('The game is a draw!')
else:
print('Player 2 is the winner!')

2 A pseudocode solution:
// Program to calculate info from three provided arrays:
// SnackName[], Nutrition[]

SampleSize  5

// Counters
reds  0
oranges  0
greens  0
health_index_total  0
// Loop to complete calculations for each snack
FOR i  0 TO SampleSize-1
mass  Nutrition[i][0] + Nutrition[i][2] + Nutrition[i][3]
carb_percent  round((Nutrition[i][0] * 100) / mass, 0)
OUTPUT SnackName[i])
OUTPUT 'Percentage carbohydrate by mass:', carb_percent

// Calculate HealthIndex
HealthIndex  Nutrition[i][0] + (Nutrition[i][1] * 2) + (
 Nutrition[i][3]
* 100)
health_index_total  health_index_total + HealthIndex
OUTPUT 'HealthIndex:', ROUND(HealthIndex, 0)

// Find Health Rating


IF HealthIndex >= 200
THEN
category  'Red'
reds  reds + 1
ELSE
IF HealthIndex >= 150
THEN
category  'Orange'
oranges  oranges + 1
ELSE
category  'Green'
greens  greens + 1
ENDIF
ENDIF
OUTPUT 'Health Rating:', category
NEXT i
OUTPUT 'Total Red category snacks:', reds
OUTPUT 'Total Orange category snacks:', oranges
OUTPUT 'Total Green category snacks:', greens
OUTPUT 'Average HealthIndex:', ROUND(health_index_total / SampleSize, 0)

116
CAMBRIDGE IGCSE™ & O LEVEL COMPUTER SCIENCE: PROGRAMMING BOOK

A Python solution:
# Program to calculate info from three provided arrays:
# SnackName[], Nutrition[]

#### Test data (Not required in a written answer) ####


SnackName = ['Caramello', 'Oaty', 'Chocbar', 'Slimaid', 'Nutter']
Nutrition = [[69.3, 59.9, 4.4, 0.42],
[65.1, 32.3, 5.1, 0.48],
[59.8, 58.7, 5.8, 0.2],
[35.4, 27.1, 3.1, 0.32],
[54.4, 44.8, 4.9, 0.45]]
######################################################

SampleSize = 5

# Counters
reds = 0
oranges = 0
greens = 0
health_index_total = 0

# Loop to complete calculations for each snack


for i in range(SampleSize):
mass = Nutrition[i][0] + Nutrition[i][2] + Nutrition[i][3]
carb_percent = round((Nutrition[i][0] * 100) / mass, 0)
print(SnackName[i])
print('Percentage carbohydrate by mass:', carb_percent)

# Calculate HealthIndex
H
ealthIndex =Nutrition[i][0] + (Nutrition[i][1] * 2) + (
Nutrition[i][3]
* 100)
health_index_total = health_index_total + HealthIndex
print('HealthIndex:', int(round(HealthIndex, 0)))

# Find Health Rating


if HealthIndex >= 200:
category = 'Red'
reds = reds + 1
elif HealthIndex >= 150:
category = 'Orange'
oranges = oranges + 1
else:
category = 'Green'
greens = greens + 1

117
CAMBRIDGE IGCSE™ & O LEVEL COMPUTER SCIENCE: PROGRAMMING BOOK

print('Health Rating:', category, '\n')

print('Total Red category snacks:', reds)


print('Total Orange category snacks:', oranges)
print('Total Green category snacks:', greens)
print('Average HealthIndex:', int(round(health_index_total / SampleSize, 0)))

3 A pseudocode solution:
FUNCTION format_check(user_id) RETURNS BOOLEAN
IF LENGTH(user_id) != 6
THEN
OUTPUT 'Error: userID is wrong length.'
RETURN FALSE
ENDIF

alphabet  ['a','b','c',''d','e','f','g','h','i',
'j','k','l','m','n','o','p','q','r',
's','t','u','v','w','x','y','z']

// Iterate through user_id character by character


counter  1
FOR i in user_id:
IF counter < 5 AND i IS NOT IN alphabet
THEN
OUTPUT 'Error: wrong format.'
RETURN FALSE
ENDIF
IF counter > 4 and IS NOT an INTEGER
THEN
OUTPUT 'Error: wrong format.'
RETURN FALSE
ENDIF
counter  counter + 1
NEXT i
RETURN TRUE
ENDFUNCTION

// Give the user 3 attempts


attempts  0
all_ok  FALSE
WHILE attempts < 3 and all_ok = FALSE DO
customerID  INPUT('Your CustomerID: ')
IF format_check(customerID) = TRUE
THEN
all_ok  TRUE
BREAK
ENDIF
attempts  attempts + 1
ENDWHILE

118
CAMBRIDGE IGCSE™ & O LEVEL COMPUTER SCIENCE: PROGRAMMING BOOK

IF all_ok = FALSE
THEN
OUTPUT 'No further attempts allowed.'
ELSE
OUTPUT 'CustomerID accepted.'
ENDIF
A Python solution:
def format_check(user_id):
if len(user_id) != 6:
print('Error: userID is wrong length.')
return False

alphabet = 'abcdefghijklmnopqrstuvwxyz'

# Iterate through user_id character by character


counter = 1
for i in user_id:
if counter < 5 and i not in alphabet:
print('Error: wrong format.')
return False
if counter > 4:
try:
int(i)
except:
print('Error: wrong format.')
return False
counter = counter + 1
return True

# Give the user 3 attempts


attempts = 0
all_ok = False
while attempts < 3 and all_ok == False:
customerID = input('Your CustomerID: ')
if format_check(customerID) == True:
all_ok = True
break
attempts = attempts + 1
if all_ok == False:
print('No further attempts allowed.')
else:
print('CustomerID accepted.')

4 A pseudocode solution:
// Program to calculate info from the provided arrays:
// Members[], Distance[]
number_members  50
overall_distance  0
// Loop to complete calculation for each member

119
CAMBRIDGE IGCSE™ & O LEVEL COMPUTER SCIENCE: PROGRAMMING BOOK

FOR i  0 TO number_members-1
print(Members[i])
pb  0
num_runs  0
total_distance  0

// Loop to calculate members data


FOR j  0 TO 2
IF Distance[i][j] != -1
THEN
total_distance  total_distance + Distance[i][j]
overall_distance  overall_distance + Distance[i][j]
num_runs  num_runs + 1
IF Distance[i][j] > pb
THEN
pb  Distance[i][j]
ENDIF
ENDIF
NEXT j

// Calculate and output member's data


average_distance  round(total_distance / (num_runs * 1000), 1)
IF pb >= 7000
THEN
category  'Elite'
ELSE
IF pb >= 5000
THEN
category  'Championship'
ELSE
category  'Club'
ENDIF
ENDIF

OUTPUT 'Number of runs completed: ' + num_runs


O
UTPUT 'Average distance covered: ' + STRING(average_distance) + 'km')
OUTPUT 'Best distance: ' + STRING(pb) + 'km')
OUTPUT 'Category awarded: ' + category)
NEXT i

// Calculate and output total distance


comp_dist  STRING(ROUND(overall_distance/1000, 1))
OUTPUT 'Total distance run in competition: ' + comp_dist + 'km')
A Python solution:
# Program to calculate info from the provided arrays:
# Members[], Distance[]

#### Test data (Not required in a written answer) ####


Members = ['Alf', 'Bee', 'Cas', 'Don', 'Eva']

120
CAMBRIDGE IGCSE™ & O LEVEL COMPUTER SCIENCE: PROGRAMMING BOOK

Distance = [[12000, 12500, -1],


[14000, 13700, 13550],
[-1, 11500, -1],
[6500, 6400, -1],
[3000, 3200, -1]]
######################################################
overall_distance = 0

# Loop to complete calculation for each member


for i in range(len(Members)):
print(Members[i])
pb = 0
num_runs = 0
total_distance = 0
# Loop to calculate members data
for j in range(3):
if Distance[i][j] != -1:
total_distance = total_distance + Distance[i][j]
overall_distance = overall_distance + Distance[i][j]
num_runs = num_runs + 1
if Distance[i][j] > pb:
pb = Distance[i][j]

# Calculate and output member's data


average_distance = round(total_distance / (num_runs * 1000), 1)
if pb >= 7000:
category = 'Elite'
elif pb >= 5000:
category = 'Championship'
else:
category = 'Club'

print('Number of runs completed:', num_runs)


p
rint('Average distance covered: ' + str(average_distance) + 'km')
print('Best distance: ' + str(pb) + 'km')
print('Category awarded:', category, '\n')

# Calculate and output total distance


comp_dist = str(round(overall_distance/1000, 1))
print('Total distance run in competition: ', comp_dist, 'km')

5 A pseudocode solution:
// Program to calculate info from three provided arrays:
// Schools[], MinTemp[] and MaxTemp[]

number_schools  30

// Initialise, with unreasonable data, the max and minimum tracker


variables
highest_temp  -20
lowest_temp  100

121
CAMBRIDGE IGCSE™ & O LEVEL COMPUTER SCIENCE: PROGRAMMING BOOK

// Loop through each school to complete calculations


FOR i  0 TO number_schools-1
OUTPUT Schools[i]
total_temp_range  0
total_max_temp  0

// Loop to calculate school totals for all 7 days


FOR j  0 TO 6
total_temp_range  total_temp_range + (MaxTemp[i][j] - MinTemp[i][j])
total_max_temp  total_max_temp + MaxTemp[i][j]
IF MaxTemp[i][j] > highest_temp
THEN
highest_temp  MaxTemp[i][j]
ENDIF
IF MinTemp[i][j] < lowest_temp
THEN
lowest_temp  MinTemp[i][j]
ENDIF
NEXT j

// Calculate and output school's averages


average_range  round(total_temp_range / 7, 1)
max_temp  round(total_max_temp / 7, 1)
OUTPUT 'Average temperature range:', average_range, 'Celsius'
OUTPUT 'Average maximum temperature:', max_temp, 'Celsius\n'
NEXT i

OUTPUT 'Highest temperature recorded at any school:', highest_temp,


'Celsius'
OUPUT 'Lowest temperature recorded at any school:', lowest_temp,
'Celsius'
A Python solution:
# Program to calculate info from three provided arrays:
# Schools[], MinTemp[] and MaxTemp[]

#### Test data (Not required in a written answer) ####


Schools = ['International', 'Beacons', 'Castle']
MinTemp = [[3,5,8,6,10,11,5], [2,5,7,5,9,11,4], [4,6,10,7,12,9,5]]
MaxTemp = [
[15,15,16,12,19,20,16], [14,15,14,10,18,19,15],
[15,16,15,13,12,22,17]]
######################################################

# Initialise, with unreasonable data, the max and minimum tracker variables
highest_temp = -20
lowest_temp = 100

122
CAMBRIDGE IGCSE™ & O LEVEL COMPUTER SCIENCE: PROGRAMMING BOOK

# Loop to complete calculation for each school


for i in range(len(Schools)):
print(Schools[i])
total_temp_range = 0
total_max_temp = 0

# Loop to calculate school totals for all 7 days


for j in range(7):
total_temp_range = total_temp_range + (MaxTemp[i][j]-MinTemp[i][j])
total_max_temp = total_max_temp + MaxTemp[i][j]
if MaxTemp[i][j] > highest_temp:
highest_temp = MaxTemp[i][j]
if MinTemp[i][j] < lowest_temp:
lowest_temp = MinTemp[i][j]

# Calculate and output school's averages


average_range = round(total_temp_range / 7, 1)
max_temp = round(total_max_temp / 7, 1)
print('Average temperature range:', average_range, 'Celsius')
print('Average maximum temperature:', max_temp, 'Celsius\n')

# Output highest and lowest temperature for all schools


print('Highest temperature recorded:', highest_temp, 'Celsius')
print('Lowest temperature recorded:', lowest_temp, 'Celsius')

Chapter 15: Examination practice


1 Maximum of six marks from:
• Declare and initialise variables.
• Decision to identify vote.
• Correct incrementing of vote records.
• Correct loop that iterates for 601 inputs.
• Correct calculation of percentage.
• Output of name and percentage.
Example of flowchart – any correct solution will achieve marks.

123
CAMBRIDGE IGCSE™ & O LEVEL COMPUTER SCIENCE: PROGRAMMING BOOK

START

Faraday ← 0
Curie ← 0
Counter ← 1

INPUT
Vote

FALSE TRUE
Vote =
Curie ← Curie + 1 Faraday ← Faraday + 1
'Faraday'

Counter ← Counter + 1

FALSE
Counter = 601

TRUE

FALSE Faraday TRUE


Percent ← (Curie / 601) * 100 Percent ← (Faraday / 601) * 100
> Curie

OUTPUT OUTPUT
STOP
'Curie' + Percent 'Faraday' + Percent

Example of pseudocode – any correct solution will achieve marks.


Faraday  0
Curie  0

FOR Counter  1 to 601


INPUT Vote
IF Vote = "Faraday"
THEN
Faraday  Faraday + 1

124
CAMBRIDGE IGCSE™ & O LEVEL COMPUTER SCIENCE: PROGRAMMING BOOK

ELSE
Curie  Curie + 1
ENDIF
NEXT

IF Faraday > Curie


THEN
Percent  (Faraday / 601) * 100
PRINT "Faraday" + Percent
ELSE
Percent  (Curie / 601) * 100
PRINT "Curie" + Percent
ENDIF

2 Maximum of eight marks.

One for each correct identification of error; one for appropriate solution to error.
• Low is declared as 0 / Low will always be lowest value/ Low  0.
• Initialise Low to a value > 200 / Set Low to be the first mark input/ Low  201.
• Comparison for High is incorrect / IF Marks <= High.
• The symbol should be > (accept >=) / IF Marks > High.
• Low is not assigned a value / Marks  Low is wrong way round.
• Low must be assigned the value of Marks / Low  Marks.
• Average is wrongly calculated / Count ÷ Total is wrong way round.
• Average  Total / Count .

3 a Maximum of four marks from:


• The check digit is generated by a calculation completed on the other numbers.
• An algorithm is applied to the numbers (accept by example) …
• … to arrive at a total.
• The check digit is the result of Modulus division of Total by 10 (accept 11).
• When the number is input, calculation is performed again …
• ... and if the calculated value does not match check digit input, an error has occurred.

125
CAMBRIDGE IGCSE™ & O LEVEL COMPUTER SCIENCE: PROGRAMMING BOOK

b Maximum of two marks – one for each correct validation {cao (correct answer only)}.

Pseudocode Type of validation


INPUT ISBN
IF ISBN = ""
THEN [1] Presence Check
PRINT "Error"
ENDIF
INPUT ISBN
IF Len(ISBN) < 13
THEN [1] Length Check
PRINT "Error"
ENDIF

c Maximum of three marks from one for each correct data value:

Type of Data Example


Normal Any Integer value between 12 and 198 (reject 11 or 199 they are extreme).
Abnormal Any value not of an integer data type, or integer values > 200 or <11.
Extreme 10, 11, 199 or 200 only.

4 Maximum of five marks from one for each correct column:

Number Count Total Large Output


0 0 0 0
15 1 15
10 2
14 3 29
0 4
12 5 41
19 6 60 3
11 7 71
−6 8
7 21

[1] [1] [1] [1] [1]

Note:
Missing unitisation zeros – penalise once and then ignore.
Can accept repeated values in a column.
Accept only one output value (reject multiple values even if final value correct).

126
CAMBRIDGE IGCSE™ & O LEVEL COMPUTER SCIENCE: PROGRAMMING BOOK

5 a Maximum of five marks from:


• Required username is input.
• A loop to check the whole array (array can be indexed from 0 or 1 – 0 to 599 or 1 to 600).
• Loop counter is correctly used to identify index locations in array.
• Selection used to check required username at each index location.
• If match is true output correct index location.
• End search when match is found.
• If no match at end if loop output correct message.
(Note: output must be in " " as text and only accept if the output is at end of loop.)
Example flowchart:

START

Counter ← 0

INPUT
Username

Username = TRUE OUTPUT


Netname(Counter) Counter

FALSE

STOP
Counter ←
Counter + 1

FALSE TRUE
Counter = OUTPUT
599 "No record"

127
CAMBRIDGE IGCSE™ & O LEVEL COMPUTER SCIENCE: PROGRAMMING BOOK

Example pseudocode (this is an example, any working solution will gain marks):
Counter  0
Found  FALSE
INPUT Username

WHILE Counter < 599 and Found = FALSE


IF Username = Netname(Counter)
THEN
OUTPUT Counter
Found  TRUE
ENDIF
ENDWHILE
IF Found = FALSE
THEN
OUTPUT "NO Record"
ENDIF

b Maximum of three marks from:


• Search could be ended earlier if username not in the array.
• Would need an extra selection statement …
• … which checks if the index value is alphabetically higher than the search value.
• Loop can be exited at this time ...
• ... as all values beyond that index cannot be the search value.

6 Maximum of three marks from:


• Use of nested loops.
• Correct range of loop counters.
• Loop counters used accurately to determine index locations.
Example pseudocode:
FOR Counter1  0 to 8
FOR Counter2  0 to 8
Board (Counter1, Counter2)  "Free"
NEXT
NEXT

7 Maximum of six marks from:


• Inputs the product number for checking.
• Correctly checks length …
• … reject if fails test.
• Correctly used substring to identify first 4 characters.
• Correctly checks first 4 characters and reject if fail.
• Accept all other product numbers.

128
CAMBRIDGE IGCSE™ & O LEVEL COMPUTER SCIENCE: PROGRAMMING BOOK

Example flowchart:

START

INPUT
product_number

TRUE
LENGTH(product_number)
!=10

FALSE

FALSE TRUE
OUTPUT SUBSTRING(product_number, OUTPUT
"Accepted" 0, 4) !="PROD" "Rejected"

STOP

129
CAMBRIDGE IGCSE™ & O LEVEL COMPUTER SCIENCE: PROGRAMMING BOOK

Example pseudocode:
INPUT product_number

IF LENGTH (product_number) != 10
THEN
OUTPUT "Rejected"
ELSE
IF SUBSTRING(product_number, 0, 4) != "PROD"
THEN
OUTPUT "Rejected"
ELSE
OUTPUT "Accepted"
ENDIF
ENDIF

8 Maximum of four marks from:


• Use of the terms CASE, OTHERWISE and END CASE correctly.
• Correctly links CASE to input Score.
• Has CASE conditions for >100, >80 and >60.
• Has used OTHERWISE to replace the ELSE statement.
INT Score  0
INPUT Score

CASE OF Score
100: OUTPUT "Excelling"
80: OUTPUT "Good"
60: OUTPUT "Acceptable"
OTHERWISE: OUTPUT "Below expectations"
ENDCASE

9 Maximum of two marks from:


• Function takes Celsius (or equivalent) as a parameter value.
• Value is returned using RETURN or function name.

Example code:
FUNCTION convert (celsius)
fahrenheit  (celsius * 1.8) + 32
RETURN fahrenheit
ENDFUNCTION

130
CAMBRIDGE IGCSE™ & O LEVEL COMPUTER SCIENCE: PROGRAMMING BOOK

10 a Maximum of two marks from:


• Variables can change during execution of the program.
• Constants cannot be changed / are fixed during execution of the program.

b Maximum of six marks from one for each correct data type.

Variable Most appropriate Date Type


Students – holds the number of students in a school INTEGER
IDNumber – holds ID numbers, such as MR145T STRING
Weight – holds the weight of parcels in kilograms REAL (Accept FLOAT / DECIMAL)
Passed – records whether a person has passed a test BOOLEAN
Name – holds the name of students at a school STRING
Grade – holds an examination grade A, B, C, D or E CHAR (reject string)

11 Maximum of eight marks.

a
START

B
A C

F
E G

I K

STOP

131
CAMBRIDGE IGCSE™ & O LEVEL COMPUTER SCIENCE: PROGRAMMING BOOK

b A age < 10

B, F, J TRUE

D, H, L FALSE

C classification  "child"

E age < 18

G classification  “junior”

I age < 60

K classification  “adult”

M classification  “senior”

This would be marked with 1 mark per correct row. Maximum of 8 marks.

However, this is not the only possible solution. If the captions for the options are given as
complete ranges, such as age >9 AND age > 18, there is no necessity for them all to be in order.

12 Maximum of eight marks.

a A name [one] used in a program to identify a memory location [one].

b One mark per answer.

StudentName string

StudentID string

ExamMark integer

Percentage real

Comments string

RetestNeeded Boolean

13 Maximum of eight marks.

a i Maximum of three marks from:


• Once written the subroutine can be used many times without the need for the code
to be written again.
• Subroutines may be made available by the programming language.
• Subroutines already available are likely to be more reliable.
• Program code is shorter.
• Programs are more understandable.
• Programs take less time to write.
• Program complexity is reduced.

132
CAMBRIDGE IGCSE™ & O LEVEL COMPUTER SCIENCE: PROGRAMMING BOOK

• Subroutines can be separately coded by different programmers.


• Subroutines can be individually tested.

ii A function returns a value, a procedure does not return a value. [one]

b i miles_to_km (or other sensible name) [one]

ii CALL miles_to_km(miles) [one]

iii km  miles_to_km(miles) [one]

14 Maximum of four marks.

Pseudocode solutions (one mark per solution):

a newString = UPPER(oldString)

b newString = SUBSTRING(oldString, 8, 1)

c newString = SUBSTRING(oldString, 0, 1)

d newString = SUBSTRING(oldString, 3, 6)

Python solutions (one mark per solution):

a newString = oldString.upper()

b newString = oldString[8]

c newString = oldString[0]

d newString = oldString[3:9]

15 Maximum of four marks.

Membership
application decision

Receive
Receive details Send decision
supporting Store decision
of applicant to applicant
details

Sorry
Welcome to
application
membership
rejected

133
CAMBRIDGE IGCSE™ & O LEVEL COMPUTER SCIENCE: PROGRAMMING BOOK

Maximum of four marks from:


System name. [one]
Second row one mark for each pair of labels. [two]
Third row one mark for the two labels. [one]
One mark for the option symbol. [one]

16 Maximum of six marks.

a It is a sorting algorithm/bubble sort. [one]

b Maximum of five marks, or maximum of four marks if no example code included in the answer,
from (one mark per line):

There is a one-dimensional array used.

There are two for loops.

There are nested iterations.

There is a procedure called swap being used.

The coding for swap will have been written elsewhere.

The loops allow successive access to elements of the array.

There are two IF statements.

There are several assignment statements.

17 a Maximum of six marks, from these edits (one mark for each):
• Changed name1 and name2 to something more descriptive.
• Provided a comment for the function.
• Gave the function a more descriptive name.
• Replaced i,j,k,l,m with something a little more related to a set of times.
• Replaced t with an identifier that indicates it is a total in minutes.
• Split RETURN ROUND(t/5) into two lines and used a descriptive identifier.
• Provided a comment to explain what CASE was doing.
• Replaced a,b,c,d,e with identifiers more related to times.
• Replaced ave with average or mean.
• Add a minimum of 3 empty lines to break up the algorithm and make it easier to read.
Example answer:
// A function that takes 5 marathon times in minutes
// as integers and calculates the average
FUNCTION calc_average(t1, t2, t3, t4, t5)
total_minutes  t1 + t2 + t3 + t4 + t5
average_minutes  ROUND(total_minutes / 5)

134
CAMBRIDGE IGCSE™ & O LEVEL COMPUTER SCIENCE: PROGRAMMING BOOK

RETURN average_minutes
ENDFUNCTION
INPUT firstname
INPUT lastname

// Times to be entered by users in minutes as integers:


FOR counter  1 TO 5
CASE OF counter:
1: INPUT time1
2: INPUT time2
3: INPUT time3
4: INPUT time4
5: INPUT time5
ENDCASE
NEXT counter

average  calc_average(time1, time2, time3, time4, time5)

OUTPUT firstname + " " + lastname + " average marathon time:"


OUTPUT (average_minutes DIV 60) + "hrs " 
+ (average_minutes MOD 60)
+ "mins"

b Maximum of six marks:


• Program that generally works with neither CASE or FUNCTION present (accept up to
two typos).
• Program that works with no typos.
• Program that is manageable.
• Program that is less than 10 lines long (excluding empty lines).
• A successful use of a loop to obtain INPUT of times (does not need to be a FOR loop).
• Still produces the same output.
Example answer:
INPUT firstname
INPUT lastname

FOR counter  1 TO 5
total_minutes  total_minutes + (INPUT marathon_time)
NEXT counter

average_minutes  total_minutes / 5

OUTPUT firstname + " " + lastname + " average marathon time:"


OUTPUT (average_minutes DIV 60) + "hrs " 
+ (average_minutes MOD 60)
+ "mins"

135
CAMBRIDGE IGCSE™ & O LEVEL COMPUTER SCIENCE: PROGRAMMING BOOK

18 Maximum of six marks.

a One mark for both answers: minLives, maxLives


b One mark for both answers: lives, gameOver
c One mark for: global variables can be accessed anywhere in a program.
One mark for: local variables can be only be accessed in the subroutine / function / procedure
where they are declared.
d Maximum of two marks from the following, one mark for each point with reason:
• It is possible to accidently use an identifier twice without noticing, whereas local variable
names can be used elsewhere in the program.
• It can make testing harder as the variable could be changed anywhere in the program.
• It can make maintenance harder as the variable could be changed anywhere in the
program.
19 Maximum of six marks.

One mark per bullet:


• Opening the correct file.
• Reading in the value.
• Add 1 to the value.
• Storing new value in the correct file.
• Calling GameOver().
• Closing the file.
• Closing file before calling GameOver().
Pseudocode example answer:
FILE  OPEN "Score.txt"
READ value FROM File
value  value + 1
WRITE value TO File
CLOSE FILE
IF value > 9
THEN
CALL GameOver()
ENDIF
Python example answer:
file = open('my_file.txt', 'r')
value = file.read()
value = value + 1
file = open('my_file.txt', 'w')
file.write(value)
file.close()
if value > 9:
GameOver()

136
CAMBRIDGE IGCSE™ & O LEVEL COMPUTER SCIENCE: PROGRAMMING BOOK

20 Maximum of six marks.

One mark per bullet:


• Inputs firstname and lastname.
• Converts firstname and lastname to lowercase string.
• Correctly selects first two letters of firstname.
• Correctly selects last five letters of lastname.
• Correctly uses RANDOM to create a 6 figure password that does not start with 0. (Note
does not need to collect all values but MUST generate most available values.)
• Outputs username and password.
Pseudocode example answer:
firstname  LOWER(INPUT('Firstname: '))
lastname  LOWER(INPUT('Lastname: '))

username  firstname[1:2] + lastname[len(lastname)-5:len(lastname)]


password  RANDOM(100000, 999999)

OUTPUT username, password


Python example answer:
import random

firstname = input('Firstname: ').lower()


lastname = input('Lastname: ').lower()

username = firstname[0:2] + lastname[len(lastname)-5:]


password = random.randint(100000,1000000)

print(username, password)

21 Maximum of seven marks.

a Three marks from one per bullet:


• The indices in the 2D array provide a coordinate system to represent the map.
• Easy calculations can be done to find locations relative to each other.
• Relationships between locations in different rows are easier to program in a single array
than in many.
• A loop can search through all locations in a row, column, a diagonal or the whole array.
• A nested loop can be used to quickly read from or write to all locations in the array.

b One mark for:


map[0:9][0:9] OF String

137
CAMBRIDGE IGCSE™ & O LEVEL COMPUTER SCIENCE: PROGRAMMING BOOK

c Three marks, one per line; max of two marks if two temporary reads made:
temp_image  map[2][2]
map[2][2]  map[4][4]
map[4][4]  temp_image
Note: temp_image identifier is just an example.

22 Maximum of ten marks.

a Two marks, one for each bullet:


• It is a primary key.
• One field is required to have unique values.

b One mark: text/alphanumeric

c i One mark:

Name
Omar
Sheila

(order is important)

ii One mark, both rows required:

BatID Name Type Wingspan Weight Length


1 Omar Pipistrelle 120 18 85
7 Sheila Pipistrelle 120 19 85

d i Max two; one for each line:


SELECT COUNT(Type) FROM Bats
WHERE Type = 'Pipistrelle'

ii Max three; one for each line:


SELECT Names FROM Bats
WHERE Weight < 20
ORDER BY Name ASC

138

You might also like