CSC ch8
CSC ch8
What is a variable?
A variable is an identifier that can change in the lifetime of a program
Identifiers should be:
o In mixed case (Pascal case)
o Only contain letters (A-Z, a-z)
o Only contain digits (0-9)
o Start with a capital letter and not a digit
A variable can be associated a datatype when it is declared
When a variable is declared, memory is allocated based on the data type
indicated
Pseudocode
DECLARE <identifier> : <datatype>
DECLARE Age : INTEGER
DECLARE Price : REAL
DECLARE GameOver : BOOLEAN
Python
score = int() # whole number
cost = float() # decimal number
light = bool() # data can only have one or two values
What is a constant?
A constant is an identifier set once in the lifetime of a program
Constants are named in all uppercase characters
Constants aid the readability and maintainability
If a constant needs to be changed, it should only need to be altered in one
place in the whole program
Pseudocode
CONSTANT <identifier> ← <value>
CONSTANT PI ← 3.142
CONSTANT PASSWORD ← "letmein"
CONSTANT HIGHSCORE ← 9999
Python
PI = 3.142
VAT = 0.20
PASSWORD = "letmein"
1|Page
Chapter 8 Programming
Data Types
Worked Example
Name and describe the most appropriate programming data type for each of the
examples of data given. Each data type must be different [6]
Data: 83
Data: [email protected]
Data: True
Answers
2|Page
Chapter 8 Programming
What is an input?
An input is a value that is read from an input device and then processed by a
computer program
Typical input devices include:
o Keyboards - Typing text
o Mice - Selecting item, clicking buttons
o Sensors - Reading data from sensors such as temperature, pressure or
motion
o Microphone - Capturing audio, speech recognition
Without inputs, programs are not useful as they can't interact with the
outside world and always produce the same result
In programming the keyboard is considered the standard for user input
If the command 'INPUT' is executed, a program will wait for the user to type
a sequence of characters
In other programming languages different command words can be used
Examples
Pseudocode (INPUT <identifier>) Python
name=input("Enter your name:
INPUT Name
")
IF Name ← "James" OR Name ←
if name == "James" or name
"Rob" THEN...
== "Rob":
What is an output?
An output is a value sent to an output device from a computer program
Typical output devices include:
o Monitor - Displaying text, images or graphics
o Speaker - Playing audio
o Printer - Creating physical copies of documents or images
In programming the monitor is considered the standard for user output
If the command 'OUTPUT' is executed, a program will output to the screen
In other programming languages different command words can be used
Examples
Pseudocode (OUTPUT <identifier(s)>) Python
name=input("Enter your name:
INPUT Name
")
IF Name ← "James" OR Name ←
if name == "James" or name ==
"Rob" THEN
"Rob":
OUTPUT "Great names!"
print("Great names!")
INPUT Name name=input("Enter your name:
IF Name ← "James" OR Name ← ")
"Rob" THEN if name == "James" or name ==
OUTPUT "Love the name ", "Rob":
Name print("Love the name "+name)
3|Page
Chapter 8 Programming
Sequence
What is sequence?
Sequence refers to lines of code which are run one line at a time
The lines of code are run in the order that they written from the first line of
code to the last line of code
Sequence is crucial to the flow of a program, any instructions out of sequence
can lead to unexpected behaviour or errors
Example 1
A simple program to ask a user to input two numbers, number two is
subtracted from number one and the result is outputted
Line Pseudocode
01 OUTPUT "Enter the first number"
02 INPUT Num1
03 OUTPUT "Enter the second number"
04 INPUT Num2
05 Result ← Num1 - Num2
06 OUTPUT Result
A simple swap of line 01 and line 02 would lead to an unexpected behaviour,
the user would be prompted to input information without knowing what they
should enter
Example 2
Python example
def calculate_area(length, width):
"""
This function calculates the area of a rectangle
Inputs:
length: The length of the rectangle
width: The width of the rectangle
Returns:
The area of the rectangle
"""
# Calculate area
return area
area = length * width
# ------------------------------------------------------------------------# Main program
# ------------------------------------------------------------------------
length = 5
width = 3
correct_area = calculate_area(length, width)
print(f"Correct area (length * width): {correct_area}")
In the example, the sequence of instructions is wrong and would cause a
runtime error
In the calculate_area() function a value is returned before it is
assigned
4|Page
Chapter 8 Programming
What is Selection?
Selection is when the flow of a program is changed, depending on a set of
conditions
The outcome of this condition will then determine which lines or block of
code is run next
Selection is used for validation, calculation and making sense of a user's
choices
There are two ways to write selection statements:
o if... then... else...
o case...
If Statements
What is an If statement?
As If statements allow you to execute a set of instructions if a condition is true
They have the following syntax:
IF <condition>
THEN
<statement>
ENDIF
Example
Concept Pseudocode Python
IF Answer ← "Yes" if answer == "Yes":
THEN print("Correct")
OUTPUT "Correct" elif answer == "No":
IF-THEN-ELSE ELSE print("Wrong")
OUTPUT "Wrong" else:
ENDIF print("Error")
Nested Selection
What is nested selection?
Nested selection is a selection statement within a selection statement, e.g.
an If inside of another If
Nested means to be 'stored inside the other'
Example
Pseudocode
IF Player2Score > Player1Score
THEN
IF Player2Score > HighScore
THEN
OUTPUT Player2, " is champion and highest scorer"
ELSE
5|Page
Chapter 8 Programming
Case Statements
If statements are more flexible and are generally used more in languages such
as Python
CASE OF <identifier>
<value 1> : <statement>
<value 2>: <statement>
....
OTHERWISE <statement>
ENDCASE
6|Page
Chapter 8 Programming
Examiner Tip
Make sure to include all necessary components in the selection statement:
o the condition,
Use proper indentation to make the code easier to read and understand
Make sure to test the selection statement with various input values to
ensure that it works as expected
Worked Example
Write an algorithm using pseudocode that:
Inputs 3 numbers
Outputs the largest of the three numbers [3]
Exemplar answer
Psuedocode
INPUT A
INPUT B
INPUT C
IF A > B
THEN
IF A > C
THEN
OUTPUT A
ELSE
OUTPUT C
ENDIF
ELSE
OUTPUT B
ENDIF
Python
if A > B AND A > C:
print(A)
elif B > C:
print(B)
else:
7|Page
Chapter 8 Programming
print(C)
8|Page
Chapter 8 Programming
What is iteration?
Iteration is repeating a line or a block of code using a loop
Iteration can be:
o Count controlled
o Condition controlled
o Nested
Examples
Iteration Pseudocode Python
FOR X ← 1 TO 10
for x in range(10):
OUTPUT "Hello"
print("Hello")
NEXT X
This will print the word "Hello" 10 times
FOR X ← 2 TO 10 STEP for x in range(2,12,2):
2 print(x)
Count OUTPUT X # Python range function excludes end
controlled NEXT X value
This will print the even numbers from 2 to 10 inclusive
FOR X ← 10 TO 0 STEP for x in range(10,-1,-1):
-1 print(x)
OUTPUT X # Python range function excludes end
NEXT X value
This will print the numbers from 10 to 0 inclusive
9|Page
Chapter 8 Programming
10 | P a g e
Chapter 8 Programming
Nested Iteration
Example
Pseudocode
Total ← 0
FOR Row ← 1 TO MaxRow
RowTotal ← 0
FOR Column ← 1 TO 10
RowTotal ← RowTotal + Amount[Row, Column]
NEXT Column
OUTPUT "Total for Row ", Row, " is ", RowTotal
Total ← Total + RowTotal
NEXT Row
OUTPUT "The grand total is ", Total
Python
// Program to print a multiplication table up to a given number
// Prompt the user to enter a number
number=int(input("Enter a number: "))
// Set the initial value of the counter for the outer loop
outer_counter = 1
// Outer loop to iterate through the multiplication table
while outer_counter <= number:
// Set the initial value of the counter for the inner loop
inner_counter = 1
// Inner loop to print the multiplication table for the current number
while inner_counter <= 10:
// Calculate the product of the outer and inner counters
product = outer_counter * inner_counter
// Print the multiplication table entry
print(outer_counter, " x ", inner_counter, " = ",
product)
// Increment the inner counter
inner_counter = inner_counter + 1
// Move to the next number in the multiplication table
outer_counter = outer_counter + 1
11 | P a g e
Chapter 8 Programming
INPUT Num
num = int(input("Enter a number: "))
TOTAL ← TOTAL + Num
total = total + num
NEXT I
print("Total:", total)
OUTPUT Total
Inputs 20 numbers
Answer
FOR x ← 1 TO 20 [1]
INPUT Number
IF Number > 50
THEN
Total ← Total + 1 [1]
NEXT x
PRINT total [1]
String Handling
12 | P a g e
Chapter 8 Programming
Worked Example
The function Length(x) finds the length of a string x. The function substring(x,y,z)
finds a substring of x starting at position y and z characters long. The first character in
x is in position 1.
Extract the word exams from the string and output it [6]
Answer
X ← "Save my exams"
[1] for storing string in X
OUTPUT LENGTH(X)
13 | P a g e
Chapter 8 Programming
[1] for calling the function length. [1] for using the correct parameter X
Y ← 9
Z ← 5
OUTPUT SUBSTRING(X,Y,Z)
[1] for using the substring function.
[1] for correct parameters
[1] for outputting length and substring return values
What is an operator?
An operator is a symbol used to instruct a computer to perform a specific
operation on one or more values
Examples of common operators include:
o Arithmetic
o Logical
o Boolean
Arithmetic Operators
Operator Pseudocode Python
Addition + +
Subtraction - -
Multiplication * *
Division / /
Modulus (remainder after division) MOD %
Quotient (whole number division) DIV //
Exponentiation (to the power of) ^ **
To demonstrate the use of common arithmetic operators, three sample
programs written in Python are given below
Comments have been included to help understand how the arithmetic
operators are being used
o Arithmetic operators #1 - a simple program to calculate if a user
entered number is odd or even
o Arithmetic operators #2 - a simple program to calculate the area of a
circle from a user inputted radius
o Arithmetic operators #3 - a simple program that generates 5 maths
questions based on user inputs and gives a score of how many were
correctly answered at the end
Python code
# -----------------------------------------------------------------------
# Arithmetic operators #1
# -----------------------------------------------------------------------
# Get the user to input a number
user_input = int(input("Enter a number: "))
# if the remainder of the number divided by 2 is 0, the number is even
if user_input % 2 == 0:
print("The number is even.")
else:
print("The number is odd.")
# -----------------------------------------------------------------------
# Arithmetic operators #2
# -----------------------------------------------------------------------
14 | P a g e
Chapter 8 Programming
Logical Operators
Operator Pseudocode Python
Equal to == ==
Not equal to <> !=
Less than < <
Less than or equal to <= <=
Greater than > >
Greater than or equal to >= >=
Boolean Operators
A Boolean operators is a logical operator that can be used to compare two or
more values and return a Boolean value (True or False) based on the
comparison
There are 3 main Boolean values:
o AND: Returns True if both conditions are True
o OR: Returns True if one or both conditions are True
o NOT: Returns the opposite of the condition (True if False, False if
True)
15 | P a g e
Chapter 8 Programming
16 | P a g e
Chapter 8 Programming
Examiner Tip
Boolean operators are often used in conditional statements such as if,
while, and for loops
It is always a good idea to test your code with different inputs to ensure
that it works as expected
17 | P a g e
Chapter 8 Programming
Procedures
PROCEDURE <identifier>
<statements>
ENDPROCEDURE
Or if parameters are being used:
Creating a procedure
Pseudocode
PROCEDURE calculate_area(length: INTEGER, width: INTEGER)
area ← length * width
OUTPUT "The area is " + area
END PROCEDURE
Python
def ageCheck(age):
if age > 18:
print("You are old enough")
else:
print("You are too young")
To call a procedure, it can be written as:
CALL <identifier>
CALL <identifier>(Value1,Value2...)
Calling a procedure
Pseudocode
CALL Calculate_area
CALL Calculate_area(5,3)
Python
ageCheck(21)
print(ageCheck(21))
Examples
A Python program using procedures to display a menu and navigate between
them
Procedures are defined at the start of the program and the main program
calls the first procedure to start
In this example, no parameters are needed
Procedures
# Procedure definition
def main_menu():
18 | P a g e
Chapter 8 Programming
Functions
Functions are defined using the FUNCTION keyword in pseudocode
or def keyword in Python
Functions always return a value so they do not use the CALL function,
instead they are called within an expression
A function can be written as:
19 | P a g e
Chapter 8 Programming
20 | P a g e
Chapter 8 Programming
(A)
Define the function, what parameters are needed? where do they go?
How do you calculate the price?
Return the result
(B)
How do you call a function?
What parameters does the function need to return the result?
Answers
Part Python
def flightCost(passengers, type):
if type == "economy":
cost = 199 * passengers
A elif type == "first":
cost = 595 * passengers
return cost
print(flightCost("economy", 3)
OR
B x = flightCost("economy", 3)
print(x)
Local Variables
21 | P a g e
Chapter 8 Programming
Global Variables
Library Routines
Random
The random library is a library of code which allows users to make use of
'random' in their programs
Examples of random that are most common are:
o Random choices
o Random numbers
Random number generation is a programming concept that involves a
computer generating a random number to be used within a program to add
an element of unpredictability
Examples of where this concept could be used include:
o Simulating the roll of a dice
o Selecting a random question (from a numbered list)
o National lottery
o Cryptography
22 | P a g e
Chapter 8 Programming
Round
The round library is a library of code which allows users to round numerical
values to a set amount of decimal places
An example of rounding is using REAL values and rounding to 2 decimal
places
The round library can be written as:
ROUND(<identifier>, <places>)
23 | P a g e
Chapter 8 Programming
Maintaining Programs
What is an array?
An array is an ordered, static set of elements in a fixed-size memory location
An array can only store 1 data type
A 1D array is a linear array
Indexes start at generally start at 0, known as zero-indexed
Concept Pseudocode Python
DECLARE scores:
scores = []
ARRAY[0:4]OF INTEGER
Creates a blank array with 5 elements
Creates a blank array
Create (0-4)
scores = [12, 10, 5,
scores ← [12, 10, 5, 2, 8]
2, 8]
Creates an array called scores with values assigned
colours[4] ← "Red" colours[4] = "Red"
Assignment
Assigns the colour "Red" to index 4 (5th element)
Example in Python
Creating a one-dimensional array called ‘array’ which contains 5 integers.
Create the array with the following syntax:
array = [1, 2, 3, 4, 5]
Access the individual elements of the array by using the following syntax:
array[index]
Modify the individual elements by assigning new values to specific indexes
using the following syntax:
array[index] = newValue
24 | P a g e
Chapter 8 Programming
Use the len function to determine the length of the array by using the
following syntax:
len(array)
In the example the array has been iterated through to output each element
within the array. A for loop has been used for this
Python
# Creating a one-dimensional array
array = [1, 2, 3, 4, 5]
# Accessing elements of the array
print(array[0]) # Output: 1
print(array[2]) # Output: 3
# Modifying elements of the array
array[1] = 10
print(array) # Output: [1, 10, 3, 4, 5]
# Iterating over the array
for element in array:
print(element)
# Output:
# 1
# 10
# 3
# 4
# 5
# Length of the array
length = len(array)
print(length) # Output: 5
2-Dimensional Arrays
25 | P a g e
Chapter 8 Programming
NamesAndNumbers[2,
3] ← "19"
NamesAndNumbers[3,
1] ← "Sarah"
NamesAndNumbers[3,
2] ← "12"
NamesAndNumbers[3,
3] ← "8"
Creates a 2D array called players with values assigned
NamesAndNumbers[0,1] NamesAndNumbers[0][1] =
← "Holly" "Holly"
Assignment
Assigns the name "Holly" to index 0, 1 (1st row, 2nd column) -
replaces "Paul"
Example in Python
Python
# Initialising a 2D array with 3 rows and 3 columns, with
the specified values
array_2d = [[1, 2, 3],
[4, 5, 6],
[7, 8, 9]]
# Accessing elements in the 2D array
print(array_2d[0][0]) # Output: 1
print(array_2d[1][2]) # Output: 6
Iterating through a 2-dimensions array
When iterating through an array, a nested for loop can be used
Python
# Nested iteration to access items in the 2D array
for row in array_2d:
for item in row:
print(item, end=" ")
print() # Print a newline after each row
Examiner Tip
In the exam, the question will always give an example to demonstrate which
order the array is being read from.
Some questions can be X,Y and others can be Y, X. Always refer to the example
before giving your answer!
Worked Example
A parent records the length of time being spent watching TV by 4 children
Data for one week (Monday to Friday) is stored in a 2D array with the
identifier minsWatched.
26 | P a g e
Chapter 8 Programming
Tuesday 1 56 43 45 56
Wednesday 2 122 23 34 45
Thursday 3 13 109 23 90
Friday 4 47 100 167 23
Write a line of code to output the number of minutes that Lyla watched TV on
Tuesday [1]
Write a line of code to output the number of minutes that Harry watched TV on
Friday [1]
Write a line of code to output the number of minutes that Quinn watched TV on
Wednesday [1]
Answers
print(minsWatched[1,1] or print(minsWatched[1][1]
print(minsWatched[2,4] or print(minsWatched[2][4]
print(minsWatched[0,2] or print(minsWatched[0][2]
File Handling
27 | P a g e
Chapter 8 Programming
"w" is for writing to a new file, if the file does not exist it will be created.
If a file with the same name exists the contents will be overwritten
Always make a backup of text files you are working with, one mistake and you
can lose the contents!
Worked Example
Use pseudocode to write an algorithm that does the following:
28 | P a g e
Chapter 8 Programming
29 | P a g e