Slides badge

Software Design and Development

NPA Software Development - Level 6

Basics

Production

Computer systems

Advanced

What this course involves

  • Throughout this course you will be learning about different software design and development techniques and how to write code to produce software.
  • This course is fairly similar to the unit with the same name from the National 5 and Higher courses.
  • Since not everyone has the same level of programming experience, we are starting from the very beginning.

Which courses have you done?

Unit outcomes

  • Read and explain code

  • Describe the purpose of programming constructs and how they work

  • Describe a range of standard algorithms and how they work

  • Describe how software relates to the way computers work 

Outcome 1 - Understanding how computers and software work

Outcome 2 - Develop modular programs

  • Apply contemporary design methodologies

  • Selecting and using appropriate constructs

  • Selecting and using appropriate simple (primitive) and structured data types such as 1-D arrays

  • Testing digital solutions systematically

  • Applying good programming technique such as meaningful variable names, internal commentary and indentation

A quick challenge

Do these individually.

  • List the steps to make a cup of tea.
  • List the steps to logon to the computer

A quick challenge

Whilst we all arrive at the same solution (i.e. we have a cup of tea), we can have different ways of doing it

Do these individually.

  • List the steps to make a cup of tea.
  • List the steps to logon to the computer

Programming using Python

  • For this course we will be using the Python programming language and the PHP programming language.

def findMaximum(l):
  i = 0
  max = l[0]
  while (i < len(l)):
    if l[i] > max:
      max = l[i]
    i = i + 1

  return max

scores = [53, 12, 95]

print(findMaximum(scores))
function findMaximum(l):
  $i = 0
  $max = l[0]
  while ($i < count($l)):
    if $l[$i] > $max:
      $max = l[$i]
    $i = $i + 1

  return $max

$scores = [53, 12, 95]

print(findMaximum($scores))
  • On your computers, open up Python IDLE. 
  • Press File > New to create a new file. This is where you will write any code.
  • Write the following code and then hit Run Module under the Debug menu:

What did it ask you to do when you pressed run?

print("Hello world")

Getting started

Getting started

  • On your computers, open up Python IDLE. 
  • Press File > New to create a new file. This is where you will write any code.
  • Write the following code and then hit Run Module under the Debug menu:
print("Hello world")

What did it ask you to do when you pressed run?

The result

  • On your computers, open up Python IDLE. 
  • Press File > New to create a new file. This is where you will write any code.
  • Write the following code and then hit Run Module under the Debug menu:
print("Hello world")

What did it ask you to do when you pressed run?

Input & output

Input and output

  • Input and output are one of the most important aspects of a program. 
  • Without input and output, a computer program is technically useless.
  • We talk about input and output devices being a mouse (input) and a screen (output).

Input and output in Python

  • Output in Python is done with the print function:
print("Hello world!")
print("Hello", "world")
  • Note, when you put a comma in the print function, the text that follows it will be displayed as well, but with a space between it and the previous text. So in the above example, it will print "Hello world" twice.

Input and output in PHP

  • Output in PHP is done with the echo keyword:
echo "Hello world!";
  • Input in Python is done with the input function:
print("Please insert your name")
print(input())

Input and output in Python

  • PHP works differently in that it is a web-based programming language. As a result, we need a page to provide data then we can read it as shown below:
echo $_GET['user_input'];

Input and output in PHP - Method 1

  • If we run PHP interactively, we can use the readline function instead:
echo 'Please insert a value';
echo readline();

Input and output in PHP - Method 2

  • PHP isn't like Python most of the time and is used with web technologies. 
  • Before you submit data using this method, create a HTML page with a form that submits data using POST to our PHP page.
<form method="post" action="process.php">
  <input name="username">
  <input type="submit">
</form>
echo $_POST['username'];

HTML

PHP

Open Python IDLE:

 

Write a program to display "Hello" and the users name which you have asked for.

 

Do the same in PHP.

Task

Maths in Python

Maths in Python

  • Being able to use mathematical statements in a programming language is one of the most commonly used constructs.
  • In Python, mathematical expressions are written similarly to how they are written in real life.
  • Maths in Python is very similar to how it is done in actual maths. For example, in maths you write 5 + 5 and in Python we just write 5 + 5.
  • Here is a list of the different maths symbols we can use in Python:
  • What will this display?

 

 

 

  • Write a program to display the result of multiplying 2.53 by 20
  • Now write both programs in PHP.
print(5 + 5 * 2 / 4)

Maths in Python

Variables and data types

Learning Intentions

  • Describe and use variables and how they are important in computer programming

Success Criteria

  • I can describe what a variable is
  • I can use variables within a program

What is a variable?

A variable is a letter which represents an unknown number. For example in the expression
5 = x + 2, x is a variable

A definition from maths

A variable is like a container with a name on it. Values are put into and taken out of this container as needed.

A computing way of thinking

Variable declaration in Python

  • Variables in Python are basically written in the same way they are in maths.
x = 10
y = 2
z = x + y

Variable declaration in PHP

  • And in PHP we use the $ sign in front of an identifier string:
$x = 10;
$y = 2;
$z = $x + $y;

Storing what the user typed

  • A very common use case for variables is to store what the user has typed into a input.
print("Please insert your name")
fullName = input()
echo "Please insert your name";
$fullName = readline();

Data types

  • A data type is the type of the data you are storing in a variable.
    For instance, when we are storing a number using the int(input()) function we are getting an integer.
    Python has 5 data types we need to know about.

Data types

  • Python also treats characters (or chars) as strings when finding the data type of a variable, but it doesn't treat them the same when using functions on characters.

Converting inputs in Python

  • Conversion (casting) in Python is a very important feature when working with input and output as well as variables.
print("Please a number")
x = input()
y = x + 5
  • This unfortunately won't work in Python. So we need to convert it first.
print("Please a number")
x = int(input())
y = x + 5

Converting inputs in pHP

  • PHP often converts values differently to Python and doesn't always require explicit conversion. 
echo "Please insert a number";
$x = readline();
$y = $x + 5
  • PHP will accept this, unlike Python, but it's still better to be safe about this and cast the value.
echo "Please insert a number";
$x = (int) readline();
$y = $x + 5;

Converting inputs in Python

  • In Python, you have the following types to cast to:
    • bool
    • str
    • int
    • float
a = bool(int(input()))
b = str(input())
c = int(input())
d = float(input())

Note the bool casting function will convert everything to True, except the number 0.

Converting inputs in PHP

  • In Python, you have the following types to cast to:
    • bool
    • string
    • int
    • float
    • array
    • object
    • unset
$a = (bool) readline();
$b = (string) readline();
$c = (int) readline();
$d = (float) readline();
$e = (array) readline();
$f = (object) readline();
$g = (unset) readline();

Note the bool casting function will convert everything to True, except the number 0.

  • The type function can determine a type of a value or variable.
a = bool(int(input()))
b = str(input())
c = int(input())
d = float(input())

print(type(a))
print(type(b))
print(type(c))
print(type(d))

Checking the data types in Python

  • The get_type function can determine a type of a value or variable.
$a = (bool) readline();
$b = (string) readline();
$c = (int) readline();
$d = (float) readline();

echo get_type($a);
echo get_type($b);
echo get_type($c);
echo get_type($d);

Checking the data types in PHP

Using Python and PHP on your computers, create a variable with each data type discussed in it by using casting to ensure that the value is converted to the correct data type.

 

Use the type and get_type functions to check the data type is correct.

Activity

Selection

Learning Intentions

  • Understand conditional selection and it's importance

Success Criteria

  • I can explain why we need selection in a computer program
  • I can use conditional selection in Python and PHP
  • Selection is another flow control construct that is very common.
  • Selection is all about making decisions based some condition. 
  • A condition is either True or False.
  • The most common type of selection construct is the if statement.
  • If is a type of conditional statement.

Selection

  • Selection allows us to make decisions based on something else, such as the result of an input.

Selection

  • Below is a program for checking if the user can drive or not Python

age = int(input())
if age > 16:
  print("You are old enough to drive")
  • It does not, however, tell the user if they cannot drive...

Selection in Python

  • Below is a program for checking if the user can drive or not Python

age = int(input())
if age > 16:
  print("You are old enough to drive")
else:
  print("You are too young to drive")
  • This version now tells if we cannot drive by using else.

Selection in Python

  • Don't forget the : symbol at the end of the condition and after the else keyword.

  • Below is a program for checking if the user can drive or not in PHP

$age = (int) readline();
if ($age > 16) {
  echo "You are old enough to drive";
} else {
  echo "You are too young to drive";
}

Selection in PHP

  • With PHP, note the importance of the brackets after the if as, unlike Python, PHP will not compile without them.

  • We also don't use a : symbol at the end of the condition, instead we contain the code routes within the { and } symbols.

  • Comparison of two values is made up of Boolean expressions and a comparator symbol. 
  • An Boolean expression might be something like x > 10, or it could be simply True or similar.

Selection

Comparators

print("Please insert your username")
username = input()
print("Please insert your password")
password = input()

if username == "Hamish" and password == "pass":
  print("Welcome!")
else:
  print("Login incorrect")

Login system in Python

echo "Please insert your username";
$username = readline();
echo "Please insert your password";
$password = readline();

if ($username == "Hamish" && $password == "pass") {
  echo "Welcome!";
} else {
  echo "Login incorrect";
}

Login system in PHP

Write a program that does each of the following:

  • Asks the user to insert a number, displays if the number is greater than 50 or not
  • Asks the user a question and checks if what the user has typed is correct

Activity

Loops

Learning Intentions

  • Understand what a loop is in computer science
  • Implement a loop in Python and PHP

Success Criteria

  • I can explain the benefit of loops in computer programming
  • I am able to develop a fixed loop in Python and PHP
  • I am able to develop a conditional loop in Python and PHP
  • A loop will do something over and over until a termination case has been met. This basically means when the computer is told that it is time to stop.
  • Some loops, called infinite loops, will never terminate. An example of this is one that will keep a slideshow on a website running forever.
  • The body of the loop is the code that is repeated.
  • There are two kinds of loops: fixed loops and conditional loops

What a loop does

n = 0

print(n)
n = n + 1

print(n)
n = n + 1

print(n)
n = n + 1

print(n)
n = n + 1

Without loops in Python

$n = 0;

echo $n;
$n = $n + 1

echo $n;
$n = $n + 1

echo $n;
$n = $n + 1

echo $n;
$n = $n + 1

Without loops in PHP

n = 0

for i in range(0, 4):
  print(n)
  n = n + 3

With loops in Python

$n = 0;

for ($i = 0; $i < 4; $i++){
  echo $n;
  $n = $n + 3;
}

With loops in PHP

Fixed loops

  • Just like with if statements you can have nested loops.
for num1 in range(0, 5):
  for num2 in range(0, 5):
    print(num1, num2)

Loops inside loops in python

  • Just like with if statements you can have nested loops.
for ($num1 = 0; $num1 < 5; $num1++){
  for ($num2 = 0; $num2 < 5; $num2++){
    echo $num1 . ' ' . $num2;
  }
}

Loops inside loops in PHP

  1. Write a for loop that will display each number in the six times table (6, 12, 18...).

 

  1. Complete the Python Fixed Loops (For) tasks in the Python book on page 29

Activity

  • A condition will always evaluate to True or False.
  • Conditional loops use a condition to loop whilst a condition evaluates to true.
  • Some conditional loops never evaluate to True and therefore are considered to be infinite loops.
  • Python has several types of conditional loops, but the one we are interested in is the while loop.

A conditional loop

For each of the following, state whether it is true or false:

Activity

x = True
y = False

print(x and y)
x = 54
y = 24

print(x > y)
x = 54
y = 24

print(x < y or y > 5)
x = True
y = True

print(not(x or y))
  • While loops will continue to loop while a condition is True.
  • If the condition is initially false, then the loop will never run.
while True:
  print("This loop is never gonna end!")
n = 0
while n < 100:
  print(n)
  n = n + 1

A while loop in Python

  • While loops will continue to loop while a condition is true.
  • If the condition is initially false, then the loop will never run.
while (true) {
  echo "This loop is never gonna end!";
}
$n = 0;
while ($n < 100) {
  echo $n;
  $n = $n + 1;
}

A while loop in PHP

print("Please insert your username")
username = input()
print("Please insert your password")
password = input()
attempts = 0

while username != "Hamish" and password != "pass":
  print("Login incorrect")
  print("Please insert your username")
  username = input()
  print("Please insert your password")
  password = input()
  attempts = attempts + 1

print("Welcome", "It took you", attempts, "to login")

A login system - using loops in Python

echo "Please insert your username";
$username = readline();
echo "Please insert your password";
$password = readline();
$attempts = 0;

while ($username != "Hamish" && $password != "pass") {
  echo "Login incorrect";
  echo "Please insert your username";
  $username = readline();
  echo "Please insert your password";
  $password = readline();
  $attempts = $attempts + 1;

echo "Welcome", "It took you", attempts, "to login";

A login system - using loops in PHP

Complete the Conditional Loops worksheet

 

Complete the Python Conditional Loops (While) tasks in the Python book on page 31

Activity

Arrays

Learning Intentions

  • Describe, use and exemplify several data types

  • Describe and use 1D arrays

Success Criteria

  • Be able to explain the different data types and what they do
  • Be able to explain what a 1D array is and use them in code

Arrays

  • An array is a data structure.

  • Arrays let programmers store ‘lists’ of related data in one data structure.

  • For example, we could use an array to store pupil marks.
    Each value in a list is given its own position/index value so it can easily be referenced.

  • Arrays can be assigned to variables.

  • Often a program will have to store lots of information at the one time, for example, when a teacher is entering in the names of all their pupils. It is unrealistic to have a separate variable for each of the names (StudentName1, StudentName2….etc).

  • Arrays allow the programmer to store more than one piece of data within a single data structure.

The element data type can be integers, reals, Booleans, characters or string

Declaring an array in Python

strings = [""] * 5
integers = [0] * 5
reals = [0.0] * 5
booleans = [False] * 5
characters = [""] * 5

Declaring an array in Python

$items = array();

Declaring an array in PHP

print("Please insert the number of pupils required.")
numberOfPupilsRequired = int(input())

pupils = [""] * numberOfPupilsRequired

for i in range(0, numberOfPupils):
  print("Please insert the name of pupil", i, ".")
  pupils[i] = input()

The fix - using an array in Python

echo "Please insert the number of pupils required.";
$numberOfPupilsRequired = intval(readline());

$pupils = array();

for ($= 0; $i < $numberOfPupils; $i++) {
  echo "Please insert the name of pupil " . $i .  ".";
  array_push($pupils, readline());
}

The fix - using an array in PHP

  • Arrays save time when declaring variables as all we need to do is specify how many elements (the parts that make up an array) we need and the type of the array.
  • Arrays can be resized as the program runs (as shown before)
  • Arrays tie very nicely to fixed and conditional loops
  • Arrays use less memory than several variables, can you think why?

The benefits of arrays

  • The SQA uses the following syntax for describing arrays using their own reference languages:

 

 

 

 

 

  • This defines an empty array – that is each element of the array contains an empty string, denoted by the ""

DECLARE playerNames AS ARRAY OF STRING INITIALLY [""]*7

Arrays in SQA Reference Language

You are required to create a program that manages and analyses student assessment scores. The program should allow users to input 10 scores, perform various operations on the scores using arrays, and provide basic statistical analysis.

Requirements:

  1. Take in a set of student assessment scores (integer values) from the user. Use an array to store these scores.
  2. Implement functions for the following array manipulation tasks:

    1. Calculate and display the average score.
    2. Calculate and display the total score.
    3. Increase all scores by 10% percent.

Activity

Best Practices

Learning Intentions

  • Understand what best practices are and how they affect programs
  • Be able to explain several best practices

Success Criteria

  • I can explain several best practices when it comes to writing code
  • I can use several methods to make my code better 

Best practices in programming

  • When programming, you should always aim to write code that follow some of the best practices for programming. These are:
    • Using whitespace and indentation
    • Using comments
    • Using suitable identifiers
    • Using efficient constructs

Whitespace and indentation

  • Whitespace and indentation are both really useful for making a program more readable. 

  • Python enforces indentation, and to some degree, will assist in the indenting a program. PHP does not, so ensure that you use indentation in your code.

Comments

  • Comments make code easier to read by describing what the code does.

  • Comments in Python are written with a # sign in front of them. PHP uses the # or // in front of a line. 

  • Multiline comments in Python are represented with a ''' in front of them and after them. In PHP a multiline comment is started with /* and ended with */.

  • If you don't already, get into the habit of putting your name, the date and what the program is meant to do at the top of the code in comments

#Asks the user for their name
print("Please insert your name")
forename = input()
//Asks the user for their name
echo "Please insert your name";
$forename = readline();

Using suitable identifiers

  • An identifier is how a compiler recognises a variable or subprogram. 

  • An identifier must be unique; this means that a variable name cannot be the same as a subprogram name.

forename = input()

def doubleNumber(x):
  return x * 2
$forename = readline();

function doubleNumber($x){
  return $x * 2;
}

Using efficient constructs

  • It's easy to start writing a program which has lots of repetition in it and not use loops.

  • Making a program more efficient involves using constructs such as loops, subprograms and subprogram calls, nested if statements

if mark > 80:
  print("A")
else:
  if mark > 60:
  	print("B")
  else:
    print("C")
if mark > 80:
  print("A")
else if mark > 60:
  print("B")
else:
  print("C")
if ($mark > 80) {
  echo "A";
} else {
  if ($mark > 60) {
    echo "B";
  } else {
    echo "C";
  }
if ($mark > 80) {
  echo "A";
} else if ($mark > 60) {
  echo "B";
} else {
  echo "C";
}

Using efficient constructs

  • It's easy to start writing a program which has lots of repetition in it and not use loops.

  • Making a program more efficient involves using constructs such as loops, subprograms and subprogram calls, nested if statements

if mark > 80:
  print("A")
else:
  if mark > 60:
  	print("B")
  else:
    print("C")
if mark > 80:
  print("A")
else if mark > 60:
  print("B")
else:
  print("C")
if ($mark > 80) {
  echo "A";
} else if ($mark > 60) {
  echo "B";
} else {
  echo "C";
}
if ($mark > 80) {
  echo "A";
} else {
  if ($mark > 60) {
    echo "B";
  } else {
    echo "C";
  }

Activity

  • Look at your existing code from other assignment. 

  • Rate your work in terms of how well you have used whitespace, commented it, used good naming conventions for identifiers and used efficient constructs.

Functions

Learning Intentions

  • Understand the term function
  • Understand that any programming language has built-in functions

Success Criteria

  • I can explain the benefits of predefined functions

What actually is a function?

  • At National 5 and Higher the SQA talk about predefined functions.

  • These are functions built-in to the programming language in the form of either a function which is provided through the runtime (like in Python) or compiled straight to the original code (like in C++)

from random import randint

x = randint(0, 10)

Parameters

x = 10
printSquareNumber(x)
  • A parameter is a value that is passed into a subprogram when the subprogram is called. These parameters are called actual parameters.
  • In Python a parameter is put within the brackets after the name of the subprogram.
 
 
 
 
 
  • What is the parameter?
  • What is the function name?

 

Order of parameters is important

  • The order of your parameters is very important. For example, if you expect the first formal parameter to be a number and the first value given as an actual parameter is a string, the program will crash or at least not run as expected.
def printAverage(name, mark1, mark2):
  average = (mark1 + mark2) / 2
  print("Pupil", name, " got an average of", average)


printAverage(21, 34, "John")

Using functions

  • You are about to go in to a world of work. You are responsible for understanding how to find a built-in function and understand the documentation about it.

  • This is an important skill for any good programmer.

Activity

  • Copy and complete this table by looking up the following functions

Function name Description Parameters and description
abs
ord

exec
eval
pow
hex
divmod
oct

Algorithms

Learning Intentions

  • Understand the concept of an algorithm
  • Understand how to implement several algorithms in Python and PHP

Success Criteria

  • I can explain the term algorithm
  • I can create several standard algorithms in Python and PHP

Algorithm

  • An algorithm is a sequence of instructions that completes a specific task.

  • The order of these instructions is important

  • At National 5 you came across three standard algorithms:

    • Traversing an array

    • Input validation

    • Running total

Traversing an array in Python

  • The traversing an array algorithm works simply by looping through an entire array of values

  • It then does something with those names (for example, simply prints them)

total = 0
names = ["Cammy", "John", "Mike"]
for i in range(0, len(names)):
  print(names[i])

Traversing an array in PHP

  • The traversing an array algorithm works simply by looping through an entire array of values

  • It then does something with those names (for example, simply prints them)

$total = 0;
$names = array("Cammy", "John", "Mike");
for ($i = 0; $i < count($names); $i++){
  echo $names[$i];
}

Input validation In Python

  • Input validation uses a conditional loop.

  • It loops while the user has not provided the correct username, asking them over and over to insert the correct username

print("Please insert your username")
username = input()
while username != "john117":
  print("Please retype your username")
  username = input()

Input validation In PHP

  • Input validation uses a conditional loop.

  • It loops while the user has not provided the correct username, asking them over and over to insert the correct username

echo "Please insert your username";
$username = readline();
while $username != "john117"{
  echo "Please retype your username";
  $username = readline();
}

Running total in Python

  • The running total algorithm works by setting a total variable to 0

  • It then loops for a set number of times (for example a set number of the size of an array using the len function)

  • Each time it loops, it adds a number to the total variable (it either asks the user to insert a number or it takes the next number from the array)

total = 0
for i in range(0, 10):
  print("Please insert a number")
  total = total + int(input())
total = 0
numbers = [2, 5, 8, 10]
for i in range(0, len(numbers)):
  total = total + numbers[i]

Running total in PHP

  • The running total algorithm works by setting a total variable to 0

  • It then loops for a set number of times (for example a set number of the size of an array using the count function)

  • Each time it loops, it adds a number to the $total variable (it either asks the user to insert a number or it takes the next number from the array)

$total = 0;
for ($i = 0; $i < 10; $i++){
  echo "Please insert a number";
  $total = $total + intval(readline());
}
$total = 0;
$numbers = [2, 5, 8, 10];
for ($i = 0; $i < 10; $i++){
  echo "Please insert a number";
  $total = $total + $numbers[$i];
}

Activity

  • Write a program that loops until the user types -1 adding each number to a total and storing it in array.

  • Write an algorithm which produces the first 10 numbers in the Fibonacci Sequence [1, 1, 2, 3, 5, 8, 13, 21, 34, 55]

  • The linear search algorithm is used to search through an array one element by one.

  • It is an inefficient algorithm because of an array consists of 10,000,000 elements - even with the fastest computer - this will take some time to process.

  • With a linear search, the user provides what is needed and the result is the index of the value that was being searched for.

Linear Search

  • This algorithm works by stepping through an array of items

  • It then checks if the item found at that position is equal to what it is searching for.

  • If it is, it sets the value of the index variable to the current position (not value) in the array

people = ["Matthew", "Flynn", "Connor"]
term = "Connor"
i = 0
index = -1
while i < len(people):
  if people[i] == term:
    index = i
  i = i + 1
print(index)

Linear Search in Python

  • This algorithm works by stepping through an array of items

  • It then checks if the item found at that position is equal to what it is searching for.

  • If it is, it sets the value of the index variable to the current position (not value) in the array

$people = array("Matthew", "Flynn", "Connor");
$term = "Connor";
$i = 0;
$index = -1;
while ($i < count(people)) {
  if ($people[$i] == $term) {
    $index = $i;
  }
  $i = $i + 1;
}
echo $index;

Linear Search in PHP

A program is required to find a user from their user ID.

 

[23, 34, 40, 43, 10, 23, 34, 22, 23, 43]

 

Write a linear search to find the index of the user with user ID of 22

Activity

Counting occurrences in Python

  • Counting occurrences is another algorithm you are expected to know. Below is an example of counting occurrences:
temperatures = [23, 34, 40, 43, 10, 23, 34, 22, 23, 43]
term = 23
total = 0
for i in range(0, len(temperatures)):
  if temperatures[i] == term:
    total = total + 1
print(total)

Counting occurrences in PHP

  • Counting occurrences is another algorithm you are expected to know. Below is an example of counting occurrences:
$temperatures = array(23, 34, 40, 43, 10, 23, 34, 22, 23, 43);
$term = 23;
$total = 0;
for($i = 0; $i < count($temperatures); $i++){
  if ($temperatures[$i] == $term) {
    $total = $total + 1;
  }
}
print(total)

A program is required to find out how many times a country was a certain temperature. A list of temperatures was provided:

 

[23, 34, 40, 43, 10, 23, 34, 22, 23, 43]

 

Write a program to count how many times a temperature has occurred. Test it with 23 and 43.

Activity

Finding the maximum in Python

  • Finding the maximum is really straightforward in Python

temperatures = [23, 34, 40, 43, 10, 23, 34, 22, 23, 43]
max = temperatures[0]

for i in range(0, len(temperatures)):
  if temperatures[i] > max:
    max = temperatures[i]

print(max)

Finding the maximum in PHP

  • Finding the maximum is really straightforward in Python

$temperatures = array(23, 34, 40, 43, 10, 23, 34, 22, 23, 43]);
$max = $temperatures[0];

for($i = 0; $i < count($temperatures); $i++){
  if ($temperatures[$i] > $max) {
    $max = $temperatures[i];
  }
}
echo $max;

Finding the minimum in Python

  • Find the minimum really only involves a few changes

temperatures = [23, 34, 40, 43, 10, 23, 34, 22, 23, 43]
min = temperatures[0]

for i in range(0, len(temperatures)):
  if temperatures[i] < min:
    min = temperatures[i]

print(min)

Finding the minimum in PHP

  • Find the minimum really only involves a few changes

$temperatures = array(23, 34, 40, 43, 10, 23, 34, 22, 23, 43]);
$min = $temperatures[0];

for($i = 0; $i < count($temperatures); $i++){
  if ($temperatures[$i] < $min) {
    $min = $temperatures[i];
  }
}
echo $min;

List of 10 test scores is show below:

 

[53, 12, 95, 54, 23, 45, 60, 72, 87, 48]

 

Implement a program to find the highest test score and the lowest test score using Python.

Activity

Modularity

Learning Intentions

  • Understand what modularity is and why it is used
  • Understand the benefits of modularity

Success Criteria

  • I can explain the term modularity in relation to programming
  • I can explain the benefits of modularity
  • I can implement a modular program

Subprograms

  • Program code often gets very messy unless it is broken up. A program can be broken into chunks to make the program more modular.

  • Programs are often made up of chunks of code that performs different tasks that are repeated throughout the program.

  • These chunks of code are called subprograms.

  • Each subprogram is given a unique name so that it can be referenced later on without having to rewrite the code each time it is used.

Subprograms

  • Often called subroutines, procedures, methods and functions, a subprogram is a clear and independent piece of code that performs a certain task.

  • We have been looking at predefined functions which are in fact themselves subprograms built in to the programming language.

  • These predefined functions, such as round will perform a specific job and nothing more.

  • We too can define our own subprograms.

Subprograms

  • When we need to run the code within a subprogram, we call it.

  • The subprogram receives data from the program and performs an action on it (for example, you might expect the printDoubleNumber subprogram to print a number multiplied by 2)

  • To call it, we use its name followed by brackets and any parameters we need to pass to it, take for example a subprogram called doubleNumber, we could call it using the parameter 2 by using:

printDoubleNumber(2)

Subprograms

def printDoubleNumber(num):
  print(num * 2)


printDoubleNumber(2)

A subprogram definition

A call to a subprogram

function printDoubleNumber($num){
  echo $num * 2;
}


printDoubleNumber(2);

A subprogram definition

A call to a subprogram

Return values and functions

  • A function is like a mathematical function, it takes in a value and then performs a process on it and gives it back as an output.

  • In general, a function is a subprogram that can give back a value. It uses the return keyword to instruct the program to send the data back:

def printDoubleNumber(num):
  return num * 2

x = 10
y = printDoubleNumber(x)

print(y)

Parameters

x = 10
printSquareNumber(x)
  • A parameter is a value that is passed into a subprogram when the subprogram is called. These parameters are called actual parameters.
  • In Python a parameter is put within the brackets after the name of the subprogram.
 
 
 
 
 
  • What is the parameter?
  • What is the subprogram name?

 

Parameters

def printDoubleNumber(num):
  print(num * 2)
  • Parameters are also provided in subprogram definitions too, for example, in the printDoubleNumber function our subprogram expects one parameter, num.
  • When they are added to the definition of a subprogram they are called formal parameters.
function printDoubleNumber($num) {
  echo $num * 2;
}

Order of parameters is important (Python)

  • The order of your parameters is very important. For example, if you expect the first formal parameter to be a number and the first value given as an actual parameter is a string, the program will crash or at least not run as expected.
def printAverage(name, mark1, mark2):
  average = (mark1 + mark2) / 2
  print("Pupil", name, " got an average of", average)


printAverage(21, 34, "John")
function printAverage($name, $mark1, $mark2) {
  $average = ($mark1 + $mark2) / 2;
  echo "Pupil " . $name . " got an average of " . $average;
}

printAverage(21, 34, "John")

Order of parameters is important (PHP)

  • The order of your parameters is very important. For example, if you expect the first formal parameter to be a number and the first value given as an actual parameter is a string, the program will crash or at least not run as expected.
function printAverage($name, $mark1, $mark2) {
  $average = ($mark1 + $mark2) / 2;
  echo "Pupil " . $name . " got an average of " . $average;
}

printAverage(21, 34, "John")
def printAverage(name, mark1, mark2):
  average = (mark1 + mark2) / 2
  print("Pupil", name, " got an average of", average)


printAverage(21, 34, "John")

Identify which of the following programs have formal parameters and which have actual parameters:

Activity

def squareIt(num):
def displayOnScreen(num):

1.

2.

print($y)

3.

print($x * 2)

4.

Passing parameters (Python)

def addNumber(n):
  print(x + n)

def setX():
  x = 10

setX()
addNumber(5)
  • When we create a larger program with many subprograms, we need to pass data between these programs by passing it as parameters.
  • Variables declared within one subprogram cannot be accessed by another subprogram unless they are passed as parameters.
  • Parameters can be passed in two ways: by reference or by value
function addNumber($n) {
  echo $x + $n;
}

function setX() {
  $x = 10;
}

setX();
addNumber(5);

Passing parameters (PHP)

def addNumber(n):
  print(x + n)

def setX():
  x = 10

setX()
addNumber(5)
  • When we create a larger program with many subprograms, we need to pass data between these programs by passing it as parameters.
  • Variables declared within one subprogram cannot be accessed by another subprogram unless they are passed as parameters.
  • Parameters can be passed in two ways: by reference or by value
function addNumber($n) {
  echo $x + $n;
}

function setX() {
  $x = 10;
}

setX();
addNumber(5);

Parameter passing by reference

  • Passing by reference sends across the memory location to the subprogram, allowing the subprogram to edit the actual value or variable in memory. 
  • This means that any changes made to the value or variable, will affect the original value or variable.
  • Python DOES NOT support explicit by reference parameter passing, but some data types, such as arrays and dictionaries, automatically are sent by reference.
  • PHP DOES support passing by reference.

Parameter passing by reference

  • In PHP or C parameter passing by reference is done by specifying it with a an & sign in front of a formal parameter definition (e.g. &$x).
function changeX(&$x){
  $x = 20;
}

$x = 10;
echo $x;

changeX($x);
echo $x;

Parameter passing by Value

  • In most languages, passing a parameter by value is the default option. 
  • Passing by value makes a copy of the original value or variable and passes it to the subprogram.
  • Any changes to the value or variable will not affect the original value.
  • The main disadvantage is that this uses CPU and memory time to make and store a second copy of that value or variable.

Local and global variables

  • There are two types of variables in a program, local variables and global variables. This is called the scope of the variable.
  • The scope of a global variable is the entire program.
  • The scope of a local variable is the sub-program where it has been declared.
  • A local variable is defined within a single subprogram and is only accessible to that subprogram. 
  • When this subprogram is run, the variable is added into memory.
  • When the execution of the subprogram is finished, the variable is released from memory.

Local variables

  • A local variable is defined within a single subprogram and is only accessible to that subprogram. 
  • When this subprogram is run, the variable is added into memory.
  • When the execution of the subprogram is finished, the variable is released from memory.
  • There are two types of variables in a program, local variables and global variables. This is called the scope of the variable.
  • The scope of a global variable is the entire program.
  • The scope of a local variable is the sub-program where it has been declared.
  • A global variable on the other hand remains accessible throughout the entire program, meaning it will remain in memory indefinitely whilst the program is running.
  • Global variables are very uncommon in larger programs because they are easier to break.

Global variables

  • A local variable is defined within a single subprogram and is only accessible to that subprogram. 
  • When this subprogram is run, the variable is added into memory.
  • When the execution of the subprogram is finished, the variable is released from memory.
  • A global variable on the other hand remains accessible throughout the entire program, meaning it will remain in memory indefinitely whilst the program is running.
  • Global variables are very uncommon in larger programs because they are easier to break.

Global variables

  • A local variable is defined within a single subprogram and is only accessible to that subprogram. 
  • When this subprogram is run, the variable is added into memory.
  • When the execution of the subprogram is finished, the variable is released from memory.
  • This program contains local and global variables. Anything defined outside of a subprogram (e.g. def) is a global variable:
def printIt(z):
  x = 20
  print(x, y, z)

y = 10
printIt(5)

Local variable

Global variable

This will not work! Python will be unable to find a variable called y!

Using global variables (Python)

  • A local variable is defined within a single subprogram and is only accessible to that subprogram. 
  • When this subprogram is run, the variable is added into memory.
  • When the execution of the subprogram is finished, the variable is released from memory.
  • In both PHP and Python, global variables are declared outside of the scope of a subprogram.
  • However, both of them require an explicit declaration to tell the program to use the variable from the global scope rather than the local scope.
def printIt(z):
  global y
  x = 20
  print(x, y, z)

y = 10
printIt(5)

Local variable

Global variable

Using global variables (PHP)

  • A local variable is defined within a single subprogram and is only accessible to that subprogram. 
  • When this subprogram is run, the variable is added into memory.
  • When the execution of the subprogram is finished, the variable is released from memory.
  • In both PHP and Python, global variables are declared outside of the scope of a subprogram.
  • However, both of them require an explicit declaration to tell the program to use the variable from the global scope rather than the local scope.
function printIt($z) {
  global $y;
  $x = 20;
  echo $x . " " . $y . " " . $z;
}

y = 10;
printIt(5);

Local variable

Global variable

In your own words, explain the difference between passing by reference and passing by value.

 

Open Python IDLE, create a subprogram which returns a number multiplied by 3. Your program should include a global variable which contains the number 3 and some local variables.

Activity

Parallel Arrays

Learning Intentions

  • Understand what parallel arrays are
  • Understand how to write them in Python and PHP

Success Criteria

  • Be able able to implement parallel arrays in a programming language

What is a parallel array?

  • A parallel array, often referred to as a parallel array structure or parallel arrays, is a programming concept where multiple arrays of the same length are used to store related data elements.
  • Each array in a parallel array structure corresponds to a specific property of the same set of entities, and elements at corresponding indexes in different arrays are associated with each other.
  • For example, suppose you have a list of students, and you want to store their names, ages, and grades. You can use three parallel arrays:

    • An array for names: This array stores the names of the students.

    • An array for ages: This array stores the ages of the students.

    • An array for grades: This array stores the grades of the students.

Parallel arrays

forename = [""] * 3
surname = [""] * 3
mark = [0] * 3

forename[0] = "John"
forename[1] = "Peter"
forename[2] = "Hamish"

surname[0] = "Thompson"
surname[1] = "Skeldon"
surname[2] = "Barbour"

mark[0] = 14
mark[1] = 19
mark[2] = 13

Declare three empty arrays

Set all of John Thompson's details to the first position in each array

Parallel arrays

And then display everything

...
for i in range(0, 3):
  print(forename[i], surname[i], "you got", mark[i], "out of 20.")

Parallel arrays

Using Python IDLE, produce programs that meet the following requirements using parallel arrays:

 

  1. Write a program to store 4 questions and 4 correct answers (as integers). E.g. "True or False: Iron Man's armour is green". In the correct answers array it would contain False. Ask the user to answer each of the four questions.
  2. Write a program to store 4 users forenames, surnames, dates of birth and their favourite colour. Count up and display how many of them said that orange was their favourite colour.

Task

Handling files

Learning Intentions

  • Understand how to implement file reading and writing in Python and PHP

Success Criteria

  • Be able to open and write to files using Python and PHP

Reading a text file, line by line

  • The Python code for this is shown below (note we are using a subroutine to read the file):
def readFile(filename, lines):

    with open(filename, 'r') as f:

        for line in f.readlines():
          #Add each line to the lines list
          lines.append(line)

lines = []

readFile("countries.txt", lines)
print(lines)

CSV files

  • A CSV or Comma Separated Values file is much like a spreadsheet, consisting of columns and rows.
  • In reality, a CSV is just a text file.
  • Below is a very simple example of this
Francis,Burnham,36
Peter,Roosevelt,94
Adam,Smith,41

CSV files

  • To work with a CSV file we need to look at each line of the file individually, and then use the 'split' function to split the row into columns
def readFile(filename, list1,list2):
    with open(filename, 'r') as csv_file:
        for row in csv_file.readlines():

          #Remove the \n line terminator character
          row = row[0:-1]
          #Split the row string by commas
          row = row.split(",")
          #Each index is a column
          print(row[0])
          print(row[1])
          print(row[2])

The split function

  • The split function is used on each row of the CSV to convert the line (which is a string) into an array.
def readFile(filename, list1,list2):
    with open(filename, 'r') as csv_file:
        for row in csv_file.readlines():

          #Remove the \n line terminator character
          row = row[0:-1]
          #Split the row string by commas
          row = row.split(",")
          #Each index is a column
          print(row[0])
          print(row[1])
          print(row[2])

The split function

  • The split function is used on each row of the CSV to convert the line (which is a string) into an array.
nums = "1,2,3,4"
##Split the row string by commas
numbers = nums.split(",") 

The numbers variable will contain an array with the following:

[1, 2, 3, 4]

Working with parallel arrays and CSV files

  • The Python code for working with CSV files is shown below (note we are again using a subroutine to read the file):
text_file = open("write.txt", "w")

text_file.write("Hello, this is a test to see if this will write")

text_file.close()

Using the provided CSV files

 

  • census2010.csv [state name, average temperature, population]
  • titanic.csv [class, survived, full name, cabin number]
  • flavours.csv [flavour name, flavour type]

 

write a program to store each row from the file in either a parallel arrays (use the names in the square brackets above to help). 

Task

Writing to a text file with Python

  • We can use similar code to write to a text file in Python.
def writeFile(filename, text):
  with open(filename, 'w') as text_file:
    text_file.write(text)
    text_file.close()

writeFile("test.txt", "Hello there world!")

Note the use of the 'w' instead of the 'r'

Writing data to a CSV file from parallel arrays

import csv

def writeFile(filename, forenames, surnames):
  with open(filename, 'w') as text_file:
    csv_file = csv.writer(text_file)

    for i in range(0, len(forenames)):
      #This bit is turning the values into an array
      row = [forenames[i], surnames[i]]
      csv_file.writerow(row)

    text_file.close()

forenames = ["John", "James", "Gillian"]
surnames = ["Smith", "Blogs", "McGlashan"]

writeFile("test.csv", forenames, surnames)

Using the data provided in the CSV file flavours.csv, read all the data into parallel arrays. At the end of the parallel arrays, using the Python list.append function, add 'kiwi' as 'fruity'.

Task

Design Notations

Learning Intentions

  • Describe and compare different means of software design
  • Use the different design tools to design software
  • Describe data flow between sections of a program

Success Criteria

  • Be able to describe and use structure diagrams, flowcharts and pseudocode.
  • Use a data flow diagram to show the flow of data

Design notations

  • There are 3 different design notations that we needed to know at National 5. These are:
    • Structure diagrams
    • Flowcharts
    • Pseudocode

Design notations: Structure diagrams

  • A structure diagram uses a variety of standard symbols with text to represent the order of events required to solve a problem.

Design notations: Structure diagrams

total = 0

for counter in range (0, 10):
  print("Please insert a number")
  number = int(input())

  while number < 0 or number > 10:
    print("Try again")
    number = int(input())

  total = total + number

print(total)

Structure diagram Symbols

Design notations: Structure diagrams

for counter in range (1, 6):
  print(counter)

Design notations: flowcharts

  • A flowchart uses a variety of standard symbols with text to represent the order of events required to solve a problem.
  • Flowcharts aren't just used in software design

Design notations: flowcharts

  • Special symbols represent each different action or control sequence in the code.

Class task and discussion

  • Create a flow chart or structure diagram that loops, asking the user for a number each time and adding it to a total variable, until the user types in 0. Extension: try creating this in Python.
  • Create a flow chart or structure diagram for taking in 10 grades and verifying they are between 0 and 100 (inclusive) and adding them to an array.

Pseudocode

  • Pseudocode is a kind of structured English for describing algorithms and intended for human reading.
  • It is a textual design notation.
  • It can look like code but it doesn’t have the same strict syntax.
  • We should start by thinking about the main steps to solve a problem.  We should then refine the steps so we have one line of pseudocode for each line of program code.

Pseudocode example

  • Lets consider calculating the volume of water in a swimming pool.
    What would be the main steps for the problem?
     
    Main Steps
    Ask user to enter dimensions of pool in metres
    Calculate volume of pool
    Display message stating the volume of the pool

Pseudocode example

  • How would we refine these main steps?
     
    Main Steps
    1. Ask user to enter dimensions of pool
    2. Calculate volume of pool
    3. Display message stating the volume of the pool
     
    Refinement
    1.1 Ask the user to enter the length of pool
    1.2 Ask the user to enter the width of pool
    1.3 Ask the user to enter the depth of pool
     
    2.1 Volume = length x width x depth
     
    3.1 Display “The volume of the pool is”, volume

Pseudocode example

  • How would we refine these main steps?
     
    Main Steps
    1. Ask user to enter dimensions of pool
    2. Calculate volume of pool
    3. Display message stating the volume of the pool
     
    Refinement
    1.1 Ask the user to enter the length of pool
    1.2 Ask the user to enter the width of pool
    1.3 Ask the user to enter the depth of pool
     
    2.1 Volume = length x width x depth
     
    3.1 Display “The volume of the pool is”, volume

OUT: length, width, depth

IN: length, width, depth OUT: volume

Top Level Design

  • When a problem is first addressed, it is written very vaguely. 
  • For example, in a structure diagram you might find a block that says Calculate the Average, but this doesn't tell you how this is done.
  • As shown on the previous slide, we can refine our program designs to make them more granular (or atomic) and give us more detail. 

Data flow

This is a very common coursework task

  1. Draw a data flow diagram for making a cup of tea
  2. Pick out one of your own programs using and describe the data flow between each of the parts of the program

Task

Testing software

Learning Intentions

  • Understand the purpose of testing and the method used in testing

Success Criteria

  • I can explain the benefit of loops in computer programming
  • I am able to develop a fixed loop in Python
  • I am able to develop a conditional loop in Python

Test plans

  • In this unit, you must develop a test plan, outlining what you intend to test in your program, based on the design and analysis stages.
  • Before you develop code for your project, you'll need to create a test plan.
  • Test plans are used to document testing strategies and data.

Types of testing

  • There are two major kinds of testing; white box and black box.
  • Simply put, black box testing is testing when someone who has no idea how the code underneath a program works tests the program. White box, which you'll be more used to, is when someone such as the programmer tests the program, knowing how it works underneath.
  • For this course, you'll be using white box testing.

When it comes to the project unit, you’ll be asked to write a proposal document and project plan, which includes mentioning your testing strategy. You could write that you’ll be using white box testing, as you know how the code works, and that you will test individual units and the whole program (see below).

Unit testing

  • Unit testing is a fundamental software testing technique where individual components or units of a software application are tested in isolation to ensure their correctness and reliability. These units can be functions, methods, or classes, and the goal is to verify that each unit performs its intended functionality correctly.
  • Unit tests are typically written by developers and are automated, making it possible to repeatedly and consistently test small pieces of code as they are developed or modified. 
  • For our course, this basically means testing modules or subprograms of our code specifically.

Unit test plan - example

Assume that we are testing a single unit. To generate a test plan, make a list of all the inputs (parameters passed in, whether they come from user input or a file).

Assume we’re testing a function that takes two parameters - an integer between 0 and 100, and a string. The function returns true or false.

Test type age year_group Expected result
Normal 15 S5 Function returns true
Normal 82 None Function returns true
Extreme 100 None Function returns true
Exceptional -50 S1 Function returns false
Exceptional Donkey 77 Function returns false

Integration testing

  • Integration testing is another type of testing of software. 
  • With integration testing, modules or subprograms are tested together, rather than separately. 
  • The purpose of integration testing is to ensure that all modules or subprograms work together well and ensures the data flow is accurate between these subprograms.
  • Integration testing can limited to test specific modules at a time, rather than a whole program.

System testing

  • System testing is the final type of program testing. 
  • In system testing, the whole application is built and tested. 

Test plan - example

Type of test Details of testing Expected result Evidence to be gathered
Keyboard input Left arrow key pressed Turns left Screen recordings
Keyboard input Right arrow key pressed Turns right Screen recordings
Collisions Collide with wall/edge Bounces off, turns 90° Screen recordings
Collisions Collide with self Lives reduced by 1 Screenshot of before/after
Lives Collide with apple sprite Lives incremented by 1 Screenshot of before/after
Game over Game ends when no lives left Game stops, message shown on screen Screenshot of before/after

Test plan for a snake game

Recording bugs and errors

  • Software developers record both fixes to bugs but also bugs themselves. 
  • In this course, you'll be expected to record errors in any programs you test. You can add these errors as a you test your programs into your test plans.

Recording bugs and errors

  • For your testing, you can use the following template to help you build a proper test plan. 
  • You can add into the 'Details of testing' section the variables or inputs that you are using. 
Type of test Details of testing Expected result Actual result Errors found How errors were fixed Comments

Recording bugs and errors

  • Attempt the task on page 27 of the workbook named Planning and Recording Tests.

Computer Structure

Learning Intentions

  • Describe the concept of the fetch-execute cycle

  • Describe factors affecting computer performance

Success Criteria

  • I can name and describe the stages of the fetch-execute cycle
  • I can name and describe several ways of measuring and comparing performance of computer systems
  1. Name the 3 parts of the processor
  2. Name the three buses that connect the CPU and main memory

Starter task

  1. Name the 3 parts of the processor - The Control Unit, the ALU and Registers
  2. Name the three buses that connect the CPU and main memory - The address bus, data bus and control bus

Starter task

What we will cover

  • In this lesson, we will cover:

    • The fetch-execute cycle

    • Factors affecting computer system performance

Computer Architecture - National 5

The processor

  • From this diagram we should also know that the CPU is broken down into 3 main parts:

Control Unit

The control unit controls the order of execution and the timing of all instructions

Arithmetic and Logic Unit (ALU)

The ALU performs the calculations for the processor and evaluates logical decisions.

Registers

The registers are temporary storage spaces for data. They are found directly on the CPU and are often only a few bytes in size.

The Control Unit

  • The control unit is used mainly to ensure the proper execution of instructions and keep the parts of the computer in sync with each other.
  • It ensures that instructions are fetched, decoded and executed in the correct order.
  • Connected to the control unit is the control bus which is then connected to several different parts of the computer system via control lines.

The Control Unit

  • The control lines in the control unit have various functions:
Control Line Function
Clock Generates a constant pulse (measured in MHz). One operation will be carried out per pulse
Read Signals that the processor wishes to read data from the memory
Write Signals that the processor wishes to write data to the memory
Reset Causes the processor to halt execution of current instruction. All registers cleared and machine reboots
Interrupt (IRQ) Notifies the processor that an external event has occurred such as I/O from a device. This type of interrupt can be ignored. 
Non-Maskable Interrupt (NMI) This is an interrupt that CANNOT be ignored such as a low power failure notification

Clock Speeds

  • Clock speed is the number of pulses that occur in a second. Which is measured in hertz

    • 1 clock pulse = 1 hertz

    • 1000 clock pulses = 1000 hertz = 1 kilohertz

    • 1000 kilohertz = 1 megahertz

    • 1000 megahertz = 1 gigahertz

    • 1000 gigahertz = 1 terahertz

The Arithmetic and logic Unit

  • The primary role of the ALU is arithmetic calculations, including addition, subtraction, multiplication and division.

  • In relation to logic it will perform calculations such as AND/OR/NOT (such as those used in programming or in a processor instruction)

  • One particular register used by the ALU is the accumulator which holds the results of calculations. (Intel calls this the EAX)

Registers

  • Registers are very small memory locations found on the CPU itself. Because they are found on the CPU die, they are incredibly quick to access. 

  • Registers are used to store small amounts of data whilst a program is being executed. The data they tend to hold varies from program data, to instructions to memory locations.

  • Registers are very close to the processing units of the CPU (such as the ALU and control unit) to improve system performance, but they are also very small and limited to around 64 bits (8 bytes).

Registers

  • Below is a simple C program to add two numbers in x86 Assembly Code:

add(int, int):
        push    rbp
        mov     rbp, rsp
        mov     DWORD PTR [rbp-4], edi
        mov     DWORD PTR [rbp-8], esi
        mov     eax, DWORD PTR [rbp-4]
        add     eax, DWORD PTR [rbp-8]
        pop     rbp
        ret

Registers

  • Some specialist registers are shown below:

Register name Description
Instruction Register Holds the address in memory of the next instruction to be executed
Memory Address Register (MAR) This is used to hold a value representing the address in memory that the processor needs to access. This would be connected to the address bus
Memory Data Register (MDR) This is used to gold data read from or being written to memory. Connected to the data bus
Program Counter Stores the instruction number that the program is currently executing. On x86 machines this is called the instruction pointer.

Buses

  • Buses are lines (wires) that connect different parts of a computer together.

  • If you flip a motherboard over, you can see all the lines (called traces) that show all the buses.

Different buses

  • Data Bus – Used to carry data to and from the CPU and memory. It holds a binary word. The data bus is bidirectional.

  • Address Bus - Used to carry the address of the memory location that is being used. It is unidirectional.

  • Control Bus – This doesn’t carry data but has a number of status signals it can send (reset, interrupt etc.)

unidirectional = one way

bidirectional = two way

Word length

  • A binary word is the number of bits that can be transferred by the data bus in a single operation.

  • Most PCs just now have a word length of 32 or 64 bits. Meaning the data bus can carry 16 (WORD), 32 (DWORD) or 64 (QWORD) bits in a single operation.

Effects of changing bus width

  • Changing the width of the data bus means that we can move more or less data in a single operation - this would lead to increased performance due to less operations required to move

  • Changing the width of the address bus means that we can address more memory - this wouldn’t necessarily lead to an increase in performance in all cases

0

1

0

1

1

0

0

1

0

0

1

1

1

0

0

1

1

1

1

1

1

0

1

1

1

1

0

0

0

0

0

0

16 bit address bus

Effects of changing bus width

  • Changing the width of the data bus means that we can move more or less data in a single operation - this would lead to increased performance due to less operations required to move

  • Changing the width of the address bus means that we can address more memory - this wouldn’t necessarily lead to an increase in performance in all cases

0

1

0

1

1

0

0

1

0

0

1

1

1

0

0

1

1

1

1

1

1

0

1

1

1

1

0

0

0

0

0

0

32 bit address bus

Past Paper Question

Explain why increasing the width of the data bus will improve the system performance.

 

2 marks

SQP Q11 b)

The wider the data bus, the more bits that can be transferred (1 mark) in a single operation (1 mark)

The fetch-execute cycle

  • Fetch-execute cycle is how the CPU reads and writes instructions from the main memory.

The memory address of the next instruction is placed on the Memory Address Register

The processor activates the read line on the control bus

The instruction is fetched from the memory location using the data bus and stored in the Instruction Register

The instruction in the Instruction Register is then interpreted by the decoder and executed

Stage

1

2

3

4

From what we just looked at, write down the four stages of the fetch-execute cycle and describe them.

Task

Factors affecting performance

  • Computer performance can often be affected or improved by a number of different factors, including:
    • The number of processors/cores
    • Width of the data bus
    • Cache memory
    • Clock speed

The number of processors/cores

  • A multi-core processor is a processor with two or more separate processing units (cores).

  • Each core contains an ALU, Control Unit and Registers.

  • The greater the number of cores on a processor, the greater the number of instructions that can be carried out simultaneously.

  • However, it’s not always possible to share tasks between cores.

An AMD EPYC chip is shown to the right. It consists of multiple smaller chiplets which themselves have multiple cores. EPYC processors can have up to 128 cores as of 2023.

The number of processors/cores

  • It's also possible to get motherboards that can take multiple processors themselves. 

  • The board pictured here is a dual AMD EPYC board that can take two 128 core EPYC CPUs and up to 1.2TB of main memory.

  • Parallelism is a big research area in computer science today.

Increasing the width of the data bus

  • We already know that the data bus is used to carry data to and from the processor.

  • Each cycle of the fetch-execute cycle requires data to be moved along the data bus.

  • Increasing the width of the data bus, increases the amount of data that can be transported in a single cycle.

Cache memory

  • Cache memory is a small amount of fast accessible memory usually on the same chip as the processor.

  • The processor will check cache for data before accessing the main memory.

  • If it finds data or an instruction, this is known as a cache ‘hit’, resulting in improved performance. If the instruction is not present, then a cache ‘miss’ occurs and a slower main memory is accessed. 

  • Many computers use multiple levels of cache, with small caches backed up by larger, slower caches. 

Cache memory

  • There are different levels of cache memory:

Level Description
L1 In the processor core, generally around about 64KB
L2 Generally attached to the core, around about 256KB per core 
L3 Generally shared between all cores, between 4MB and 32MB
  • The processor always checks the fastest cache first. If the hit is not found it goes to the next fastest level and so on.

  • Cache memory is used to store frequently used data and instructions.

Clock speed

  • Clock speed is the measure of how many instruction cycles the system can work through within one second.

  • Clock pulses are used to trigger components to take their next step.

  • The higher the clock speed, the faster the computer can complete a set of instructions.

Clock speed - overclocking

  • It is possible with some CPUs (for example Intel K series CPUs and all AMD Ryzen CPUs) to push them passed their set clock speed. 

  • This is called overclocking.

  • The stability of a system can suffer as the clock speed gets higher, and since power consumption is directly proportional to the frequency the power draw can increase. Often overclockers tend to overvolt the system as well as overclock it to improve stability.

Past Paper Questions

Increasing clock speed is one method of improving processor performance.

 

a) State one other method of improving processor performance.

1 mark

b) Explain how your answer to part (a) improves performance

1 mark

2021 Q2 (a) & (b)

  1. Increasing the number of cores: multiple instructions can be processed simultaneously   
  2. Increasing the width of the data bus: more bits can be transferred in a single operation
  3. Increasing cache memory size: reduces the number of memory operations to slower memory
Presentation Overview
Close
JB
Software Design & Development
© J Balfour
13:13 | 07-12-2023
Join Live Session
Start Remote
Save Progress
Slideshow Outline
Presenter Mode
Widget Screen
Canvas Controls
Dark Mode
Bold Text
Random Selector
Timer
Binary Converter
Python Editor
Show Knox 90
Provide Feedback
Help
!
Keywords
    Random selector
    Sections
      Binary conversion
      Denary to binary conversion
      Binary to denary conversion
      Feedback 👍
      Accessibility

      Apply a filter:

      ×
      All slideshow files