Edexcel International GCSE Chapter 5
Edexcel International GCSE Chapter 5
CHAPTER 5
DEVELOP CODE
PROGRAMMING LANGUAGES
Once an algorithm has been developed to
solve a particular problem, it has to be coded
into the programming language that the
developer is using.
This usually means that the written
descriptions, flowcharts and pseudocode have
to be converted into actual programming
code.
As you will be expected to understand, use
and edit Pearson Edexcel pseudocode in the
examination, examples will be given in the
pseudocode as well as in Python, Java and C#.
1
6/19/2023
PROBLEM SOLVING
Unit 1, an algorithm is a precise method of solving a problem.
It consists of a sequence of unambiguous, step-by-step instructions.
A program is an algorithm that has been converted into program code so that it can be executed by a
computer.
A well-written algorithm should be free of logic errors and easy to code in any high-level language.
As part of this course you will learn to write programs in a high-level programming language.
All high-level programming languages are like natural human languages, which makes them easier for
humans to read and write but impossible for computers to understand without the help of a
translator.
You will learn more about how a program written in a high-level language is translated into machine
code - the language of computers - in Unit 4.
The aim of this unit is to develop your programming skills.
Source code
Source code is the term given to a set of instructions that are
written in human-readable programming language.
The Python program shown before is an example of source code.
This code must be translated into machine code before the
computer can understand and execute it.
2
6/19/2023
Translators
Any program written in a high-level
language is known as source code.
However, computers cannot understand
source code.
Before it can be run, source code must
first be translated into machine code.
A translator is a program that converts
source code into machine code. Generally,
there are three types of translator:
❑ compilers
❑ interpreters
❑ assemblers
Compiler Vs Interpreter
3
6/19/2023
Compilers
A compiler takes the source code as a whole and
translates it into machine code all in one go.
Once converted, the machine code can be run at
any time. This process is called compilation.
Compilers have several advantages: Compilers have several disadvantages:
❑ Compiled programs run quickly, since they have
already been translated. ❑ The source code must be re-
❑ A compiled program can be supplied as compiled every time the
an executable file. An executable file is a file programmer changes the program.
that is ready to run. Since an executable file ❑ Source code compiled for one
cannot be easily modified, programmers prefer platform will not run on another -
to supply executables rather than source code.
the machine code is specific to
❑ Compilers optimize code. Optimized code can the central processing unit’s
run quicker and take up less memory space.
(CPU) architecture.
4
6/19/2023
Interpreters
An interpreter translates source code
into machine code one instruction at
a time.
It is similar to a human translator
translating what a person says into
another language, sentence by
sentence, as they speak.
The resulting machine code
(sometimes called object code) is
then executed immediately.
The process is called interpretation.
Interpreters
Interpreters have several advantages: Interpreters also have several disadvantages:
❑ Instructions are executed as soon as ❑Interpreted programs run more slowly as the
they are translated. processor has to wait for each instruction to be
translated before it can be executed.
❑ Errors can be quickly spotted - the
moment an error is found, the ❑Additionally, the program has to be translated
program stops running and the user every time it is run.
is notified at which part of the
program the interpretation has ❑Interpreters do not produce an executable file
failed. This makes interpreters that can be distributed. As a result, the source
extremely useful when developing code program has to be supplied, and this could
programs. be modified without permission.
❑Interpreters do not optimize code - the
translated code is executed as it is.
5
6/19/2023
Assemblers
Assemblers are a third type of translator.
The purpose of an assembler is to
translate assembly language into
machine code.
Whereas compilers and interpreters
generate many machine code
instructions for each high-level
instruction, assemblers create one
machine code instruction for each
assembly instruction.
Data Type
6
6/19/2023
Cont’d
When writing pseudocode, you don't have to specify the data types of variables.
However, data types become much more important once you start programming in
a high-level language.
This is because the data type of a variable determines the operations that can be
performed on it.
For example, the result of multiplying a value by 5 differs according to its data type.
integer 8*5=40
real 8.0 * 5 = 40.0
Character ‘8’ * 5 = ‘88888’
The method of declaring variables differs between programming languages.
Some languages, such as Python, automatically select the appropriate data type for
a variable based on the data assigned to it.
Others, such as Java and C#, require the data type of variables to be declared
before the variables can be used.
7
6/19/2023
Once a variable has been initialised an assignment statement is used to change its value (e.g. SET total TO total +
admissionCharge).
In Python this would be:
total = 0
total = total + admissionCharge
In Java this would be:
Scanner scan = new Scanner(System.in);
int admissionCharge = scan.nextlnt(); int total = O; total = total + admissionCharge;
In C#, variables must be declared before use. When you declare a variable, you need to state the data type that the
variable will store, for example:
// declare a variable called total that will be used to store floating point numbers and assign the value 0.0 to it
float total = 0.0;
// add the value stored in the variable admissionsCharge to the total
total = total + admissionsCharge;
If a variable, such as a loop counter, is intended to hold a running total, then it should always be initialised to a
starting value. Some programming languages won't execute if the programmer fails to do this; others will do so but
may well produce some unexpected results.
2 What do you think is an appropriate data type for each of these items?
a the test score of an individual learner
b the average score for a group of learners
c whether or not the pass mark for the test has been achieved.
3 Look back over the algorithms you wrote in Unit 1 and find instances of variable initialisation.
8
6/19/2023
ACTIVITY 1
1 Students should create a table listing data types. High-level programming languages often
provide more than the four basic data types.
ACTIVITY 1
2 What do you think is an appropriate data type for each of these items?
a the test score of an individual learner
b the average score for a group of learners
c whether or not the pass mark for the test has been achieved.
2
a integer
b real
c Boolean
9
6/19/2023
ACTIVITY 1
3. Look back over the algorithms you wrote in Unit 1 and find instances of variable initialisation.
3 There is no single correct solution to this activity.
Variable initialization – position=1, switch=0, total=0, number=0
Instances of variable initialization for Activity 5 – firstNumber and seconNumber
TYPE COERCION
Sometimes the data type of a variable gets changed during program execution. This is known as
type coercion. For example, if an integer value and a real value are used in an arithmetic
operation, the result will always be a real.
In Python, type coercion is done automatically, for example, the output from the following
program is 3.25.
X=1
Type coercion is also automatic in Java:
Y=2.25 int x = l;
Z=x+y double y = 2.25;
double z = x + y;
print(z) System.out.print(z);
10
6/19/2023
ACTIVITY 2
11
6/19/2023
ACTIVITY 3
UNDERSTANDING ALGORITHMS
Read the following algorithm written in pseudocode
and then answer the questions below.
1 What does this algorithm do?
1. RECEIVE numberl FROM (INTEGER) KEYBOARD
2 What is the output of the algorithm, given the
2. RECEIVE number2 FROM (INTEGER) KEYBOARD following inputs:
3. SET resultl TO numberl / number2 a 4, 2
4. SEND resultl TO DISPLAY b 10,3
5. SET result2 TO numberl MOD number2 C 20, 6?
6. SEND result2 TO DISPLAY Implement this algorithm in the high-level language
you are studying.
7. SET result3 TO numberl DIV number2
8. SEND result3 TO DISPLAY
Num1=4
Num2=2
Result1=num1/num2=4/2=2.0
Result2=num1%num2=4%2=0
Result3=num1//num2=4//2=2
Num1=10
Num2=3
Result1=num1/num2=10/3=3.3333
Result2=num1%num2=4%2=1
Result3=num1//num2=4//2=3
Num1=20
Num2=6
Result1=num1/num2=20/6=3.33333
Result2=num1%num2=20%6=2
Result3=num1//num2=20//6=3
12
6/19/2023
ACTIVITY 3
1 The algorithm takes in two integer numbers entered from the keyboard and displays:
◼ the result of dividing the first number by the second number
◼ the number remaining after dividing the first number by the second number
◼ the integer division.
ACTIVITY 3
2 a With 4 and 2 as inputs, the outputs would be: 2.0, 0, 2.
b With 10 and 3 as inputs, the outputs would be: 3.33333333333333, 1, 3.
c With 20 and 6 as inputs, the outputs would be: 3.33333333333333, 2, 3.
13
6/19/2023
ACTIVITY 3
3 Here is the algorithm implemented in Python:
number1=int(input("Enter number1:"))
number1 = int(input(‘Enter first number:’)) number2=int(input("Enter number2:"))
result1=number1/number2
number2 = int(input(‘Enter second number:’)) print(result1)
print(‘number1 / number2 =’, number1/number2) result2=number1%number2
print(result2)
print(‘number1 MOD number2 =’, number1 % number2) result3=number1//number2
print(result3)
print(‘number1 DIV number2 =’, number1 // number2)
SELECTION
The selection construct is used to create a branch in a program. The computer
selects which branch to follow based on the outcome of a condition, using an
IF ... THEN ... ELSE statement. For example, in pseudocode:
14
6/19/2023
Worked Example
A learner handed in three homework
assignments, which were each given a
mark out of 10.
All the marks were different. Write an
algorithm that would print out the highest
mark.
Figure 2.1 shows the algorithm expressed
as a flowchart.
Worked Example
HINT
When you are creating nested IF statements, you have to ensure that each one is completed
with an END IF statement at the correct indentation level. Some programming languages do not
need an END IF statement and just use the indentation levels to indicate when statements are
grouped.
15
6/19/2023
Python Code
In Python, Java and C# this does not have to be done as they have an 'else if' statement.
In Python the 'else if' statement is elif and the algorithm above could be:
16
6/19/2023
#ch5_workexample
mark1=int(input("Please enter the first mark"))
mark2=int(input("Please enter the second mark"))
mark3=int(input("Please enter the third mark"))
RELATIONAL OPERATORS
The relational operators are used to compare two values and in Python, Java and C# are all the same.
relational operator an operator that tests the relationship between two entities
logical operator a Boolean operator using AND, OR and NOT
17
6/19/2023
Activity 4
Look at the following algorithm and answer the
questions.
IF score <= highScore THEN
SEND 'You haven't beaten your high score.' TO DISPLAY
ELSE
SEND 'You've exceeded your high score!' TO DISPLAY
END IF
What is the output of the algorithm when
■ score= 5 and highScore = 1 O?
■ score= 20 and highScore = 10?
■ score= 15 and highScore = 15?
Activity 4 - Answer
18
6/19/2023
LOGICAL OPERATORS
AND
If two conditions are joined by the AND operator, then they must both be true for the whole
statement to be true.
OR
If two conditions are joined by the OR operator, then either one must be true for the whole
statement to be true.
NOT
The NOT operator reverses the logic of the AND and OR statements. The statement IF A = 3 AND B = 6
will be true only if the conditions are met, i.e. A and Bare both equal to the values stated.
The statement IF NOT (A = 3 AND B = 6) will be true whenever both A and Bare NOT equal to the
values stated, i.e. either or both are not equal to those values.
19
6/19/2023
Activity 5
A driving school uses this rule to estimate how many
lessons a learner will require.
■ Every learner requires at least 20 lessons.
■ Learners over the age of 18 require more lessons
(two additional lessons for each year over 18).
Create a program in a high-level language that inputs a
learner's age and calculates the number of driving
lessons they will need.
20
6/19/2023
LOOPS
A loop is another name for an iteration. Loops are used to make a computer repeat a set of
instructions more than once. There are two types of loop: definite and indefinite.
A definite loop is used when you know in advance how often the instructions in the body of the
loop are to be repeated. For example, if you want the computer to display a character on the
screen for a fixed amount of time and then remove it.
An indefinite loop is used when the number of times a loop will need to be repeated is not
known in advance. For example, if you want to give a user the option of playing a game as often
as they want. Indefinite loops are repeated until a specified condition is reached.
Every programming language has a number of built-in loop constructs. You will need to explore
the ones provided in the language you are studying.
Definite Iteration
21
6/19/2023
Definite Iteration
22
6/19/2023
Recursion
Activity 6
Produce a program in a high-level language that asks a user to enter a start
number and an end number and then outputs the total of all the numbers in the
range. For example, if the start number was 1 and the end number was 10, the
total would be 55 (10 + 9 + 8 + 7 + 6 + 5 + 4 + 3 + 2 + 1 ).
ACTIVITY 6 - Python:
start = int(input(‘Enter the start number’))
end = int(input(‘Enter the end number’))#5
total = 0
for count in range(start, end+1):
◦ total = total + count
print(total)
23
6/19/2023
NESTED LOOPS
A nested loop is made of a loop within a loop.
When one loop is nested within another, each iteration of the outer
loop causes the inner loop to be executed until completion.
Activity 7
a It uses nested loops to calculate
the average mark for 5 pieces of
work from each of twenty students.
24
6/19/2023
ACTIVITY 7
a It uses nested loops to calculate the average mark for 5 pieces of work from each of twenty
students.
b To ensure that the marks entered by the user are recognised as integers and not strings.
ACTIVITY 8 - Python:
25
6/19/2023
INDEFINITE ITERATION
An indefinite loop is used when the number of times a loop will need to be repeated is not known in advance. For
example, if you want to give a user the option of playing a game as often as they want. Indefinite loops are
repeated until a specified condition is reached.
Python
For indefinite iteration, Python uses the 'while' loop - something is done while a condition is met.
The following program asks a user to enter a number while the number is less than 20.
number = 1
while number <= 20:
number = int(input('Please enter a number'))
print('You entered a number greater than 20')
As soon as the number is greater than 20, the program breaks out of the loop and prints a message for the user.
26
6/19/2023
ACTIVITY 9
1 a Algorithm A displays the numbers 1 to 10 cubed, i.e. 1–1000.
Here is the algorithm implemented in Python:
for index in range(1, 11):
◦ print (index * index * index)
RANDOM NUMBERS
Random numbers are commonly used in games of chance such as flipping a coin or rolling a
dice. The aim is to make an event random.
All high-level programming languages have functions to create random numbers.
Python Python has a random module. The following code will generate a random number
between 1 and 10.
import random
x = random.randint(l, 11)
print(x)
The 'import' command is necessary so that the 'random' module can be used.
27
6/19/2023
Activity 10
28
6/19/2023
import random
play = True
correct = False
if guess == randomNumber:
correct = True
reply = reply.upper()
if reply == ‘Y’:
play = True
correct = False
else:
play = False
Checkpoint
Strengthen
S1 Why are variables needed?
S2 Provide examples of the four data types.
S3 How are selection and iteration implemented in the high-level
language you are studying?
Challenge
C1 Outline the following structural components of a program:
variable and type declarations, command sequences, selection and
iteration constructs.
29
6/19/2023
S2 and S3
S2 Provide examples of the four data types.
S2 Ideally, students should give examples of different data types from their own programs.
Eg.
age = 10 #integer
first_name=“John”#string
Temperature=97.5#real or float
Pass=True#Boolean
S3 How are selection and iteration implemented in the high-level language you are studying?
S3 The description will vary according to the high-level language the student is studying.
The main thing for them to realise is that the language will have a number of different selection
and loop constructs.
30