75% developed

A-level Computing/AQA/Print version/Unit 1

From Wikibooks, open books for an open world
Jump to navigation Jump to search

A-level Computing is an A-level course run for students in the UK

Note: current version of this book can be found at http://en.wikibooks.org/wiki/A-level_Computing/AQA

Authors

  • (AQA) Peter EJ Kemp (editor) - London
  • (CIE) Peter Astbury - Alexandria, Egypt

Contributors and proof readers

  • Students from Christ the King Sixth Form College
  • Students from Loxford School
  • Students from Wreake Valley Academy
  • Peter L Higginson - Reading

Thanks for helping out!

Book Overview

This is a book about A-Level Computer Science. It aims to fit with the AQA GCE A-Level Computer Science 2015 syllabus but is not endorsed by AQA. It should be useful as a revision guide or to find alternative explanations to the ones in your textbook. If you haven't heard of an A-Level then this book probably won't be of much interest to you but you can find out about them at Wikipedia.

If any part of this book is unclear or even wrong then please post a comment on the discussion page or simply fix it yourself! In particular, please say if the book assumes any knowledge or skills which not all A-Level Computer Science students have.


A-level

Paper 1 Index

Paper 2 Index

Non-exam assessment

Programming

Accepted languages

A-Level Projects can be written in any language.

Old Specification (up to 2017)

AS modules

A2 modules


How to read the book

You will meet several coloured boxes, here are their meanings:

Specification link

What the specification says you must learn for each chapter


Examples

Example questions and how to solve them


Questions

Questions to test yourself, click below

Answer:

to check if you were right

Extension

Topics that aren't examined but you might be interested in


There will be a lot of concepts that you need to be familiar with, definitions are highlighted like so:

Word - meaning


Unit 1 - Summary

This exam is worth 60% of your AS grade (30% of the full A-Level). It is examined in June only.

Definitions

Unit 1 definition list

The examination

Problem solving

A-level Computing/AQA/Problem Solving, Programming, Data Representation and Practical Exercise/Problem/Solving

Introduction to principles of computation

Computing is a very different course from ICT and if you have studied ICT at secondary school you should see a big difference between the two. This course will introduce you to the theory, mathematics and logic that sit behind the computing revolution. Over the course of this book I also hope to take you through the steps needed to practice computational thinking, the art of using computers to solve problems. This doesn't mean getting you to think like a computer, but it does mean getting you to think in ways that you can use computers to solve problems. Computational thinking is made up of four parts:[1]

  • Decomposition
  • Pattern recognition
  • Pattern generalisation and abstraction
  • Algorithm design

Let's take a look at what each of these mean:

Decomposition

Part of being a computer scientist is breaking down a big problem into the smaller problems that make it up. If you can break down a big problem into smaller problems then you can give them to a computer to solve. For example if I gave you a cake and asked you to bake me another one you might struggle, but if you watched me making the cake and worked out the ingredients then you'd stand a much better chance of replicating it. If you can look at a problem and work out the main steps of that problem then you'll stand a much better chance of solving it.

Let's look at an example, the equation to work out the roots of a quadratic equation.

On first look it might appear a little scary, but if we decompose it we should stand a better chance of solving it:

  1. repeat for

By noting the steps down to solve a problem we can often recognise patterns, and by giving a list of steps we are one step closer to creating an algorithm.

Pattern recognition

Often breaking down a problem into its components is a little harder than taking apart an algorithm, we often get given a set of raw data then are asked to find the pattern behind it:

This is pretty easy with number sets, the above has the pattern. But pattern recognition might also involve recognising shapes, sounds or images. If your camera highlights faces when you point it at some friends, then it is recognising the pattern of a face in a picture.

The face was automatically detected by pattern recognition

If your phone tells you the weather when you ask it "What is the weather like in Witham", then it has recognised the word "weather" and that "Witham" is a small town in Essex, linking them together. Pattern recognition is the computing behind why you get given tailored adverts when you log into your mail account or social network, they have recognised the pattern of what someone like you wants to buy. Pattern recognition might predict the weather, but chaos theory means that it's not always perfect.

Pattern generalisation and abstraction

Once we have recognised a pattern we need to put it in its simplest terms so that it can be used whenever we need to use it. For example, if you were studying the patterns of how people speak, we might notice that all proper English sentences have a subject and predicate.

Algorithm design

Once we have our patterns and abstractions we can start to write the steps that a computer can use to solve the problem. We do this by creating Algorithms. Algorithms aren't computer code, but are independent instructions that could be turned into computer code. We often write these independent instructions as pseudo code. Examples of algorithms could be to describe orbit of the moon, the steps involved in setting up a new online shopping account or the sequences of tasks involved for a robot to build a new car.

declare robot
robot.on;
robot.get(body);
robot.get(roof);
do
  robot.weld(roof, body);
until (robot.weld == success)
robot.off;
Exercise: Computational thinking
What are the four main parts of computational thinking?

Answer:

  • Decomposition
  • Pattern recognition
  • Pattern generalisation and abstraction
  • Algorithm design
Can you spot a pattern in this set of numbers?

Answer:

In mathematical terms, the sequence Fn of Fibonacci numbers is defined by:

with seed values

Can you come up with an algorithm to make a cup of tea?

Answer:

(your answer might differ considerably from this, to see if it works give it to a friend to see if they can follow it)

  1. put water into kettle
  2. turn kettle on
  3. get out cup and saucer
  4. put tea bag into cup
  5. when water boiled add to cup
  6. stir with spoon
  7. remove tea bag
  8. if milk needed
    1. add milk

Limits?

Nowadays computers are ubiquitous and some would argue that there are no problems out there that a computer, given enough time, couldn't solve. But is this true? Is every problem solvable by a machine and can we ever know if this is the case?

Exercise: Introduction to principles of computation
Do you think that every process in nature can be simulated by a computer?

Answer:

The jury is still out of this one. There are people who say yes and others no, with people such as some existentialists arguing that you cannot get a computer to simulate consciousness. This line of thought soon turns into philosophy.
Extension: The halting problem

Very early on in modern computing, a British academic named Alan Turing devised the halting problem. This problem is to do with whether we can determine if a program will ever come to a halt or run for ever, for example:

console.writeline("hello")

Would write hello to the screen then stop. However, take a look at:

dim x as integer = 9
while x > 8
  console.writeline("hello")
end while

This would never finish, it would never come to a halt as x will always be larger than 8 and never get any smaller. This means the while loop will continue for ever, constantly printing out "hello". In the two cases shown it is easy to tell if a program will halt or not, but it isn't so easy. Imagine we get a more complex piece of code:

dim x as integer = 9
dim total as integer = 0
while total < 100
  total = total + x
  x = x / 2
end while

This is harder but still solvable taking a little more thinking and a little time on the processor. We could get a piece of code that takes weeks, years or even thousands of years to finish. But how can we know that all programs will end or not? To determine whether the program halts we:

  • run a program with a given input, if it stops we know it stops
  • BUT if it keeps running beyond a reasonable amount of time we cannot conclude that it will loop for ever (maybe we need to wait a little longer...)

Surely we create a mathematical proof to determine whether code will end or not I hear you say. Well let's prove just the opposite:

The halting solution H takes an input program A and a set of inputs X, it then determines whether the program will finish executing or not
You can replace the Input X with a copy of the program A. As the program A is made from code, this can be transformed into 1s and 0s, giving H a data input

Let us create a program K that will loop forever if the result of H is to halt, and halt if the result of H is to loop for ever:

function K(i):
    if H(i,i) = halt then
        loop forever
    else
        halt
If H says halt, K will loop. If H says loop K will halt, thus the Halting Solution H will be undecidable

We can therefore see that there are examples of programs such as K that we cannot determine whether they are ever going to halt.

References

Stages of problem solving

Solving problems is never easy, so you need to break them down into manageable chunks:

Understand the problem

Before we should start solving a problem, we need to understand exactly what the problem is that we are dealing with. Only then can we start to think of solutions. By doing this we can avoid spending a lot of time on unsuitable solutions that we'd then have to throw away.

Knowing the level of thinking required to solving the problem and having an idea of a solution which is relevant to the problem.

Define the problem

To fully understand a problem we need to think about the following:

  • Given(s): the initial situation
  • Goal: desired target situation
  • Ownership: who does what
  • Resources and constraints: tools, knowledge, skills, materials and rules, regulations, guidelines, boundaries, timing

For example:

Example: Defining the problem (Football game)

After observing and researching the business I have found out the following:

  • Given(s)
Electronic Crafts is a small programming house looking to create a football game for the mass market. They have experience making games for the Super MES and are looking for the next hit.
  • Goal
To create a football game for the Super MES.
  • Ownership
Barry is a graphics designer, Mike is the lead programmer, Coral is an AI programmer, Jaya is the boss.
  • Resources and constraints
The Electronic Crafts offices have 4 development machines running Linux and C++, The platform that is being developed for is the Super MES using Visual Basic. Barry, Coral and Jaya have all programmed the Super MES before, but Mike hasn't. Mike is skilled in C++. The game must be complete within 9 months. Electronic Crafts have a game engine already running on the Super MES that you could use. Electronic Crafts specialise in cartoon like games for children and this football game should be branded as such. There should be no violence or swearing.

Define boundaries

Understanding the limits to coming up with a solution and knowing what can and cannot be done through lateral thinking. These boundaries may also be known as a type of constraint.

It is important to define what your system is not going to do - as important as considering what it should do. Most software projects fail because of specification creep - where the code in development moves away from the requirements because someone (often the developers themselves) feels that it would be good if the application also did <this> and <why not put it in while you can> thinking. You will end up with code that you do not know how to test or fix when it goes wrong - which is a sign of poor development that markers will not be able to ignore!

Plan solution

Once you have defined the problem, given, goal, ownership and resources you need to start thinking about how you will implement a solution. This might involve using tools such as flow charts, pseudo code, top down design, finite state machines etc. These will allow you to get started with actually making the solution. We will meet all of these methods shortly.

Check solution

Once you have created a solution you need to check it against the original problem. If it solves the problem then you have a successful solution. If it doesn't then you have failed and will have to go back to the drawing board to try another solution that works.

Note that you can (and should) test your design on paper against the specification (and your test plans) before you code it. This "walk through" approach is often done in team working - which encourages the consideration of abnormal data input, or using work flows that had not been thought of.

Top-down design and Step-wise refinement

A top-down approach (also known as stepwise design) is essentially the breaking down of a system to gain insight into the sub-systems that make it up. In a top-down approach an overview of the system is formulated, specifying but not detailing any first-level subsystems. Each subsystem is then refined in yet greater detail, sometimes in many additional subsystem levels, until the entire specification is reduced to base elements. Once these base elements are recognised then we can build these as computer modules. Once they are built we can put them together, making the entire system from these individual components.

Top-down design - in which design begins by specifying complex pieces and then dividing them into successively smaller pieces


Example: Making Pancakes

To show you an example of Top-Down design we'll take the act of making pancakes. Starting from the top we have the task to:

  • Make some pancakes

But saying that by itself isn't enough to actually make any pancakes, we need to break the task down:

  • Make some pancakes
  1. Organise Kitchen
  2. Make Pancakes
  3. Serve

Each of these tasks can then be broken down further:

  1. Organise Kitchen
    1. Clean surfaces
    2. Get out mixing bowl, whisk, spoon, sieve
    3. Get out plain flour, salt, eggs, full fat milk, butter
    4. Put on apron
  2. Make Pancakes
    1. Sift salt and flour into bowl
    2. Break eggs into bowl
    3. Whisk
    4. Add water and milk
    5. Add butter
    6. Whisk
    7. Cook
  3. Serve

And each of these tasks can be broken down further, let us take a look at the Cook:

  • Cook
  1. Get pan to temperature
  2. Pour batter in
  3. Spread batter to edges
  4. Use plastic spatula to check bottom of pancake
  5. When brown, flip
  6. Use plastic spatula to check bottom of pancake
  7. When brown finish

We can break down some of these tasks even further. So starting at a single point, the creation of a pancake, we have broken down the task into it individual parts

Exercise: Top-down design
Draw a top-down design tree to three level depth for making a modern First Person Shooter

Answer:

Your answer probably won't be the same as this as the question is open to interpretation, but hopefully it'll be similar:

  • Make First Person Shooter
  1. Create graphics
    1. Characters
    2. Guns
    3. Maps
    4. Interface
  2. Create sounds
    1. Music
    2. SFX
  3. Create AI
    1. Non-playable characters
    2. Monsters

Stages of problem solving

Solving problems is never easy, so you need to break them down into manageable chunks:

Understand the problem

Before we should start solving a problem, we need to understand exactly what the problem is that we are dealing with. Only then can we start to think of solutions. By doing this we can avoid spending a lot of time on unsuitable solutions that we'd then have to throw away.

Knowing the level of thinking required to solving the problem and having an idea of a solution which is relevant to the problem.

Define the problem

To fully understand a problem we need to think about the following:

  • Given(s): the initial situation
  • Goal: desired target situation
  • Ownership: who does what
  • Resources and constraints: tools, knowledge, skills, materials and rules, regulations, guidelines, boundaries, timing

For example:

Example: Defining the problem (Football game)

After observing and researching the business I have found out the following:

  • Given(s)
Electronic Crafts is a small programming house looking to create a football game for the mass market. They have experience making games for the Super MES and are looking for the next hit.
  • Goal
To create a football game for the Super MES.
  • Ownership
Barry is a graphics designer, Mike is the lead programmer, Coral is an AI programmer, Jaya is the boss.
  • Resources and constraints
The Electronic Crafts offices have 4 development machines running Linux and C++, The platform that is being developed for is the Super MES using Visual Basic. Barry, Coral and Jaya have all programmed the Super MES before, but Mike hasn't. Mike is skilled in C++. The game must be complete within 9 months. Electronic Crafts have a game engine already running on the Super MES that you could use. Electronic Crafts specialise in cartoon like games for children and this football game should be branded as such. There should be no violence or swearing.

Define boundaries

Understanding the limits to coming up with a solution and knowing what can and cannot be done through lateral thinking. These boundaries may also be known as a type of constraint.

It is important to define what your system is not going to do - as important as considering what it should do. Most software projects fail because of specification creep - where the code in development moves away from the requirements because someone (often the developers themselves) feels that it would be good if the application also did <this> and <why not put it in while you can> thinking. You will end up with code that you do not know how to test or fix when it goes wrong - which is a sign of poor development that markers will not be able to ignore!

Plan solution

Once you have defined the problem, given, goal, ownership and resources you need to start thinking about how you will implement a solution. This might involve using tools such as flow charts, pseudo code, top down design, finite state machines etc. These will allow you to get started with actually making the solution. We will meet all of these methods shortly.

Check solution

Once you have created a solution you need to check it against the original problem. If it solves the problem then you have a successful solution. If it doesn't then you have failed and will have to go back to the drawing board to try another solution that works.

Note that you can (and should) test your design on paper against the specification (and your test plans) before you code it. This "walk through" approach is often done in team working - which encourages the consideration of abnormal data input, or using work flows that had not been thought of.

Structure charts

Structure charts can map the structure and data flow of complicated tasks

A Structure Chart in software engineering is a chart which shows the breakdown of a system to its lowest manageable parts. They are used in structured programming to arrange program modules into a tree. Each module is represented by a box, which contains the module's name. The tree structure visualizes the relationships between modules, showing data transfer between modules using arrows. Structured Charts are an example of a top-down design where a problem (the program) is broken into its components. The tree shows the relationship between modules, showing data transfer between the models.

Symbol Name Meaning
Module
Name
Process Each Box represents a programming module, this might be something that calculates the average of some figures, or prints out some pay slips
Data Couple Data being passed from module to module that needs to be processed.
Flag [Extension - you don't need to know this for the exam] Check data sent to process to stop or start processes. For example when the End of a File that is being read is reached, or a flag to say whether data sent was in the correct format

Let's take a look at a simple example of how this might be executed when representing the following code:

dim num1, num2 as integer

sub calculateAverage()
  dim avg as integer
  inputNums()
  avg = average(num1, num2)
  outputAvg(avg)
end sub

function average(a,b)
  return (a + b) / 2
end function

sub inputNums()
  num1 = console.readline()
  num2 = console.readline()
end sub

sub outputAvg(x)
  console.writeline("average = " & x)
end sub
A structure chart for the above code
Exercise: Structure Charts

Create structure charts for the following code:

sub main()
  dim num1 as integer
  dim num2 as integer
  dim avg as integer
  sayHello()
  num1 = 34
  num2 = 89
  avg = average(num1, num2)
end sub

function average(a,b)
  return (a + b) / 2
end function

sub sayHello()
  console.writeline("hello")
end sub

Answer:

Selection

Structure Chart representation of the selection code

A selection in a Structure Chart is determined by the diamond symbol. This means a condition will be checked and depending on the result, different modules will be executed.

sub main()
  dim num1 as integer
  num1 = console.readline()
  if num1 = 7 then
     luckyNumber()
  else
     otherNumber()
  endif
end sub

Iteration

Structure Chart of the code to the left

Using the semi circular arrow we can represent iteration in Structure Charts. The arrow encompasses a link to a module, implying that module is executed multiple times. Let's take a look at a coded example:

sub main()
  dim num1 as integer
  num1 = console.readline()
  while num1 > 0 do
     num1 = countdown(num1)
  end while
end sub

Function countdown(a)
  return a - 1
End Function
Exercise: Structure Charts, Iteration and Selection

Create structure charts for the following code:

sub howManyThrees()
  dim num1, count, total as integer
  num1 = startMsg()
  count = 0
  total = 0
  while num1 > 0 do
     checkNumber(count, total, num1)
     num1 = num1 - 1
  end while
  endMsg(count)
end sub

sub checkNumber(byRef c, byRef t, byVal n)
  If n MOD 3 = 0 Then
     c = divBy3(c)
  Else
     t = add(n, t)
  EndIf
end sub

function divBy3(x)
  return x + 1
end function

function add(n, t)
  return n + t
end function

function startMsg()
  console.writeline("program started, enter your number")
  return console.readline()
end function

sub endMsg(n)
  console.writeline("number of threes : " & n)
end sub

Answer:

Decision tables

Decision tables are compact and precise ways of modelling complicated logic, such as that which you might use in a computer program. They do this by mapping the different states of a program to an action that a program should perform. Decision tables take on the following format:

The four quadrants
Conditions Condition alternatives
Actions Action entries

The limited-entry decision table is the simplest to describe. The condition alternatives are simple Boolean values, and the action entries are check-marks, representing which of the actions in a given column are to be performed.

A technical support company writes a decision table to diagnose printer problems based upon symptoms described to them over the phone from their clients. They type the following data into the advice program:

  1. Printer does print
  2. Red light is flashing
  3. Printer is recognised

The program then uses the decision table to find the correct actions to perform, namely that of Check / Replace ink.

Printer troubleshooter
Rules
Conditions Printer does not print Y Y Y Y N N N N
A red light is flashing Y Y N N Y Y N N
Printer is unrecognised Y N Y N Y N Y N
Actions Check the power cable     X          
Check the printer-computer cable X   X          
Ensure printer software is installed X   X   X   X  
Check/replace ink X X     X X    
Check for paper jam   X   X        
Example: Decision Tables

Let's take a look at a computer game example, for a football simulation the following rules are set up.

Rules
Conditions 90 minutes Y Y Y
Team A Winning Y
Team B Winning Y Y
Draw Y
Actions Game Over X X
Team A Wins X
Team B Wins X
Extra Time X
Keep Playing X X

What happens when:

  1. 90 minutes up
  2. the game is a draw

Answer: Keep Playing and give them some extra time

Exercise: Decision Tables
Create a decision table for the following program in an office email system
  • Send email when Recipient address present, subject present, before 5:30pm
  • If after 5:30pm then put in pending folder
  • If Recipient address missing or subject message, give warning message

Answer:

This question is open to interpretation, but you should have something resembling this:

Rules
Conditions Address Present Y Y Y
Subject Present Y Y Y
Before 5:30 Y Y Y
Actions Send Mail X
Error Message X X
Make pending X

Describe the use of Decision Tables

Answer:

Determine logical conditions and consequential actions.


Finite state machines

Finite state machines

A finite state machine is a form of abstraction (WHY/HOW?). It models the behaviour of a system by showing each state it can be in and the transitions between each state.

Consider an elevator :

Possible states of the system:

'static on floor 1', 'moving up', 'static on floor 2', 'moving down'


[picture of states inserted here]


The transitions and their inputs:

  • from 'static on floor 1' to 'moving up' triggered by 'up button'
  • from 'moving up' to 'static on floor 2' triggered by 'arrival 2'
  • from static on floor 2 to 'moving down' triggered by 'down button'
  • from 'moving down' to 'static on floor 1' triggered by 'arrival 1'

Form the above we can draw the finite state machine for the elevator.

[picture of completed finite state machine to be inserted here]

We can also produce a state transition table (DEFINE THIS LANGUAGE BOX?):

[picture of state transition diagram to be inserted here]


Representing a system as a finite state machine is very powerful because the model allows us to demonstrate the behaviour very clearly. We can prove that the system is robust and will not behave in any unexpected manner. Consider the example of the elevator: by modelling the system as a finite state machine, it is possible to show that the elevator is not able to move up and down without stopping. This is because the design clearly shows that it is impossible to transition from the state 'moving up' to the state 'moving down'.

Applications of finite state machines are found in many sciences. Mainly engineering, biology and most commonly in linguistics, where they are used to describe languages.


A finite state automata accepting binary input

Looking at the above diagram we can see that it starts in state S1, an input of 1 will keep it in state S1, and an input of 0 will move it to state S2. Once in S2 an input of 1 will keep it there, and an input of 0 will switch it back to S1. This means that the following inputs are valid:

110011001
001110011

It might appear to accept any binary value, but this isn't true. The only state it can accept in is state S1. This places the following rule on all accepted inputs: "A combination of binary digits involving an even number of zeros". This is useful for parity checks. If I try the following:

110011011

I am stuck in state S2 and the FSM has not accepted. Can you create a FSM to only accept Binary numbers with odd numbers of 1s?

Exercise: Finite State Automaton

For the FSM above which of these inputs are valid:

  1. aaacdb
  2. ababacdaaac
  3. abcdb
  4. acda
  5. acdbdb

Answer:

  1. aaacdb (CORRECT)
  2. ababacdaaac(CORRECT)
  3. abcdb (ERROR no input that accepts b then c)
  4. acda (ERROR S1 is not a accepting state)
  5. acdbdb (CORRECT)

For the FSM above which of these inputs are valid:

  1. 987654321+994-0
  2. 5-5+2*4
  3. 9+8+7+6+5+4+3+2+1
  4. 0+1+2+1+
  5. 99+88-77

Answer:

  1. 987654321+994-0 (CORRECT)
  2. 5-5+2*4 (ERROR no input *)
  3. 9+8+7+6+5+4+3+2+1 (CORRECT)
  4. 0+1+2+1+ (ERROR S3 is not a accepting state)
  5. 99+88-77 (CORRECT)

Draw a finite state automata that will accept the word Banana whilst using only 3 states

Answer:

Draw a single finite state automata that will accept all the words:

  • Tim
  • Grit
  • Grrrrrim

Answer:

Mealy Machines

Mealy Machine - an FSM with outputs

Some FSMs output values dependent on the state and the input values:

The above Mealy Machine outputs a value for each input. You can tell which is which by: input / ouput. So for the following input:

000101010

It outputs

000010101

Shifting all the bits right, and dividing the binary number input by two.

Exercise: Mealy Machines

For the Mealy machine above, what do the following inputs output:

  1. 50
  2. 20,10,20
  3. 10,10,10,20

What does this machine do, what do the outputs tell you?

Answer:

  1. 0
  2. 30,20,0
  3. 40,30,20,0

This machine could be used to track the money going into a vending machine, letting you know how much you have left to pay on a 50p chocolate bar

What is the difference between a mealy machine and a finite state automaton?

Answer:

  • mealy machines output values
  • finite state automata do not
Extension: non-determinism

In this section we are learning about deterministic finite automaton. This means that for a state and a valid input there is only one possible transition to take. There are such things a nondeterministic finite automaton where, for a given input there are multiple paths (or none) that could be taken:

In state p, for input 1 there are two possible transitions

State transition tables

A state transition table follows every state and input. Inputs are usually placed on the left, and separated from the outputs, which are on the right. Here's a simple example of a state machine with two states, and a binary input:

Input Current State Next State Output
0 S1 S2 null
1 S1 S1 null
0 S2 S1 null
1 S2 S3 null
Exercise: State transition tables

Create a state transition table for the following FSM:

Answer:

Input Current State Next State Output
0 S1 S2 null
1 S1 S1 null
0 S2 S1 null
1 S2 S2 null

Create a state transition table for the following FSM:

Answer:

Input Current State Next State Output
0 S0 S2 0
1 S0 S1 0
0 S1 S2 1
1 S1 S1 1
0 S2 S2 0
1 S2 S1 0


Draw the FSM for the following state transition table:

Input Current State Next State Output
Timer Green Green null
Button Green Yellow null
Timer Yellow Red null
Timer Red Green null

Answer:

You might have already cottoned on. This represents a traffic light system


Draw the FSM for the following state transition table:

Input Current State Next State Output
a q0 q0 null
b q0 q1 null
a q1 q2 null
b q1 q1 null
a q2 q1 null
b q2 q1 null

Answer:

Algorithm design

Algorithm - a set of instructions independent of any programming language that calculates a function or solves a problem.


Express the solution to a simple problem as an algorithm using flowcharts, pseudo-code or structured English and the standard constructs:

Sequence

performing or operating each step consecutively in the order they arise

Console.writeline("This is line 1")
Console.writeline("This is line 2")
Console.writeline("This is line 3")
  1. include<stdio.h>

int main() {

   // Read n
   int n;
   printf("Enter number n : ");
   scanf("%d", &n);

   // Declare sum to 0 
   // counter variable i to 1
   int sum = 0;
   int i = 1;

   // loop to input n numbers
   // loop continues until i<=n
   for(i=1;i<=n;i++){
       // read num
       int num ;
       printf("Enter number %d: ", i);
       scanf("%d", &num);

       // update sum to sum + num
       sum = sum + num;
   }

   // print sum
   printf("Sum of given numbers is %d", sum);
   return 0;

}

Selection

Selection is choosing a step

If x > 0 then
   Console.writeline("x is positive")
End If
If x = 0 then
   Console.writeline("x equals 0")
End If
If x < 0 then
   Console.writeline("x is negative")
End If

Repetition

A sequence of steps that loop until a requirement is met

x = 0
y = 5
Do
   x = x + 1
Loop Until x = y


Trace tables

Trace table - a technique used to test algorithms to make sure that no logical errors occur


Hand tracing or 'dry running' allows you to use a trace table to

  • see what code will do before you have to run it
  • find where errors in your code are

Taking a program like the one below we need to keep track (trace) all the variables and outputs.

#include<stdio.h>
 
int main() {
 
    // Read n
    int n;
    printf("Enter number n : ");
    scanf("%d", &n);
 
    // Declare sum to 0 
    // counter variable i to 1
    int sum = 0;
    int i = 1;
 
    // loop to input n numbers
    // loop continues until i<=n
    for(i=1;i<=n;i++){
        // read num
        int num ;
        printf("Enter number %d: ", i);
        scanf("%d", &num);
 
        // update sum to sum + num
        sum = sum + num;
    }
 
    // print sum
    printf("Sum of given numbers is %d", sum);
    return 0;
}

To do this we create a trace table:

y x output
3 1
4 2
6 3
9 4
13 13

The exam will normally ask you to create a trace table of some sort so you need to be very confident with them. The exam will usually give you the headings but just in case, there are several steps in making a trace table, the first one is to note the table headings, this involves the following:

  1. VARIABLES: note all the variables in the piece of code you are looking at (this includes arrays). Note each variable as a heading
  2. OUTPUTS: note if there is an output and put this as a heading
  3. INPUTS: if there are inputs specified, put an inputs column and be prepared to fill it in.

It is very easy to jump right in when filling in trace tables, but you must be careful. The exam will try and trick you, so trying to predict what a trace table will do is not a good idea. In fact, the best idea is to switch your brain off and tackle the problem line by line, exactly as a computer would. Take a look at the following example:

Example: Simple trace table
Dim num() as integer = {10,8,3,5,6,1,2}
Dim sum as integer = 0
Dim avg as decimal
For x = 0 to 5
	sum = sum + num(x)
Loop
avg = sum / (x + 1)
Console.writeline("average =" & avg)
  1. note all the variables: num array / sum / avg / x
  2. note if there is an output: yes
  3. if there are inputs specified: no

So we should construct the following table:

num
0 1 2 3 4 5 6 sum avg x output
10 8 3 5 6 1 2 0
  0

Now looking at the names of the variables you might be tempted to add all the values in the array together to find the sum, and then find the average number from this calculation . However, you'd be wrong, create a trace table and see if you can find the correct answer:

Answer:

num
0 1 2 3 4 5 6 sum avg x output
10 8 3 5 6 1 2 0
10 0
18 1
21 2
26 3
32 4
33 5.5 5 average =5.5

So what went wrong? If you look at the trace table you can see that we never added the number 2 from the num array to the sum, it stopped at element 5. To fix this we would adjust the following line:

For x = 0 to 6
Exercise: Trace tables

Complete the trace table for the following code, where the number input is 39

Dim input As Integer = 78
Dim r As Integer
Console.Write("Input a number:")
input = Console.ReadLine()

Dim op As String = ""

While (input > 0)
	r = input Mod 2
	input = input \ 2
	op = r & op
End While

Console.Write(op)
Console.ReadLine()

Answer:

input r op output
78
39 1 1
19 1 11
9 1 111
4 0 0111
2 0 00111
1 1 100111
0 100111

As always with programming there is a shorter way of performing this task, take a look at:

Dim num As Integer = 239938

Dim ss As String = Convert.ToString(num, 2)
Console.WriteLine(ss)

Do you think you can work out how to output an hex, base 16 number? I bet you can.


What does the above code do?

Answer:

It converts a base10 (denary/decimal) number into its binary equivalent


Complete the trace table for the following code:

Dim nums() = {6,2,8,1,9,2}
Dim n as integer = 0

for i = 0 to 5
  if nums(i) > n
    n = nums(i)
  end if
loop

Answer:

i n nums
0 1 2 3 4 5
0 6 2 8 1 9 2
0 6
1
2 8
3
4 9
5


What function does the above code perform?

Answer:

It finds the highest value in an array of values


Pseudo code

Pseudocode - informal high-level description of a computer program or other algorithm, intended for human reading rather than machine reading.

Pseudocode uses a combination of programming terminology and plain English to describe algorithms in a form that is easier for people to understand than conventional programming language code. There are no standards for pseudocode and a program in pseudocode is not an executable program. Psuedocode is used in textbooks and scientific publications to describe various algorithms, and also in planning of computer program development, for sketching out the structure of the program before the actual coding takes place. It typically leaves out details that are not essential for human understanding of the algorithm, such as variable declarations, system-specific code and some subroutines.

Example: Pseudocode

Below is an example of a pseudocode algorithm

For i  1 to 100
    output_number  true
    if i mod 3 equals 0
        output "Bizz"
        print_number  false
    if i mod 5 equals 0
        output "Buzz"
        print_number  false
    if print_number equals true
        output i
    output newline

Converting this into VB.NET, we get:

dim print_number as boolean
For i = 1 to 100
    print_number = true
    if i mod 3 = 0 then
       console.writeline("Bizz")
       print_number = false
    end if
    if i mod 5 = 0 then
       console.writeline("Buzz")
       print_number = false
    end if
    if print_number then
       console.writeline(i)
    end if
    console.writeline()

Structured English

Structured English - A restricted part of the English language used to describe algorithms

Structured English is very similar to Pseudo code, but it tends not to use so many mathematical symbols. Often people start with Structured English, convert it to Pseudo Code and then write Executable Code. Examples of common keywords: START, BEGIN, END, STOP, DO, WHILE, DO WHILE, FOR, UNTIL, DO UNTIL, REPEAT, END WHILE, END UNTIL, END REPEAT, IF THEN, IF, ELSE, IF ELSE, END IF, THEN, ELSE THEN, ELSE IF, SO, CASE, EQUAL, LT, LE, GT, GE, NOT, TRUE, FALSE, AND, OR, XOR, GET, WRITE, PUT, UPDATE, CLOSE, OPEN, CREATE, DELETE, EXIT, FILE, READ, EOF, EOT, WITH, RETURN

Structured English Pseudo Code Executable Code
BEGIN 
READ name
IF name EQUAL "Harry" THEN
WRITE "Why don't you marry Pippa?"
ELSE
WRITE "Are you Royal enough?"
END IF
END
BEGIN 
INPUT name
IF name == "Harry" THEN
OUTPUT "Why don't you marry Pippa?"
ELSE
OUTPUT "Are you Royal enough?"
END IF
END
dim name as string
name = console.readline()
if name = "Harry" then
  console.writeline("Why don't you marry Pippa?")
else
  console.writeline("Are you Royal enough?")
End if
Exercise: Pseudocode

What are the rules when writing pseudocode?

Answer:

There are no set rules, but the code should provide clear descriptions of the algorithms being outlined.

What is the difference between pseudocode and a programming language such as javascript?

Answer:

Pseudocode cannot create executable code, whilst javascript can.

For the following pseudocode write a VB.NET equivalent:

for x from 1 to 7 inclusive
  add x to total
loop
print total

Answer:

dim total as integer = 0
for x = 1 to 7
  total = total + x
next
console.writeline(total)

Write pseudocode for the following problem:

Find the average of 4 numbers and display it

Answer:

There are many ways to answer this correctly as long as it is clear you got it right. Ask your friend to check it.

input 4 numbers
sum = add numbers together
avg = sum / 4
print avg


Searching and sorting

A searching algorithm looks for a given item in a given data structure. The algorithm used depends on how the data is structured.

Linear Search

If you have a list (or array) that is not sorted, then the simplest searching algorithm is linear search: go through the list item by item and compare to the searched item. If a comparison succeeds, the algorithm has found the item. If all comparisons fail, the item doesn't exist in the array or list.

In the simplest variant, the algorithm returns a boolean to indicate success or failure. Here is the pseudo-code:

for each item in the list:
    if that item has the desired value then
        stop the search and return true
return false

which can be directly translated to Python:

def exists(soughtItem, aList):
  """Return True if and only if soughtItem occurs in aList."""
  for item in aList:
    if item == soughtItem:
      return True
  return False

# automatic tests
assert exists(2, [2, 1, 3]) # sought item in first position
assert exists(3, [2, 1, 3]) # sought item in last position
assert not exists(3, []) # list is empty
assert not exists(0, [2, 1, 3]) # sought item doesn't exist

A second variant returns the position of the item in the list, if it exists. If it doesn't, the algorithm returns an impossible position, like -1. Here's the pseudo-code:

For each position in the list:
    If the item at that position has the desired value then
        stop the search and return the position
Return -1

Here is the Python code:

def index(soughtItem, aList):
  """Return the position of soughtItem in aList if it exists, otherwise return -1."""
  for position in range(len(aList)):
    if aList[position] == soughtItem:
      return position
  return -1

# automatic tests
assert position(2, [2, 1, 3]) == 0 # sought item in first position
assert position(3, [2, 1, 3]) == 2 # sought item in last position
assert position(3, []) == -1 # list is empty
assert position(0, [2, 1, 3]) == -1 # sought item doesn't exist

The following complete VB program asks the user for a letter and searches it in an array.

dim items() = {"h","g","a","d","w","n","o","q","l","b","c"}
dim searchItem as string

console.write("What are you searching for: ")
searchItem = console.readline()

For x = 0 to 10
  If items(x) = searchItem Then
    console.writeline("Found item " & searchItem & " at position " & x)
    Exit For
  End If
Next
console.writeline(-1)

Try the code above searching for letter "w" and then for letter "z":

   Code Output

What are you searching for: w
Found item w at position 4

   Code Output

What are you searching for: z
-1

Exercise: Linear Search

Consider the list of strings "Cat","Mouse","Frog","Lion","Panda","Llama","Bee", in this order. How many comparisons would it take to find "Panda"?

Answer:

5

And how many when searching for "Camel"?

Answer:

It would take 7 to reach the conclusion the string is not in the list.

Make a trace table for the code above, where searchItem = "d".

Answer:

searchItem x Output item
0 1 2 3 4 5 6 7 8 9 10
d 0 h g a d w n o q l b c
1
2
3 Found item d at position 3

For a list with items, what is the maximum number of comparisons it would take to see if an item is there or not?

Answer:

It would take comparisons if the item is in the last position or not at all in the list.

Binary Search

Binary Search
ClassSearch algorithm
Data structureArray
Worst case performanceO(log n)
Best case performanceO(1)
Average case performanceO(log n)
Worst case space complexityO(1)

As the last question points out, a linear search may take as many comparisons as there are items in the list, so searching for a name among a list of several million names (e.g. the electoral register of a country) could take a very long time.

If your list was put in ascending order by a sorting algorithm then you can perform a binary search. This involves splitting the data into half at each comparison, thereby 'zooming in' more quickly into the part of the list where the item must be, if it exists in the list. This results in much better performance, as the side box shows (the Big-O notation is explained in Unit 4).

  • Let's search for the name Miles in the following sorted list:
Ali, Bernie, Claire, Mohammed, Peter, Simon, Yvonne
  • We compare Miles to the middle name, Mohammed:
Ali, Bernie, Claire, Mohammed, Peter, Simon, Yvonne
  • Miles comes alphabetically before Mohammed, so we know that Miles won't be to the right of Mohammed. We can thus 'throw away' the right half of the list:
Ali, Bernie, Claire, Mohammed, Peter, Simon, Yvonne
  • We now compare Miles to the middle name in the remaining list, Bernie:
Ali, Bernie, Claire, Mohammed, Peter, Simon, Yvonne
  • Miles comes alphabetically after Bernie, so we can throw the left hand side away:
Ali, Bernie, Claire, Mohammed, Peter, Simon, Yvonne
  • Finally we compare Miles to the middle name of this single item list, Claire:
Ali, Bernie, Claire, Mohammed, Peter, Simon, Yvonne
  • Miles isn't the same as Claire, there are no more items to compare so we know that Miles isn't in the list.

This only took 3 comparisons using binary search, it would have taken 7 using linear search. It gets even better when the list is large. For example, a 1,000,000,000 item list would only take a maximum of 30 comparisons using binary search! It's very useful to have sorted data.

Exercise:Linear vs Binary Search

Sorted data is also useful for linear search. How could a modified linear search algorithm make fewer than 7 comparisons when searching Miles?

Answer:

The modified linear search would know after 4 comparisons (against Ali, Bernie, Claire and Mohammed) that Miles is not in the sorted list, because Miles should have appeared before Mohammed.

For the list of 7 names shown above, can you think of a case where linear search is faster than binary search?

Answer:

If we search for the first item in the list, Ali, binary search still takes 3 comparisons (against Mohammed, Bernie and Ali) but linear search only needs 1 comparison.

For linear search of a large list, the best case is if the sought item is in the first position. What is the best case for binary search of a large list?

Answer:

Binary search only requires 1 comparison If the sought item is in the middle of the list.

After each unsuccessful comparison, binary search reduces the search space by half. The sublist that is being searched can be represented by two integers, with the start and end positions of the sublist. The Python code is:

def index(soughtItem, sortedList):
  """Return the position of soughtItem in sortedList if it exists, otherwise return -1.
  sortedList must be in ascending order."""
  # Initially, the sublist is the whole list of N items, from positions 0 to N-1
  start = 0
  end = len(sortedList) - 1
  while start <= end:                    # while the sublist is not empty
    middle = (start + end) // 2
    if soughtItem == sortedList[middle]: # the item is in the middle of the sublist
        return middle
    if soughtItem >  sortedList[middle]: # the item is in the right half
        start = middle + 1  
    if soughtItem <  sortedList[middle]: # the item is in the left half
        end = middle - 1   
  return -1                              # empty sublist, the item doesn't exist
  
# tests
assert index(3, [1, 2, 3]) == 2
assert index(1, [1, 2, 3]) == 0
assert index(1, []) == -1
assert index(0, [1, 2, 3]) == -1


Fundamentals of programming

Fundamentals of programming

Features of Imperative High Level Languages

Illustrate these features for a particular imperative, third-generation language such as Pascal.
Data Types

Use the following appropriately.

  • Built-in
Integer, byte, real, boolean, character, string, date/time.
  • User-defined
Enumerated, subrange, sets, records, arrays
Programming statements
  • Type Definitions
  • Variable Declarations
  • Constant Definitions
    • Explain the advantages of named variables and constants.
  • Assignment
  • Iteration
  • Selection
  • Procedure/Function Declarations
  • Procedure and Function calling - Explain the advantages of procedure/functions.
  • Procedure and Function Parameters
    • Describe the use of parameters to pass data within programs.
    • Understand the different mechanisms for parameter passing: by value and by reference

Arithmetic operators including modulo arithmetic +, –, /, x, DIV, MOD

Relational operators =, <, >, <>, <=, >=

Boolean operators NOT, AND, OR

Logical bitwise operators NOT, AND, OR, XOR

Set operators Union, difference, intersection, membership

Built-in functions

  • Arithmetic functions: round, truncation.
  • String handling functions: length, position, substring, concatenation.
  • String conversion functions to/from integer, real, date/time.
The Role of Variables

Recognise the different roles a variable can take:

fixed value, stepper, most recent holder, most wanted holder, gatherer, transformation, follower, temporary.
Fundamentals of Structured Programming

Understand the structured approach to program design and construction.

  • Construct and use structure tables, structure charts and hierarchy charts when designing programs.
  • Use meaningful identifier names.
  • Use procedures/functions with interfaces.
  • Use procedures that execute a single task.
  • Explain the advantages of the structured approach.
Data Structures

Arrays

One- and Two-Dimensional Arrays - Use arrays in the design of solutions to simple problems.
Fields, Records and Files
Read/write from/to a text file (including csv file)
Read/write records from/to a file of records
Validation
  • Understand the importance of validation of input data.
  • Program simple validation

Variables

questions

Introduction

When you first load Visual Studio and select to run a Console Application, you will be presented with some source code:

module module1
  sub main()

  end sub
end module

These lines of code will tell the computer what to do, currently they do very little and we need to get started:

Tradition has it that the first program a programmer should write is "Hello World!". Write the following sourcecode into a command line VB.NET programming environment:

module module1
  sub main()
    console.writeline("Hello World!")
    console.readline()
  end sub
end module

If you are using Visual Studio then you can make the program run by pressing F5 or hitting the Run button that looks a little like this:

You should get the following output:

   Code Output
Hello World!


There it is, you're on your way to becoming a programmer! There is a lot more to learn and over the course of the next few sections you'll get a crash course in programming.

First of all let's look at another program and find out what it's doing:

module module1
  sub main()
    console.writeline("Hello there, my name is Peter and my age is 29")
    console.writeline("6 * 6 = " & 6 * 6)
    console.readline()
  end sub
end module

We'll take a look at each line:

  1. module module1 - this line tells the computer that this particular program is called module1
  2. sub main defines the section of code that is executed first
  3. console.writeline("Hello...29") - this line writes plain text to the console window. There are lots of other console commands we can perform such as console.beep and console.color. We'll learn about them in the input/output section
  4. console.writeline("6 * 6 = " & 6 * 6) - this writes out a combination of text (everything between the "speech marks") and calculation (6*6), joining the two together with the ampersand (&).
  5. console.readline() - If you are running VB from a command line this won't be necessary, but for people using Visual Studio it is. console.readline() waits for you to hit the return key. Modern computers are very fast and if you didn't have this then the words displayed on the screen would appear and then disappear too fast for the eye to see, the screen would appear, then instantly disappear, take this line out and see what I mean.
  6. end sub defines the end of the main code section.
  7. end module - signifies the end of the small program we have written

This should output the following:

   Code Output
Hello there, my name is Peter and my age is 29
6 * 6 = 36

But wait a second, this program isn't much use! Your name probably isn't Peter and you're even less likely to be 29. Time for you to write some code yourself:

Exercise: Hello World!
Create a short program to write the following to the screen, replacing the name Dave with your own name (unless it also happens to be Dave):
   Code Output
Dear Teacher,

My name is Dave and this homework is too easy.
2+2 = 4

Yours Sincerely,
Dave

Answer:

module module1
  sub main()
    console.writeline("Dear Teacher,")
    console.writeline("My name is Dave and this homework is too easy.")
    console.writeline("2 + 2 = " & 2 + 2) 'bonus points for using a sum!
    console.writeline("")
    console.writeline("Yours Sincerely,")
    console.writeline("Dave")
    console.readline()
  end sub
end module

You can show your friends and family. But wait! It's a rubbish program if you want to share it amongst your friends! Each one of them will have to go and change the source code, then hit run. Rubbish unless you live in a country where everyone has the same name, let's call that country 'Davia', I'm pretty sure you don't live there. We better look at making a program that is a little more interactive, where people can change parts of the program without having to keep re-writing it. For that we'll need something called a variable.

Variables

Let's take a look at this program:

VB.NET Python
        Dim name As String
        Dim age As Integer
        name = "Peter"
        age = 29
        Console.WriteLine("Hello " & name & " you are " & age & " years old")
        Console.WriteLine("This also means you are " & age * 12 & " months old")
        Console.WriteLine("Bye " & name & "!")
        Console.ReadLine()
        name = "Peter"
        age = 29
        print("Hello " + name + " you are " + str(age) + " years old")
        print("This also means you are " + str(age * 12) + " months old")
        print("Bye " + name + "!")

you might be expecting both programs to print out:

Hello name you are age years old

But instead they say:

   Code Output

Hello Peter you are 29 years old
This also means you are 348 months old
Bye Peter!

What friendly programs!

Let's break the VB.NET program down line by line:

  1. dim is a variable declaration, creating a temporary data store, a variable, and calling it name It also makes sure that whatever goes into name will be a string by setting it to as string
  2. We declare another variable called age and make sure it is stored as an integer (a whole number)
  3. The variable name that we created earlier is now assigned a value and as it's a string we better use speech marks - "Peter"
  4. The variable age that we created earlier is now assigned a value and as it's an integer we better not use speech marks - 29
  5. This line writes things to the screen, starting with the text "Hello " which attaches that variable we saw earlier to, but instead of putting the variable name, it puts the contents of the variable ("Hello Peter"), then it attaches some more text ("Hello Peter you are ") and adds another variable, age. Even though age is an integer we can stick it together with a string ("Hello Peter you are 29"). Then finally it uses the ampersand once more to attach the final piece of text ("Hello Peter you are 29 years old)
  6. This line works in pretty much the same way, but it does a calculation, working out the age in months. Computers are like giant calculators you can use to do all the things your little pocket calc can do (and far far more!)
  7. The great thing about variables is that we can use them again and again. Here we say "Bye " and use an ampersand to stick on the name of the person. This is great, by using a variable we only need to write "Peter" once and save it as name. If someone else came along and wanted to change the program they just need to change the value of name. Programming is all about being as lazy as possible.
  8. Good old console.readline() stops the screen disappearing too fast.
Variables work like labelled boxes that allow you to store things inside them to retrieve later.

What you have just seen is a declaration of two variables, name and age. A variable is a known or unknown value that has been given a symbolic name. This allows the name to be used independently of the value. It is advisable that a meaningful name for readability and convenience. This name is known as the identifier. To declare a variable in VB.NET we do the following:

Dim identifierName As datatype

Most programming languages have rules about identifiers: they generally have to use only Alphanumeric characters (a..Z, 0..9) and some languages are case sensitive (name != Name).

variable - short term memory used to store temporary values in programming code


Once you have declared a variable you need to assign it a value. Assignment, in programming terms, is the giving of a value to a variable, for example:

identifierName = 7

Here we are assigning the value 7 to the variable identifierName, so when we use identifierName, we mean the value 7:

dim identifierName as integer
identifierName = 7
console.writeline("The value stored in identifierName is: " & identifierName)

Producing:

   Code Output

The value stored in identifierName is: 7


Exercise: Variables
Update the code above to display the age in days, hours, minutes and seconds. No use of calculators! Use the code to do all the work for you.

Answer:

dim name as string
dim age as integer
name = "Syeda"
age = 31
console.writeline("Hello " & name & " you are " & age & " years old")
console.writeline("This also means you are " & age * 12 & " months old")
console.writeline("This also means you are " & age * 365 & " days old")
console.writeline("This also means you are " & age * 365 * 24 & " hours old")
console.writeline("This also means you are " & age * 365 * 24 * 60 & " minutes old")
console.writeline("This also means you are " & age * 365 * 24 * 60 * 60 & " seconds old")
console.writeline("Bye " & name & "!")
console.readline()
Give a good reason why you made age a variable in the previous code

Answer:

To keep track of a changing value that is used in many places but only needs to be updated in one.

What will the following code output:
dim x, y as integer
x = 45
y = 9
console.writeline("The sum of x + y = " & x + y)
console.writeline("y goes into x " & x / y & " times")
console.writeline("x multiplied by y = " & x * y)
console.readline()

Answer:

   Code Output

The sum of x + y = 54
y goes into x 5 times
x multiplied by y = 405

A couple of things to note here:

  • on line 1 We declared two variables on the same line. I told you programmers were lazy
  • on line 5 we did a division using a forward slash. Look at your keyboard there isn't a division sign
  • on line 6 we performed a multiply using a star/asterisk. If x can be used as a variable name we better use another symbol, the symbol is *


Let's break the Python program down line by line:

  1. This line contains a variable declaration, creating a temporary data store, a variable, called name. We assign a value to it with = "Peter". In this case it's a string (which Python can tell automatically) so we better use speech marks1
  2. We declare another variable called age , assigning a value to it. As it's an integer we better not use speech marks - 29.
  3. This line writes things to the screen, starting with the text "Hello ". Next, the plus symbol (+) is used to attach the name variable we saw earlier, but instead of putting the variable name, it puts the contents of the variable ("Hello Peter"). It attaches some more text ("Hello Peter you are ") and adds the other variable, age ("Hello Peter you are 29"). To add the age integer variable we convert it to a string using the built-in string function str(). Finally it uses the plus symbol (+) once more to attach the final piece of text ("Hello Peter you are 29 years old).
  4. This line works in pretty much the same way, but it does a calculation, working out the age in months. Computers are like giant calculators you can use to do all the things your little pocket calc can do (and far far more!)
  5. The great things about variables is that we can use them again and again. Here we say "Bye " and use a plus to stick on the name of the person. This is great, by using a variable we only need to write "Peter" once and save it as name. If someone else came along and wanted to change the program they just need to change the value of name. Programming is all about being as lazy as possible.
Variables work like labelled boxes that allow you to store things inside them to retrieve later.

What you have just seen is a declaration of two variables, name and age. A variable is a known or unknown value that has been given a symbolic name. This allows the name to be used independently of the value. It is advisable to use a meaningful name for readability and convenience. This name is known as the identifier. To declare a variable in Python we simply create it with a meaningful name.

Most programming languages have rules about identifiers: they generally have to use only Alphanumeric characters (a..Z, 0..9) and some languages are case sensitive (name != Name).

variable - short term memory used to store temporary values in programming code


Once you have declared a variable you need to assign it a value. Assignment, in programming terms, is the giving of a value to a variable, for example:

identifierName = 7

Here we are assigning the value 7 to the variable identifierName, so when we use identifierName, we mean the value 7:

identifierName = 7
print("The value stored in identifierName is: " + identifierName)

Producing:

   Code Output

The value stored in identifierName is: 7


Notes

1.^ You get a choice in Python between using speech marks or apostrophes for strings, so "Peter" and 'Peter' are the same. This is important to know if you start looking online for examples of Python code since some people will use speech marks whereas other people like to use apostrophes instead.

Comments

Over the course of the next few chapters you might see a lot of text in the code examples that doesn't seem to do anything other than aid understanding of the code. This text is called a comment and if you have this book in colour you'll see that these comments are highlighted in green.

comment - programmer-readable annotation in the source code of a computer program that helps programmers understand the code but is usually ignored at run time


In Visual Basic all comments start with an apostrophe ' or the word REM. Let's take a look at a quick example:

' this is a comment
dim a, b, c as string' declare variables to store names

'''' read the three names ''''
a = console.readline()
b = console.readline()
c = console.readline()

console.writeline("the names are :" & a & b & c)

Another use for comments is to disable code that you don't want to delete but you do want to keep. By commenting out the code it means that you can always restore it later if you want to. It isn't a good idea to leave commented out code in final code, but it is a very common practice when you are developing something:

'the code below now only takes one name as input instead of three
dim a as string ' declare variables to store names
', b, c as string ' this code does nothing!

'''' read the three names ''''
 a = console.readline()
' b = console.readline()
' c = console.readline()

console.writeline("the names are :" & a)
' & b & c)


Python example

Comments in Python use the hash # character, like this:

# this is a comment
animal = "bunny"  # initialise a variable with the string "bunny"
print(animal)
# this is another comment

Inputs and outputs

An important part of computer code is allowing your user to input data into the program, things such as text, key presses or even a data feed from a motion sensor games controller.

Once the data is in the program you want the system to output responses, these may take the form of output to a screen: graphics, text, output to a sound device, printed documents or data output to another program.

For this unit you need to be familiar with a few input and output commands. The little black box that appears on your screen is called the console. In VB.NET all the commands to read and write from this are accessed from the console. command, let's take a look at some:

Outputs

For the AS course it is unlikely you will need anything beyond the print to screen command and the write to file command (see later). In VB.NET there are two write to screen commands that you should be familiar with:

console.write("Hello") 'writes the word hello to the screen
console.writeline("Hello") 'writes the word Hello to the screen and adds a carriage return (new line)

Let's see an example of this in action:

console.write("Hello ")
console.write("how ")
console.write("are ")
console.writeline("you?")
console.writeline("I'm fine thank ")
console.write("you.")

This would output the following:

   Code Output

Hello how are you?
I'm fine thank
you.


Notice the difference between a writeline and a write command.

Python does not have two separate commands in the way VB.NET does. The print command will by default add a new line on to the end of each string. Here's an example:

print("This is the first line. This is the second half of the first line.")
print("This is the second line.")

will produce the output:

   Code Output

This is the first line. This is the second half of the first line.
This is the second line.


If you want to output several things all on the same line you have to add end="" to the print command. This tells Python that instead of ending with a new line you instead want to end with nothing. So the following example outputs all on the same line:

print("This output will", end="")
print(" all appear ", end="")
print("on the same line.", end="")
   Code Output

This output will all appear on the same line.


Extension: Console methods in VB.NET

We can do a lot of things with the console command. If you are using Visual Studio then type the following:

console.

Up should pop some suggestions. Play around with BackgroundColor and ForegroundColor

There is also a command to output a small and annoying sound, it's unlikely you'll need to know this for the exam, and your teachers will most likely hate it.

console.beep() 'plain beep
console.beep(2000,500) 'beep at 2000Hz for 0.5 seconds

Find out more about the console command on the MSDN website

Inputs

To make your program interactive you'll need your user to input commands, for the exam these will most likely be text instructions or reading from a file (covered later). You might look at buttons and games controllers next year. In VB.NET there are two types of input command that you need to know:

variable1 = console.readline() 'reads input until user presses enter and stores it in variable1
variable2 = console.read() 'reads one key press/character and stores the ASCII code in variable2.  We'll learn more about this later

Let's take a look at a quick example of where this might be used:

dim name as string   'declare a variable called name
console.write("Please insert your name:") ' write "Hello" and the name to the screen
name = console.readline() 'assign the user's input into the variable name
console.writeline("Hello " & name) ' write "Hello" and the name to the screen
   Code Output

Please insert you name: Ali
Hello Ali


There is also the console.ReadKey()command that reads in a single character. Take a look at this example:

dim urChoice as char 'declare the name
console.writeline("Please select from options 1,2,3 or 4:")
urChoice = console.Readline() 'read the users input into the variable name
console.writeline("You chose : " & urChoice )
   Code Output

Please select from options 1,2,3 or 4:
4
You chose : 4


In Python there is just the one command for reading user input from the keyboard which is input. Here's an example:

print("Please enter your name:")
name = input()
print("Hello ", name)

which if you type in your name as Alice will give the following:

   Code Output

Please enter your name:
Alice
Hello Alice


Exercise: Inputs and Outputs
What does the following code output:
console.writeline("The ")
console.write("Cat")
console.write("sat ")
console.writeline("on ")
console.writeline("the " & "mat")

Answer:

   Code Output

The
Catsat on
the mat

dim num as integer = 19
console.writeline("The average age ")
console.write("of a combat soldier ")
console.write("in Vietnam was " & num)

Answer:

   Code Output

The average age
of a combat soldier in Vietnam was 19

Write code to display the following to the screen:

   Code Output

My favourite colours:
Red
Blue

Answer:

console.writeline("My favourite colours:")
console.writeline("Red")
console.writeline("Blue")

What would the following look like:

dim age as string
dim name as integer
console.writeline("Enter your name: ")
age = console.readline()
console.writeline("Enter your age: ")
name = console.readline()
console.writeline("Hello " & name & ". You are " & age & " years old ")

for the input:

John
16

Answer:

   Code Output

Enter your name: John
Enter your age: 16
Hello 16. You are John years old


Whoops! Fix this:

Answer:

dim age as integer
dim name as string
console.writeline("Enter your name: ")
name = console.readline()
console.writeline("Enter your age: ")
age = console.readline()
console.writeline("Hello " & name & ". You are " & age & " years old ")

Arithmetic operators

Arithmetic Operation - is a function which can perform one of the following tasks: adding, subtracting, multiplying and dividing
Operator - a programming device that performs a function on one or more inputs, for example arithmetic operators (+,-,/,*)


Programming languages provide a basic set of operators to calculate simple arithmetic.

+   Addition
-   Subtraction
*   Multiplication
/   Division
\   Integer division
Mod Remainder Division
^   Exponentiation
&   String concatenation
7 + 2     produces 9
7 – 2     produces 5
7 * 2     produces 14
7 / 2     produces 3.5
7 \ 2     produces 3
7 Mod 2   produces 1
7 ^ 2     produces 49
"7" & "7" produces "77"

Let's look at a short example of arithmetic operations before we jump into the operators themselves.

In this example we will also be using some basic variables. In VB.NET the Dim operator creates the variable, whilst in Python you can simply assign the value to the variable.

VB.NET Python
 Dim Commission As Single
 Dim Sales As Single
 Sales = 3142.51
 Commission = 0.3 * Sales  ' Calculate 30% commission.
 Sales = 3142.51
 Commission = 0.3 * Sales  # Calculate 30% commission.


First, we set the total Sales to 3142.51.

The * operator calculates multiplication, so line 4 is equivalent to multiplying 0.3 and Sales together. Sales is 3142.51, so our result should be the product of 0.3 and 3142.51, and stored in Commission.

Why the funny symbols?

With the exception of addition and subtraction, the symbols used are different to the ones used in real life. This is simply because the other symbols are not available on a standard keyboard (try and find ÷ ≠ m² on yours!) or the symbol is in the alphabet and can be used for naming a variable (x).

Addition

This adds two numbers together, and is denoted by the "+" symbol. If strings are involved it may also do String concatenation, that means sticking the two strings together. Examples:

VB.NET Python
 x = 7 + 2     ' Results in 9.
 x = 25 + -4   ' Results in 21.
 Dim StringA As String
 StringA = "A string" + "Another string" ' Results in "A stringAnother string"
 x = 7 + 2     # Results in 9.
 x = 25 + -4   # Results in 21.
 
 StringA = "A string" + "Another string" # Results in "A stringAnother string"

There is a second addition operator, "+=". It increments the variable on the left of the += by the amount indicated on the right. Examples:

VB.NET Python
 Dim x As Integer = 54
 x += 89       ' result is 143
 x += 7       ' result is 150
 x = 54
 x += 89       # result is 143
 x += 7       # result is 150

It also works with Strings as a concatenation operator. Examples:

VB.NET Python
 Dim x As String = "A fox"
 x += " jumped"          ' result is "A fox jumped"
 x += " over the fence"  ' result is "A fox jumped over the fence"
 x = "A fox"
 x += " jumped"          # result is "A fox jumped"
 x += " over the fence"  # result is "A fox jumped over the fence"

Subtraction

This subtracts two numbers, and is denoted by the "-" symbol. Examples:

VB.NET Python
 Dim x As Integer
 x = 7 - 2    ' Results in 5.
 x = 25 - -4  ' Results in 29.
 
 x = 7 - 2    # Results in 5.
 x = 25 - -4  # Results in 29.

Multiplication

This multiplies two numbers, and is denoted by the "*" symbol. Examples:

VB.NET Python
 Dim x As Integer
 x = 7 * 2    ' Results in 14.
 x = 25 * -4  ' Results in -100.
 
 x = 7 * 2    # Results in 14.
 x = 25 * -4  # Results in -100.

Division

There are more types of division than the one denoted by the "/" symbol. There is also integer division and remainder division.

Normal

This is the most commonly used form of division and is denoted by the "/" operator. Examples:

VB.NET Python
  Dim x As Single
 ' (note that we must use the Single class to have decimals)
 x = 7 / 2  ' Results in 3.5.
 x = 25 / 4 ' Results in 6.25
 
 
 x = 7 / 2  # Results in 3.5.
 x = 25 / 4 # Results in 6.25

Integer division

This divides two numbers, and gives the result without the remainder if the quotient is a decimal. Examples:

VB.NET Python
  Dim x As Integer
 x = 7 \ 2    ' Results in 3.
 x = 25 \ 4   ' Results in 6.
 x = 7 \ 2    # Results in 3.
 x = 25 \ 4   # Results in 6.

Remainder Division

This divides two numbers, and gives the result's remainder if the quotient is a decimal. This is denoted by the operator "Mod" in VB.NET and "mod" in Python. Examples:

VB.NET Python
 Dim x As Integer
 x = 7 Mod 2  ' Results in 1.
 x = 25 Mod 4 ' Results in 1.
 
 x = 7 mod 2  # Results in 1.
 x = 25 mod 4 # Results in 1.

Exponentiation

This is raising a number to a power, i.e. is 49 . For example is:

VB.NET Python
 Dim x As Integer
 x = 7 ^ 2   ' Results in 49.
 
 x = 7 ^ 2   # Results in 49.

This results in the number 49 being assigned to the variable x. It can also be used to calculate the square root of a number. The square root of a number is the number raised to the power of 0.5.

VB.NET Python
 Dim x As Integer
 x = 7 ^ 0.5   ' Results in 2.645.
 
 x = 7 ^ 0.5   # Results in 2.465.

Note: It is necessary to ensure that the variables be correctly declared to get the desired results. The following example works, but will produce the wrong result. This is because the Integer class does not allow decimal places (just like mathematical integers.)

VB.NET Python
 Dim x As Integer
 x = 9 ^ 0.5   ' Results in 3.
 
 x = 9 ^ 0.5   # Results in 3.

Since x is declared as an Integer type, the value square root, a real number, is stored incorrectly.

Any nth root of number can be calculated by raising the number to the power of :

VB.NET Python
 Dim x As Single
 Dim n As Single
 n = 7
 x = 2 ^ (1 / n)
 n = 7
 x = 2 ^ (1 / n)

This is because .

BODMAS

You have probably learnt about the order of operations in maths. BODMAS also applies to computer calculations. This means that when calculating a sum, the program will calculate:

  1. Brackets
  2. Order (powers n^2 etc)
  3. Division
  4. Multiplication
  5. Addition
  6. Subtraction
Example:BODMAS in vb

For example:

console.writeline( (3+4)/7 )
console.writeline( 3+4/7 )
console.writeline( 3+4/7-1 )
   Code Output
1
3.57142857
2.57142857


If in doubt use the brackets!

Built-in data types

Most programming languages have built in data types that are used when declaring variables. Some common data types, and the ones you need to know for the exam, are as follows:

Type Description Memory Space Example
Integer a whole number from -2,147,483,648 through 2,147,483,647 4 bytes 37,453
Byte a whole positive number from 0 to 255 1 byte 12
Real Visual Basic does not use Real Numbers, instead it uses {Single} and {Double}, which both allow for decimal places - -
{Single} 1.5 x 10−45 to 3.4 x 1038 4 bytes 1002.375
{Double} 5.0 x 10−324 to 1.7 x 10308 8 bytes 9997.775
Decimal 7.9228 x 10−28 to 7.9228 x 1028 16 bytes 3.8
Boolean either TRUE or FALSE
Alternatively 1 or 0
Alternatively Yes or No
4 bytes (!) TRUE
Character A single character 2 bytes j
String A collection of characters A unicode string with a maximum length of 2,147,483,647 characters cabbage
Date/Time There are several different types of date format that you can apply. 01/01/0001 to 12/31/9999 and times from 12:00:00 AM (midnight) through 11:59:59.9999999 PM 8 bytes 08/17/1924 14:34:23

Using these data types we can start to write a simple computer program:

dim name as string
dim age as integer
name = "Barry"
age = 56.3

Console.writeline("hello " & name & "! you are "  & age & " years old")

But wait a second, this gives you an odd output, it says:

   Code Output

hello Barry! you are 56 years old

I told it that Barry was 56.3 years old! The reason is because I have used an integer to store the age and not a real (single or double) datatype, it therefore drops the decimal part. Integers, afterall, don't store decimal places!

Assignments

Depending on the datatype, we assign values in different ways:

  • Integers, Bytes, Real, Singles, Doubles = Plain assignment without speech marks
exampleNumber = 7.65
  • Boolean = Plain assignment without speech marks
paidMember = TRUE
  • String, Char = Assignment with speech marks
name = "Henry"
  • Date = Assignment with speech marks
doB= "12/12/45"
Exercise:Data types
Using the correct datatype declare variables for a person's:
  • Age
  • Name
  • Gender
  • Height (metres)
  • Date of Birth
  • License (Do they have a driving license?)

Answer:

dim age as integer
dim name as string
dim gender as char  'OR  dim gender as string
dim height as decimal
dim DoB as date
dim license as boolean


Write assignment statements for the following variables using yourself as an example:
  • Name
  • Age
  • Gender

Answer:

name = "Peter" 'we must use speech marks for text, so we don't mistake the value for a variable
age = 56 'we don't need speech marks for numbers
gender = "m"
Which of the following declarations are correct, which are wrong and why?
dim colour as string
dim wheelNum as integer
dim topSpeed as single
dim hasElectricWindows as char

Answer:

dim colour as string 'CORRECT, also we could use a single to store the frequency
dim wheelNum as integer 'CORRECT
dim topSpeed as single 'WRONG, we don't need such precision, an integer would do
dim hasElectricWindows as char 'WRONG, a boolean would work better
Which of the following assignments are correct, which are wrong and why:
name = Pete
age = "34"
height = twenty
electricWindow = True

Answer:

name = Pete 'WRONG, we're assigning a string so we need to use speech marks
name = "Pete"
age = "34" 'WRONG, we're assigning an integer so we don't need speech marks
age = 34
height = "twenty" 'WRONG, height is numeric, so we need to assign a number without speech marks
height = 20
hasElectricWindow = True 'CORRECT assuming you made the change from the previous question
Give two reasons why is it important to get the correct datatypes:

Answer:

  • Prevents mistakes in code and calculations at run time
  • Makes for smaller and faster programs

Write code that asks the user to insert three numbers with decimals, then outputs them (1) all multiplied together, and (2) added together. For example:

   Code Output

Please insert number 1: 2
Please insert number 2: 3
Please insert number 3: 7.8
multiplied together = 46.8
added together = 12.8

Answer:

dim num1, num2, num3 as single 'NOT integer, we need decimal numbers!  You can use different identifiers
console.write("Please insert number 1:")
num1 = console.readline()
console.write("Please insert number 2:")
num2 = console.readline()
console.write("Please insert number 3:")
num3 = console.readline()
console.writeline("multiplied together = " & num1 * num2 * num3)
console.writeline("added together = " & num1 * num2 * num3)
console.readline()
Extension: Strongly and weakly typed languages
You don't need to know this part for the exam, but it should help you understand why we need to convert.

We have two types of programming language: strongly typed and weakly typed. Strong typing means that you can't add a string to a integer, even if the string contains a number. Weakly typed languages allow you to add a string to an integer if the string contains a number.

Weak Typing Strong Typing
Pseudocode
a = 2
b = '2'

concatenate(a, b) # Returns '22'
add(a, b)         # Returns 4
a = 2
b = '2'

concatenate(str(a), b) # Returns '22'
add(a, int(b))         # Returns 4
concatenate(a, b)     # Type Error
add(a, b)             # Type Error
Languages Visual Basic, Perl, PHP, Rexx Java, C, C++, Python

Constant definitions

Constants are like variables in their declarations and the ability to look at the value stored inside them, however you can not change the values while the program is running, the value of a constant remains (rather unsurprisingly) constant.

Example: Declaring pi as a constant
Const pi as Single = 3.14
console.writeline(pi)
   Code Output

3.14

If you try to change a constant value it will bring up an error. They are very useful for values that do not change or rarely change such as VAT, pi, e, etc. By using a constant you don't run the risk that you might accidentally change the value, you wouldn't want to accidentally change pi to equal 4 as All your calculations would go wrong!

Exercise: Constants

Write a program that works out the area and circumference of a circle, setting pi to a constant. Use the equations: area = Πr2 and circumference = 2Πr For example:

   Code Output

Insert radius: 5
area = 78.5398163
circumference = 31.4159265

Answer:

const pi as single = 3.14
dim r as single
console.write("Insert radius: ")
r = console.readline()
console.writeline("area = " & pi * r * r)
console.writeline("circumference= " & 2 * pi * r)
console.readline()


Write a program that works out the cost of two clothing items showing the price, VAT, and price inclusive of VAT. VAT = 17.5%. For example

   Code Output

Insert price of item 1: 10.40
Insert price of item 2: 19.99
item 1 = 10.40 + 1.82 VAT = £12.22
item 2 = 19.99 + 3.49825 VAT = £23.48825

Answer:

const VAT as single = 0.175
dim price1, price2 as single
console.write("Insert price of item 1: ")
price1 = console.readline()
console.write("Insert price of item 2: ")
price2 = console.readline()
console.writeline("item 1 = " & price1 & " + " & price1 * VAT & " VAT = £" & price1 * (VAT + 1))
console.writeline("item 2 = " & price2 & " + " & price2 * VAT & " VAT = £" & price2 * (VAT + 1))
console.readline()
Why might you want to use a constant in your code instead of a normal variable?

Answer:

Constants are fixed values, so you can't accidentally assign them new values in other parts of your code.

When is it suitable to use a constant?

Answer:

When you are using a value that doesn't need to change at run time and will be used in more than one location.

Selection

An important part of programming is the use of selection, that is the ability to do something if certain criteria is met. This may be as simple as increasing your health bar in a computer game if you eat a chicken drumstick or inserting the cooling rods into the nuclear reactor if the temperature exceeds a certain value.

IF Statement

The most common selection statement is the IF statement, the idea is that you compare a value to some criteria, IF the value and criteria match then you proceed in a certain way, otherwise you do something else. For example:

If It is the queen Then
 Salute her
Else
 Treat them like a commoner
End


VB.NET Python
 If name = "Queen" Then
	console.writeline("Hello your Majesty")
 Else
	console.writeline("Get to the back of the queue!")
 End If
 if name == "Queen":
    print ("Hello your Majesty")
 else:
    print ("Get to the back of the queue!")

The Else part is optional, you can just ignore the commoner! (and dump the Else)

VB.NET Python
 If name = "Queen" Then
	console.writeline("Hello your Majesty")
 End If
 if name == "Queen":
    print ("Hello your Majesty")

You might also want to test multiple things in the If statement. For example:

VB.NET
 If name = "Queen" And age >= 18 Then
	console.writeline("Hello your Majesty, I can serve you beer")
 Else
	console.writeline("Get out of my bar!")
 End If
Python
 if name == "Queen" and age >= 18:
    print ("Hello your Majesty, I can serve you beer")
 else:
    print ("Get out of my bar!")

Relational operators

We often want to write IF statements that do some kind of comparison or test. We just did exactly that in the example above with age >= 18 which tests if the value of the age variable is greater or equal to 18.

Most of these operators you will recognise from learning maths but some are slightly different in computing. The following operators are straightforward:

Operator Meaning
> Greater than
< Less than
>= Greater than or equal to
<= Less than or equal to

The most important operator that is different in computing is one that you have already used many, many times probably without even noticing, which is the = operator. In most programming languages the = operator is used for assignment, for example if we want to assign the value "bunny" to a variable called animal we write animal = "bunny" which is the same in both VB.NET and Python. These two languages are different when it comes to equals which we saw in the example above testing if the value of the name variable was equal to "Queen". In VB.NET the equals operator is just = whereas Python uses == instead. This can lead to a very common programming mistake when writing Python - if we try to write an IF statement which uses = by mistake:

 if name = "Queen" and age >= 18:
    print("Hello your Majesty, I can serve you beer")

we will get an error message similar to this:

   Code Output

Traceback (most recent call last):
  File "python", line 4
      if name = "Queen" and age >= 18 then:
                   ^
SyntaxError: invalid syntax


Finally we need an operator for not equals. In VB.NET we use <> whereas in Python we use !=. Here's an example in the form of a really quite rubbish game:

VB.NET Python
	Dim secret_word, your_guess As String
	secret_word = "unlikely"
	console.WriteLine("Try to guess the secret word:")
	your_guess = console.ReadLine()
	If your_guess <> secret_word Then
		console.WriteLine("You lose")
	End If
secret_word = "unlikely"
print("Try to guess the secret word:")
your_guess = input()
if your_guess != secret_word:
	print("You lose")
Exercise: IF statements
Write a single IF statement for the following:

Ask a user for their eye colour, if they say green call them a "Goblin", else they must be a different type of monster:

   Code Output

What eyes have thee?
Green
Thou art a Goblin?

Alternatively:

   Code Output

What eyes have thee?
Blue
Pray tell, be thou another form of beast?

Answer:

dim eyes as string
console.writeline("What eyes have thee?")
eyes = console.readline()
If eyes = "Green" Then
	console.writeline("Thou art a Goblin?")
Else
	console.writeline("Pray tell, be thou another form of beast?")
End If

Try the code by inputting "green". It doesn't work! We need to adjust the IF statement: If eyes = "Green" or eyes = "green" Then 'the Or part makes sure it picks up upper and lower case letters alternatively we could use UCase() we'll find out more about this later If UCase(eyes) = "GREEN" Then 'UCase converts the entire input into capitals </syntaxhighlight>


   Code Output

How old are you:
11.8
You're probably at secondary school


   Code Output

How old are you:
9
You're not at secondary school


   Code Output

How old are you:
19
You're not at secondary school


Using one IF statement write code to handle the above. HINT: you might need more than one clause in the IF ... THEN section.

Answer:

dim age as single
console.writeline("How old are you:")
age = console.readline()
If age >= 11 And age < 17 Then
	console.writeline("You're probably at secondary school")
Else
	console.writeline("You're not at secondary school")
End If


Now for some very simple AI:

   Code Output

How do you feel today: Happy or Sad?
Sad
Have you had some exercise: Yes or No? No Go for a walk, you might feel better

In all other situations the program should say: "Sorry I don't know how to help". Using one IF statement write code to handle the above:

Answer:

dim feel as string
dim exercise as string
console.writeline("How do you feel today: Happy or Sad?")
feel = console.readline()
console.writeline("Have you had some exercise: Yes or No?")
exercise = console.readline()
If feel = "Sad" AND exercise = "No" Then
	console.writeline("Go for a walk, you might feel better")
Else
	console.writeline("Sorry I don't know how to help")
End If
Example: Multiple Ifs versus Nested Ifs

Sometimes when we are trying to write complex code we will need to use a combination of IFs. In the example above we might want to still treat an under-age queen with respect, an under-age commoner with contempt, serve an 18+ queen with respect, and serve an 18+ commoner with common manners. In fact it seems as if we need 4 different IF statements. We could solve it like this:

VB.NET

If name = "Queen" And age >= 18 Then
	console.writeline("Hello your Majesty, may one serve you beer?")
End If
If name = "Queen" And age < 18 Then
	console.writeline("I'm sorry your Majesty, you are too young to buy beer")
End If
If name <> "Queen" And age >= 18 Then '<> means not equal (so does !=)
	console.writeline("Hello mate, can I serve you beer?")
End If
If name <> "Queen" And age < 18 Then
	console.writeline("Get out of my pub, you are too young to buy beer")
End If

Python 3

if name == "Queen" and age >= 18:
   print ("Hello your Majesty, may one serve you beer?")
elif name == "Queen" and age <18:
   print ("I'm sorry your Majesty, you are too young to buy beer")
elif name != "Queen" and age >= 18:
   print ("Hello mate, can I serve you beer?")
elif name != "Queen" and age <18:
   print ("Get out of my pub, you are too young to buy beer")

This seems awfully cumbersome and we will now look a more elegant way of solving this, using Nested IF's. First of all, nested means placing one thing inside another, so we are going to place an IF inside another.

VB.NET

If name = "Queen" Then
	If age < 18 Then
		console.writeline("I'm sorry your Majesty, you are too young to buy beer")
	Else
		console.writeline("Hello your Majesty, may one serve you beer?")	
	End If
Else
	If age >= 18 Then
		console.writeline("Hello mate, can I serve you beer?")
	Else
		console.writeline("Get out of my pub, you are too young to buy beer")
	End If
End If

Python 3

if name == "Queen":
   if age < 18:
      print ("I'm sorry your Majesty, you are too young to buy beer")
   else:
      print ("Hello your Majesty, may one serve you beer?")
else:
   if age >= 18:
      print ("Hello mate, can I serve you beer?")
   else:
      print ("Get out of my pub, you are too young to buy beer")

Try the examples above with the following data, both solutions should provide the same answer:

1. The name is Queen and the age is 18
2. The name is Quentin and the age is 28
3. The name is Queen and the age is 17
4. The name is Aashia and the age is 15
Exercise: Nested IF statements
Write nests of IF statements for the following:

A car can be hired when a person is over 21 and not intoxicated.

   Code Output

How old are you?
22
Good, that's old enough. Have you been drinking?
Yes
Come back tomorrow

It should also handle:

   Code Output

console.writeline("How old are you?")
20
console.writeline("You're too young I'm afraid. Come back in a few years")

Answer:

dim age as integer
dim drinking as string
console.writeline("How old are you?")
age = console.readline()
if age >= 21 then
  console.writeline("Good, that's old enough. Have you been drinking?")
  drinking = console.readline()
  if drinking = "Yes" then
    console.writeline("Come back tomorrow")
  else
    console.writeline("Your carriage awaits")
  end if
else
  console.writeline("You're too young I'm afraid. Come back in a few years")
end if


Create a login screen to do the following:

   Code Output

Enter username
Jonny5
RECOGNISED! Enter password:
Alive
Please enter Jonny5

If they get the username wrong it should immediately kick them out and not ask for the password. If they get the password wrong it should kick them out.

Answer:

dim name as string
dim password as string
console.writeline("Enter username:")
name = console.readline()
if name = "Jonny5" then
  console.writeline("RECOGNISED!  Enter password:")
  password = console.readline()
  if password = "Alive" then
    console.writeline("Please enter " & name)
  else
    console.writeline("INCORRECT! Get out!")
  end if
else
  console.writeline("Username not recognised. Get out!")
end if


Extension: Single line IF statements

As you should be aware by now a lot of programming is doing things as quickly as possible. You might be fed up with writing long if statements, having to keep hitting that enter key to make new lines. There is a faster way to code: single line IF statements.

VB.NET
 If(input >= 18,console.writeline("drink beer"),console.writeline("drink cola"))
Python
 print ("drink beer") if int(input()) >= 18 else print ("drink cola")

This is a much shorter way of writing:

VB.NET Python
 If input >= 18 then
  console.writeline("drink beer")
 Else
  console.writeline("drink cola")
 End if
 if int(input()) >= 18:
   print ("drink beer")
 else:
   print ("drink cola")

But be careful, code like this can often be harder to read and therefore debug. Once it has been through the interpreter / compiler it almost certainly won't be running any faster either, it's just there for you to save a little space. For the exam keep to the longer version.

Case Statement

The other type is the Case statement, this can be summarised by several if statements where the value is compared to several criteria and the action of first criteria matched is performed, otherwise a default action may be performed.

Case Enter Restaurant and pick up menu
If Egg and Chips available Then
 Order Egg and Chips
End If
If Pie and Chips available Then
 Order Pie and Chips
End If
If Curry and Chips available Then
 Order Curry and Chips
End If
If Pizza and Chips available Then
 Order Pizza and Chips
End If
Default
 Leave hungry
End

However, most programming languages will give you a shortened way of implementing a case statement without the need to write all of these if statements. For example in VB.NET we use the select case

Dim number As Integer = 5
Select Case number
    Case 1, 2, 3
        Console.WriteLine("Between 1, 2, 3 inclusive")
    Case 4 to 8
        Console.WriteLine("Between 4 and up to 8")
        'This is the only case that is true
    Case 9
        Console.WriteLine("Equal to 9")
    Case 10
        Console.WriteLine("Equal to 10")
    Case Else
        Console.WriteLine("Not between 1 and up to 10")
End Select
   Code Output

Between 4 and up to 8


Exercise: Case statements
Create a program where someone types in the name of an animal and it outputs the sound the animal makes. The animals it should handle are:
  • Pig - Oink
  • Cow - Moo
  • Bear - Grr
  • Sheep - Baa
  • Tiger - Grr
  • everything else - Meow

Try and complete this task by only using 5 case statements.

Answer:

Dim animal As string
animal = console.readline()
Select Case animal 
    Case "Pig"
        Console.WriteLine("Oink")
    Case "Cow"
        Console.WriteLine("Moo")
    Case "Bear", "Tiger"
        Console.WriteLine("Grr")
    Case "Sheep"
        Console.WriteLine("Baa")
    Case Else
        Console.WriteLine("Meow")
End Select


You are now going to use a case statement to create an electronic piano.
Note Frequency
A 220.00
B 246.94
C 261.63
D 293.66
E 329.63
F 349.23
G 392.00

Create a case statement in the code below, that will play the notes written above. The while true loop means that the code will never end and will continue for ever. For bonus points try and get the code to accept both upper and lower case inputs

'instruction statement here
While True
  'input and case statements here
While End

Remember to make sound you use:

console.beep(2000,500) 'beep at 2000Hz for 0.5 seconds

Answer:

dim note as char
console.writeline("please insert a musical note:")
While True
  note =  Console.ReadKey().KeyChar
  'note =  Console.Readline() 'also works, but it less fun
  Select Case UCase(note)
    Case "A"
        Console.Beep(220,50)
    Case "B"
        Console.Beep(247,50)
    Case "C"
        Console.Beep(262,50)
    Case "D"
        Console.Beep(294,50)
    Case "E"
        Console.Beep(330,50)
    Case "F"
        Console.Beep(349,50)
    Case "G"
        Console.Beep(392,50)
  End Select
End While

Iteration

An incredibly important part of computing is the idea of iteration, that is repeating the same thing again and again. You probably use iteration every day. Take writing lines in a detention for example; you write some lines, check to see if you have met the line limit, and if you haven't you write some more lines, check if you have met the line limit and so on, until you do meet the line limit and then you can stop.

'Programmers are lazy and can get computers to write detention lines for them
'they are also lazy as they can do a declaration and assignment at the same time:
dim count as integer = 0

While count <= 100
   console.writeline(count & ". I should always do my programming homework.")
   count = count + 1
End While
   Code Output

0. I should always do my programming homework.
1. I should always do my programming homework.
2. I should always do my programming homework.
3. I should always do my programming homework.
...
100. I should always do my programming homework.


Comprehension Exercise: While Loops
  1. How many lines will be printed by this while loop?
  2. What value will be stored in the variable count immediately after the loop has finished executing?
  3. How many times will the condition at the top of the loop (count <= 100) be tested?

Think carefully before you answer each of these.

Answer:

  1. 101 lines, starting with the line numbered 0, and ending with the line numbered 100.
  2. count will contain the value 101 upon exiting the loop.
  3. The test will be performed 102 times. The first 101 times the condition count <= 100 will be true, so the body of the loop will be executed. On the 102nd occasion (when count is 101), the condition count <= 100 will be false, so execution of the loop is terminated. At this point program execution continues from the next instruction after the end of the loop (in this case there are none, so it stops).


A further example might be in a computer game, where the speed of a car is increased all the time the accelerator pedal is pressed down until you hit its maximum speed.

dim maxSpeed as integer = 120
dim speedNow as integer = 0
dim pedalDown as boolean = True

While speedNow < maxSpeed And pedalDown
   console.writeline(speedNow)
   speedNow = speedNow + 1
End While
console.writeline("MAXSPEED!")
   Code Output

0
1
2
3
...
119
MAXSPEED!


Exercise: While Loops
Write a program that counts from 20 to 60 inclusive like so:
   Code Output

20
21
22
...
60

Answer:

dim count as integer = 20
While count <= 60
   console.writeline(count)
   count = count + 1
End While


Write a program that takes an input and outputs the times table for that number:
   Code Output

insert a number: 7
1 * 7 = 7
2 * 7 = 14
3 * 7 = 21
4 * 7 = 28
5 * 7 = 35
6 * 7 = 42
7 * 7 = 49
8 * 7 = 56
9 * 7 = 63
10 * 7 = 70

Answer:

dim count as integer = 1
dim times as integer
console.write("insert a number: ")
times = console.readline()
While count <= 10
   console.writeline(count & " * " & times & " = " & count * times)
   count = count + 1
End While


Write a program that adds all the numbers from 10 to 20 inclusive together and finally outputs the result

Answer:

dim count as integer = 10
dim total as integer = 0
While count <= 20
   total = total + count
   count = count + 1
End While
console.writeline("the total is: " & total)

While Do

The while loop: For example:

While not top speed Do
increase speed
End
dim speed as integer = 0
While speed < 120
	console.writeline(speed)
	speed = speed + 1
End While
   Code Output

0
1
...
118
119

Do While Loop

Another type of while loop is a Do-While loop. This is slightly different from the While loop in that you perform the task before you check that you have to perform the task again. This means you perform the task whatever the circumstances of the check:

Do
increase speed
While not top speed
End

Visual Basic handles this with some slight syntax differences

console.write("how old are you?")
age = console.readline()
Do 
	console.writeline(age & " year olds should attend school!")
	age = age + 1
Loop Until age > 17
console.writeline(age & " is too old to attend school!")

This is great for young students:

   Code Output

how old are you? 15
15 year olds should attend school!
16 year olds should attend school!
17 is too old to attend school!

But we run into a problem when we have a 78 year old:

   Code Output

78 year olds should attend school!
78 is too old to attend school!

Exercise: Do While and While Do

For the dodgy example above re-write the Do While as a While Do loop

Answer:

console.write("how old are you?")
age = console.readline()
While age < 17
	console.writeline(age & " year olds should attend school!")
	age = age + 1
End While
console.writeline(age & " is too old to attend school!")

Be careful when you use each loop!

For Loop

The most complicated tool you may meet is the for loop. This is a glorified While loop and don't be put off by how complicated it looks. It also tends to be one of the easiest ways to iterate in Visual Basic

For (speed = 0, not top speed, increase speed)
 drive

It is far easier to use in vb

For speed = 0 to 120
	drive()
Loop

For loops also allow you to count downwards. For example if you creating a timer that counts down to a target. To do this we use the step - 1 code, making the following code:

For x = 10 To 1 Step -1
   Console.Write(x & ",")
Next
console.writeline("Test over!")

display:

   Code Output

10,9,8,7,6,5,4,3,2,1,Test over!

Exercise: For loops

Write a for loop to display the words "I will eat my greens" 40 times:

Answer:

for x = 1 to 40
  console.writeline("I will eat my greens")
next


Write code that will input a lower and higher number, then write the numbers on the screen, starting at the lower and writing each number until you reach the higher. Use a for loop, it should display the following:

   Code Output

insert lower number: 10
insert higher number: 13
10
11
12
13

Answer:

dim lower, higher as integer
console.write("insert lower number: ")
lower = console.readline()
console.write("insert higher number: ")
higher = console.readline()
For x = lower to higher
  console.writeline(x)
Next


Write a for loop that will output the frequencies: 100,200,300,400, ... , 20000. HINT, you might want to start at 1 and multiply. Remember console.beep(200, 200)

Answer:

For x = 1 to 200
  console.beep(x* 100, 100)
Next


Get the computer to keep asking a user whether they are "Ready to launch?". If they say anything other than "Yes", then keep asking the question. If they say yes, then count down from 5 and end with the words "BLAST OFF!".

   Code Output

Ready to launch? No
Ready to launch? Not yet
Ready to launch? Yes
5
4
3
2
1
BLAST OFF!

Extension: If you want to really show that you know how to use case statements, get it to say: FIVE, FOUR, THREE, TWO, ONE instead of showing the numbers

Answer:

Dim answer As String
Do
   Console.Write("Ready to launch? ")
   answer = Console.ReadLine()
Loop While answer <> "Yes"
For x = 5 To 1 Step -1
   Console.WriteLine(x)
Next
Console.Write("BLAST OFF!")

You have met the three main sorts of iteration that you can use, some being more suited for solving certain problems than others:

  • While Do
  • Do While
  • For

Click here to learn more

Loopy Loops (Nested Loop)

Some times it might be a good idea to combine several loops together. Take a look at this example

For x = 1 to 10
  console.writeline(x & " : ")
  for y = 0 to 10
    console.writeline(x & " * " & y & " = " & x * y)
  Next
Next

This code uses a loop inside a loop to print out the times tables. All that time you spent learning them at school can be rewritten in six lines of code!

   Code Output

1 :
1 * 0 = 0
1 * 1 = 1
1 * 2 = 2
1 * 3 = 3
1 * 4 = 4
1 * 5 = 5
1 * 6 = 6
1 * 7 = 7
1 * 8 = 8
1 * 9 = 9
1 * 10 = 10
2 :
2 * 0 = 0
...

Exercise: Loopy loops

Write a for loop inside a loop to display a Christmas Tree, like so:

   Code Output

\
\\
\\\
\\\\
\\\\\

Answer:

For x = 1 to 5
  For y = 1 to x
   Console.Write("\")
  Next
  Console.WriteLine()
Next


Adjust the code above so that the user inputs how high the tree is

Answer:

dim h as integer
console.writeline("please insert a height")
h = console.readline()
For x = 1 to h
  For y = 1 to x
   Console.Write("\")
  Next
  Console.WriteLine()
Next

Built-in functions

You need to be familiar with several programming routines that come built into most common programming languages. These routines are very useful and should save you a lot of effort in writing code to perform common tasks. You might be asked to use them in the exam so learn them!

Arithmetic functions

You'll have to be familiar with several

Round

The round function is used to round numbers to a limited number of decimal places using the Math.Round() function

Math.Round(1.94, 1) 'Returns 1.9
Math.Round(1.95, 1) 'Returns 1.9 !0.5 rounds down!
Math.Round(1.96, 1) 'Returns 2.0
Math.Round(1.9445, 2) 'Returns 1.94
Math.Round(1.9545, 3) 'Returns 1.954
Math.Round(6.765, 2) 'Returns 6.76
Math.Round(1.9445) 'Returns 2 - the equivalent of saying round to 0 dp

Truncation

The truncate function returns the integer part of a number, regardless of the decimal places.

Math.Truncate(19.45) 'Returns 19
Math.Truncate(19.9999) 'Returns 19

This is particularly useful when you are trying to perform DIV in modular arithmetic.

Extension: Random numbers

An essential part of most games is the ability to use random numbers. These might be used to randomly place gold coins on a map, or to calculate whether you hit a target with a rifle at some distance.

Dim rndGen As New Random()
Dim randomNumber As Integer
randomNumber = rndGen.Next()

The above code will give you a random number between 1 and 2,147,483,647. You might well require a number that is a little smaller. To get a random number between two set numbers, in this case 5 and 10 you can use the following:

randomNumber = rndGen.Next(5,10)

So how exactly can we use this? Take a look at the following game:

Dim rndGen As New Random()
Dim randomNumber As Integer
Dim guess as Integer
randomNumber = rndGen.Next(1,100)
console.writeline("Please guess the random number between 1 and 100")
Do 
  console.write("your guess:")
  guess = console.readline()
  if guess > randomNumber
    console.writeline("Too High")
  end if
  if guess < randomNumber
    console.writeline("Too Low")
  end if
Loop While guess <> randomNumber
console.writeline("Well done, you took x guesses to find it!")

Adjust the code above to tell the user how many guesses they took to find the random number. HINT: you'll need a variable

Answer:

    Sub Main()
        Dim rndGen As New Random()
        Dim randomNumber As Integer
        Dim guess As Integer
        Dim count As Integer = 1
        randomNumber = rndGen.Next(1, 100)


        Console.WriteLine("Please guess the random number between 1 and 100")
        Do
            Console.Write("your guess:")
            guess = Console.ReadLine()
            If guess > randomNumber Then
                Console.WriteLine("Too High")
            End If
            If guess < randomNumber Then
                Console.WriteLine("Too Low")
            End If
            If guess <> randomNumber Then
                count = count + 1
            End If
            If guess = randomNumber Then
                Console.WriteLine("Well done, you took " & count & " guesses to find it!")
            End If

        Loop
    End Sub
Exercise: Arithmetic function
What does the following code output:
dim num1 as single = 12.75
dim num2 as single = 12.499
dim total as single

num2 = Math.Round(num2, 1)
num1 = Math.Truncate(num1)
total = num1 + num2
console.writeline(Math.Round(total))

Answer:

   Code Output

24


Write some code to output the integer part of a number input by the user

Answer:

Math.Truncate(input)


Write code to output the integer and decimal parts of an input number:
   Code Output

Please insert a decimal number: 13.78
The whole number part of this number is: 13
The decimal part is: 0.78

Answer:

dim num as single
console.write("Please insert a decimal number: ")
num = console.readline()
console.writeline("The whole number part of this number is: " & Math.Truncate(num))
console.writeline("The decimal part is: " & num - Math.Truncate(num))

String handling functions

Very popular examination questions involve manipulating strings. These simple functions will help you with this task.

Length

This function is used to find the length of any string you pass it, counting all the characters, including the spaces. In visual basic to find the length of a string we use the Len("some string") function that returns the integer length of the string that it has been passed:

someText = "Gary had a little lamb"
Console.writeline(Len(someText))
   Code Output

22


Position

This function allows us to find the position of an item within a given string and returns the position's location. In visual basic this is performed by the following command: InStr([string], [item]) For example we might want to find the location of an end of a sentence by looking for a fullstop:

someText = "Gary had a little lamb. His fleece was white as snow."
Console.writeline(InStr(someText,"."))
   Code Output

23

We can also use this command to search for strings within strings. For example if we were to look for to see if a sentence contained a certain name:

someText = "Gary had a little lamb. Dave's fleece was white as snow."
Console.writeline(InStr(someText,"Dave"))
   Code Output

25

If the search item is not contained in the string then it will return 0

someText = "Gary had a little lamb. Dave's fleece was white as snow."
Console.writeline(InStr(someText,"Julie"))
   Code Output

0


Substring

This function allows you to snip items out of a string and return a substring. Visual Basic uses the following command: [string].Substring([startPosition],[lengthOfReturnString]). For example we might want to find the local number from a landline phone number we have been given. We'll have to ignore the area code:

phone = "(01234)567890"
local = phone.Substring(7, 6)
console.writeline(local)
   Code Output

567890


Concatenation

This function allows you to stick strings together (concatenate) so that you can start to build strings using variables. Visual Basic uses the following command: [stringA & stringB] For example we might have a users name stored in a variable dim name as string and a greeting that we would like to give them:

name = "Charles"
console.writeline("Hello " & name & ". How are you today?")
   Code Output

Hello Charles. How are you today?


String conversion functions

When you declare a variable you give it a datatype. This datatype restricts the values that you can place into the variable. For example:

dim age as integer
would allow: age = 34
would NOT allow: age = "cabbages"

This seems to make sense, but what would happen when you try to place a real number into a integer:

dim age as integer
age = 34.3
console.writeline(age)
   Code Output

34

This might seem OK, but in other lanuages we might run into trouble. To perform this we would have to convert from one datatype to another:

dim age as decimal
age = 34.3
console.writeline(age)
age = CInt(34.3) 'converts the decimal into an integer
console.writeline(age)
   Code Output

34.3 34


Exercise: String functions
Write a short program to tell someone how many letters they have in their name (just in case they don't know!), for example:
   Code Output

Input: Fremlin
Hello Fremlin, you have 7 letters in your name.

Answer:

  Dim name As String
  console.write("Input: ")
  name = console.readline()
  console.writeline("Hello " & name & " you have " & Len(name) & " letters in your name.")


Some people have stupidly typed their firstname and their surname into a database, write some code to display the first name, then their surname
Dim name as string = "Elizabeth Sheerin"
   Code Output

Input: Elizabeth Sheerin
Firstname: Elizabeth
Surname: Sheerin

Answer:

        Dim name As String = "Elizabeth Sheerin"
        Dim firstname, secondname As String
        Dim space, textlength As Integer

        space = InStr(name, " ")
        textlength = Len(name)

        firstname = name.Substring(0, space)
        secondname = name.Substring(space, textlength - space)

        Console.WriteLine("first name is: " & firstname)

        Console.WriteLine("second name is: " & secondname)


A telephone number has been typed into a computer as a string: (01234)567890
dim phonenum as string = "(01234)567890"

Write some code to output the number without brackets:

   Code Output

Input: (01234)567890
Output: 01234567890

Answer:

        Dim phonenum As String = "(01234)567890"
        Dim firstbracket, secondbracket As String
        Dim textlength, arealength As Integer

        firstbracket = InStr(phonenum, "(")
        secondbracket = InStr(phonenum, ")")
        textlength = Len(phonenum)
        arealength = secondbracket - firstbracket

        Console.Write(phonenum.Substring(firstbracket, arealength - 1) & phonenum.Substring(secondbracket, textlength - secondbracket))


A similar question to the one above, telephone numbers are currently stored in a very unreadable format: 01234567890, completely missing off the area code. Can you convert them to display the first 5 figures are the area code:
dim phonenum as string = "01234567890"

This should then be output as:

   Code Output

Input: 01234567890
Output: (01234)567890

Answer:

        Dim phonenum As String = "01234567890"
        Console.Write("(" & phonenum.Substring(0, 5) & ")" & phonenum.Substring(6, 5))
        Console.ReadLine()


A palindrome is a word, phrase or number that may be read the same way in either direction. For example 1234321, RACECAR, TOOT and NUN. You need to write a program that checks to see if any input given is a palindrome and let the user know:
   Code Output

Input: NUN
That is a palindrome!
Input: nune
That is NOT a palindrome

Answer:

  Dim name As String
  Dim length As Integer
  Dim Pal As Boolean = TRUE
  console.write("Input: ")
  name = console.readline()
  length = Len(name)
  For x = 0 to (length / 2)
    If name.Substring(x, 1) != name.Substring(length - x, 1) then
       Pal = FALSE
    End If
  Next
  
  If Pal then
    console.writeline("That is a palindrome!")
  Else
    console.writeline("That is NOT a palindrome!")
  End If


Extension: REGEX

You will often want to check the format of a string being input and if it is incorrect you will want it to be submitted again. For example you might want someone to input the name of their best friend, meaning that they shouldn't be inputting any numbers or spaces, and it should start with a capital letter:

   Code Output

Name of best friend: Beanie(CORRECT)
Name of best friend: jonny5(STOP THIS)

To do this we can match the input string against some rules, regular expressions or regex, in this case we only want characters from the alphabet:

[A-Z][a-z]+

Breaking apart the rule:

  • [A-Z] - start exactly one instance of a capital letter
  • [a-z]+ - followed by as many lower case letters as you like (that's what the + means)

Another example might be checking for the correct spelling of a famous composer:

"Handel", "Händel", and "Haendel"

We can check this using the pattern H(ä|ae?)ndel. Let's take a look at what this means:

  • H - start with an H
  • (ä|ae?) - includes an ä or (the | symbol) an a followed by an optional e (e? means the e is optional)

Most regular expression tools provide the following operations to construct expressions.

Boolean "or"

A vertical bar separates alternatives. For example, gray|grey can match "gray" or "grey".

Grouping

Parentheses are used to define the scope and precedence of the operators (among other uses). For example, gray|grey and gr(a|e)y are equivalent patterns which both describe the set of "gray" and "grey".

Quantification

A quantifier after a token (such as a character) or group specifies how often that preceding element is allowed to occur.

  • ? The question mark indicates there is zero or one of the preceding element. For example, colou?r matches both "color" and "colour".
  • * The asterisk indicates there is zero or more of the preceding element. For example, ab*c matches "ac", "abc", "abbc", "abbbc", and so on.
  • + The plus sign indicates there is one or more of the preceding element. For example, ab+c matches "abc", "abbc", "abbbc", and so on, but not "ac".

Most programming languages have regular expression functions. In VB.NET we can use regular expressions by using the Regex routine:

' this code enforces the name rule from earlier
Dim name As String
Console.Write("Name of best friend: ")
name = Console.Readline()

' match the string against a regular expression
Dim m As Match = Regex.Match(name, "[A-Z][a-z]+")

If (m.Success) Then
    Console.WriteLine("You have input the name correctly")
Else
    Console.WriteLine("Incorrect format!")
End If

A common use for regular expressions is in checking that you have a correctly typed email address. A rule for that is this: ^[a-zA-Z0-9_.+-]+@[a-zA-Z0-9-]+\.[a-zA-Z0-9-.]+$.

You can find out more about Regular expression on wikipedia and you will cover regular expressions in more detail in A2.

to/from integer, real, date/time.

One-dimensional arrays

A diagram showing how a 2d array works, the equivalent of the following:
dim animals(3) as string
animals(0) = "Dog"
animals(2) = "Cat"
Dim friends(0 To 2) As String

friends(0) = "Barry"
friends(1) = "Aubrey"
friends(2) = "Gertrude"

You can also declare arrays by placing the values directly into them, this code does exactly the same as the above:

Dim friends() As String = {"Barry", "Aubrey", "Gertrude"}

You can pick out individual items by using their index

Console.WriteLine(friends(2))
Console.WriteLine(friends(0))

Would output:

   Code Output

Gertrude
Barry


You can treat indexed array items as variables and change their values:

friends(0) = console.readline()
Exercise: One-Dimensional Arrays
Declare an array listing 5 animals in a zoo (aardvark, bear, cuckoo, deer, elephant) in alphabetical order:

Answer:

dim zooanimals() as string = {"aardvark","bear","cow","deer","elephant"}
Write code to output the first and last animal

Answer:

console.writeline(zooanimals(0))
console.writeline(zooanimals(4))
Someone has accidentally eaten the cuckoo, let the user add a new third animal and print them all out:
   Code Output

Insert new third animal: Crocodile
1: Aardvark
2: Bear
3: Crocodile
4: Deer
5: Elephant

Answer:

console.write("Insert new third animal:")
zooanimals(2) = console.readline()
console.writeline("1: " & zooanimals(0))
console.writeline("2: " & zooanimals(1))
console.writeline("3: " & zooanimals(2))
console.writeline("4: " & zooanimals(3))
console.writeline("5: " & zooanimals(4))
''Alternatively an A-grade student might write:
for x = 0 to 4
  console.writeline(x + 1 & ": " & zooanimals(x))
next

To print out the entire array it is best to use some form of iteration:

For x As Integer = 0 To 2
	Console.WriteLine(friends(x))
Next

Would print out:

   Code Output

Barry
Aubrey
Gertrude


To overwrite something, you treat it like a variable:

friends(1)="Peter"
For x As Integer = 0 To 2
	Console.WriteLine(friends(x))
Next

Would output:

   Code Output

Barry
Peter
Gertrude


Exercise: One-Dimensional Arrays
What is the output of the following code:
dim primes() as integer = {2,3,5,7,11,13,17,19,23}
dim count = 8
While count >= 0
  console.write(primes(count) & ", ")
  count = count - 1
end while

Answer:

   Code Output

23,19,17,13,11,7,5,3,2


Declare an array that will hold the names of your 5 best friends, call is befr

Answer:

dim befr(5) as string 'befr(4) would also be accepted


Write a loop so that you can input each of your five best friends and it will output them in the order you input them. For example:

   Code Output

Insert best friends:
1: Nell
2: Al
3: Sean
4: Paley
5: Jon
You listed: Nell,Al,Sean,Paley,Jon

Answer:

dim befr(5) as string
console.writeline("Insert best friends:")
for x = 1 to 5
  console.write(x & ": ")
  befr(x) = Console.ReadLine()
next
console.writeline("You listed:")
for x = 1 to 5
    console.write(befr(x) & ", ")
next


Adjust the code above so that it outputs the list in reverse order:

Answer:

dim befr(5) as string
console.writeline("Insert best friends:")
for x = 1 to 5
  console.write(x & ": ")
  befr(x) = Console.ReadLine()
next
console.writeline("You listed:")
for x = 5 to 1 step -1
    console.write(befr(x))
next
Extension: For each

Sometimes you might not know the length of an array that you area dealing with yet you will still want to cycle through all the elements. If you don't know what numbers to put into the for x = 0 to ?? code then how will you cycle through everything? Visual Basic and most languages offer a for each routine that allows you to look at each element until you find the last one. This makes for far more robust code where you don't have to keep changing the variables of loops each time you change the size of arrays:

Dim someNumbers() as integer = {1,2,3,4,5,6,7,23,77}
For Each n In someNumbers
   Console.Write(n & ", ")
Next

The above code would output:

   Code Output

1, 2, 3, 4, 5, 6, 7, 23, 77,

Uses

Arrays are very useful for solving all manner of problems, ranging from sorting lists to storing the results to calculations.

Take the Fibonacci sequence of numbers where: the first two numbers in the Fibonacci sequence are 0 and 1, and each subsequent number is the sum of the previous two.

A tiling with squares whose sides are successive Fibonacci numbers in length

For example:

This could take some time to calculate by hand but and we can use an array to calculate and store this sequence:

dim fib(30) as integer
'initiate the first two values
fib(0) = 0 
fib(1) = 1
for x = 0 to 28
  fib(x+2) = fib(x) + fib(x+1)
next
console.writeline("The first 31 fibonacci numbers are:")
for y = 0 to 30
  console.write(fib(y) & ",")
next
Exercise: Calculating with arrays
Update the above code to allow the user to input a number, then the program to store and display that many fibonacci numbers. Test it for 10 and 1000

Answer:

dim size as integer
size = console.readline()
'integer is too small to hold this value so we change to single
dim fib(size) as single 
'initiate the first two values
fib(0) = 0 
fib(1) = 1
for x = 0 to size - 2
  fib(x+2) = fib(x) + fib(x+1)
next
console.writeline("The first " & size & " fibonacci numbers are:")
for y = 0 to size
  console.write(fib(y) & ",")
next

Arrays are also very important when we are searching and sorting data. You will learn a lot more about this in A2, but for the moment take a look at this linear search routine:

dim attendance() as string = {"Callum", "John", "Olamide", "Mathew", "Gabriel", "Dong"}
dim search as string
console.writeline("Who are you searching for:")
search = console.readline()

for x = 0 to attendance.length - 1 'why do we need -1 here?
  if attendance(x) = search then
    console.writeline(search & " found at position : " & x)
  end if
next

If we were to try and find Olamide we should see the following:

   Code Output

Who are you searching for:
Olamide
Olamide found at position : 2

Exercise: Searching arrays
Why do we have attendance.length - 1 in the above code?

Answer:

As the array starts at location 0, the length of the array will be 1 more than the largest index number.

Adjust the code above to tell you when it hasn't found a person:

Answer:

'there are multiple ways of doing this:
dim attendance() as string = {"Callum", "John", "Olamide", "Mathew", "Gabriel", "Dong"}
dim search as string
dim found as boolean = false
console.writeline("Who are you searching for:")
search = console.readline()

for x = 0 to attendance.length - 1 'why do we need -1 here?
  if attendance(x) = search then
    console.writeline(search & " found at position : " & x)
    found = true
  end if
next
if found = false then
  console.writeline(search & " NOT found in the array")
end if


Functions and procedures

To save you rewriting lots of code again and again you might use a sub routine, there are two types: Procedures and Functions. For example in a program you wanted to know today's date, instead of having to write a separate sub routine to calculate the date each time you wanted to work it out, you would probably use date(). This is a function, when you call it, it returns a value. It was written by someone else and you can keep reusing it as many times as you want. Any program written in industry will use sub routines calling things like: console.writeline(), printScore(), deleteRecord() . Procedures and Functions allow for you to:

  • Reuse code
  • structure your programming
  • Easily incorporate other peoples code

An easy way to tell the difference between a Procedure and a Function is to look at the names:

  • Functions are fun: if you would call them, they would return a value
  • Procedures aren't fun: if you call them they don't return any value. (these are known as sub in Visual Basic)

The difference between functions and procedures is a little more complex than this, but the above works as a rule of thumb

Declarations

Declarations are where you state the name of your procedure/function and the code that you want to execute. Even if you declare a procedure/function, it doesn't mean that the code will run, you need a Call to actually get the code to execute.

Sub printNumber()
	console.writeline(number1)
End Sub

Functions are slightly different, as they return values you must include a return function in their declaration. And you must specify the datatype of the value being returned, in the case below that is an Inteteger specified by: ..) as Integer

Function printNumber() as Integer
	return number1
End Function

Calls

Calls allow you to run the code declared in a procedure/function. You can build up all sorts of programming structures by making Calls part of the code. Remember that Functions are fun, so you should be doing something with the returned value.

printNumber() ' a procedure call
console.writeline(printNumber()) ' a function call
dim x = MaximumSpeed() ' another function call

Parameters (and Arguments)

Parameters allow you to pass values to the procedures and functions that you declare, you can pass all sorts of data as parameters and you can pass as many as you like.

Extension: Parameters vs Arguments

Parameters are often called Arguments. Technically, they are very similar but not the same thing. When you describe a procedure or a function, and identify the data it can accept, each thing is a Parameter. When you later use the procedure or function within a program, and provide it with an actual piece of data (or multiple pieces), those things are called Arguments. In practice, the terms are often used interchangeably (c.f. StackOverflow: What's the difference between an argument and a parameter?)

'declaration
Sub printNumber(number1 as integer) 'one parameter
	console.writeline(number1)
End Sub
'...
'call
printNumber(4)

The output would be:

   Code Output

4


'declaration
Sub printNameAge(name as string, age as integer) 'two parameters
	console.writeline(name & " is " & age & " years old")
End Sub
'...
'call
printNameAge("Mounir", 17)

The output would be:

   Code Output

Mounir is 17 years old


'declaration
function squareNumber(number1 as integer) as integer 'one parameter
	return (number1 * number1)
End Function
'...
'call
console.writeline(squareNumber(4))

Note that as it's a function, we had to include the call in an equation. It returns a value, it can't sit on its own. The output would be:

   Code Output

16


Exercise: Functions and Procedures

What is the difference between a function and procedure?

Answer:

Functions return values, Procedures may or may not return a value.


Why would you use subroutines (functions and procedures) in your code?

Answer:

  • They help you structure your code
  • They allow you to create a common routine once and re-use as many times as you want
  • They allow you to share code with other programs
  • They allow you to test sub routines independently of the rest of the code


Write a function declaration with the identifier of Avg that will accept 3 numbers (num1, num2, num3) and return the average:

Answer:

Function Avg(num1, num2, num3)
  return (num1 + num2 + num3) / 3
End Function


For the above function, write code with a function call to work out the average of three numbers input by a user:

   Code Output

num1 = 4
num2 = 7
num3 = 10
Average = 7

Answer:

dim a, b, c as integer
console.write("input num1 = ")
a = console.readline()
console.write("input num2 = ")
b = console.readline()
console.write("input num3 = ")
c = console.readline()
console.write("Average = " & Avg(a,b,c))


Sub nameTimes(name, num)
  for x = 1 to num
    console.writeline(name)
  next
End Sub

For the procedure above list:

  • the identifier
  • the parameters, what are their data types?
  • create a procedure call to print out the name "Kane" 5 times.

Answer:

  • identifier = nameTimes
  • parameters = name (string) and num (integer)
  • nameTimes("Kane",5)

ByRef

The parameter that you are passing to a procedure or function is referred to. That means you are pointing at it, you are going to directly change its value and anything that happens to it within the procedure or function will change the original value.

Dim number1 as integer = 123

Sub Main()
	console.writeline(number1)
	IncPrintNumber(number1)
	console.writeline(number1)
End Sub

Sub IncPrintNumber(ByRef num as integer)
	num = num + 1
	console.writeline(num)
End Sub

The output would be:

   Code Output

123
124
124


ByVal

The parameter that you are passing to a procedure or function is copied. That means you are taking a copy of the original value put into the procedure or function call. Anything that happens to it within the procedure or function will NOT change the original value.

Dim number1 as integer = 123

Sub Main()
	console.writeline(number1)
	IncPrintNumber(number1)
	console.writeline(number1)
End Sub

Sub IncPrintNumber(ByVal num as integer)
	num = num + 1
	console.writeline(num)
End Sub

This saves a local variable of the number1 value, storing it in num, it is only valid inside the IncPrintNumber sub routine The output would be:

   Code Output

123
124
123


Exercise: ByRef and ByVal
Sub Main()
	dim a as integer = 7
	dim b as integer = 8
	Add(a,b)
	console.writeline(a)
End Sub

Sub Add(ByXXX num1 as integer, ByXXX num2 as integer)
	num1 = num1 + num2
End Sub

What is the output of the above code when ByXXX = ByVal?

Answer:

   Code Output

7


What is the output of the above code when ByXXX = ByRef?

Answer:

   Code Output

15


Sub Swap(ByRef p as string, ByVal q as string)
	dim temp as string
	temp = p
	p = q
	q = temp
        console.writeline(p & " - " &  q)
End Sub
Sub Main()
	dim s1 as string = "hello"
	dim s2 as string = "goodbye"
	Swap(s2, s1)
	console.writeline(s2 & " - " &  s1)
End Sub

What is the output of the above code?

Answer:

   Code Output

hello - goodbye
hello - hello


What is the difference between a parameter passed by Value and a parameter passed by Reference?

Answer:

A parameter passed by value copies the value of the parameter passed into the sub routine. Any changes made to this value do not impact on the original value.

A parameter passed by Reference passes a link to a variable. Any changes made to the parameter in the sub routine change the original variable.

Global and local variables

Global variable - declared at the start of the program, their global scope means they can be used in any procedure or subroutine in the program

It is seldom advisable to use Global variables as they are liable to cause bugs, waste memory and can be hard to follow when tracing code. If you declare a global variable it will continue to use memory whilst a program is running even if you no longer need/use it.

Local variable - declared within subroutines or programming blocks, their local scope means they can only be used within the subroutine or program block they were declared in


Local variables are initiated within a limited scope, this means they are declared when a function or subroutine is called, and once the function ends, the memory taken up by the variable is released. This contrasts with global variables which do not release memory.

Take a look at this example:

Module Glocals
	Dim number1 as integer = 123
	
	Sub Main()
		console.writeline(number1)
		printLocalNumber()
		printGlobalNumber()
	End Sub
	
	Sub printLocalNumber
		Dim number1 as integer = 234
		console.writeline(number1)
	End Sub

	Sub printGlobalNumber
		console.writeline(number1)
	End Sub
End Module

What would the output be?

   Code Output

123
234
123


Why is this? Well we seem to have two versions of the variable number1.

  • The first version is declared on line 2, this isn't declared inside any sub routines so the variable has Global scope
  • The second version is declared inside the printLocalNumber sub routine. As it is declared inside a sub routine it is only able to be used inside this subroutine. And on line 12 when we use: console.writeline(number1) it prints out the local variable

So looking at the code inside the main sub routine we have 3 different ways of printing out the variable number1.

  1. Line 5. console.writeline(number1):This uses the global value of number1, as it is inside a sub routine with no other local declarations
  2. Line 6. printLocalNumber():This is calling on the subroutine printLocalNumber() which has a local variable number1 contained within it on line 11, therefore it uses the number1 value declared on line 11.
  3. Line 7. printGlobalNumber():This is calling on the subroutine printGlobalNumber() which has no local variable for number1, therefore it uses the global value for number1
We can visualise the scope of the different variables

Rules of thumb: If you want to quickly tell the difference between a global and a local variable use these quick rules. But be warned they might try to trick you!

  • If a variable is declared inside a function or a procedure it is a local variable
  • If a variable is declared inside an iterative or selective statement it is local
  • If the declaration is indented from the left hand boundary it probably meets one of the above criteria and is local
  • If it meets none of the above statements and is declared in the main body of code it is a global variable
Title
What is the difference between a global and a local variable?

Answer:

Global variables are accessible from all parts of a program, whilst local variables are only accessible within a programming construct such as a loop, function or procedure
Why is it a good idea to use local variables instead of global variable?

Answer:

Local variables release memory when you have finished with them, global variables are always stored in memory whether you need them or not
In what situation might you want to use a global variable?

Answer:

When you want to declare a variable that needs to be accessible by all parts of your code


List the global and local variables for the following. What will be the output for input 16:
Module calcAge
	Sub Main()
		dim age as integer
		console.writeline("age?")
		age = console.readline()
		printMonths(age)
		printDays(age)
	End Sub
	Dim months as integer
	Sub printDays(a)
		Dim d as integer
		d = a * 365
		console.writeline(d)
	End Sub
	Sub printMonths(a)
		months = a * 12
		console.writeline(months)
	End Sub
End Module

Answer:

Locals: age, d

Globals: months

   Code Output

age?
16
192
5840

For the above code how could you make the code more efficient, and why would it be more efficient?

Answer:

Make the months variable a local variable by putting it inside the printMonths(a) sub routine, if you leave it as a global variable it will be taking up memory even when you don't need it.
List the Global and Local variables in the following code, list the output:
Module greetings
	Dim q as integer = 6
	Sub sayGoodbye()
		for y = 1 to q
			console.write("bye,")
		loop
	End Sub
	Sub sayHello()
		dim q as integer = 4
		if q =< 4 then
			console.write("hi,")
		else
			console.write("hello,")
		endif
	End Sub
	Sub Main()
		console.writeline(q)
		sayHello()
		sayGoodbye()
		console.writeline(q)
	End Sub
End Module

Answer:

Locals: y (on line 4), q (on line 9)

Globals: q (on line 2)

   Code Output

6
hi,bye,bye,bye,bye,bye,bye
6

Two-dimensional arrays

You have already learnt how to use one dimensional arrays in your computer programs. You should be familiar with code such as:

Dim friends(6) As String

friends(0) = "Barry" 
friends(1) = "Monica"
friends(2) = "Xiao"

This is great for storing lists of things, but what about if we want to simulate something more complex such as a game board or a map? Wouldn't it be great if we could use a two-dimensional array?

Most major programming languages allow you to use two-dimensional arrays. They work in much the same way as a one-dimensional array but allow you to specify a column index and a row index.

Treat a 2D array like a grid, the location of a cell is shown above

We can create the two-dimensional array shown above and assign values by doing the following:

Dim grid(4,4) As String

grid(0,3) = "A"
grid(3,2) = "B"
grid(1,4) = "C"
Console.Writeline("The content of 3,2 is:" & grid(3,2))
The code would also output the value B
Example: Two-Dimensional Arrays

Two-dimensional arrays are very useful and a good place to get started is to create your own version of the game Battleships with a 4 cell by 4 cell grid. See if you can win, or even break it!

We are modelling the following board using the two dimensional board variable:

0 1 2 3
0 x o o o
1 o o x o
2 o o o o
3 o o o o
Dim x, y As Integer
Dim board(3, 3) As Char

board(0, 0) = "x"
board(0, 1) = "o"
board(0, 2) = "o"
board(1, 0) = "o"
board(1, 1) = "o"
board(1, 2) = "x"
board(2, 0) = "o"
board(2, 1) = "o"
board(2, 2) = "o"
board(2, 0) = "o"
board(2, 1) = "o"
board(2, 2) = "o"

For z = 1 To 3
	Console.WriteLine("This is guess number " & z)

	Console.Write("please insert you x location:")
	x = Console.ReadLine()
	Console.Write("please insert you y location:")
	y = Console.ReadLine()
	If board(x, y) = "x" Then
		Console.WriteLine("you win!")
	End If
Next
Exercise: Two-Dimensional Arrays
Declare an array to make a small checkers board of type char, 3 squares by 3 squares

Answer:

dim checkBoard(3,3) as char 'also checkBoard(2,2)
create a chequered pattern using b for black and w for white

Answer:

 checkBoard(1, 1) = "b"
 checkBoard(1, 2) = "w"
 checkBoard(1, 3) = "b"
 checkBoard(2, 1) = "w"
 checkBoard(2, 2) = "b"
 checkBoard(2, 3) = "w"
 checkBoard(3, 1) = "b"
 checkBoard(3, 2) = "w"
 checkBoard(3, 3) = "b"

A much smarter way is to use a loop, this will allow for you to quickly create an board of any size you wish. There is a question coming up that will want you to build this!

Write a sub routine to display this board (HINT: you need loops), that takes checkBoard as a parameter

Answer:

sub display(checkBoard())
for x = 1 to 3
   for y = 1 to 3
      console.write(checkBoard(x,y))
   Next
   console.writeline()
Next
Declare a chessBoard (8*8 squares), programmatically colour it in with b for black and w. You might want to look for a pattern in the colour assignments for the checker board above and make friends with the MOD function You might also go a little loopy trying to answer this question

Answer:

dim chessBoard(8,8) as char 'also chessBoard(7,7)

for x = 1 to 8
   for y = 1 to 8
      if (x + y) MOD 2 = 1 then
         chessBoard(x,y) = "w"
      else
         chessBoard(x,y) = "b"
      end if
   next
next

display(chessBoard()) ' using a slightly updated version of the subroutine display()

If you've done this you might want to get the program to print some massive boards, whatever floats your boat.

Using the following two-dimensional array, grid(4,4):
  • Write code to output the name CRAIG
  • Insert MARY on row 2 (the third row)
  • Overwite STEVE with SAM

Answer:

Console.Writeline(grid(3,0) & grid(3,1) & grid(3,2) & grid(3,3) & grid(3,4))
grid(2,0) = "M"
grid(2,1) = "A"
grid(2,2) = "R"
grid(2,3) = "Y"

grid(1,0) = "S"
grid(1,1) = "A" ' you could skip this
grid(1,2) = "M"
grid(1,3) = ""
grid(1,4) = ""

Noughts and Crosses

Another game you might play on a 2D grid is the popular game of noughts and crosses:

Game of tic-tac-toe, won by X
Game of tic-tac-toe, won by X

To do this we need to build a 3 by 3 grid:

Sub main()
    Dim board(3, 3) As Char

    board(1, 1) = "-"
    board(1, 2) = "-"
    board(1, 3) = "-"
    board(2, 1) = "-"
    board(2, 2) = "-"
    board(2, 3) = "-"
    board(3, 1) = "-"
    board(3, 2) = "-"
    board(3, 3) = "-"

  'main game function call to go here
end sub

Next we need a subroutine to display the grid, passing the board as a parameter

Sub display(ByVal b(,) As Char)
	For i = 0 To 3
		For j = 0 To 3
			Console.Write(b(i, j))
		Next

		Console.WriteLine()
	Next
End Sub

We need the ability to check whether the game has been won and who has won it. We'll do this by building a win check that returns true if the specified player has won, or false otherwise. We need to pass it some values to check, namely the board - b() and the player you are checking for - p. Both are passed byVal as we don't need to change them:

Function win(ByVal b(,) As Char, ByVal p As Char)
	If b(1, 1) = p And b(1, 2) = p And b(1, 3) = p Then 'first row check
		Console.WriteLine(p + " WINS!")
		Return True
	ElseIf b(2, 0) = p And b(2, 1) = p And b(2, 2) = p Then 'second row check
		Console.WriteLine(p + " WINS!")
		Return True
	Else
		Return False 'if the game hasn't been won
	End If
	' this needs more rules, it only has 2 at the moment and one of them doesn't work!  Could you use a loop instead?
End Function

It's a bit of a rubbish game so far, so we better let someone move:need the ability for players to play a move:

Sub move(ByRef b(,) As Char, ByVal p As Char)
	Dim x, y As Integer
	Dim move As String
	Console.WriteLine(p + " - make your move in the format: x,y")
	move = Console.ReadLine()
	x = move.Substring(0, 1)
	y = move.Substring(2, 1)
	If b(x, y) = "-" Then
		b(x, y) = p
		display(b)
	Else
		Console.WriteLine("Invalid move!  Miss a turn")
	End If
End Sub

We need to end the game in a draw if all the spaces have been taken

Function drawn(ByVal b(,) As Char)
	Dim c As Integer = 0 ' set a counter to keep track of how many spaces there are
	For i = 0 To 3
		For j = 0 To 3
			If b(i, j) = "-" Then
				c = c + 1
			End If
		Next
	Next

	If c = 9 Then
		Console.WriteLine("Draw, game over!")
		Return True
	Else
		Return False
	End If
End Function

Finally we'll bring everything together

Sub Main()
	'array declaration from earlier...   

	game(board)
	console.readline()
End Sub

Sub game(ByVal b(,) As Char)
	Dim togo As Char
	Do
		If togo = "x" Then
			togo = "o"
		Else
			togo = "x"
		End If

		move(b, togo)
		display(b)
	Loop While Not (win(b, togo)) And Not (drawn(b))
End Sub
Exercise: More Two-Dimensional arrays
Fix the program above so that an incorrect move allows the user to try again:
   Code Output

xxo
o--
---
x - make your move in the format: x,y
1,2
x - make your move in the format: x,y
1,2
x - make your move in the format: x,y

Answer:

sub move(byRef b() As Char, byVal p As Char)
  dim x,y as integer
  dim move as string
  Do 
     console.writeline(p + " - make your move in the format: x,y")
     move = console.readline()
     x = move.Substring(0, 1)
     y = move.Substring(2, 1)
  While  b(x + 1,y + 1) <> "-"
  b(x + 1,y + 1) = p
  display(byVal b())
end sub


Fix the program above so that is checks rows, columns and diagonals for a winning position. Try to keep your answer below 19 lines and 550 characters.

Answer:

function win(ByVal b(,) As Char, byVal p As Char)
  for x = 0 to 2
    if b(x,0) = p AND b(x,1) = p AND b(x,2) = p then 'check columns
     console.writeline(p + " WINS!")
     return true
  next
  for y = 0 to 2
    if b(0,y) = p AND b(1,y) = p AND b(2,y) = p then 'check rows
     console.writeline(p + " WINS!")
     return true
  next
  if b(0,0) = p AND b(1,1) = p AND b(2,2) = p then 'second row check
     console.writeline(p + " WINS!")
     return true
  end if
  if b(0,2) = p AND b(1,1) = p AND b(2,0) = p then 'second row check
     console.writeline(p + " WINS!")
     return true
  end if
  return false 'if the game hasn't been won
end function
Extension: Many more dimensional arrays

You have met one and two dimensional arrays so far, but this isn't the limit to the number of dimensions that you can use. For example you might want to model a three dimensional world by using a 3D array

Dim space(2, 2, 2) As integer ' 3 dimensional array


User-defined data types

You have already met a variety of built-in datatypes with integers, strings, chars and more. But often these limited datatypes aren't enough and a programmer wants to build their own datatypes. Just as an integer is restricted to "a whole number from -2,147,483,648 through 2,147,483,647", user-defined datatypes have limits placed on their use by the programmer.

Enumerated, subrange, sets

Enumerated

If you are using lots of constants in your program that are all related to each other it is a good idea to keep them together using a structure called an Enum. For example you might want to store the names of each set of cards in a deck, instead of writing:

Const heart as integer = 1
Const club as integer = 2
Const spade as integer = 3
Const diamond as integer = 4

dim cardset as string
cardset = spade

We can bring them together in a nice neat structure called an enum:

Enum suits
   HEARTS = 1
   CLUBS = 2
   SPADES = 3
   DIAMONDS = 4
End Enum
dim cardset as suits
cardset = suits.HEARTS

This allows you to set meaningful names to the enum and its members, meaning it it easier to remember and makes your code more readable.

We might also create separate constants to store the points of football results

Const Win as Integer = 3
Const Draw as Integer = 1
Const Lose as Integer = 0

With enums we can create a datatype called Result and store the points within it, under easy to remember name:

Enum Result
    Win = 3
    Lose = 1
    Draw = 0
End Enum

dim ManUvChelsea as Result
ManUvChelsea = Result.Win
Console.Writeline("ManU scored " & ManUvChelsea & " points" )
Exercise: Enumerated types
Declare an enum called months that holds the months along with how many days in each for a non-leap year

Answer:

Enum months
   January = 31
   February = 28
   March = 31
   April = 30
   May = 31
   June = 30
   July = 31
   August = 31
   September = 30
   October = 31
   November = 30
   December = 31
End Enum
What would the following code do:
Enum DayOfWeek
    Monday = 1
    Tuesday = 2
    Wednesday = 3
    Thursday = 4
    Friday = 5
    Saturday = 6
    Sunday = 7
End Enum

Answer:

   Code Output

Records and Fields


Record - a value that contains other values, indexed by names
Field - an element of a record

Records are collections of data items (fields) stored about something. They allow you to combine several data items (or fields) into one variable. An example at your college they will have a database storing a record for each student. This student record would contain fields such as ID, Name and Date of Birth. The following example that DOESN'T USE RECORDS might be simple enough for one student:

   Dim studentID As Integer 
   Dim studentName As String 
   Dim studentDoB As Date
Sub Main()
	Console.write("insert the id: ")
	newStudentid = console.readline()
	console.write("insert the name: ")
	newStudentname = console.readline()
	console.write("insert the Date of Birth: ")
	newStudentDoB = console.readline()

	console.writeline("new record created: " & newStudentid & " " & newStudentname & " " & newStudentDoB)
End Sub

For the following input:

   Code Output

insert the id: 12
insert the name: Nigel
insert the Date of Birth: 12/12/1994
new record created: 12 Nigel 12/12/1994

But what if your college has more than one student, we'd have to write:

   Dim studentID1 As Integer 'field
   Dim studentName1 As String 'field
   Dim studentDoB1 As Date 'field
   Dim studentID2 As Integer 'field
   Dim studentName2 As String 'field
   Dim studentDoB2 As Date 'field
   Dim studentID3 As Integer 'field
   Dim studentName3 As String 'field
   Dim studentDoB3 As Date 'field
   ...
   ...
   Dim studentID2400 As Integer 'field
   Dim studentName400 As String 'field
   Dim studentDoB400 As Date 'field

It would take an awfully long time to declare them all, let alone saving writing data to them. So how do we solve this? Well we need to combine two things we have learnt about so far, the record and the array. We are going to make an array of student records:

    Structure student 'record declaration
        Dim id As Integer 'field
        Dim name As String 'field
        Dim DoB As Date 'field
    End Structure

    Sub Main()
        Dim newStudents(400) As student 'declare an array of student records,  a school with 401 students

        for x = 0 to 400 'insert the details for each student
            Console.WriteLine("insert the id")
            newStudents(x).id = Console.ReadLine()
            Console.WriteLine("insert the name")
            newStudents(x).name = Console.ReadLine()
            Console.WriteLine("insert the Date of Birth")
            newStudents(x).DoB = Console.ReadLine()
        next
        for x = 0 to 400 'print out each student
            Console.WriteLine("new record created: " & newStudents(x).id & " " & newStudents(x).name & " " & newStudents(x).DoB)
        next
    End Sub

This seems to solve our problem, you might want to try it out yourself but decrease the number of students slightly!

Exercise: Records
Declare an record called player to store the following Role Playing Game attributes: health, name, characterclass (barbarian, wizard, elf), gold, gender

Answer:

Enum type
   WIZARD
   BARBARIAN
   ELF
End Enum

Structure player 'remember Visual Basic uses structure instead of record
   name as string
   health as integer
   gold as integer
   gender as char
   ' class as string ' you might have already noticed, the word class is 'reserved'
   ' this means it is has a special purpose in VBNET and we'll have to use another
   characterclass as type 'a string would work, but it's better to use an enum
End player
Creates 2 characters, Gandolf and Conan using the player record

Answer:

'you can of course give them different attributes
Dim Gandolf As player
Gandolf.name = "Gandolf"
Gandolf.health = 70
Gandolf.gold = 50
Gandolf.gender = "m"
Gandolf.characterclass = type.WIZARD

Dim Conan As player
Conan.name = "Conan"
Conan.health = 100
Conan.gold = 30
Conan.gender = "m"
Conan.characterclass = type.BARBARIAN

However, what use is a program that only saves all the students for as long as it is running? We need to know how to write to files, and read the data back, we'll look at that in the next chapter.

Extension: Object Orientation

It's pretty cool creating your own datatypes where you can set up collections of attributes (fields), but it would be even cooler if you could store custom procedures and functions as well. This is where Object Orientation comes in. It's a very common way of writing code with many of the world's most popular languages (Java, C++, C#, Python) making use of it. You'll learn a lot more about it in A2 but there is nothing to stop you getting started now.

File handling

Donkey Kong wiped your top score when you turned it off!

Early Arcade machines stored your high scores, but as soon as you turned the machine off then all the scores were wiped! Nowadays it is unthinkable to have a game where you don't save scores, trophies, achievements or your progress. Writing to files allows people to do this alongside all the other essential file writing such as saving text documents, music and images.

Another use of files is reading data into your program: think about when you load a saved game, or open a spreadsheet. Both of these things involve reading a file.

Files might have lots of strange file extensions like .doc .txt .html .css .odt. In fact there are thousands of them and they tell the Operating System what program to use to read the file. However, if you open each file with a text editor such as notepad++ you might be able to see underlying structure of the file. Some of them will be plain text and some of them gobbledygook. We are going to learn how to read and write data directly to these files.

firefox.exe file.rtf
MZ NULETXNULNULNULEOTNULNULNUL��NUL

NUL,NULNULNULNULNULNULNUL@NULNULNUL NULNULNULNULNULNULNULNULNULNULNULNUL NULNULNULNULNULNULNULNULSOHNULNUL SOUSºSONUL´ Í!¸SOHLÍ!This program cannot be run in DOS mode.

{\rtf1\ansi\ansicpg1252\uc0\stshfdbch0 \stshfloch0\stshfhich0\stshfbi0\deff0 \adeff0{\fonttbl{\f0\froman\fcharset0 \fprq2{\*\panose 02020603050405020304} Times New Roman;}{\f1\froman\fcharset2 \fprq2{\*\panose 05050102010706020507} Symbol;}
As you can see the firefox.exe file is almost impossible to read in a text editor, but there are some recognisable strings in there file.rtf is much clearer to read

When using text files, you read or write one line of text at a time as a string

Reading files

A common function needed in programs is to load data: saved games, text documents, spreadsheets.

Example: Reading from a text file

The following programs show how to open and read from a text (.txt) file

VB.NET

To do this you'll need the StreamReader, a collection of functions used to read data from files into our program. To get this program to work you are going to need a file called myfile.txt and put it into a location you know the full address of, for example the root of the C:\ drive:

'you might need this so that you can use StreamReader
Imports System.IO
Module Module1
    Sub Main()
        Dim filereader As StreamReader
        Dim filename As String

        Console.Write("name of file to load:")
        filename = Console.ReadLine() 'this must be the full path of the file and the file extension
        filereader = New StreamReader(filename)
        Console.WriteLine("contents of file:")
        Console.WriteLine(filereader.ReadToEnd()) 'write the whole file
        'you can also use line = filereader.ReadLine() to read a single line

        filereader.Close()
    End Sub
End Module

The above code would produce the following:

   Code Output

name of file to load: C:/belloc.txt
contents of file:
To sleep and smell the incense of the tar,
To wake and watch Italian dawns aglow
And underneath the branch a single star,
Good Lord, how little wealthy people know.


Python 3

To get this program to work you are going to need a file called myfile.txt and put it into a location you know the full address of, for example the root of the C:\ drive. Alternatively placing the text file in the same directory as your python program means you only need to specify the file name:

filename = input("name of file to load: ")

textFile = open(filename,"r")
content = textFile.read()
textFile.close()

print("Contents of file:")
print(content)

The above code would produce the following:

   Code Output

Name of file to load: C:/belloc.txt
Contents of file:
To sleep and smell the incense of the tar,
To wake and watch Italian dawns aglow
And underneath the branch a single star,
Good Lord, how little wealthy people know.


Writing files

As well as reading files it's important that we can write to files.

Example: Writing to a text file

The following programs show how to open and write to a text (.txt) file. Note that doing this will overwrite existing files of the same name without warning!

VB.NET

This time we are using the StreamWriter:

'you might need this so that you can use StreamReader
Imports System.IO

Module Module1
    Sub Main()
        Dim filewriter As StreamWriter
        Dim filename As String
        Dim texttofile As String

        filename = "C:/test1.txt" 'this is the location, file name and extension of what you are writing to.
        filewriter = New StreamWriter(filename)
        texttofile = Console.ReadLine

        filewriter.WriteLine(texttofile) 'write the line to the file
        filewriter.Close()
    End Sub
End Module


Python 3

filename = "C:/test1.txt" #this is the location, file name and extension of what you are writing to

textToFile = input()

textFile = open(filename,"w") #opens the file for write "w" access
textFile.write(textToFile) #writes the line to the file
textFile.close()


Exercise: Reading and Writing Files
write code to save a shopping list typed in by a user (they finish typing the list by entering a blank line) to a file called specified by the user

VB.NET answer

Answer:

Imports System.IO

Dim filewriter As StreamWriter
Dim filename As String
Dim texttofile As String
Dim line As String

Console.Writeline("Please insert your shopping list:")
While line <> ""
   line = Console.ReadLine()
   If line <> "" Then
      texttofile = texttofile + line
   End If
End While

Console.Writeline("Where would you like to save it (give full location):")

filename = Console.Readline()
filewriter = New StreamWriter(filename)
filewriter.WriteLine(texttofile) 'write the line to the file

filewriter.Close()

Python 3 answer

Answer:

textToFile = ""

line = input("Please insert your shopping list:\n")

while line != "":
    textToFile = textToFile + line + "\n"
    line = input()

filename = input("Where would you like to save it (give full location):\n")

textFile = open(filename,"w")
textFile.write(textToFile)
textFile.close()
What does the extension of a file change about a file?

Answer:

It only changes how a program or an Operating System handles the file, it doesn't change anything inside the file

CSV

A special sort of file is a Comma Separated Value (.csv) file. This file is used for store spreadsheet information with each comma denoting a new cell, and each new line a new row. For example in the code below there are three columns and three rows. If you need to include a comma in a cell you have to encase the cell text in speech marks

ID, name, DoB, Comment
1, Peter, 12/12/12, Nice person
2, Simon, 13/13/13, "Must try harder, or he will fail"

This would produce:

ID name DoB Comment
1 Peter 12/12/82 Nice person
2 Simon 13/09/73 Must try harder, or he will fail

You might notice that .csv files are very simple and don't store any information on datatypes or style. So if you were to save your spreadsheet in Microsoft Excel as a .csv file you would lose all this information. In general .csv files are a small and simple way to transfer data.

Exercise: CSV
write a CSV file to hold the following table structure
POBOX Company Description
223 Computering Co. badly spelt, slight smell.
657 Acme Deals in everything.

Answer:

POBOX,Company,Description
223,Computering Co.,"badly spelt, slight smell"
657,Acme,Deals in everything.


File of records

When stored as (.csv), each line of a file is a data record. Each record consists of one or more fields, separated by commas. You should be able to move data between a 2d array and a csv file. The following code gives you an example of how to do this.

Example: Writing to a text file

Creating a .csv file from a 2d array.

Python 3

This example uses ",".join(inner). Join is a method of a string in python. It takes an array of strings and joins them into a single string using (in this case) a comma as glue. Note that if your array contains any non-string data types, this will not work and you will need to convert the elements of your array into strings first.

# mainArray contains the headers and 3 records for a database

mainArray = [["Name","Age","Favourite Fruit"],
             ["Alice","23","Apple"],
             ["Bob","34","Banana"],
             ["Claire","45","Cherry"]]

outputArray = []    #empty array. Each element will contain one line of csv data

for inner in mainArray:
    csvLine = ",".join(inner)       #each inner array (record) is turned into a single string
    csvLine = csvLine+"\n"          #a newline character is added to the end
    outputArray.append(csvLine)     #the finished string is appended to the output array

outFile = open("C:\database.csv",mode="w")
outFile.writelines(outputArray)     #outputArray written in one go to C:\database.csv
outFile.close()

Reading a .csv file into a 2d array

Python 3

Note that readlines() reads a text file into a one dimensional array of text. Each line from the original text file becomes a unique element in that array and includes the \n character from the end of each line.

inFile = open("database.csv",mode="r")
csvLines = inFile.readlines()   #csv file read into a 1d array
inFile.close()

mainArray = []                  #empty array defined        

for line in csvLines:
    line = line.strip()         #removes \n character from end of line
    inner = line.split(",")     #line is split into an array "inner"
    mainArray.append(inner)     #inner array appended into mainArray
Exercise: CSV File access
Write a program that asks you for the names, email and mobile phone number of your friends then writes them into a csv file.

Python 3 answer

Answer:

looping = ""
outputArray = []

while looping != "n":
    forename = input("Forename :")
    surname = input("Surname  :")
    email = input("Email    :")
    mobile = input("Mobile   :")

    csvLine = forename + "," + surname + "," + email + "," + mobile + "\n"
    outputArray.append(csvLine)
    
    looping = input("Hit enter to add another, enter n to stop")

op = open("friends.csv",mode="w")
op.writelines(outputArray)
op.close()
Write a program that reads the .csv file from the question above into a 2d array.

Python 3 answer

Answer:

inFile = open("friends.csv",mode="r")
csvLines = inFile.readlines()
inFile.close()

friends = []

for line in csvLines:
    line = line.strip()
    innerArray = line.split(",")
    friends.append(innerArray)
Extension: CSV Files

Write a program which extends the tasks above allowing you to maintain a friends list. You could include features such as searching for, adding, editing and deleting friends.

Extension: XML

A lot of modern programs and data formats such as LibreOffice and .odf use XML to store data, then compress the data to make the files smaller. XML is very similar to HMTL and SVG in that is uses tags, but the great thing about it is that you define what each tag is. Take a look at this example:

<?xml version="1.0"?>
<school>
  <class name="UCOM2">
    <student>
      <name>Omer</name>
      <age>12</age>
    </student>
    <student>
      <name>Sandra</name>
      <age>12</age>
    </student>
  </class>
</school>

XML has become increasingly important, especially with regards to the internet, if you want to learn more you can check out the tutorial at w3schools.

However there are people who hate XML: the files it makes are generally quite large, having to store all that tag information and when the internet is involved speed is often of the essence. A leaner way of sending data from one place to another is JSON which you can also find out about at w3schools.


Validation

Error types

When you write a program it often won't work as you expect. It might not compile, it might crash when you run it, or it might give you the wrong result. These are all errors with your code and we can place them into 3 different error categories:

  • Compilation Errors
  • Run-time Errors
  • Logic Errors

Let's take a look at what each of them mean.

Compilation (Syntax) error

You have probably met this error a lot, when you try and run your program it won't compile, giving you an error message. If you are using something like Visual Studio it will even underline the problem code with a blue squiggly line. There is a problem with the structure, or syntax, of the code that you have written. This might be a situation where you have forgotten to add a closing bracket or you have misspelt a key word. Take a look at this example:

For x = 1 two 9
  console.WriteLine(x)
Next

You should be able to see that in line 1 the programmer has misspelt the word to. This code won't work at all.

Run-time error

Sometimes you will have a program that compiles fine, but breaks when you actually run it. For example this code here:

Dim x as integer = 0
Dim total as integer = 0
While x < 5
  total = total + 1
Loop

The programmer has created an infinite loop, and the value of total will head towards infinity, eventually breaking the program.

Logic (Semantic) error

A logic error is when a program compiles, doesn't crash, but the answers that it gives are incorrect. The logic, semantics or meaning, conveyed by the code is wrong. Take a look at the next example:

Dim Price as decimal = 45.99
Dim Tax as decimal = 0.20

Console.Writeline("Price {{=}} " & Price)
Console.Writeline("VAT {{=}} " & Price * Tax)
Console.Writeline("Total {{=}} " & Price + Tax)

In the above example you would expect it to print out:

   Code Output
Price = 45.99
VAT = 9.198
Total = 55.188

But because there is a logic error on line 6, it prints:

   Code Output
Price = 45.99
VAT = 9.198
Total = 46.19

To fix it, you have to fix the logic of the code and change line 6 to:

Console.Writeline("Total = " & Price + (Price * Tax))
Exercise: Exception Handling

Name and give examples of the three error types in programming code:

Answer:

  • Compilation (Syntax)
  • Logic (Symantic)
  • Runtime


What error is in the following code, how would you fix it:

dim x as integer
do until x > 5
  x = 1
  x = x + 1
loop

Answer:

There is a Runtime error. x will never be greater than 5, since line 3 gives x the value of 1, thus, the loop will always end in 2 and the loop will never end. This could be fixed by moving the x = 1 instruction outside the loop, between line 1 and 2.


What error is in the following code, how would you fix it:

dim n as sting
console.writeline("enter your name")
n = console.readline

Answer:

The first line has a compilation (syntax) error. dim n as sting should read dim n as string


What error is in the following code, how would you fix it:

Dim names() As String = {"Harry", "Dave", "Princess", "Nicky"}
'print all the names
For x = 1 to 3
   Console.Writeline("name " & x & " = " & names(x))
Next

Answer:

The third line has a Logic (semantic) error. For x = 1 to 3 should read For x = 0 to 3


What error is in the following code, how would you fix it:

Dim names() As Sting = {"Harry", "Dave", "Princess", "Nicky"}
Dim y As Integer
y = Console.Readline()
'print some of the names
For x = 0 to y
   Console.Writeline("name " & x & " = " & names(x))
Next

Answer:

Line 1 has a compilation error, Sting should read String. There is also a potential Runtime error on line 5, if the user inputs a value of y that is greater than 3 then the code will break. Errors like these can be solved in a number of ways, we are going to look at one now.


Catching errors

Dim age as integer
console.writeline("How old are you?")
age = console.readline()
console.writeline("What is your name?")

For the above code we can easily break it if we type the following:

   Code Output

How old are you?
cabbages!

The reason, as you should already be aware, is that variable age is an integer and you are trying to save the string cabbages into an integer. It's like trying to fit a cannon into a camel, they just aren't compatible, and VB will definitely complain ruining all your code. What is needed is a way in which we can stop or catch these errors, we are going to take a look at try and catch.

Dim age as integer
console.writeline("How old are you?")
Try
  age = console.readline()
Catch ex As Exception
  console.writeline(ex.message)
End Try
console.writeline("What is your name?")

This will deal with the issue:

   Code Output

How old are you?
Socrates!
Conversion from string "Socrates!" to type 'Integer' is not valid.
What is your name?

Letting us know that you're put a string in when it was expecting an integer. The program doesn't crash.

Exercise: Exception Handling
Use a try and catch to avoid the issue of a person inputting a value for y that would break the array.
Dim names() As String = {"Harry", "Dave", "Princess", "Nicky"}
Dim y As Integer
y = Console.Readline()
'print some of the names
For x = 0 to y
   Console.Writeline("name " & x & " = " & names(x))
Next

Answer:

Dim names() As String = {"Harry", "Dave", "Princess", "Nicky"}
Dim y As Integer
y = Console.Readline()
'print some of the names
Try
   For x = 0 to y
      Console.Writeline("name " & x & " = " & names(x))
   Next
Catch ex As Exception
   console.writeline("Looks like we're exceeded our array index")
   console.writeline(ex.message)
End Try


The role of variables

As we have seen variables can play a very important role in creating programs and especially when executing loops. The roles of these variables can be categorised into several types:

Type Description Examples
fixed value A variable that is given a value that then does not change for a duration of a loop This might be an upper or lower bounds that the array is tending towards
stepper A variable used to move through an array or other data structure, often heading towards a fixed value and stepping through elements in an array Stepping through the values in an array, or outputting a certain number of lines of text
most recent holder A variable used to record the last thing inserted by a user or the latest value being read from an array input = console.readline() or getting the next value from an array
gatherer A variable that accumulates or tallies up set of data and inputs. It is very useful for calculating totals or totals that will be used to calculate averages. the total of ages of students in a class, the scores or batsmen in a cricket game, tally UMS points for an A-Level student or tell you the combined price of all the objects in your shopping basket
Example: fixed value / stepper / most recent holder
dim fixedvalue as integer = 10
for stepper = 1 to fixedvalue
  console.writeline("the stepper value is : " & stepper & " and the fixed value is : " & fixedvalue)
next

in the above code it is easy to see the use of a fixed value and a stepper. Let's look at a more complicated example:

dim totalnum as integer = 10
dim t as integer = 0
dim input as integer
console.writeline("The following loop will collect 10 values and gather them together:")
for x = 1 to totalnum
  console.writeline("the stepper value is : " & x & " the fixed value is : " & totalnum )
  console.writeline("please insert a value:")
  input = console.readline()
  t = t + input 
  console.writeline("so far we have gathered numbers totalling:" & t)
next

In the above code you can see the various roles of variables in collecting together 10 inputs and adding them all together (gathering):

Variable Role
totalnum fixed value
x stepper
t gatherer
input most recent holder
Type Description Examples
most wanted holder A variable that keeps track of the lowest or highest value in a set of inputs calculating the top scorer in a football team, the lowest score in an exam and the highest number of pied wag tails seen by a bird watcher in a particular year
follower used to keep check of a previous value of a variable, so that a new value can be compared followers are often used when sorting arrays, in routines such as bubble or insertion sort
temporary A variable used for storing something for a very short period of time temporary variables are often used for swapping values between other variables
transformation used to store the result of a calculation involving more than one variable transformation variables are used to calculate such things as compound interest
Example:most wanted holder / transformation / follower / temporary
dim scores() as integer = {12,32,43,2,11,23,7,9}
dim mostwantedholder as integer = 0
for c = 0 to 7
  if scores(c) > mostwantedholder then
    mostwantedholder = scores(c)
  end if 
next
console.writeline("the highest score is: " & mostwantedholder)

In the code above you can see the use of the most wanted holder to store the maximum value from an array of numbers. As you cycle through each item in the array (using the stepper c), you update the mostwantedholder to store the maximum value that you come across. Let's take a look at a more complex example

dim scores() as integer = {12,32,43,2,11,23,7,9}
dim temp, prev as integer
dim arLen as integer = 7
dim mostwantedholder as integer = 0

for c = 1 to arLen
  prev = scores(c-1)
  if prev > scores(c) then
    temp = prev
    prev = scores(c)
    scores(c) = temp
  end if
next

The code above describes a single pass of bubble sort. Using the temporary variable, temp, we bubble the largest array value to the top of the array, by comparing the current array value (scores(c)) and the follower prev. In summary:

Variable Role
temp temporary
prev follower
arLen fixed value
c stepper

Finally let's look at an example of a transformation, we have used lots of loops so far, but variables certainly aren't only used in loops:

Const pi as single = 3.14
dim r as single
dim a, c as single
console.write("insert the radius: ")
r = console.readline()
a = pi * r * r
console.writeline("area = " & a)
c = 2 * pi * r
console.writeline("circumference = " & c)

In the code above there are two transform variables a and c.

Exercise: Role of Variables
dim numCats as integer = 9
for x = 1 to numCats
  console.writeline("cat number :" & x & " says meow!")
next

For the above code name the role of each of the following variables:

Variable Role
x
numCats

Answer:

Variable Role
x stepper
numCats fixed value
dim total, highest, avg, current as integer = 0
dim max as integer = 10
console.writeline("insert " & max  & " numbers:")
for count = 1 to max
  current = console.readline()
  total = total + current
  avg = total / count
  if current > highest then
    highest = current
  end if
next

For the above code name the variables that act as a:

Role Variable
transformation
most wanted holder
most recent holder
gatherer
fixed value
stepper

Answer:

Role Variable
transformation avg
most wanted holder highest
most recent holder current
gatherer total
fixed value max
stepper count
Extension: Other Roles

The roles you see here are included in the syllabus and it is very likely that they will be examined. There are several other roles out there which aren't covered here, these include:

  • one-way flag
  • organizer
  • container
  • walker

You can find out more about them here

Fundamentals of structured programming

You should already have seen how you can use structure tables, structure charts, hierarchy charts and procedures/functions in breaking down a complex task. This section will look at how to write the best formed and most readable code we can.

If you want to be a good programmer (and get good marks in the exam) then you have to make sure that your code is easily read by other people. There are several things you should try and do when coding:

Use procedures that execute a single task

Each procedure / Function does a single thing, such as calculate the current health of a player in a game. This means you can then use them as building blocks to build bigger solutions. If you make your procedures / functions do too many things at once, then they are very hard to re-use in different projects and difficult to test.

Use procedures/functions with interfaces

  • Breaks the problem into chunks
  • You can test each separately
  • You can reuse code

Use sensible variable datatypes

Make sure that the datatype you use are sensible. You will get marked down for using the wrong datatypes in your database tables and variables.

For example: If you are recording the total number of chocolate bars in a shop you don't need to use a Long or Float, you can only have whole numbers of chocolate bars and it is unlikely you'll have over a few million items. Use an Integer!

Meaningful identifier names

When you are declaring parts of your program and you return to the code some time later, you want to be able to understand what each variable, procedure and function does without having to trace out the code. The easiest way to start doing this is to name them correctly:

Use sensible variable names

If you are using variables to store things they must have a name that makes sense so you know what it does when you read its name in your code.

For example: If you are recording the total number of chocolate bars in a shop you don't want to use a name like variable1. What does variable1 mean? Use a sensible name such as NumChoc.

Use sensible Function/Procedure names

If you are creating subroutines to process things in your code make sure you give them a sensible name so that people know what they are doing when they see them in the code.

For example: If you have written a piece of code to calculate the average price of a chocolate bar then don't call it FunctionA(), what does FunctionA() mean?! Call it ChocAverage().

Try to stick to one naming convention

If you are using lots of variable names and function names, stick to a single style for naming them. If you use lots of different conventions things are going to look ugly. Wikipedia guidance

For example:

  • firstName, lastName, calculateDoB, numLegs
  • FirstName, LastName, CalculateDoB, NumLegs
  • First_Name, Last_Name, Calculate_DoB, Num_Legs

Don't make your names too long

Long variables can be very hard to read and much easier for you to make mistakes when writing them, try to shorten things where possible.

For example:

Too Long Just Right
ThisIsYourFirstName FirstName
the_value_of_a_chocolate_bar ChocVal

Indent your work

A lot of programming environments help to indent your code automatically and you should be able to find one for the language you are using. Indenting helps people to read and understand your code quickly as it clearly shows the structure of functions, procedures, selection and iteration statements. For example the following is very hard to read:

int main(int argc, char *argv[])
{
...
while (x == y) {
something();
somethingelse();
if (some_error)
do_correct();
else
continue_as_usual();
}
finalthing();
...
}

If you indent it is becomes much easier to read:

int main(int argc, char *argv[])
{
    ...
    while (x == y) {
        something();
        somethingelse();
        if (some_error)
            do_correct();
        else
            continue_as_usual();
    }
    finalthing();
    ...
}

Use comments where necessary

Some of the best written code doesn't need comments because if you have structured it correctly and used all the proper naming conventions it should be pretty easy to read. However for the code you are writing you should put some comments to explain what each section does.

'this function takes an array of prices and outputs the average
function calculateAverage(num1(20) as integer)
{
    'add all the numbers together
    while ...
          ...
          ...
    end while
    
    console.writeline(average)
}

The advantages of the structured approach

  • Easy to read and fix code
  • Problems broken down into easy to manage chunks
  • procedures / functions are reusable, you can use them in different projects.
  • You can test modules individually
Exercise: Structured programming
sub calcEverything(byref a as integer, byref b as integer, byref c as integer)
  dim total, avg as integer
  total = a + b + c
  console.writeline("the total of inputs = " & total)
  avg = total / 3
  console.writeline("the average of inputs = " & avg)
end sub

What might be considered wrong about the use of the subroutine above? How could it be fixed?

Answer:

The sub routine is performing multiple function: it calculates the total AND the average. Functions/procedures should only perform one task at a time. You could replace the above with two subroutines:

  • calcAvg(...)
  • calcTotal(...)

List three reasons for using functions and procedures to structure your code

Answer:

  • You can re-use the code
  • You can test parts of the code individually
  • The code is easier to read and understand
dim ppdpdp as string
dim cheesy as integer
console.write("hello, please insert your name: ")
ppdpdp = console.readline()
console.write("hello, please insert your age: ")
cheesy = console.readline
if ppdpdp = "Dave" then
if cheesy = 23
console.write("daisy, daisy...")
else
console.write("I'm sorry dave")
end if
else
console.write("Get off my spaceship")
end if

Give three structured programming techniques that could be used to improve the code above:

Answer:

  • proper use of indentation
  • sensible variables names (why on earth have they used cheesy to store the age, why not use age?)
  • use comments


Modulo arithmetic

Modular arithmetic is all about finding the remainder from long division (MOD), and the total number of times that a number goes into a division (DIV). Let's take a look at a quick example of 10 divided by 7 (you might want to remind yourself about long division):

    1 r 3
 7)10
    7
    3

Hopefully that wasn't too hard. We now need to introduce some terminology, MOD and DIV:

  • MOD = finds the remainder from long division i.e. 10 MOD 7 = 3
  • DIV = finds the number of divides in long division i.e. 10 DIV 7 = 1
Exercise: MOD and DIV
Try these examples, working out the MOD and DIV of each: 7 / 2

Answer:

MOD = 1 DIV = 3

17 / 5

Answer:

MOD = 2 DIV = 3

8 / 2

Answer:

MOD = 0 DIV = 4

6 / 9

Answer:

MOD = 6 DIV = 0 (9 does not divide into 6 at all!)

Now try these explicit calculations: 11 MOD 8

Answer:

= 3

8 MOD 4

Answer:

= 0

6 DIV 5

Answer:

= 1

600 DIV 20

Answer:

= 30

Hopefully you are now pretty good with MOD and DIV, but what exactly is the point of all this? A very common example in past exam paper has been using the MOD and DIV to work out a binary equivalent of a denary number.

Example: Converting Denary to Binary using DIV
sub convertDtoB(byVal base10 as integer)
  dim base2(7) as integer 'create an array to store the binary
  dim temp as integer = base10
  for i = 7 to 0 step -1 'loop through each binary bit starting from the biggest value
    base2(i) =  temp \ (2^i)  'temp DIV 2^i
    temp = temp MOD 2^i
  next
  console.write(base10 & " in binary = ")
  for i = 7 to 0 step -1 'loop through each binary bit starting from the biggest value
    console.write(base2(i))
  next
end sub

Try the code out and see if it works. Try to write a trace table and see how it works for the number 67 (again another popular question in exams):

Answer:

base10 temp 2^i i base2
0 1 2 3 4 5 6 7
67 67
128 7 0
3 64 6 1
32 5 0
16 4 0
8 3 0
4 2 0
1 2 1 1
0 1 0 1

Output:

67 in binary = 01000011

Another common use is in finding out whether a number is odd or even using the MOD function. We know that MOD returns the remainder from a division sum. So for example 4 MOD 2 = 0, 5 MOD 2 = 1, 6 MOD 2 = 0 and so on. By modding something with 2 we can work out whether it is odd or not due to the return value.

Example: Finding out if a number is Odd using MOD
Dim testNum as Integer
Dim temp as Integer
console.writeline("please insert a number to test:")
testNum = console.readline()
If testNum MOD 2 = 0 Then
  Console.Writeline("The number is even")
Else
  Console.Writeline("The number is odd")
End If

Logical bitwise operators

As you have probably discovered already, converting a positive binary number into a negative binary number involves changing bits. As does converting a capital ASCII letter into a lower case ASCII letter. How exactly does a computer perform this action? The answer lies with bitwise operators:

Bitwise Operator NOT() AND() OR() XOR()
Description invert input where exactly two 1s where one or more 1s where exactly one 1
Input 01001010 01001010 01001010 01001010
Input 11110000 11110000 11110000
Output 10110101 01000000 11111010 10111010

So how can we use these for useful tasks in a computer? If we look closer at the examples above we can see that setting Input 2 bits to 1s or 0s has a direct inpact on the Output. We'll call Input 2 a mask, and we apply this mask to change the values in Input 1 in certain ways. Consider these questions about Masks:

  • If we have an AND mask bit as 0 what is the output in all cases?
  • If we have an AND mask bit as 1 what is the output in all cases?
  • If we have an OR mask bit as 0 what is the output in all cases?
  • If we have an OR mask bit as 1 what is the output in all cases?
  • If we have an XOR mask bit as 0 what is the output in all cases?
  • If we have an XOR mask bit as 1 what is the output in all cases?

In summary:

AND OR XOR
0 clears the value retains the value retains the value
1 retains the value sets the value inverts the value
uses setting chosen bits to 0 setting chosen bits to 1 inverting chosen bits, finding differences between bit sets
Exercise:Bitwise operators
So know we know how each Bitwise Operator works we can use them with masks to calculate things: Input data 11011011, I want an output with bits 4 and 5 set to 0 and I don't care about the others. (???00???)

Answer:

By using an AND I can set bits to 0 and keep other bits. The mask I need is :11100111

Input data 11011011, I want an output with bits 1 and 8 set to 1 and I don't care about the others. (1??????1)

Answer:

By using an OR I can set bits to 1 and keep other bits. The mask I need is :10000001

Input data 11011011, I want an output with bits 3,4,5,6 set to 1, bits 1 and 8 set to 0 and I don't care about the others. (0?1111?0)

Answer:

AND: 01111110 followed by
OR: 00111100

Alternatively:

XOR: 10100101

This might all sound a little academic, what are the actual practical uses of this? Take a look at the following:

Example: Turning a positive binary integer into a negative

We are going to convert the number 37 into -37

37 = 00100101

1. Flip the number by XORing it

    00100101
 XOR11111111
  = 11011010

2. Add 1

  11011010
+ 00000001
  11011011 = -37
Example: Finding a lowercase ASCII letter

We are going to find out the how to convert any Upper case ASCII value into its lower case equivalent. First lets find out the difference between two letters, we'll look at 'P' and 'p', and 'A' and 'a':

P: 01010000
p: 01110000
A: 01000001
a: 01100001

You can probably work out the difference by looking at them, but let's use a XOR to make sure:

    01010000 (P)
XOR 01110000 (p)
    00100000 (difference)
    01000001 (A)
XOR 01100001 (a)
    00100000 (difference)

We can clearly see that it is the 6th bit that defines whether a number is upper case (not set) or lower case (set). Now let's apply this rule to see if it works:

If given the letter g what is the upper case ASCII value?
g = 01100111
We know that all we have to do is get rid of the 6th bit.  But how can we perform this?
By using an AND mask, to return all the bits excluding the 6th:
    01100111 (g)
AND 11011111(mask)
    01000111 (G)
Exercise: Masks
For the example above we can also do this by using a XOR, can you find out how?

Answer:

    01100111 (g)
XOR 00100000(mask)
    01000111 (G)

What about converting an upper-case letter into a lower-case letter, try with X (01011000), you can't use AND what can you use?

Answer:

   01011000(X)
OR 00100000 (mask)
   01111000(x)

Programming

You can program logical bitwise operators to change the case of letters and even encrypt messages. Unfortunately it isn't always possible to play around with binary digits and you may have to work with decimals instead. Let's take a look an an example using an AND:

We know that 3 = 011 and 5 = 101.  If we AND the two together we get:
011 (3)
101 (5)
===
001 (1)

Let's check:

Console.Writeline(3 AND 5)
   Code Output

1

You can also use NOT, XOR, NOT and any combination of them. Let's look at a slightly more interesting example:

Example: Bitwise programming

We are going to write a short program to swap the case of a sentence that you input, for example, if you typed:

   Code Output

The Cat sat on the Matt
converting...
tHE cAT SAT ON THE mATT

Dim sentence As String
Dim converted As String = ""
sentence = Console.ReadLine()
Console.WriteLine("converting...")
For x = 0 To sentence.Length - 1
   'as the 6th binary digit defines upper and lower case
   'mask with 000100000
   converted += Chr(Asc(sentence.Substring(x, 1)) Xor 32) 
Next
Console.WriteLine(converted)
Exercise: Bitwise programming
Program a bitwise mask that will flip the 2nd and 5th binary bits of each letter of an entered sentence to convert it into a secret code:

Answer:

Dim sentence, converted As String
sentence = Console.Readline()
Console.Writeline("converting...")
For x = 0 to sentence.Length - 1
   'as 2nd and 5th = 00010010
   converted += Chr(Asc(sentence.Substring(x,1)) XOR 18)
Next
Console.Writeline(converted)

Write code that uses bitwise operators to display whether an input number is a Odd or Even. For example if the user inputs 9, the program should output 1. If they input 64 it should output 0

Answer:

Dim input As Integer
input = Console.Readline()
Console.Writeline("converting...")
Console.Writeline(input AND 00000001)


Set operators

Basic set understanding

Sets describe collections of things or values, such as numbers, animals or people.

In a set, each value occurs only once. For example, the value fox will occur only once in the set of animals. Just as the value 3 occurs only once in the element of all natural numbers, N.

The cardinality of a set refers to the number of elements it contains.

An empty set is written ∅ and its cardinality is 0.

Sets may be finite or infinite. For example, the set of people currently alive in the world will be finite, but the set of N is infinite.

A set may be countable or uncountable. A countable set is a set, whose elements can be matched with the set of natural numbers. In other words, it is possible to count the elements one-by-one. If a set is finite, it will always be countable. The best example of an uncountable set is R. It is impossible to match each element of R with an element of N. This is because there are not enough elements in N to match each one with an element of R.

Membership ∈ and its reverse ∉

x ∈ S, x is an element of S.

Examples:

  • x ∈ ℕ, meaning that x is an element of the set of natural numbers. For example, 3 ∈ ℕ. Whereas 3.5 ∉ ℕ
  • x ∈ Q, meaning that x is an element of the set of rational numbers. Whereas pi ∉ Q
  • x ∈ WorkingDays, meaning that x is an element of the set of all WorkingDays. For example, Monday ∈ WorkingDays. Whereas Saturday ∉ WorkingDays
  • x ∈ WeekendDays, meaning that x is an element of the set of all WeekendDays. For example, Saturday ∈ WeekendDays. Whereas Monday ∉ WeekendDays
Questions relating to membership and basic understanding

Using set notation, state that Sunday is a weekend day.

Answer:

Sunday ∈ WeekendDays

Using set notation, state that Monday is not a weekend day.

Answer:

Monday ∉ WeekendDays

What is the cardinality of the set WeekendDays.

Answer:

2

Let set A be the set of all atoms in the world. Which of the following words can be used to describe this set? Countable, uncountable, finite, infinite.

Answer:

Countable, finite.

Let set P be the set of all prime numbers. Which of the following words can be used to describe this set? Countable, uncountable, finite, infinite.

Answer:

Countable, infinite.

Union

The union of two sets:

A ∪ B, meaning that all elements of the set A form a union with all of the elements in set B. This is a set comprehension, since this generates a new set.

Examples:

  • Q ∪ Irrational Number Set, meaning that all numbers in the set of rational numbers form a union with the set of all irrational numbers. This set comprehension generates the set of real numbers.
  • WorkingDays ∪ WeekendDays, meaning that all of the working days (elements of WorkingDays) form a union with weekend days (elements of WeekendDays). This set comprehension generates the set of WeekDays.
  • {1, 2} ∪ {2,3,4} = {1,2,3,4} (notice that only once instance of 2 is in the resulting set)
  • {1, 2, green} ∪ {red, white, green}={1, 2, red, white, green}
  • {1, 2} ∪ {1, 2} = {1, 2}
Questions relating to union

Let A = {0,2,4,6,8,10,12}

and B = {0,3,6,9,12}.

Write out all elements of A ∪ B

Answer:

{0,2,3,4,6,8,9,10,12}

{3,4} ∪ B

Answer:

={0,3,4,6,9,12}.

A ∪ {7,13,red}

Answer:

={0,2,4,6,7,8,10,12,13,red}.

B ∪ B

Answer:

={0,3,6,9,12}.

Intersection

The intersection of two sets:

A ∩ B, meaning that the set A and set B form an intersection. The generated set will be ∅, if the two sets share no elements.

Examples:

Let A be the set of numbers which are divisible by 3 and B the set of numbers divisible by 4.

  • A ∩ B, meaning that A and B form an intersection, which generates a set, which contains all of the numbers divisible by 3 and 4.
  • WorkingDays ∩ WeekendDays, meaning that WorkingDays and WeekendDays form an intersection, which is ∅

Now let A be the set of all A-level students who take computer science and B the set of all A-level students who take mathematics.

  • A ∩ B, meaning that A and B form an intersection, which generates a set, which contains all students who take both computer science and mathematics.
  • {1, 2, 3} ∩ {2, 3, 4} = {2, 3}
  • {1, 2, 3} ∩ {bear,hen,squirrel} = Ø (this means an empty set)
  • {cat, dog, canary} ∩ {wolf, canary, whale, cat} = {cat, canary}
Questions relating to intersection

As above,

let A = {0,2,4,6,8,10,12}

and B = {0,3,6,9,12}.

A ∩ B =

Answer:

{0,6,12}

A ∩ {goat,4,6,9} =

Answer:

{4,6}

A ∩ {goat,3,9} =

Answer:

It has no intersected values (Ø)

B ∩ {3,5,7,9,11} =

Answer:

{3,9}

Difference \

A \ B, meaning that the set A and set B form a set difference. This will generate a set, which contains the elements of A, which are NOT also in B.

The difference of two sets:

Examples:

  • R \ Q, meaning that R and Q form a set difference. This will generate the set of irrational numbers.

Let A be the set of all A-level students who take computer science and B the set of all A-level students who take mathematics.

  • A \ B, meaning that A and B form a set difference. This will generate the set of all computer science students, who do not also take mathematics.
  • {1, 2, 3} ∩ {2, 3, 4} = {2, 3}
  • {1, 2, 3} ∩ {bear,hen,squirrel} = Ø (this means an empty set)
  • {cat, dog, canary} ∩ {wolf, canary, whale, cat} = {cat, canary}
Questions relating to difference

As above,

let A = {0,2,4,6,8,10,12}

and B = {0,3,6,9,12}.

Let us take a look at the two sets we are using as examples:

A ∖  B    =

Answer:

{2,4,8,10}

B ∖  A    =

Answer:

{3,9}

B ∖  {1,2,3,5,7,11}    =

Answer:

{0,6,9,12}

A ∖  {0,1,2,3,5,8,13}    =

Answer:

{4,6,10,12}

Proper Subsets

S ⊂ T, meaning that S is a proper subset of T, such that all elements in S are also elements of T. However, there will need to be at least one element in T, which is not in S.

Examples:

  • N ⊂ Z, meaning that the set of natural numbers is a proper subset of the set of integers. In other words, all natural numbers are also integers. There are some elements in Z, which are not in N - these are the negative integers.
  • Z ⊂ Q, meaning that the set of integers is a proper subset of the set of rational numbers. In other words, all integers are also rational numbers. But there are rational numbers which are not integers.
Questions relating to proper subsets

As above,

let A = {0,2,4,6,8,10,12}

and B = {0,3,6,9,12}.

Is A a proper subset of B, so that we can write A ⊂ B? Explain your answer.

Answer:

No, because there are elements in the set A which are not in the set B. In other words we can find an element, for which x ∈ A and x ∉ B

Relating to the above definitions for A, define a set which is a proper subset of A.

Answer:

Any valid answer, for example {0,2,12} or {8,12}

Subsets

A ⊆ B, meaning that A forms a subset of B. In other words, A could be identical to B, but does not have to be!

Examples:

Let A be the set of all students in 6th form and B the set of all students taking computer science.

  • A ⊆ B, meaning that A forms a subset of B. In other words, all students in the 6th form could be taking computer science. In which case the two sets would be the same, but they may not be!

Now let A be all of the students present in school and B the set of students currently in the assembly hall.

  • A ⊆ B, meaning that A forms a subset of B. In other words, all students currently in present in school may all be located in the assembly hall, but they may not be!
Questions relating to subsets

Let A be all students who sit the A-level exam in computer science. Let B be all the students who gain a 'B' grade or above in the A-level computer science exam.

Is B a subset of A? Explain your answer.

Answer:

Yes, because it may be the case that all students who sit the exam will also gain grade 'B' or above.

Let A be the set of customers in a restaurant. Let B be the set of all the vegetarian customers in the restaurant.

Is B a subset of A? Could A be a subset of B? Could A be a proper subset of B? Explain your answer.

Answer:

B is a subset of A since every vegetarian customer is a customer. A could be a subset of B, because it may be the case that all customers present are also vegetarian. It cannot be a proper subset, since A contains B.

Fundamentals of data representation

From the Specification : Binary number system

Pure Binary Representation of Denary Integer

  • Describe the representation of unsigned denary integers in binary. Perform conversion from denary to binary and vice-versa.

Binary Arithmetic

  • Add two binary numbers and multiply two binary numbers.

Representation of signed integers by Two’s Complement

  • Describe the use of Two’s Complement to perform subtraction. Convert a denary integer into Two’s Complement and vice versa.

The Concept of Number Bases: Denary, Binary and Hexadecimal

  • Describe the conversion of a denary integer to hexadecimal form and vice versa. Describe the use of hexadecimal as shorthand for binary.

Integers and Numbers with a Fractional Part

  • Draw a distinction between integers and numbers with a fractional part in a computer context.Describe how an unsigned denary number with a fractional part is represented in fixed-point form in binary.
From the Specification : Information Coding Schemes

Describe standard coding systems for coding character data.

  • Understand ASCII
  • Understand Unicode

Differentiate between the character code representation of a denary digit and its pure binary representation. Error checking and correction

  • Parity bits, Hamming code.

Gray coding

  • Describe Gray coding. Explain why and where it is used.
From the Specification : Representing Images, Sound and other data

Images

Describe how bit patterns may represent other forms of data including graphics and sound.
Bitmapped Graphics
  • Bitmaps: resolution, colour depth and simple bitmap file calculations.
Vector Graphics
  • Vector graphics: drawing list – objects and their properties.
Compare bitmaps to vector graphics; advantages, disadvantages.
The need for compression and basic techniques for compression.

Sound files

The need for compression and basic techniques for compression.
Sampled Sound and Nyquist-theorem
  • Sampling resolution, sampling rate.
Sound Synthesis
  • Describe MIDI and its advantages for storing sound digitally.
Streaming audio
  • Explain what it is and why it is used.
Analogue and Digital Data. Analogue and Digital Signals
  • Differentiate between analogue and digital data and analogue and digital signals.
Analogue to Digital Converter
  • (ADC) Describe the principles of operation of an analogue to digital converter.

Bit patterns in a computer

Bits and Bytes

The language that a computer understands is very simple, so simple that it only has 2 different numbers: 1 and 0. This number system is called Binary. This is because 1 represents high voltage and 0 to represent low voltage.

A 1 or 0 is called a Bit which is short for BInary DigiT. This is the fundamental unit of information.

Everything you see on a computer, images, sounds, games, text, videos, spreadsheets, websites etc. Whatever it is, it will be stored as a string of ones and zeroes.

monochrome image of a smiley face
monochrome image of a smiley face
Bit - a standard unit to measure computer memory, consisting of a value that is either 1 or 0
Byte - a standard unit to measure computer memory, usually consisting of a group of 8 bits. e.g. 10101011


Exercise: Bit patterns in a Computer

How do computers store data?

Answer:

as binary values, using a pattern of 1s and 0s

What sort of data can be stored in binary?

Answer:


  • Video
  • Sound
  • Picture
  • Text
  • Code
  • Spreadsheet
  • Game
  • etc

What does the following binary string represent: 10011100

Answer:

This could be anything:

  • sound data
  • picture data
  • text ASCII for œ
  • unsigned integer = 156
  • video data
  • etc

How many bits in a byte?

Answer:

8, but it is originally the amount of bits used to represent a character

How many bits in 7 bytes?

Answer:

7 * 8 = 56

How many different patterns can be made from 4 bits?

Answer:

24 = 16 different patterns or combinations can be created

Minimum and Maximum Number vs. Number of Different Values

From the Specification : Binary number System - Unsigned binary

Know that in unsigned binary the minimum and maximum values for a given number of bits, n, are 0 and 2n -1 respectively.

A common question that you'll need to know the answer to, and one that many people get wrong, is a question about the minimum and maximum denary value you can store in a set number of binary digits.

If I were to have 3 binary digits, the minimum value I could store would be 0002 = 0. Whereas, the maximum value that I could store would be 1112, this equates to 4 + 2 + 1 = 710. So for 3 binary digits the range of numbers I can store is 0 (minimum) to 7 (maximum).

From the Specification : Units of information - Bits and bytes

Know that the 2n different values can be represented with n bits.

A similar, but different question, is how many different binary patterns (and therefore values) can you represent with a set number of binary digits. If I were to be asked how many binary patterns can be represented from 3 binary digits, then we have 8 options:

# 000
# 001
# 010
# 011
# 100
# 101
# 110
# 111

We could count these all out and write down: "There are 8 different values 3 binary digits can take". But this isn't very clever, what is you wanted to find out the range and maximum values for 34 bits, you can't be expected to write them all out.

We are looking for a rule to save us the job and stop us making mistakes. Can you work out a rule in terms of for:

Maximum denary value of binary digits:

Number of different values/binary patterns for binary digits:


Example

2 bits can be configured in 22 = 4 different ways. 3 bits can be configured in 23 = 8 different ways.

2 bits 3 bits
00

01

10

11

000

001

010

011

100

101

110

111

Min = 0 Min = 0
Max = 22-1 = 3 Max = 23-1 = 7
22 = 4 23=8
4 combinations 8 combinations


Exercise: Max and range of binary numbers

Give both the maximum value and number of different values for the following n binary digits:

4

Answer:

Maximum :

Range :

5

Answer:

Maximum :

Range :

8

Answer:

Maximum :

Range :

10

Answer:

Maximum :

Range :

For an address bus with 6 wires, what is the highest address that can be given? How many addresses can accessed?

Answer:

highest address :

Different number of addresses :

This is a very popular exam question!

Denary, Binary and Hexadecimal number systems

Before we jump into the world of number systems we'll need a point of reference, I recommend that you copy the following table that you can refer to throughout this chapter to check your answers.

Hexadecimal Binary Denary
0 0000 0
1 0001 1
2 0010 2
3 0011 3
4 0100 4
5 0101 5
6 0110 6
7 0111 7
8 1000 8
9 1001 9
A 1010 10
B 1011 11
C 1100 12
D 1101 13
E 1110 14
F 1111 15
10 0001 0000 16

Denary/Decimal

Denary is the number system that you have most probably grown up with. It is also another way of saying base 10. This means that there are 10 different numbers that you can use for each digit, namely:

0,1,2,3,4,5,6,7,8,9

Notice that if we wish to say 'ten', we use two of the numbers from the above digits, 1 and 0.

Thousands Hundreds Tens Units
10^3 10^2 10^1 10^0
1000 100 10 1
5 9 7 3

Using the above table we can see that each column has a different value assigned to it. And if we know the column values we can know the number, this will be very useful when we start looking at other base systems. Obviously, the number above is: five-thousands, nine-hundreds, seven-tens and three-units.

5*1000 + 9*100 + 7*10 + 3*1 = 597310

Binary

You should know denary pretty well by your age, but there are different base systems out there, and the most important one for computing is the binary base system. Binary is a base-2 number system, this means that there are two numbers that you can write for each digit:

0, 1

With these two numbers we should be able to write (or make an approximation) of all the numbers that we could write in denary.

One-hundred and twenty-eights Sixty-fours Thirty-twos Sixteens Eights Fours Twos Units
2^7 2^6 2^5 2^4 2^3 2^2 2^1 2^0
128 64 32 16 8 4 2 1
0 1 1 0 1 0 1 0

Using the above table we can see that each column has a value assigned to it that is the power of two (the base number!), and if we take those values and the corresponding digits we can work out the value of the number: 1*64 + 1*32 + 1*8 + 1*2 = 106.

If you are asked to work out the value of a binary number, the best place to start is by labelling each column with its corresponding value and adding together all the columns that hold a 1. Let's take a look at another example:

000111112
128 64 32 16 8 4 2 1
0 0 0 1 1 1 1 1

So now all we need to do is to add the columns containing 1s together: 1*16 + 1*8 + 1*4 + 1*2 + 1*1 = 31

Exercise: Binary

Convert the following binary numbers into denary

000011002

Answer:

128 64 32 16 8 4 2 1
0 0 0 0 1 1 0 0
8+4 = 1210

010110012

Answer:

128 64 32 16 8 4 2 1
0 1 0 1 1 0 0 1
64 + 16 + 8 + 1 = 8910

000001112

Answer:

128 64 32 16 8 4 2 1
0 0 0 0 0 1 1 1
4 + 2 + 1 = 710

010101012

Answer:

128 64 32 16 8 4 2 1
0 1 0 1 0 1 0 1
64 + 16 + 4 + 1 = 8510

How do we tell if a binary number is odd?

Answer:

Its right most digit is a one

Is there a short cut to working out a binary number that is made of solid ones, such as: 011111112

Answer:

Yes, take the first 0's column value and minus one

128 64 32 16 8 4 2 1
0 1 1 1 1 1 1 1
= 128 - 1 = 127 = 64 + 32 + 16 + 8 + 4 + 2 + 1
000011112 = 16 - 1 = 15 = 8 + 4 + 2 + 1
000001112 = 8 - 1 = 7 = 4 + 2 + 1

If we were to use octal, a base 8 number system, list the different numbers each digit could take:

Answer:


0, 1, 2, 3, 4, 5, 6, 7

Max and range

A common question that you'll need to know the answer to, and one that many people get wrong, is a question about the maximum denary value you can store in a set number of binary digits, or alternatively, the range of values that you can store in a set number of binary digits. Read carefully, these are not the same thing.

Consider the following example:

If I were to have 3 binary digits, the maximum value that I could store would be 1112, this equates to 4 + 2 + 1 = 710.

If I were to be asked, the range of numbers then we have 8 options:

# 000
# 001
# 010
# 011
# 100
# 101
# 110
# 111

We could count these all out and write down: "There are 8 different values 3 binary digits can take". But this isn't very clever, what is you wanted to find out the range and maximum values for 34 bits, you can't be expected to write them all out. We are looking for a rule to save us the job and stop us making mistakes. Can you work out a rule in terms of for:

Maximum denary value of binary digits:

Number of different values for binary digits:

Exercise: Max and range of binary numbers

Give both the maximum value and number of different values for the following n binary digits:

4

Answer:

Maximum :

Range :

5

Answer:

Maximum :

Range :

8

Answer:

Maximum :

Range :

10

Answer:

Maximum :

Range :

For an address bus with 6 wires, what is the highest address that can be given? How many addresses can accessed?

Answer:

highest address :

Different number of addresses :

This is a very popular exam question!

Hexadecimal

You may notice from the table that one hexadecimal digit can represent exactly 4 binary bits. Hexadecimal is useful to us as a shorthand way of writing binary, and makes it easier to work with long binary numbers.

Hexadecimal is a base-16 number system which means we will have 16 different numbers to represent our digits. The only problem being that we run out of numbers after 9, and knowing that 10 is counted as two digits we need to use letters instead:

0,1,2,3,4,5,6,7,8,9,A,B,C,D,E,F

We can do exactly the same thing as we did for denary and binary, and write out our table.

16^5 16^4 16^3 16^2 16^1 16^0
1 048 576 65536 4096 256 16 1
0 0 3 4 A F

So now all we need to do is to add the columns containing values together, but remember that A = 10, B = 11, C = 12, D = 13, E = 14, F = 15.

3*4096 + 4*256 + (A)10*16 + (F)15*1 = 1348716

You might be wondering why we would want to use hexadecimal when we have binary and denary, and when computer store and calculate everything in binary. The answer is that it is entirely for human ease. Consider the following example:

Error messages are written using hex to make it easier for us to remember and record them
Representation Base
EFFE11 base-16 hexadecimal
15728145 base-10 denary
111011111111111000010001 base-2 binary

All the numbers are the same and the easiest version to remember/understand for humans is the base-16. Hexadecimal is used in computers for representing numbers for human consumption, having uses for things such as memory addresses and error codes. NOTE: Hexadecimal is used as it is shorthand for binary and easier for people to remember. It DOES NOT take up less space in computer memory, only on paper or in your head! Computers still have to store everything as binary whatever it appears as on the screen.

Exercise: Hexadecimal

Convert the following Hex numbers into decimal/denary:
A1

Answer:

16  1
 A  1

16 * 10 + 1 * 1 = 16110

FF

Answer:

16  1
 F  F

16 * 15 + 1 * 15 = 25510

0D

Answer:

16  1
 0  D

16 * 0 + 1 * 13 = 1310

37

Answer:

16  1
 3  7

16 * 3 + 1 * 7 = 5510

Why would we use the Hexadecimal system?

Answer:

Hexadecimal is used for humans, it is easier to understand and write

Name a use of the hexadecimal system

Answer:

Hexadecimal is used for error message codes and memory addresses

Converting Between Bases

The sum that you saw previously to convert from hex to denary seemed a little cumbersome and in the exam you wouldn't want to make any errors, we therefore have to find an easier way to make the conversion.

Since 4 binary bits are represented by one hexadecimal digit, it is simple to convert between the two. You can group binary bits into groups of 4, starting from the right, and adding extra 0's to the left if required, and then convert each group to their hexadecimal equivalent. For example, the binary number 0110110011110101 can be written like this:

0110 1100 1111 0101

and then by using the table above, you can convert each group of 4 bits into hexadecimal:

0110 1100 1111 0101
  6    C    F    5

So the binary number 0110110011110101 is 6CF5 in hexadecimal. We can check this by converting both to denary. First we'll convert the binary number, since you already know how to do this:

32768 16384 8192 4096 2048 1024 512 256 128 64 32 16 8 4 2 1
0 1 1 0 1 1 0 0 1 1 1 1 0 1 0 1

By multiplying the columns and then adding the results, the answer is 27893.

Notice that the column headings are all 2 raised to a power, , , , , and so on. To convert from hexadecimal to denary, we must use column headings that are powers with the base 16, like this:

4096 256 16 1
6 C F 5

(You should memorize the values A-F)

Totalling them all up gives us 27893, showing that 0110110011110101 is equal to 6CF5.

To convert from denary to hexadecimal, it is recommended to just convert the number to binary first, and then use the simple method above to convert from binary to hexadecimal.

In summary, to convert from one number to another we can use the following rule: Hexadecimal <-> Binary <-> Denary

Exercise: Hexadecimal and Base Conversion

Convert the following Hexadecimal values into Denary:

1216

Answer:

  1    2  (Hex)
0001 0010 (Binary)

128 64 32 16  8  4  2  1
  0  0  0  1  0  0  1  0 = 16+2 = 18 (decimal)

A516

Answer:

  A    5  (Hex)
1010 0101 (Binary)

128 64 32 16  8  4  2  1
  1  0  1  0  0  1  0  1  = 128+32+4+1 = 165 (decimal)

7F16

Answer:

  7    F  (Hex)
0111 1111 (Binary)

128 64 32 16  8  4  2  1
  0  1  1  1  1  1  1  1  = 64+32+8+4+2+1 = 127 (decimal)

1016

Answer:

  1    0  (Hex)
0001 0000 (Binary)

128 64 32 16  8  4  2  1
  0  0  0  1  0  0  0  0  = 16(decimal)

Convert the following Binary numbers into hex:

101011012

Answer:

1010 1101 (Binary)
  A    D  (Hex)

1101112

Answer:

0011 0111 (Binary)
  3    7  (Hex)

101011112

Answer:

1010 1111 (Binary)
  A    F  (Hex)

1110101000012

Answer:

1110 1010 0001 (Binary)
  E    A    1  (Hex)

Convert the following decimal numbers into hex:

8710

Answer:

128 64 32 16  8  4  2  1
  0  1  0  1  0  1  1  1  = 64+16+4+2+1 = 87(decimal)
0101 0111 (Binary)
  5    7  (Hex)

1210

Answer:

128 64 32 16  8  4  2  1
  0  0  0  0  1  1  0  0  = 8+4 = 12(decimal)
0000 1100 (Binary)
  0    C  (Hex)

11710

Answer:

128 64 32 16  8  4  2  1
  0  1  1  1  0  1  0  1  = 64+32+16+4+1 = 117(decimal)
0111 0101 (Binary)
  7    5  (Hex)

Why might you use Hexadecimal?

Answer:

So that it makes things such as error messages and memory address easier for humans understand and remember

Give two uses of hexadecimal?

Answer:


  • Error message codes
  • Memory address locations

Binary arithmetic

You should be comfortable with adding, subtracting and multiplying in decimal. Computers need to do the same in binary, and you need to know it for the exam!

Addition

Let's look at an example of adding in decimal:

 25
+43
---
 68

This is pretty simple, we just add up each column, but what happens if we have can't fit the result in one column. We'll have to use a carry bit:

 98
+57
---
155
11

Hopefully you're good with that. Now let's take a look at how it's done in binary with a very quick example, with a check in denary:

 01010 (1010)
+00101 (510)
------
 01111 (1510)

This seems pretty straight forward, but what happens when we have a carry bit? Well pretty much the same as in denary:

 01011 (1110)
+00001 (110)
------
 01100 (1210)
   11
How carry bits are used in binary addition
Exercise: Binary Addition

1010 + 0001

Answer:

 1010
+0001
 ----
 1011

01001001 + 00110000

Answer:

 01001001 
+00110000
 --------
 01111001

01010100 + 00110000

Answer:

 01010100 
+00110000
 --------
 10000100

01001010 + 00011011

Answer:

 01001010 
+00011011
 --------
 01100101

01111101 + 00011001

Answer:

 01111101 
+00011001
 --------
 10010110

00011111 + 00011111

Answer:

 00011111 
+00011111
 --------
 00111110

10101010 + 01110000

Answer:

 10101010 
+01110000
 --------
100011010
Note we have some overflow, this will come in useful when doing subtraction

Multiplication

You should hopefully have learnt how to multiply numbers together in decimal when you were at primary school. Let's recap:

 12
x 4
 --
  8   =  4*2
 40   =  4*10–48

And with a more complicated example:

 12
x14–8   =  4 * 2
 40   =  4 * 10
 20   =  10* 2
100   =  10* 10–168

The same principle applies with binary. Let's take a look at an example:

 101
x 10
----
   0   =  0 * 101
1010   = 10 * 101 [or in denary 2 * 5 = 10]

Let's try a more complicated example:

   1011 [11]
  x 111 [7]
  ----
   1011 =   1 * 1011 
  10110 =  10 * 1011
 101100 = 100 * 1011
 ------ now add them together
1001101 = [77 double check with the decimal earlier]
Exercise: Binary Multiplication

101 * 10

Answer:

 101
x 10
----
1010

11 * 11

Answer:

  11
x 11
----
  11
 110
----
1001

1011 * 101

Answer:

  1011 
x  101
------
  1011
101100
------
110111

1111 * 111

Answer:

    1111  = 15
  x  111  = 7
  ------
    1111
   11110
  111100
  ------
 1101001 = 105

If you multiply a binary number by 2, how many spaces does it move to the left?

Answer:

1

If you multiply a binary number by 16, how many spaces does it move to the left?

Answer:

4 (as 2^4 = 16)

This is a short cut for multiplication in computers, and it uses machine code shift instructions to do this. Don't worry you don't need to know them for this syllabus

Extension: Bit Shifts

If you look at the binary representations of the following numbers you may notice something peculiar:

0001 = 1
0010 = 2
0100 = 4
1000 = 8

Each time we shift the number one space to the left, the value of the number doubles. This doesn't only work for one bit, take a look at this more complicated example.

0001 0101 = 21
0010 1010 = 42

Again, one shift to the left and the number has doubled. On the other hand, one shift to the right halves the value.

Computers are notoriously bad at doing multiplication and division, it takes lots of CPU time and can really slow your code down. To try and get past this problem computers can shift the values in registers and as long as multiplication or division is by powers of 2, then the CPU time is reduced as the action takes only one line of Machine Code. There are several types of shifts that processors can perform:

  • Logical Shift

Shifting either left or right, you add a 0 on the empty end.

  • Arithmetic Shift

You maintain the sign bit of the number being shifted.

Please note the Logical shift example is also an example of an arithmetic shift as the sign remains the same. You'll find out about sign bits when learning about two's complement

  • Circular Shift

The bit that is pushed off one end appears on the other

Binary fractions

Binary Fractions - using Fixed Point notation

So far we have only looked at whole numbers (integers), we need to understand how computers represent fractions.

From the Specification : Introduction to Principles of Computation

Know how numbers with a fractional part can be represented in:

  • fixed point form in binary in a given number of bits
  • floating point form in binary in a given number of bits.

Be able to convert for each representation from:

  • decimal to binary of a given number of bits
  • binary to decimal of a given number of bits.

You should have learned at Primary School how a decimal fraction works:

10 1
1 2 . 7 5

As you can see, the column headings have been extended to and . We can do the same thing in binary with the column headings , , and so on. The number 12.75 in 8 bit binary with 4 bits after the binary point is therefore 8 + 4 + 0.5 + 0.25:

8 4 2 1
1 1 0 0 . 1 1 0 0

Notice that for the same number of bits after the point, the binary fraction provides less accuracy. It can only take 4 different values, whereas the decimal number can have 100 different values with two digits. You'll see in a moment how this can cause trouble.

Example: converting decimal to binary decimal using fixed point notation

We are going to convert the number 6.125 into a binary fraction by using the grid below

8 4 2 1
0 1 1 0 . 0 0 1 0

This seems simple enough as 6.125 = 4 + 2 + 0.125, but what about this more interesting number: 6.4

8 4 2 1
0 1 1 0 . 0 1 1 0

But this doesn't look right?! This number isn't correct as it only reaches 4 + 2 + 0.25 + 0.125 = 6.375, we need more bits for the binary fraction places. However, a computer might restrict you to the number of bits you can use, so we'll use the number closest to the one we were aiming for. You could feel a bit annoyed at this, but don't worry, you make this compromise every time you try to represent with the decimal factions, 0.33333333.

So you might ask how a computer does complicated mathematics if it struggles so hard with fractions. The answers we have looked at so far have only used one byte, computers can use far more space than this. They can also manipulate the number of bits they have been given in two ways:

  • increase the number of bits to increase range of number
  • increase number of bits after the decimal point to increase accuracy

In practice they will also use clever techniques such as floating point numbers (see below).

Exercise: converting from denary to binary fractions

Now try some questions yourself and see how you get on. Remember, where there aren't enough bits for the decimal place, write down the number closest to your target number. In each case use 8 bits for the binary with four bits after the decimal point:

7.5

Answer:

0111.1000

4.5625

Answer:

0100.1001

1.6

Answer:

0001.1010 (this is the closest we are going to get)

3.3333333

Answer:

0011.0101 (this is the closest we are going to get)

Try and convert these binary fractions into denary:

0111.0100

Answer:

7.25

1011.1001

Answer:

11.5625 (notice that we treated this as a positive number, some of you might already know about twos complement, if you haven't heard about it before, don't worry, we'll get there very soon)
To interpret it as a two's complement number let's flip it: 0100.0111 = 4 + 0.25 + 0.125 + 0.0625 = -4.4375

If I want to increase the range of numbers stored in a fixed point binary number, what should I do?

Answer:

Increase the number of bits before the decimal point

If I want to increase the accuracy of numbers stored in a fixed point binary number, what should I do?

Answer:

Increase the number of bits after the decimal point

Two's complement

Nearly all computers work purely in binary. That means that they only use ones and zeros, and there's no - or + symbol that the computer can use. The computer must represent negative numbers in a different way.

We can represent a negative number in binary by making the most significant bit (MSB) a sign bit, which will tell us whether the number is positive or negative. The column headings for an 8 bit number will look like this:

-128 64 32 16 8 4 2 1
MSB LSB
1 0 1 1 1 1 0 1

Here, the most significant bit is negative, and the other bits are positive. You start with -128, and add the other bits as normal. The example above is -67 in denary because: (-128 + 32 + 16 + 8 + 4 + 1 = -67)

-1 in binary is 11111111.

Note that you only use the most significant bit as a sign bit if the number is specified as signed. If the number is unsigned, then the msb is positive regardless of whether it is a one or not.

Signed binary numbers

If the MSB is 0 then the number is positive, if 1 then the number is negative.

0000 0101 (positive)
1111 1011 (negative)
Method: Converting a Negative Denary Number into Binary Twos Complement

Let's say you want to convert -35 into Binary Twos Complement. First, find the binary equivalent of 35 (the positive version)

32  16   8   4   2   1 
 1   0   0   0   1   1

Now add an extra bit before the MSB, make it a zero, which gives you:

64 32  16   8   4   2   1 
 0  1   0   0   0   1   1

Now 'flip' all the bits: if it's a 0, make it a 1; if it's a 1, make it a 0:

64 32  16   8   4   2   1 
 1  0   1   1   1   0   0

This new bit represents -64 (minus 64). Now add 1:

64 32  16   8   4   2   1 
 1  0   1   1   1   0   0
                      + 1
 1  0   1   1   1   0   1

If we perform a quick binary -> denary conversion, we have: -64 + 16 + 8 + 4 + 1 = -64 + 29 = -35

Converting Negative Numbers

To find out the value of a twos complement number we must first make note of its sign bit (the most significant, left most bit), if the bit is a zero we work out the number as usual, if it's a one we are dealing with a negative number and need to find out its value.

Method 1: converting twos complement to denary

To find the value of the negative number we must find and keep the right most 1 and all bits to its right, and then flip everything to its left. Here is an example:

1111 1011 note the number is negative
1111 1011 find the right most one

1111 1011 
0000 0101 flip all the bits to its left

We can now work out the value of this new number which is:

128  64  32  16   8   4   2   1 
  0   0   0   0   0   1   0   1
                      4   +   1 = −5   (remember the sign you worked out earlier!)
Method 2: converting twos complement to denary

To find the value of the negative number we must take the MSB and apply a negative value to it. Then we can add all the heading values together

1111 1011 note the number is negative
-128  64  32  16   8   4   2   1 
   1   1   1   1   1   0   1   1
-128 +64 +32 +16  +8      +2  +1 = -5

How about a more complex example?

Method 1: converting twos complement to denary
1111 1100 note the number is negative 

1111 1100 find the right most one

1111 1100
0000 0100 flip all the bits to its left
128  64  32  16   8   4   2   1 
  0   0   0   0   0   1   0   0
                      4         = −4   (remember the sign you worked out earlier!)
Method 2: converting twos complement to denary

To find the value of the negative number we must take the MSB and apply a negative value to it. Then we can add all the heading values together

1111 1100 note the number is negative
-128  64  32  16   8   4   2   1 
   1   1   1   1   1   1   0   0
-128 +64 +32 +16  +8  +4          = -4

So we know how to work out the value of a negative number that has been given to us. How do we go about working out the negative version of a positive number? Like this, that's how...

Method 1: converting twos complement to binary

Take the binary version of the positive number

0000 0101 (5)
0000 0101 find the right most one

0000 0101 
1111 1011 flip all the bits to its left

So now we can see the difference between a positive and a negative number

0000 0101 (5)
1111 1011 (−5)
Method 2: converting twos complement to binary

Take the binary version of the positive number

starting with -128, we know the MSB is worth -128. We need to work back from this:

-128  64  32  16   8   4   2   1 
   1   1   1   1   1   0   1   0   
-128 +64 +32 +16  +8      +1      = -5
0000 0101 (5)
1111 1011 (−5)
Exercise: two's complement numbers

Convert the following two's complement numbers into denary:

0001 1011

Answer:

(positive number) 27

1111 1111

Answer:

(negative number) 0000 0001 = -1

0111 1101

Answer:

(positive number) 125

1001 1001

Answer:

(negative number) 0110 0111 = -103

1011 1000

Answer:

(negative number) 0100 1000 = -72

81 (hexadecimal)

Answer:

(using 4 bits for each HEX char) 1000 0001 (negative number) -> 0111 1111 = -127

A8 (hexadecimal)

Answer:

(using 4 bits for each HEX char) 1010 1000 (negative number) -> 0101 1000 = -88

Convert the following numbers into negative numbers written in binary

0000 0001

Answer:

1111 1111

0110 0000

Answer:

1010 0000

0111 1111

Answer:

1000 0001

12 (denary)

Answer:

0000 1100 = +12 -> 1111 0100 = -12

67 (denary)

Answer:

0100 0011 = +67 -> 1011 1101 = -67

34

Answer:

0010 0010 = +34 -> 1101 1110 = -34

34 (hexadecimal)

Answer:

(using 4 bits for each HEX char) 0011 0100 = +52 -> 1100 1100 = -52

7E (hexadecimal)

Answer:

(using 4 bits for each HEX char) 0111 1110 = +126 -> 1000 0010 = -126

Binary Subtraction

Example: binary subtraction

When it comes to subtracting one number from another in binary things can get very messy.

X (82 denary) 0101 0010
Y (78 denary) 0100 1110 −

An easier way to subtract Y from X is to add the negative value of Y to the value of X

X−Y = X+(−Y)

To do this we first need to find the negative value of Y (78 denary)

0100 1110 find the right most one

0100 1110 
1011 0010 flip all the bits to its left

Now try the sum again

   0101 0010     X( 82 denary) 
   1011 0010 +   Y(−78 denary)
   0000 0100
(¹)¹¹¹   ¹       the one carried over the bit 9 is ignored

Which comes out as:

128  64  32  16   8   4   2   1 
  0   0   0   0   0   1   0   0
                      4         = 4 = 82-78
Exercise: Binary subtraction

Find the answers to the following sums in binary, show your working

  0110 1100 (108)
- 0000 0111 (7)

Answer:

Convert the 0000 0111 into a negative number 1111 1001 = -7 Add both numbers together:

   0110 1100
 + 1111 1001
   0110 0101 = 101
(¹)¹¹¹¹         the one carried over the bit 9 is ignored
  0001 1111 (31)
- 0001 0011 (19)

Answer:

Convert the 0001 0011 into a negative number 1110 1101 = -19 Add both numbers together:

   0001 1111
 + 1110 1101
   0000 1100 = 12
(¹)¹¹¹¹ ¹¹¹    the one carried over the bit 9 is ignored
  0111 0111 (119)
- 0101 1011 (91)

Answer:

Convert the 0101 1011 into a negative number 1010 0101 = -91 Add both numbers together:

   0111 0111
 + 1010 0101
   0001 1100 = 28
(¹)¹¹   ¹¹¹    the one carried over the bit 9 is ignored
23 (hex)  - 1F (hex)

Answer:

Convert the HEX values to binary
0010 0011 = 23 HEX or 35 denary
0001 1111 = 1F HEX or 31 denary
Now let's find the negative value of 1F
1110 0001 = -31
Add both numbers together:

   0010 0011
 + 1110 0001
   0000 0100 = 4
(¹)¹¹¹   ¹¹    the one carried over the bit 9 is ignored
  0000 1010 (10)
- 1110 0001 (-31)

Answer:

They have tried to trick you. What is a negative number minus a negative number? X - (-Y) = X + Y
Let's start by finding the value of the bottom number: 1110 0001 -> 0001 1111 = 31
And by working this out we have the positive value (0001 1111) Add both numbers together:

   0000 1010 (10)
 + 0001 1111 (31)
   0010 1001 = 41
      ¹ ¹¹     

Status register

Maths in a processor is normally performed using set numbers of bits. For example where you add 8 bits to 8 bits. This will often cause no problems at all:

 00110011 (51)
+00001010 (10)
 --------
 00111101 (61)

But what happens if we add the following numbers together:

 01110011 (115)
+01001010 (74)
 --------
 10111101 (189)

This may appear to have gone ok, but we have a problem. If we are dealing with twos complement numbers the answer from adding two positive numbers together is negative!

 01110011 (115)
+01001010 (74)
 --------
 10111101 (-67!)

Overflow

Let's take a look at another problem example, the problem of overflow

Overflow - When the result of a calculation is too large to fit into a set number of bits


    1010 (-6)
   +1010 (-6)
    --------
 (1)0100 (+4!)

As you can see in the sum above, we have added two negative numbers together and the result is a positive number.

To deal with the situations mentioned above we use the status register

Status Register - information about process states such as whether a result is zero, positive/negative or resulted in overflow.


The most common flags

Flag Name Description
Z Zero flag Indicates that the result of an arithmetic or logical operation (or, sometimes, a load) was zero.
C Carry flag Enables numbers larger than a single word (in the examples above 4 or 8 bits) to be added/subtracted by carrying a binary digit from a less significant word to the least significant bit of a more significant word as needed
S / N Sign flag / Negative flag One indicates whether the result was negative whereas the other indicates whether a subtraction or addition has taken place.
O Overflow flag Indicates that the signed result of an operation is too large to fit in the register width using twos complement representation.
P Parity flag Indicates whether the number of set bits of the last result is odd or even.
Status register working

For the sum that we met earlier we will take a look at how the status register can be used to stop the incorrect answer arising:

 01110011 (115)
+01001010 (74)
 --------
 10111101 (-67)

Status register: Z = False | C = False | N = True | O = True | P = Even

Using these flags you can see that the result is negative, if the original sum used only positive values, then we know we have an error.

Looking at the other equation:

    1010 (-6)
   +1010 (-6)
    ----
 (1)0100

Status register: Z = False | C = True | N = False | O = True | P = Odd

Using these flags you can see that the result is positive when the original used two negative numbers. We can also see that overflow occurred.

Exercise: Status register
What is the problem with the result of the following 4 bit sum:
    1011 (-5)
   +1011 (-5)
    ----

Answer:

The result would create overflow, giving an incorrect answer:

    1011 (-5)
   +1011 (-5)
    ----
 (1)0110 (+6)

In the context of calculations what is overflow?

Answer:

When a the result of a calculation is too large to fit into a set number of bits.

What do we need the status register for?

Answer:

The status register holds flags keeping track of the results of sums, this helps us to see when there is an error in a result and correct it accordingly

Name three flags in a status register:

Answer:

Overflow, Carry, Negative, Zero

Show the Status register for the following sum:
    1001 (-7)
   +1001 (-7)
    ----
 (1)0010 (+2)

Answer:

Status register: Z = False | C = True | N = False | O = True | P = Odd

Information coding schemes

So far we have seen the different ways that binary can be used to store numbers. As we already know, most computers can only understand binary and we often need to store alpha-numeric text (numbers, letters and other characters). To do this a computer will use a coding scheme. The most popular coding schemes are ASCII and Unicode. You'll need to know how each works and the benefits and drawbacks of using them.

ASCII

ASCII

The 104-key PC US English QWERTY keyboard layout evolved from the standard typewriter keyboard, with extra keys for computing.

ASCII normally uses 8 bits (1 byte) to store each character. However, the 8th bit is used as a check digit, meaning that only 7 bits are available to store each character. This gives ASCII the ability to store a total of

2^7 = 128 different values.
The 95 printable ASCII characters, numbered from 32 to 126 (decimal)

ASCII values can take many forms:

  • Numbers
  • Letters (capitals and lower case are separate)
  • Punctuation (?/|\£$ etc.)
  • non-printing commands (enter, escape, F1)

Take a look at your keyboard and see how many different keys you have. The number should be 104 for a windows keyboard, or 101 for traditional keyboard. With the shift function valus (a, A; b, B etc.) and recognising that some keys have repeated functionality (two shift keys, the num pad). We roughly have 128 functions that a keyboard can perform.

Binary Dec Hex Abbr
000 0000 0 00 NUL
000 0001 1 01 SOH
000 0010 2 02 STX
000 0011 3 03 ETX
000 0100 4 04 EOT
000 0101 5 05 ENQ
000 0110 6 06 ACK
000 0111 7 07 BEL
000 1000 8 08 BS
000 1001 9 09 HT
000 1010 10 0A LF
000 1011 11 0B VT
000 1100 12 0C FF
000 1101 13 0D CR
000 1110 14 0E SO
000 1111 15 0F SI
001 0000 16 10 DLE
001 0001 17 11 DC1
001 0010 18 12 DC2
001 0011 19 13 DC3
001 0100 20 14 DC4
001 0101 21 15 NAK
001 0110 22 16 SYN
001 0111 23 17 ETB
001 1000 24 18 CAN
001 1001 25 19 EM
001 1010 26 1A SUB
001 1011 27 1B ESC
001 1100 28 1C FS
001 1101 29 1D GS
001 1110 30 1E RS
001 1111 31 1F US
111 1111 127 7F DEL
Binary Dec Hex Glyph
010 0000 32 20 ?
010 0001 33 21 !
010 0010 34 22 "
010 0011 35 23 #
010 0100 36 24 $
010 0101 37 25 %
010 0110 38 26 &
010 0111 39 27 '
010 1000 40 28 (
010 1001 41 29 )
010 1010 42 2A *
010 1011 43 2B +
010 1100 44 2C ,
010 1101 45 2D -
010 1110 46 2E .
010 1111 47 2F /
011 0000 48 30 0
011 0001 49 31 1
011 0010 50 32 2
011 0011 51 33 3
011 0100 52 34 4
011 0101 53 35 5
011 0110 54 36 6
011 0111 55 37 7
011 1000 56 38 8
011 1001 57 39 9
011 1010 58 3A :
011 1011 59 3B ;
011 1100 60 3C <
011 1101 61 3D =
011 1110 62 3E >
011 1111 63 3F ?
Binary Dec Hex Glyph
100 0000 64 40 @
100 0001 65 41 A
100 0010 66 42 B
100 0011 67 43 C
100 0100 68 44 D
100 0101 69 45 E
100 0110 70 46 F
100 0111 71 47 G
100 1000 72 48 H
100 1001 73 49 I
100 1010 74 4A J
100 1011 75 4B K
100 1100 76 4C L
100 1101 77 4D M
100 1110 78 4E N
100 1111 79 4F O
101 0000 80 50 P
101 0001 81 51 Q
101 0010 82 52 R
101 0011 83 53 S
101 0100 84 54 T
101 0101 85 55 U
101 0110 86 56 V
101 0111 87 57 W
101 1000 88 58 X
101 1001 89 59 Y
101 1010 90 5A Z
101 1011 91 5B [
101 1100 92 5C \
101 1101 93 5D ]
101 1110 94 5E ^
101 1111 95 5F _
Binary Dec Hex Glyph
110 0000 96 60 `
110 0001 97 61 a
110 0010 98 62 b
110 0011 99 63 c
110 0100 100 64 d
110 0101 101 65 e
110 0110 102 66 f
110 0111 103 67 g
110 1000 104 68 h
110 1001 105 69 i
110 1010 106 6A j
110 1011 107 6B k
110 1100 108 6C l
110 1101 109 6D m
110 1110 110 6E n
110 1111 111 6F o
111 0000 112 70 p
111 0001 113 71 q
111 0010 114 72 r
111 0011 115 73 s
111 0100 116 74 t
111 0101 117 75 u
111 0110 118 76 v
111 0111 119 77 w
111 1000 120 78 x
111 1001 121 79 y
111 1010 122 7A z
111 1011 123 7B {
111 1100 124 7C |
111 1101 125 7D }
111 1110 126 7E ~

If you look carefully at the ASCII representation of each character you might notice some patterns. For example:

Binary Dec Hex Glyph
110 0001 97 61 a
110 0010 98 62 b
110 0011 99 63 c

As you can see, a = 97, b = 98, c = 99. This means that if we are told what value a character is we can easily work out the value of subsequent or prior characters.

Example: ASCII characters

Without looking at the ASCII table above! If we are told that the ASCII value for the character '5' is 011 0101, what is the ASCII value for '8'.

We know that '8' is three characters after '5', as 5,6,7,8. This means that the ASCII value of '8' will be three bigger than that for '5':

  011 0101  ASCII '5'
+      011
  --------  
  011 1000  ASCII '8'

Checking above this is the correct value.

If you are worried about making mistakes with binary addition, you can deal with the decimal numbers instead. Take the example where you are given the ASCII value of 'g', 110 0111, what is 'e'?

We know that 'e' is two characters before 'g', as e, f, g. This means that the ASCII value of 'e' will be two smaller than that for 'g'.

64 32 16  8  4  2  1
 1  1  0  0  1  1  1 = 10310 = ASCII value of 'g'

103 - 2 = 10110

64 32 16  8  4  2  1
 1  1  0  0  1  0  1 = 10110 = ASCII value of 'e'
Exercise: ASCII

Without using the crib table (you won't get it in the exam!) answer the following questions:

The ASCII code for the letter 'Z' is 90(base10), what is the letter 'X' stored as

Answer:

88 - as it is 2 characters down in the alphabet

How many ASCII 'characters' does the following piece of text use:

Hello Pete,
ASCII rocks!

Answer:

27 or 26. If you said 23 you'd be wrong because you must include the non-printing characters at the end of each line. Each end of line needs a EOL command, and a new line needs a carriage return (CR), making the text like so:

Hello Pete,[EOL][CR]
ASCII rocks![EOL]

For the Latin alphabet ASCII is generally fine, but what if you wanted to write something in Mandarin, or Hindi? We need another coding scheme!

Extension: Coding ASCII

You might have to use ASCII codes when reading from text files. To see what each ASCII code means we can use the folliwing function ChrW(x) which returns the ASCII code with denary value x. Try out the following code to see the first 128 characters. What is special about character 10?

For x = 0 To 127
  Console.WriteLine("ASCII for " & x & " = " & ChrW(x))
Next
Console.ReadLine()

Unicode

The problem with ASCII is that it only allows you to represent a small number of characters (~128 or 256 for Extended ASCII). This might be OK if you are living in an English speaking country, but what happens if you live in a country that uses a different character set? For example:

You can see that we quickly run into trouble as ASCII can't possibly store these hundreds of thousands of extra characters in just 7 bits. What we use instead is unicode. There are several versions of unicode, each with using a different number of bits to store data:

Name Descriptions
UTF-8 8-bit is the most common unicode format. Characters can take as little as 8-bits, maximizing compatibility with ASCII. But it also allows for variable-width encoding expanding to 16, 24, 32, 40 or 48 bits when dealing with larger sets of characters
UTF-16 16-bit, variable-width encoding, can expand to 32 bits.
UTF-32 32-bit, fixed-width encoding. Each character takes exactly 32-bits

With over a million possible characters we should be able to store every character from every language on the planet, take a look at these examples:

code point glyph* character UTF-16 code units (hex)
U+007A z LATIN SMALL LETTER Z 007A
U+6C34 CJK UNIFIED IDEOGRAPH-6C34 (water) 6C34
U+10000 LINEAR B SYLLABLE B008 A D800, DC00
U+1D11E MUSICAL SYMBOL G CLEF D834, DD1E

You can find out more about unicode encoding on Wikipedia

Exercise: ASCII and Unicode

Without using the crib table (you won't get it in the exam!) answer the following questions:

The ASCII code for the letter 'D' is 100 0100, what is the letter 'G' stored as

Answer:

100 0111 - as it is 3 characters further on in the alphabet

The ASCII code for the letter 's' is 111 0011, what is the letter 'm' stored as:

Answer:

110 1101 - as it is 6 characters down in the alphabet

Give a benefit of using ASCII:

Answer:

Each character only takes up 8 bits, meaning that storing data in ASCII may take up less memory than unicode

Give a benefit of using unicode over ASCII:

Answer:

ASCII stores a much smaller character set than unicode, meaning that you are limited to the Latin character set and cannot represent characters from other languages.

How many different characters can 7-bit ASCII represent?

Answer:

2^7 = 128

You are designing a computer system for use worldwide, what character encoding scheme should you use and why?

Answer:

unicode as it would allow you to display non Latin character sets such as Hindi and Cyrillic

Unicode

The problem with ASCII is that it only allows you to represent a small number of characters (~128 or 256 for Extended ASCII). This might be OK if you are living in an English speaking country, but what happens if you live in a country that uses a different character set? For example:

You can see that we quickly run into trouble as ASCII can't possibly store these hundreds of thousands of extra characters in just 7 bits. What we use instead is unicode.

Each Unicode character can be encoded on a computer using three different standards, that differ on the minimum number of bits used:

Name Descriptions
UTF-8 8-bit is the most common unicode format. Characters can take as little as 8-bits, maximizing compatibility with ASCII. But it also allows for variable-width encoding expanding to 16, 24, 32, 40 or 48 bits when dealing with larger sets of characters
UTF-16 16-bit, variable-width encoding, can expand to 32 bits.
UTF-32 32-bit, fixed-width encoding. Each character takes exactly 32-bits

With over a million possible characters we should be able to store every character from every language on the planet, take a look at these examples:

code point glyph* character UTF-16 code units (hex)
U+007A z LATIN SMALL LETTER Z 007A
U+6C34 CJK UNIFIED IDEOGRAPH-6C34 (water) 6C34
U+10000 LINEAR B SYLLABLE B008 A D800, DC00
U+1D11E MUSICAL SYMBOL G CLEF D834, DD1E

You can find out more about unicode encoding on Wikipedia

Exercise: ASCII and Unicode

Without using the crib table (you won't get it in the exam!) answer the following questions:

The ASCII code for the letter 'D' is 100 0100, what is the letter 'G' stored as

Answer:

100 0111 - as it is 3 characters further on in the alphabet

The ASCII code for the letter 's' is 111 0011, what is the letter 'm' stored as:

Answer:

110 1101 - as it is 6 characters down in the alphabet

Give a benefit of using ASCII:

Answer:

Each character only takes up 8 bits, meaning that storing data in ASCII may take up less memory than unicode

Give a benefit of using unicode over ASCII:

Answer:

ASCII stores a much smaller character set than unicode, meaning that you are limited to the Latin character set and cannot represent characters from other languages.

How many different characters can 7-bit ASCII represent?

Answer:

2^7 = 128

You are designing a computer system for use worldwide, what character encoding scheme should you use and why?

Answer:

unicode as it would allow you to display non Latin character sets such as Hindi and Cyrillic

Error checking and correction

When you send data across the internet or even from your USB to a computer you are sending millions upon millions of ones and zeros. What would happen if one of them got corrupted? Think of this situation: You are buying a new game from an online retailer and put £40 into the payment box. You click on send and the number 40 is sent to your bank stored in a byte: 00101000. Now imagine if the second most significant bit got corrupted on its way to the bank, and the bank received the following: 01101000. You'd be paying £104 for that game! Error Checking and Correction stops things like this happening. There are many ways to detect and correct corrupted data, we are going to learn two.

Parity bits

Sometime when you see ASCII code it only appears to have 7 bits. Surely they should be using a byte to represent a character, after all that would mean they could represent more characters than the measly 128 they can currently store (Note there is extended ASCII that uses the 8th bit as well but we don't need to cover that here). The eighth bit is used as a parity bit to detect that the data you have been sent is correct. It will not be able to tell you which digit is wrong, so it isn't corrective.

There are two types of parity odd and even. If you think back to primary school you would have learnt about odd and even numbers, hold that thought, we are going to need it.

  • Odd numbers : 1,3,5,7,9
  • Even numbers : 0,2,4,6,8 (note 0 is here too)
Example: How to detect errors using parity bits

When we send binary data we need to count the number of 1s that are present in it. For example sending the ASCII character 'B' 1000010. This has two occurrences of 1. We can then apply another bit to the front of it and send it across the internet.

  • If we are using even parity 01000010
  • If we are using odd parity 11000010

Now when the data gets to the other end and we were using even parity

  • 01001010 - odd parity, there has been an error in transmission, ask for data to be sent again
  • 01000010 - even parity, the data has been sent correctly
Exercise: Test your knowledge of parity bits

Try and apply the correct parity bit to the following:

_1011010 (even parity)

Answer:

01011010

_1011010 (odd parity)

Answer:

11011010

_1111110 (even parity)

Answer:

01111110

_0000000 (odd parity)

Answer:

10000000

However, if we receive 10010110, knowing that the number had odd parity, where is the error? The best we can do is ask for the data to be resent and hope it's correct next time. Parity bits only provide detective error. We need something that detects and corrects..

Hamming code

Building on what you have learnt about parity bits we are now going to see a system that not only allows you to detect if the data you have been sent is incorrect, but it will allow you to correct the error. The way hamming code does this is to use multiple check digits in the same piece of sent data.

Checking if correct

  1. Number the column headings
  2. Highlight the column headings that are powers of 2 (1,2,4,8), these are the parity bits
  3. Insert your data and highlight the parity bits
  4. Work your way through the parity bits
    1. 2^0 = 1 : check 1, skip 1, check 1, skip 1 ... write down whether it's odd or even parity
    2. 2^1 = 2 : check 2, skip 2, check 2, skip 2 ... write down whether it's odd or even parity
    3. 2^2 = 4 : check 4, skip 4, check 4, skip 4 ... write down whether it's odd or even parity
    4. etc..
Example: Odd Parity Hamming Code Check

Let's take a look a an example of data sent with odd parity

11 10 09 08 07 06 05 04 03 02 01 number the columns and highlight the powers of 2
1 0 0 0 0 0 0 1 1 1 1 insert your data
1 0 0 0 0 0 0 1 1 1 1 highlight the check bits
1 0 0 0 1 1 taking the 1st power of 2^0 (1) check 1 skip 1 = odd parity
1 0 0 0 1 1 taking the 2nd power of 2^1 (2) check 2 skip 2 = odd parity
0 0 0 1 taking the 3rd power of 2^2 (4) check 4 skip 4 = odd parity
1 0 0 0 taking the 4th power of 2^3 (8) check 8 skip 8 = odd parity

Note that for the check 8 skip 8 we ran out of digits, not to worry, take it as far as the bits given allow. As we can see each line is odd parity, and the sent data was supposed to be odd parity, this number is correct.

Exercise: Even Parity Hamming Code Question

Now try this example with even parity:

10101100011

Answer:

11 10 09 08 07 06 05 04 03 02 01 number the columns and highlight the powers of 2
1 0 1 0 1 1 0 0 0 1 1 insert your data
1 0 1 0 1 1 0 0 0 1 1 highlight the check bits
1 1 1 0 0 1 taking the 1st power of 2^0 (1) check 1 skip 1 = even parity
1 0 1 1 0 1 taking the 2nd power of 2^1 (2) check 2 skip 2 = even parity
1 1 0 0 taking the 3rd power of 2^2 (4) check 4 skip 4 = even parity
1 0 1 0 taking the 4th power of 2^3 (8) check 8 skip 8 = even parity

All are even parity, the data should be even parity, therefore it has been sent and received correctly

11011110010 being sent with odd parity

Answer:

11 10 09 08 07 06 05 04 03 02 01 number the columns and highlight the powers of 2
1 1 0 1 1 1 1 0 0 1 0 insert your data
1 1 0 1 1 1 1 0 0 1 0 highlight the check bits
1 0 1 1 0 0 taking the 1st power of 2^0 (1) check 1 skip 1 = odd parity
1 1 1 1 0 1 taking the 2nd power of 2^1 (2) check 2 skip 2 = odd parity
1 1 1 0 taking the 3rd power of 2^2 (4) check 4 skip 4 = odd parity
1 1 0 1 taking the 4th power of 2^3 (8) check 8 skip 8 = odd parity

All are odd parity, the data should be odd parity, therefore it has been sent and received correctly

00100011110 being sent with even parity

Answer:

11 10 09 08 07 06 05 04 03 02 01 number the columns and highlight the powers of 2
0 0 1 0 0 0 1 1 1 1 0 insert your data
0 0 1 0 0 0 1 1 1 1 0 highlight the check bits
0 1 0 1 1 0 taking the 1st power of 2^0 (1) check 1 skip 1 = odd parity! Dodgy!
0 0 0 0 1 1 taking the 2nd power of 2^1 (2) check 2 skip 2 = even parity. OK
0 0 1 1 taking the 3rd power of 2^2 (4) check 4 skip 4 = even parity! OK
0 0 1 0 taking the 4th power of 2^3 (8) check 8 skip 8 = odd parity. Dodgy!

We have a mixture of odd and even parity, this means that there has been a mistake in sending this data. But where is the error? It has something to do with the lines that have odd parity!

Detecting and correcting errors

  1. Number the column headings
  2. Highlight the column headings that are powers of 2 (1,2,4,8), these are the parity bits
  3. Insert your data and highlight the parity bits
  4. Work your way through the parity bits
    1. 2^0 = 1 : check 1, skip 1, check 1, skip 1 ... write down whether it's odd or even parity
    2. 2^1 = 2 : check 2, skip 2, check 2, skip 2 ... write down whether it's odd or even parity
    3. 2^2 = 4 : check 4, skip 4, check 4, skip 4 ... write down whether it's odd or even parity
    4. etc..
  5. If there is a disparity between rows, highlight all the error data and find where it overlaps
Example: Even Parity Hamming Code Check

Let's take a look a an example of data sent with even parity

11 10 09 08 07 06 05 04 03 02 01 number the columns and highlight the powers of 2
1 0 0 1 0 0 1 0 1 1 1 insert your data
1 0 0 1 0 0 1 0 1 1 1 highlight the check bits
1 0 0 1 1 1 taking the 1st power of 2^0 (1) check 1 skip 1 = even parity
1 0 0 0 1 1 taking the 2nd power of 2^1 (2) check 2 skip 2 = odd parity PROBLEM!
0 0 1 0 taking the 3rd power of 2^2 (4) check 4 skip 4 = odd parity PROBLEM!
1 0 0 1 taking the 4th power of 2^3 (8) check 8 skip 8 = even parity

Note that two of the lines, 2^1 and 2^2, show that an error has been detected. This means that somewhere that these lines cross over a bit has been corrupted, namely bit 6 or bit 7. If we know which one it is we can then switch it and correct the error.

Look at the other checks that are in play, do any of them take part in this crossover? Looking at it, the 2^0 line also checks column 7 and it found it fine. So we are left with column 6 being the problematic one. As Hamming code is corrective, let's flip that column and we should have a correct piece of data.

Another way of finding errors is to add the check digit values together, the error occurs where the check digit equals 4 and 2. Add 4 +2 = 6, the error is with the 6th digit!

11 10 09 08 07 06 05 04 03 02 01 number the columns and highlight the powers of 2
1 0 0 1 0 1 1 0 1 1 1 insert your data
1 0 0 1 0 1 1 0 1 1 1 highlight the check bits
1 0 0 1 1 1 taking the 1st power of 2^0 (1) check 1 skip 1 = even parity
1 0 0 1 1 1 taking the 2nd power of 2^1 (2) check 2 skip 2 = even parity
0 1 1 0 taking the 3rd power of 2^2 (4) check 4 skip 4 = even parity
1 0 0 1 taking the 4th power of 2^3 (8) check 8 skip 8 = even parity

The number is now even parity and correct: 10010110111

Exercise: Detect and Correct the error in the following Hammed Code

Now try this example with even parity:

01101001011

Answer:

11 10 09 08 07 06 05 04 03 02 01 number the columns and highlight the powers of 2
0 1 1 0 1 0 0 1 0 1 1 insert your data
0 1 1 0 1 0 0 1 0 1 1 highlight the check bits
0 1 1 0 0 1 taking the 1st power of 2^0 (1) check 1 skip 1 = odd parity PROBLEM!
0 1 1 0 0 1 taking the 2nd power of 2^1 (2) check 2 skip 2 = odd parity PROBLEM!
1 0 0 1 taking the 3rd power of 2^2 (4) check 4 skip 4 = even parity
0 1 1 0 taking the 4th power of 2^3 (8) check 8 skip 8 = even parity

The error is in the lines crossing over, that is on lines 2^0 and 2^1, but which bit is it?

You'll notice that the 2^2 and 2^3 lines are correct so we can discount any bits that are covered in those lines. This leaves us with the third column. Flipping this value gives us the corrected value of: 01101001111

11111101000 sent with odd parity

Answer:

11 10 09 08 07 06 05 04 03 02 01 number the columns and highlight the powers of 2
1 1 1 1 1 1 0 1 0 0 0 insert your data
1 1 1 1 1 1 0 1 0 0 0 highlight the check bits
1 1 1 0 0 0 taking the 1st power of 2^0 (1) check 1 skip 1 = odd parity
1 1 1 1 0 0 taking the 2nd power of 2^1 (2) check 2 skip 2 = even parity PROBLEM!
1 1 0 1 taking the 3rd power of 2^2 (4) check 4 skip 4 = odd parity
1 1 1 1 taking the 4th power of 2^3 (8) check 8 skip 8 = even parity PROBLEM!

The error is in the lines crossing over, that is on lines 2^1 and 2^3, but which bit is it? We can look at the place they cross over, bit ten, alternatively we can add the parity bit numbers together the row of parity bit 2 plus the row of parity bit: 2 + 8 = bit 10.

Flipping this value gives us the corrected value of: 10111101000

00111000101 sent with even parity

Answer:

11 10 09 08 07 06 05 04 03 02 01 number the columns and highlight the powers of 2
0 0 1 1 1 0 0 0 1 0 1 insert your data
0 0 1 1 1 0 0 0 1 0 1 highlight the check bits
0 1 1 0 1 1 taking the 1st power of 2^0 (1) check 1 skip 1 = even parity
0 0 1 0 1 0 taking the 2nd power of 2^1 (2) check 2 skip 2 = even parity
1 0 0 0 taking the 3rd power of 2^2 (4) check 4 skip 4 = odd parity. PROBLEM!
0 0 1 1 taking the 4th power of 2^3 (8) check 8 skip 8 = even parity

There is only one line with an error, the line of parity bit 4. This means that the error is in bit 4,5,6 or 7. Parity bit lines 1 and 2 imply that bits 5,6,7 are all fine, leaving us with the error in bit 4. Alternatively, as the error only occurs on parity bit line 4, then we know the error is with bit 4!

Flipping this value gives us the corrected value of: 00111001101

Applying hamming code

  1. Number the column headings
  2. Highlight the column headings that are powers of 2 (1,2,4,8), these are the parity bits
  3. Insert your data into the bits that aren't parity bits
  4. Work your way through the parity bits
    1. looking at 2^0 : check 1, skip 1, check 1, skip 1 ... write the parity bit in column 1 to make the bits the desired parity
    2. looking at 2^1 : check 2, skip 2, check 2, skip 2 ... write the parity bit in column 2 to make the bits the desired parity
    3. looking at 2^2 : check 4, skip 4, check 4, skip 4 ... write the parity bit in column 4 to make the bits the desired parity
    4. ...
Example: Applying Hamming code to an ASCII character

We are going to take a look at sending the ASCII letter e: 1100101 with odd parity. This data would then be ready to send

11 10 09 08 07 06 05 04 03 02 01 number the columns and highlight the powers of 2
1 1 0 ? 0 1 0 ? 1 ? ? insert your data in columns that aren't parity bits
1 0 0 0 1 ? taking the 1st power of 2^0 (1) check 1 skip 1 then work out the digit that is needed to go into the parity bit to apply odd parity ? = 1
1 1 0 1 1 ? taking the 2nd power of 2^1 (2) check 2 skip 2 then work out the digit that is needed to go into the parity bit to apply odd parity ? = 1
0 1 0 ? taking the 3rd power of 2^2 (4) check 4 skip 4, then work out the digit that is needed to go into the parity bit to apply odd parity ? = 0
1 1 0 ? taking the 4th power of 2^3 (8) check 8 skip 8, then work out the digit that is needed to go into the parity bit to apply odd parity ? = 1

We have now worked out the odd parity Hammed number ready for sending: 11010100111

Exercise: Applying Hamming code to an ASCII character

Apply even parity hamming code so we can transmit the ASCII character 'D' (1000100):

Answer:

11 10 09 08 07 06 05 04 03 02 01 number the columns and highlight the powers of 2
1 0 0 ? 0 1 0 ? 0 ? ? insert your data in columns that aren't parity bits
1 0 0 0 0 ? taking the 1st power of 2^0 (1) check 1 skip 1 then work out the digit that is needed to go into column one to apply even parity ? = 1
1 0 0 1 0 ? taking the 2nd power of 2^1 (2) check 2 skip 2 then work out the digit that is needed to go into column one to apply even parity ? = 0
0 1 0 ? taking the 3rd power of 2^2 (4) check 4 skip 4, then work out the digit that is needed to go into column one to apply even parity ? = 1
1 0 0 ? taking the 4th power of 2^3 (8) check 8 skip 8, then work out the digit that is needed to go into column one to apply even parity ? = 1

We have now worked out the even parity Hammed number ready for sending: 10010101001


Apply even parity hamming code so we can transmit the ASCII character 'G':

Answer:


ASCII 'G' = 1000111

11 10 09 08 07 06 05 04 03 02 01 number the columns and highlight the powers of 2
1 0 0 ? 0 1 1 ? 1 ? ? insert your data in columns that aren't parity bits
1 0 0 1 1 ? taking the 1st power of 2^0 (1) check 1 skip 1 then work out the digit that is needed to go into column one to apply even parity ? = 1
1 0 0 1 1 ? taking the 2nd power of 2^1 (2) check 2 skip 2 then work out the digit that is needed to go into column one to apply even parity ? = 1
0 1 1 ? taking the 3rd power of 2^2 (4) check 4 skip 4, then work out the digit that is needed to go into column one to apply even parity ? = 0
1 0 0 ? taking the 4th power of 2^3 (8) check 8 skip 8, then work out the digit that is needed to go into column one to apply even parity ? = 1

We have now worked out the even parity Hammed number ready for sending: 10010110111

Apply odd parity hamming code so we can transmit the denary value 9:

Answer:

9 = 0001001

11 10 09 08 07 06 05 04 03 02 01 number the columns and highlight the powers of 2
0 0 0 ? 1 0 0 ? 1 ? ? insert your data in columns that aren't parity bits
0 0 1 0 1 ? taking the 1st power of 2^0 (1) check 1 skip 1 then work out the digit that is needed to go into column one to apply odd parity ? = 1
0 0 1 0 1 ? taking the 2nd power of 2^1 (2) check 2 skip 2 then work out the digit that is needed to go into column one to apply odd parity ? = 1
1 0 0 ? taking the 3rd power of 2^2 (4) check 4 skip 4, then work out the digit that is needed to go into column one to apply odd parity ? = 0
0 0 0 ? taking the 4th power of 2^3 (8) check 8 skip 8, then work out the digit that is needed to go into column one to apply odd parity ? = 1

We have now worked out the even parity Hammed number ready for sending: 00011000111


Gray coding

Changing binary numbers from one value to another can involve changing several bits at once. For example changing from 7 to 8, 0111 to 1000 involves 4 digits changing, but why is this an issue?

As you know, computers are very fast and sometimes multiple things happen at once, especially if you are dealing with realtime systems. If program 'A' wanted to read a number stored by program 'B', and read the number mid way through that number changing, program 'A' might read a midstate, an incorrect number.

0111 Program 'B' tells the number 7 to increment by 1 to 8
0101 (midstate 5) digit 2 changes
1101 (midstate 13) digit 4 changes <-Program 'A' fetches this number
1001 (midstate 9) digit 3 changes
1000 (final 8) digit 1 changes

Taking the simple example above, imagine if we were dealing with money where program B was working out the interest on your account, increasing your money from £7 to £8. Program A might be a cash machine telling you how much money you had in your account. If you look at the program above you see that the cash machine would tell you that you had £13, so you take out £13 and then become immediately overdrawn. (Bank databases actually use locking to solve this, but the example is a good one).

This could be particularly catastrophic if this error occurred in the military. Can you imagine an anti-air battery (Program A) deciding where to fire its missiles, and due to reading the direction of enemy planes stored on a remote radar system (Program B), shooting the missile in the wrong direction and shooting down an allied plane!

What is needed is Gray Code, a number system that changes one bit at a time to avoid midstates. Take a look at the examples below and see how only one bit changes for subsequent number:

Binary Number Gray Code
Rotary encoder for angle-measuring devices marked in 3-bit binary
0 = 000
1 = 001
2 = 010
3 = 011
4 = 100
5 = 101
6 = 110
7 = 111
Rotary encoder for angle-measuring devices marked in 3-bit binary-reflected Gray code (BRGC)
0 = 000
1 = 001
2 = 011
3 = 010
4 = 110
5 = 111
6 = 101
7 = 100

Usually in the exam you wouldn't be asked to convert anything more that 3 or 4 bits. But in case you do here is an easy method for converting binary to gray code.

Converting binary to gray code


  1. Take the first bit as it is.
  2. For the next bit, add the previous bit to the current bit.
  3. If you have a carry ignore it. E.g. 1+1=10. Take it as 0 rather than 10.
  4. Repeat for the rest of the bits.
Exercise: Gray Code

Explain how Gray Code works:

Answer:

Gray code works by only one bit changing between subsequent numbers. This is to avoid midstates

Explain why we might want to use Gray Code

Answer:

We need to use gray code in situations where we are worried about midstates. That means in situations where we might accidentally read a value before it has completely changed from one state to another, giving us an incorrect value.

Complete the following sequence of Gray Code states:

0 = 000
1 = 001
2 = ...
3 = ...
4 = ...
5 = 111
6 = 101
7 = 100

Answer:

0 = 000
1 = 001
2 = 011
3 = 010
4 = 110
5 = 111
6 = 101
7 = 100

Images

A large part of using modern computers involves sending pictures and films to each other, along with using a graphical user interface. All of this involves computers saving and processing images. This section will cover the two main image types: vector and bitmap, along with some compression techniques.

a comparison between a vector and bitmap representation of an image

Bitmaps

Overview

Bitmap Graphics - a collection of pixels from an image mapped to specific memory locations holding their binary colour value
Pixel - the smallest possible addressable area defined by a solid colour, represented as binary, in an image
This example shows an Bitmap image with a portion greatly enlarged, in which the individual pixels are rendered as little squares and can easily be seen. Try looking closely at your monitor or mobile phone screen to see if you can spot the pixels
Bitmaps are very good for storing things such as photographs

Resolution

Image Resolution - how many pixels an image contains per inch/cm
Screen Resolution - the number of pixels per row by the number of pixels per column
The higher the resolution, the more pixels are available. Therefore the crisper the picture
There are many different video display formats out there, with different widths and heights, and total numbers of pixels

Example

Example: Calculating screen resolutions

Using the diagram above we are going to work out how many pixels are required to display a single frame on a VGA screen.

Checking the resolution:

Height = 480
Width = 640
Area = Width * Height = Total Pixels
Area = 640 * 480 = 307200

Questions

Exercise: Calculating screen resolutions

What is a Pixel?

Answer:

The smallest possible addressable area defined by a solid colour, represented as binary, in an image.

What is Image Resolution?

Answer:

The amount of pixels an image contains per inch/cm

What is Screen Resolution?

Answer:

the number of pixels per row by the number of pixels per column

What is the resolution of a 100 pixel by 70 pixel image?

Answer:

100 * 70 = 7000 pixels

What is the resolution of a 30 pixel by 40 pixel image?

Answer:

30 * 40 = 1200 pixels

What is the resolution of HD 1080p image? (use the diagram above to help)

Answer:

1920 x 1080 = 2073600 pixels

If I have an image resolution of 700 pixels, and the height is 35, what is the width of the image?

Answer:

700 / 35 = 20 pixels

What is a benefit of having a higher resolution image?

Answer:

higher resolution images are able to display more detail, providing crisper images

What might be a draw back of having a very high resolution image

Answer:

It will require a lot of space to store it. Meaning you'll quickly run out of memory, or it'll take a long time to transmit images across the internet or other data route.

Colour Depth

Colour depth - The number of bits used to represent the colour of a single pixel


Colour depth 1 bit 2 bit 4 bit
Example
Description Mono-chrome, only stores black and white stores 4 colours:
RGB(70,61,55), RGB(79,146,85)
RGB(129,111,134), RGB(149,146,166)
Stores limited colours
Number of colours
per pixel
Colour depth 8 bit 24 bit
Example
Description close to reality hard to see any difference between reality
Number of colours
per pixel

It seems pretty obvious that the higher the colour depth, the closer the picture will look to reality. Why then don't we just ramp up the colour depth on every image that we make? The answer should be obvious, for a fixed resolution, the higher the colour depth, the larger the file size.

Example

Example: Calculating file size for different colour depths

All the images above are of the same resolution:

300*225 = 67500 pixels

If the first image uses 1 bit to store the colour for each pixel, then the image size would be:

Number of Pixels * Colour Depth = Image Size
      67500      *     1 bit    = 67500 bits

For the second image uses 2 bits to store the colour for each pixel, then the image size would be:

Number of Pixels * Colour Depth = Image Size
      67500      *    2 bit    = 135000 bits

Questions

Exercise: Colour Depth

What does colour depth mean?

Answer:

The number of bits used to represent the colour of a single pixel

For a colour depth of 8 bits, how many colours could each pixel store?

Answer:


To represent 1024 colours per pixel, what colour depth would I need?

Answer:


For an image of 30 by 40 pixels, what would the file sizes be for the following colour depths:

4 bits

Answer:


6 bits

Answer:


2 bits

Answer:


How many colours can each pixel store if it has a colour depth of 4bits?

Answer:


How many bits does the colour depth have to be if we want to store 64 colours per pixel?

Answer:

6 as: 

How many bits would an image be that has a size of 20 by 30 pixels, with each pixel able to display 8 colours?

Answer:

8 colours is 3 bits per pixel as: 
h * w * b = 20 * 30 * 3 = 1800 bits

When might one want to decrease the colour depth for an image?

Answer:

When you want to save file space or when you only need a specific palate of colours such a mono-chrome

Vectors

Vector Graphics - images defined using mathematics and geometry such as points, lines, curves, and shapes or polygon(s). Allowing for scalability.

Objects and properties stored mathematically.

Drawing list - a set of commands used to define a vector image


Vector graphics are made up of objects and their properties. An object is a mathematical or geometrically defined construct such as a rectangle, line or circle.

<rect ... />
<line ... />
<circle ... />

Each of these objects has properties to tell you the size, colour, position etc. Take a look at the next example to see how drawing lists are built from objects and properties.

Rectangle Circle Combination
Image
Drawing
List
<rect x="14" y="23"
 width="250" height="50"
 fill="green"
 stroke="black" stroke-width="1" />
<circle cx="100" cy="100" r="50"
 fill="red"
 stroke="black" stroke-width="5" />
  <rect
     width="100" height="80"
     x="0" y="70"
     fill="green" />
  <line
     x1="5" y1="5"
     x2="250" y2="95"
     stroke="red" />
  <circle
     cx="90" cy="80"
     r="50"
     fill="blue" />
   <text x="180" y="60">
     Un texte
   </text>
Notes x and y give the top left start location Note that the centre co-ordinate is defined through cx and cy
r gives the radius
Note that the circle is on top, this is because it was drawn last.
To leave out an edge stroke don't put the stroke command in.
The line has start x1,y1 and end x2,y2 coordinates.
Extension:SVG

There are several vector graphic formats out there, but an easy one to get started with is Scalable Vector Graphics (SVGs). SVGs are very easy to create and are supported by all modern major web browsers. To create an SVG, you need to add the tags <svg xmlns="http://www.w3.org/2000/svg"> at the beginning and </svg> at the end. Copy the following into a text file and save it as image.svg

<svg xmlns="http://www.w3.org/2000/svg">
  <rect
     width="100" height="80"
     x="0" y="70"
     fill="green" />
  <line
     x1="5" y1="5"
     x2="250" y2="95"
     stroke="red" />
  <circle
     cx="90" cy="80"
     r="50"
     fill="blue" />
   <text x="180" y="60">
     Un texte
   </text>
</svg>

Once you have saved this, drag it into a browser window and you should see some shapes. SVGs are very powerful and you can attach code to their structure, making them interactive. If you want to learn more about how make SVGs take a look at w3schools

Exercise: Vector Graphics

What is a drawing list

Answer:

a set of commands used to define a vector image

Give some objects that can be used in vector graphics:

Answer:

  • Line
  • Text
  • Rectangle
  • Circle

Give the properties needed to display a rectangle:

Answer:

  • x,y
  • width, height
  • fill
  • stroke (colour), stroke-width

Give the properties needed to display a line:

Answer:

  • x1,y1 - start coordinates
  • x2,y2 - end coordinates
  • width
  • fill
  • stroke (colour)

Give the definition of a vector image:

Answer:

images defined using mathematics and geometry such as points, lines, curves, and shapes or polygon(s). Allowing for scalability

Write a drawing list to create the following image:

Answer:

<rect
     width="1" height="1"
     x="2" y="1"
     fill="white" <!--optional you can leave this out-->
     stroke="black"
     stroke-width=1 /> <!--another small value will do-->
<rect
     width="1" height="1"
     x="11" y="0"
     fill="white" <!--optional you can leave this out-->
     stroke="black"
     stroke-width=1 />
<rect
     width="10" height="4"
     x="2" y="6"
     fill="black"
     stroke="red"
     stroke-width=5 /> <!--another small value will do-->
<circle
     cx="7" cy="5"
     r="2"
     fill="blue" />
What would the following drawing list produce:
<line
     x1="0" y1="0"
     x2="6" y2="6"
     stroke="red" />
<rect
     width="4" height="4"
     x="1" y="1"
     fill="yellow"
     stroke="green"
     stroke-width=1 />
<line
     x1="6" y1="0"
     x2="0" y2="6"
     stroke="black" />

Answer:

In the above code, name the objects involved

Answer:

rect and line

In the above code, list 4 different properties

Answer:

  • Fill
  • Stroke
  • Stroke-width
  • Width
  • Height
  • X,Y

Comparison between vector and bitmaps

This image illustrates the difference between bitmap and vector images. The bitmap image is composed of a fixed set of dots (pixels), while the vector image is composed of a fixed set of shapes. In the picture, scaling the bitmap reveals the pixels and scaling the vector image preserves the shapes.
  • Vector images scale without file size increase / decrease
  • Bitmap images scale resulting in file size increase / decrease
  • Vector images scale without distortion to the image
  • Bitmap images distort (pixellate) when scaling
  • Bitmaps are better for photo editing
  • Bitmaps require less processing power to display
Exercise: Vector vs Bitmap

You wish to create an image that will be made into a giant banner for the side of a building. What type should you use and why?

Answer:

Vector, as it allows for scaling without distortion and retaining its file size

You wish to create an image that will be used in a game, that will run on a mobile phone and a home console. What type should you use and why?

Answer:

Vector, as it allows for scaling without distortion and retaining its file size. You would only need one image to use on all the different systems.

You want to take an image of a local cat stuck in a tree. What type should you use and why?

Answer:

Bitmap as it is better for photographs.

Sounds

Sound is an oscillation of pressure transmitted through a solid, liquid, or gas (there is no sound in outer space as space is a vacuum and there is no solid, liquid or gas to transmit sound through!). A speaker works by moving its centre cone in and out, this causes the air particles to bunch together forming waves. These waves spread out from the speaker travelling at 340 m / s. If your ear is in the way, then the waves of sound particles will collide with your ear drum, vibrating it and sending a message to your brain. This is how you hear:

When you hear different volumes and pitches of sound all that is happening is that each sound wave varies in energy for the volume (larger energy waves, the louder the sound), or distance between sound waves which adjusts the pitch, (smaller distances between waves leads to higher pitched sound).

1 - base volume and frequency
2 - double volume and frequency
3 - same volume treble the frequency

Sound is often recorded for two channels, stereo, feeding a left and right speaker whose outputs may differ massively. Where one channel is used, this is called mono. 5.1 surround sound used in cinemas and home media set ups use 6 channels.

A computer representation of a stereo song, if you look carefully you'll see the volume of the song varying as you go through it

This section of the book will cover how we record, store and transmit sound using computers. Sound waves in nature are continuous, this means they have an almost infinite amount of detail that you could store for even the shortest sound. This makes them very difficult to record perfectly, as computers can only store discrete data, data that has a limited number of data points.

Sound is a continuous set of data points formed by a wave. Computers sample this sound at discrete points to store a digital approximation The discrete approximations (in red) can be used to recreate the original sound (grey). However, due to limitations in the number of samples we take we are often unable to truly represent a sound wave, though we can get close enough for the human ear not to notice the difference.

Analogue and digital

For a computer to store sound files we need to get the continuous analogue sound waves into discrete binary values:

An analogue sound wave is picked up by a microphone and sent to an Analogue to Digital (ADC) converter in the form of analogue electrical signals. The ADC converts the electrical signals into digital values which can be stored on a computer.

Once in a digital format you can edit sounds with programs such as audacity.

To play digital audio you convert the sound from digital values into analogue electrical signals using the DAC, these signals are then passed to a speaker that vibrating the speaker cone, moving the air to create sound waves and analogue noise.
Analogue to Digital Converter (ADC) - Converts analogue sound into digital signals that can be stored on a computer
Digital to Analogue Converter (DAC) - Converts digital signals stored on a computer into analogue sound that can be played through devices such as speakers
fig 1. The original analogue sound wave is a continuous set of points
fig 2. ADC converts sound into digital data
fig 3. DAC converts digital data into analogue sound, the analogue wave produced may differ significantly from the original sound wave
Exercise: Analogue and digital
What is the difference between analogue and digital data?

Answer:

Analogue data is continuous, allowing for an infinite number of possible values. Digital data is discrete, allowing for a finite set of values
Name the device used by computers to convert sound files into sound coming out of the speaker

Answer:

Digital to Analogue converter
Name a peripheral that could be used to feed sound into an ADC

Answer:

A microphone


This is a diagram of a system set up for recording, storing and saving sound. Fill in the numbers from the following options

  • ADC
  • DAC
  • Headphones
  • Main Memory
  • Microphone
  • Secondary Storage

Answer:

  1. Microphone
  2. ADC
  3. DAC
  4. Main Memory
  5. Headphones
  6. Secondary Storage


Why is it difficult to save analogue sound waves in a digital format?

Answer:

Analogue is continuous data, converting continuous data to discrete values may lose some of the accuracy

Sampled sound

So we should know by now that sound waves are continuous and computers can only store discrete data. How exactly does an Analogue to Digital Converter convert a continuous sound wave into discrete digital data? To do this we need to look at how computers sample sound.


Sampling rate

Sampling Rate - The number of samples taken per second
Hertz (Hz) - the SI unit of frequency defined as the number of cycles per second of a periodic phenomenon

To create digital music that sounds close to the real thing you need to look at the analogue sound waves and try to represent them digitally. This requires you to try to replicate the analogue (and continuous) waves as discrete values. The first step in doing this is deciding how often you should sample the sound wave, if you do it too little, the sample stored on a computer will sound very distant from the one being recorded. Sample too often and sound stored will resemble that being recorded but having to store each of the samples means you'll get very large file sizes. To decide how often you are going to sample the analogue signal is called the sampling rate. Take a look at the following example:

Original Sound High sample rate 1/2 high sample rate 1/3 high sample rate 1/4 high sample rate
original continuous sound wave digital looks like original digital loses sharpness loss of peaks poor resemblance to original

To create digital sound as close to the real thing as possible you need to take as many samples per second as you can. When recording MP3s you'll normally use a sampling rate between 32,000, 44,100 and 48,000 Hz (samples per second). That means that for a sampling rate of 44,100, sound waves will have been sampled 44,100 times per second! Recording the human voice requires a lower sampling rate, around 8,000 Hz. If you speak to someone on the phone it may sound perfectly acceptable, but try playing music down a telephone wire and see how bad it sounds.

Comparison of the same sound sample recorded at 8kHz, 22kHz and 44kHz sample rate. Note the spacing of the data points for each sample. The higher the sample rate the more data points we'll need to store

Sampling resolution

Sampling resolution - the number of bits assigned to each sample

As you saw earlier, different sounds can have different volumes. The sampling resolution allows you to set the range of volumes storable for each sample. If you have a low sampling resolution then the range of volumes will be very limited, if you have a high sampling resolution then the file size may become unfeasible. The sampling resolution for a CD is 16 bits used per sample.

File sizes

Bit rate - the number of bits required to store 1 second of sound

To work out the size of a sound sample requires the following equation:

File Size = Sample Rate * Sample Resolution * Length of sound

This is the same as saying:

File Size = Bit Rate * Length of sound

Let's look at an example:

Example: Sound File Sizes

If you wanted to record a 30 second voice message on your mobile phone you would use the following:

Sample Rate = 8,000 Hz
Sample Resolution = 16 bit
Length of Sound = 30 seconds

Therefore the total file size would be:

8,000 * 16 * 30 = 3 840 000 Bits = 480 000 Bytes
Extension: Sound Editing

If you are interested in sound editing you can start editing your own music using a program called Audacity. Using Audacity you can create your own sound samples with different sample rates and sample resolutions, listening to the difference between them and noting the different file sizes. Check out the following sound files recorded at different sampling rates:

Exercise: Sampled sound
Why might a digital representation of a sound struggle to be a perfect representation?

Answer:

A sound wave is continuous data, whilst digital data is discrete and the representation is an approximation of the original


Why might you choose to have a lower sampling rate than a higher one for storing a song on your computer?

Answer:

The higher the sampling rate the more data is needed to be stored, meaning the larger the file size.


What is the sampling resolution?

Answer:

the number of bits assigned to each sample, affecting the range of volumes that can be stored in a sample


What is the equation to work out the bit rate of a song

Answer:

Sampling Rate * Sampling Resolution


For the following sound sample work out its size:
Sample Rate = 16,000 Hz
Sample Resolution = 8 bit
Length of Sound = 10 seconds

Answer:

16,000 * 8 * 10 = 1 280 000 Bits


Work out the sample rate of the following sound file:
Sound File = 100,000 bits
Sample Resolution = 10 bit
Length of Sound = 5 seconds

Answer:

100,000 / (10 * 5) = 2,000 Hz

Why might a song recorded with the following settings:
Sample Rate = 22,000 Hz
Sample Resolution = 16 bit
Length of Sound = 10 seconds

have a file size of 7,040,000 bits?

Answer:

The file might be recorded in stereo, meaning twice the amount of data would have to be stored


Using the grid below, plot the following sample points for a sample resolution of 3 bits per sample: 000001100101100011100110111101

Answer:


Sample the sound wave below and convert it into binary form:

Answer:

101 101 101 011 001 000 001 001 100 100
Notice that you must approximate samples where the sample resolution doesn't allow for the needed level of detail


Sound compression

As you can see we have some serious issues with the size of sound files. Take a look at the size of a 3 minute pop song recorded at a sample rate of 44 kHz and a sample resolution of 16 bits.

44,000 * 16 * 180 = 126 720 000 bits (roughly 15 MB)

As you are probably aware an mp3 of the same length would be roughly 3Mb, a fifth of the size. So what gives? It is easy to see that the raw file sizes for sounds are just too big to store and transmit easily, what is needed it a way to compress them.

Lossless

Lossless compression - compression doesn't lose any accuracy and can be decompressed into an identical copy of the original audio data

WAV files don't involve any compression at all and will be the size of files that you have calculated already. There are lossless compressed file formats out there such as FLAC which compress the WAV file into data generally 50% the original size. To do this it uses run length encoding, which looks for repeated patterns in the sound file, and instead of recording each pattern separately, it stores information on how many times the pattern occurs in a row. Let us take a hypothetical set of sample points:

00000000000000000000012345432100000000000000000123456787656789876

As you can see the silent area takes up a large part of the file, instead of recording these individually we can set data to state how many silent samples there are in a row, massively reducing the file size:

(21-0)123454321(17-0)123456787656789876

Another technique used by FLAC files is Linear prediction.

Lossy

FLAC files are still very large, what is needed is a format that allows you to create much smaller file sizes that can be easily stored on your computer and portable music device, and easily transmitted across the internet.

Lossy compression - compression loses file accuracy, generally smaller than lossless compression

As we have already seen, to make smaller audio files we can decrease the sampling rate and the sampling resolution, but we have also seen the dreadful effect this can have on the final sound. There are other clever methods of compressing sounds, these methods won't let us get the exact audio back that we started with, but will be close. This is lossy compression.

Some audiophiles stick by vinyl records as this uncompressed music format doesn't lose audio accuracy like an mp3. However dirt and wear degrade the quality of vinyl

There are many lossy compressed audio formats out there including: MP3, AAC and OGG (which is open source). The compression works by reducing accuracy of certain parts of sound that are considered to be beyond the auditory resolution ability of most people. This method is commonly referred to as perceptual coding. It uses psychoacoustic models to discard or reduce precision of components less audible to human hearing, and then records the remaining information in an efficient manner. Because the accuracy of certain frequencies are lost you can often tell the difference between the original and the lossy versions, being able to hear the loss of high and low pitch tones.

Exercise: Sound compression
Why is it necessary to compress sound files?

Answer:

So that they take up less space and can be sent quickly across the internet or stored on portable music players


Name the two categories of compression available and give a file format for each

Answer:

Lossy (mp3/AAC/ogg) and lossless(FLAC)


perform run length encoding on the following sound file

012344444444444432222222222222211111111111111000000000000

Answer:

0123(12-4)3(14-2)(14-1)(12-0)


Describe a technique used to compress mp3 files

Answer:

perceptual coding reduces the quality of frequencies stored in a sound file that are beyond the auditory resolution of most people


When would it be best to use FLAC instead of ogg and vice-versa?

Answer:

  • when you really care about the sound quality and you're not bothered about the file size
  • when you are trying to make a sound file as small as possible

Nyquist-theorem

We have seen the various ways that you can reduce the size of files, we have also seen that humans have a limit to the frequencies that they can perceive, so what sampling rate would be needed to only store the samples that humans can perceive. The full range of human hearing is between 20 Hz and 20 kHz.

Extension: Human hearing limit

People are able to hear different frequencies, up to what level can you hear?

For x = 0 To 25
	Console.WriteLine("Can you hear: " & x * 1000 & "Hz?")
	Console.Beep(x * 1000, 500)
Next

You lose your hearing with age, so the older you are the less likely you are to be able to hear the full spectrum.

So why not just use 20 kHz as our sampling rate record 20k cycles per second and be done with it? There is a small problem:

Cycle - A complete oscillation (up and down) in a sound wave
Period - The time that a wave takes to oscillate one cycle.
Frequency - The number of waves passing a point per second
we are going to try and sample this sound that shows 3 cycles
taking one sample per cycle leads to a straight line! We're going to need more samples
taking 1.5 samples per cycle leads to a skewed representation

What we need to properly represent a sound wave is to sample it at least two times per cycle:

2 samples per cycle gives us a close representation of the sound

Therefore the minimum sampling rate that satisfies the sampling for the human ear is 40 kHz (2*20 kHz). The 44.1 kHz sampling rate used for Compact Disc was chosen for this and other technical reasons.

Nyquist's theorem - the sample rate should be at a frequency which is at least twice the value of the highest frequency in the sampled signal


Shannon's version of the theorem states:[1]

If a function x(t) contains no frequencies higher than B Hz, it is completely determined by giving its ordinates at a series of points spaced 1/(2B) seconds apart.

We can relate Frequency and period together using this equation. This equation will be very useful for working out the sample rate of a given wave.

 

What happens when you have a graph of time against displacement?
We know that Nyquist's Theorem is that the sample rate should be double than the highest frequency. So to calculate the sample rate,

  1. Work out the period by looking at the time taken for one complete oscillation.
  2. Work out the frequency
  3. Work out the sample rate with this:
 
  • TIP - sometimes the period is hard to determine in one go as it may not cross an easily readable point on the axis.
    • To Compensate, you can go to where it does cross the axis at a readable point, then divide by how many oscillations have occurred from 0 to the time
Exercise: Nyquist-theorem
Describe Nyquist's-theorem

Answer:

You should set the sample rate at a frequency which is at least twice the value of the highest frequency in the sampled signal


For a sound sample of maximum frequency 16 kHz what should the sample rate be?

Answer:

32 kHz


How many cycles per second in the following sample?

For the sample what should the sample rate be according to Nyquist's-theorem?

Answer:

the sample has a frequency of 4 cycles per second. using Nyquist's theorem you would have to sample this at at least 8 Hz

References

  1. C. E. Shannon, "Communication in the presence of noise", Proc. Institute of Radio Engineers, vol. 37, no. 1, pp. 10–21, Jan. 1949. Reprint as classic paper in: Proc. IEEE, vol. 86, no. 2, (Feb. 1998)

Sound synthesis

Fairlight CMI series II – an early digital synthesiser
Sound synthesis - Electronically generated sounds that mimic musical instruments or the human voice

Sound Synthesisers are also used to create electronic sounds, unknown in the traditional music scene. In 1951 the University of Manchester created the earliest example of computer generated music using the Ferranti Mark 1 computer. Since then computers have had a massive impact on the music industry and this section will look into sound synthesis.

Sound Synthesis generally creates smaller file sizes compared to recordings taken from live recordings such as MP3 and AAC as it records notation which the computer performs using a selection of programmed or digital instruments, rather than recording the wave forms of each second of sound. However, the recordings often don't sound as real as the live recordings. Listen to the music on the left to see what I mean.


MIDI connectors and a MIDI cable

A common means to produce sound synthesised music is by using MIDI. MIDI does not record analogue sound, but send digital signals recording musical notation, pitch and intensity, control signals for parameters such as volume, vibrato and panning, cues, and clock signals to set the tempo. The computer then interprets these commands and outputs sound corresponding to them. MIDI is a popular way to record music from devices such as electronic keyboards.


Extension: Creating a Sound Synthesiser

As we know each character on our keyboard has an ASCII code attached to it. We are going to take this code and turn our computer keyboard into a musical keyboard!

console.beep(frequency,duration)

Where frequency is the number of oscillations per second and duration is the length that the beep will last in milliseconds.

AscW(key)

Where AscW is the ASCII number of key pressed. Giving us:

        Dim duration As Integer = 200
        Dim frequency As Integer
        Dim key As String 'stores the numeric ASCII value

        Console.WriteLine("press any key to play music, press q to quit")

        Do
            key = Console.ReadKey().KeyChar 'get the numeric ASCII value input
            frequency = (AscW(key) + 50) * 50
            Console.Beep(frequency, duration)
        Loop Until key = "q"

To extend this try to add the following:

+ - increase and decrease frequency
= _ increase and decrease duration of sound
Exercise: Sound synthesis
Why might you prefer to use sound synthesis over recording an orchestra

Answer:

  • Sound synthesis produces smaller file sizes without loss of quality
  • Sound synthesis allows for easy editing of files after they have been recorded
  • Sound synthesis allows for sounds that would be unachievable using traditional instruments
Why might you not want to use sound synthesis

Answer:

  • Sound synthesis struggles to recreate the sounds made by traditional instruments
  • Sound synthesis struggles to recreate the human voice

Streaming audio

Gone are the days when you had to buy music on a wax cylinder, LP, tape, CD or MiniDisc. Nowadays if you want to get some music you can download it using a program such as iTunes or stream it using a website such as MySpace, YouTube, BBC iPlayer or Spotify.

The big difference between downloading audio and streaming it is that when you download something you generally have to acquire the whole file before you can play it, with streaming audio you play the file whilst you are downloading it. There are two types of streaming technology that you need to know, multi-cast and uni-cast.

Unicast connections require multiple connections from the same streaming server even when it streams the same content.
Multicasting broadcasts the same copy of the audio file over the entire network to a group of clients
Exercise: Streaming audio

Why might you want to stream audio instead of downloading it?

Answer:

Streaming audio allows you to play sound as soon as you have buffered a few seconds, downloading might require you to download the entire file before you can play any of it

Name a benefit and a drawback of using multicast streaming:

Answer:

a sever only has to distribute one version of a file to serve many people, saving processing power and bandwidth. on the other hand if someone wants to join a stream after it has started they might miss the beginning

Name a benefit and a drawback of using unicast streaming:

Answer:

Unicast streaming allows users to access an individual version of a file accessible as and when they want it. On the other hand it places a lot of stress on the server as 10 people watching a video will require ten times the bandwidth to deliver than through multicast

System development life cycle

From the Specification : The Life Cycle Model

Describe the stages of development of a hardware/software system

  • Analysis
  • Design
  • Implementation - Program the solution as per design.
  • Testing - Test the solution using selected test data.
    • Specify the method of testing the programmed solution (dry run testing, black box testing, white box testing)
    • Specify the selection of test data including normal (typical), boundary and erroneous data
  • Evaluation - Reflect on how successful the operational system is

The cycle

When creating software, hardware, or any kind of product you will go through several stages, we define these stages in the System Development Life Cycle. There are many other models out there that you might be interested in learning more about, but for this course we are going to learn the model shown below.

Any System Development Life Cycle should result in a high quality system that meets or exceeds customer expectations, is finished within time and cost limits, works effectively and efficiently and is inexpensive to maintain and cost-effective to improve upon. For this chapter we are going to look at how a computer games firm, 'Electronic Crafts', would look at making a new computer game.

Cycle

As this is called the Systems Development Life Cycle, it's quite usual that a company will then go back to the analysis once it has evaluated a product. Think about some of the software products that you use, they probably have a version number or a year, and reuse code and designs from previous years

  • Windows 95 -> Windows 98 -> Windows ME -> Windows XP -> Windows Vista -> Windows 7 -> Windows 8 -> Windows 8.1 -> Windows 10
  • FIFA International Soccer -> FIFA Soccer 95 -> FIFA Soccer 96 -> FIFA 97 -> FIFA Road to the World Cup 98 -> FIFA 99 -> FIFA 2000 -> etc.

With the Systems Development Life Cycle, you never just quit, you are always looking at ways to improve or surpass what you have created.

Analysis

When you are given any problem you should start off by finding out about the problem and getting an idea of what you will make to solve the problem by:

  • A detailed look at current systems
  • Establish the objectives of the new system

Electronic Crafts wants to create a game that will sell successfully, so it needs to see what the market wants to buy and what their current interests are. It will gather data on:

  • How previous similar products have sold (market data)
  • What customers are interested in (questionnaires and interviews)
  • Whether it has any code that could be adapted or reused (internal data)
  • Feasibility of making any proposed game (is it possible within the time, technical, cost and personnel limits to make the game?)

Once it has done its research, it will create a document listing objectives for the new system. These objectives must be SMART so that we can check if the system has been created successfully.

SMART means:

Letter Major Term Description Example Not acceptable!
S Specific Make sure that it's not ambiguous and it concerns a part of your system The system should be able to display 5 top scores in descending order My system should be good
M Measurable Is there any way that you can easily prove that you have met this objective. The game should load in less than 5 seconds My pages will be beautiful
A Attainable Make sure that within the time and resources available you will be able to complete the objective My system will allow the saving of user preferences The system needs to be complete and ready to ship within 4 days
R Relevant Is the objective going to help you meet your user needs? A receipt will be printed and emailed to the customer My cashier system will play MP3s in the background
T Time-bound You are limited in the time you have to complete this project. You must list the deadline in your Analysis somewhere and can you finish each objective in time? The system will re-use code from previous products The system will involve a completely new game engine and code
Example: Electronic Crafts Analysis

Electronic Crafts finds out that football games have sold very well in the past.

It finds out that with a new football season approaching, customers are interested in playing a game with the latest names and kits. The most popular console is the Super MES.

It has created previous football games, so it can re-use and adapt some of the code.

It has a budget of $5million, a team of 20, a year to create it, and the code from previous years to build upon.

Exercise: Analysis
Now we have all the data from Electronic Crafts we can set the Objectives, remember these must be SMART. Which of these are suitable:
  • The system will allow users to change player positions and keep track of game results:

Answer:

  • S - Yes
  • M - Yes, Yes you could demonstrate this
  • A - Yes, this should be possible
  • R - Yes, this is core to playing the game
  • T - Yes, this should be achievable within the time given


  • The game will have a real world clock displaying the time on the screen at all times

Answer:

  • S - Yes
  • M - Yes, Yes you could demonstrate this
  • A - Yes, this should be possible
  • R - No, this is very unusual, why would they need it? Unless the users specifically ask for it
  • T - Yes, this should be achievable within the time given
  • The system completely rebuild the game engine to use cutting edge 3D

Answer:

  • S - Yes
  • M - Yes, you could demonstrate this
  • A - Maybe, this might be possible, but why are you writing your own code, can't you re-use code from a previous version
  • R - Yes, the game will need graphics
  • T - No, doing this within a year time limit is too difficult.
  • The system will calculate and display the player ratings from each game, number of cards, goals etc.

Answer:

  • S - Yes
  • M - Yes, you could demonstrate this
  • A - Yes
  • R - Yes, this is a feature used in competing games
  • T - Yes


  • The system will always be online, every game you to play will be against people from around the world

Answer:

  • S - Yes
  • M - Yes, you could demonstrate this
  • A - No, you can't guarantee that everyone will have an internet connection, or their connections will be fast enough
  • R - No, technical restraints as above
  • T - Yes, this could be programmed within the time frame


  • The system should be really, really, really good

Answer:

  • S - No', what does 'really, really, really mean? Be more specific, e.g. 80% of test users should rate it outstanding
  • M - No, see above
  • A - Maybe, but how do you measure it?
  • R - Yes, you're aiming to be the best
  • T - Yes, you're hoping to make a top notch game within the time given
What is main aim of the Analysis:

Answer:

  • Create objectives that are SMART
Name some methods of carrying out your Analysis

Answer:

  • Look at competing products
  • Interviews and questionnaires with users
  • look at current systems
What restraints/limits might you have when looking at making a new product?

Answer:

  • Time
  • Money
  • Technical

Name the stages of the system life cycle in order

Answer:

Design

Once we have settled on what we are going to make and the objectives for the system, we need to set about designing the components. Design is important as it allows you to start thinking about how you will make things, and hopefully avoid making mistakes later.

The Process involved in the design of a product is looking at:

  • User interface
  • Processes
  • Data storage requirements
Example: Electronic Craft Design

For Electronic Crafts they now know we are making a football game for the Super MES.

This system only has a joypad interface, they'll have to note which buttons should do what, and where everything will appear on the screen

types of input are important to consider when designing interfaces

The process design is probably the most complicated part. How will the game work out when someone has scored, what will the code for playing a game on the internet look like etc. This may be designed using tools such as UML, Data flow diagrams and pseudo code. You don't need to know the specifics for this Unit but they will come in useful for the A2 project.

The design stage is very important to avoid mistakes later on

Finally, Electronic Crafts would need to think about how the game would be delivered to the customer (download vs disc), how games will be saved (On the machine, online or on a memory unit), and how online data would be stored (database details).

more and more products no longer require physical media
Exercise: Design
Why is it important for companies to design products?

Answer:

So that they can avoid mistakes later on by spotting them in the design stage

Name 3 things that a company should design

Answer:

  • User Interface
  • Processes
  • Data storage
How would you recommend a company distributes the latest computer game and why?

Answer:

They should do it online, so that it is faster to get to the customer and companies don't have to pay so much in distribution costs. It also allows for updates to be released without having to recall all the discs

Alternatively

They should distribute it using Blu-ray discs as they offer lots of space and some people have very slow internet connections. They can also be sold in shops, meaning customers will see them and be tempted to buy them

Implementation

You might think that all implementation involves is creating the game. You'd be wrong, it involves the following:

  • Programming the software / creation of hardware
  • Installation of hardware and software
  • Preparation of data files
  • Training of users
  • Writing the system documentation

And at the same time make sure that the system that you build fits in with what you designed

Example: Electronic Crafts Implementation

Electronic Crafts will use the designs and code from previous products to code the game, probably in C++.

They will set up the servers to handle the online play, they will write code to install the game automatically on users machines after paying for it and downloading/putting the disc in the drive.

They will set up data files on the users Super MES and on the online server to handle user and game data

They will create a user manual and website to guide users in playing the game

Exercise: Implementation
On top of programming a solution, what else does the Implementation involve?

Answer:

  • Installation of hardware and software
  • Preparation of data files
  • Training of users
  • Writing the system documentation
For a firm creating supermarket checkout machines, explain what they would do for each stage:

Answer:

  • Programming the software / creation of hardware
    • Put hardware together and program software
  • Installation of hardware and software
    • put new machines in store, and install software on them. Make sure that tills talk to central pricing database
  • Preparation of data files
    • make sure pricing information is up to date
  • Training of users
    • train shop staff in using the new system
  • Writing the system documentation
    • create user manual and online resources to aid use
What forms might system documentation take:

Answer:

The most common is a user manual. There might also be a website and videos

Testing

Once we have created our solution we need to test that the whole system functions effectively. To do this should be easy, as all we need to do is compare the finished product next to the objectives that we set out in the Analysis. There are several ways of testing a system, you need to know them all and the types of data that might be used.

Test Plan

At an early stage in a project you should consider how the system will be tested to see if it works correctly. There are three main test methodologies that you need to be aware of, and able to choose between.

Black Box Testing

Black Box testing model

Consider the box to contain the program source code, you don't have access to it and you don't have to be aware of how it works. All you do is input data and test to see if the output is as expected. The internal workings are unknown, they are in a black box. Examples of Black Box testing would be if you were working as a games tester for a new console game. You wouldn't have been involved in the design or coding of the system, and all you will be asked to do is to input commands to see if the desired results are output.

White Box Testing

White Box testing model showing various routes through the code being put to test

With white box testing you understand the coding structure that makes up the program. All the tests that you perform will exercise the different routes through the program, checking to see that the correct results are output.

Dry Run Testing

A dry run is a mental run of a computer program, where the computer programmer examines the source code one step at a time and determines what it will do when run. In theoretical computer science, a dry run is a mental run of an algorithm, sometimes expressed in pseudocode, where the computer scientist examines the algorithm's procedures one step at a time. In both uses, the dry run is frequently assisted by a trace table. And whilst we are here we might as well get some more practice in:

Exercise: Dry run testing

Complete the trace table for the following code:

var a <- 5
var b <- 4
var count <- 0
while count < b
  a <- a + a
  count <- count + 1
end while
a b count
5 4

Answer:

a b count
5 4 0
10 4 1
20 4 2
40 4 3
80 4 4


Complete the trace table for the following code:

array nums() <- {4,2,5,2,1}
var z <- 4
var high <- nums(0)
while z > 0
  if high < nums(z)
    high <- nums(z)
  end if
  z <- z - 1
end while
z high
4 4

Answer:

z high
4 4
3 4
2 4
1 5
0 5


Summary

Method Availability of Source Header text
Black Box No Example
White Box Maybe (understanding required) Example
Dry Run Yes Example
Exercise: Testing Methodology

Name the suitable testing methods for each of the following scenarios:

  • You don't have access to the source code and need to check that some input produces the desired output:

Answer:

Black Box Testing as you don't have access to the internal workings of the program

  • There is a bug somewhere in the code producing the wrong output for a given input, you have access to the code

Answer:

Dry Run Testing as you have access to the source and this will allow you to find the offending line(s) of programming

Dry run test the following algorithms:

Typical, Erroneous, Extreme

There are three types of test data we can use. What are they? The answer lies mostly in their name, let's take a look at this example where someone has created a secondary school registration system which lets students register themselves. We don't want people who are too young attending, and we don't want students who are too old. In fact we are looking for students 11–16 years old.

  • A Typical Student will be 12,13,14 or 15
  • An Erroneous (or wrong) aged student will be 45, 6 or any age outside those allowed.
  • An Extreme (or boundary) aged student has just started or is just about to leave, they will be 11 or 16

If you are testing data that has Typical, Erroneous and Extreme data, show tests for all three. Some tests might only have typical and erroneous, for example entering a correct password might only have a typical and an erroneous value. Some things might only have typical testing, such as if a button to a next page works or not, or if a calculation is correct.

Example: Electronic Crafts Test Data

Imagine that the following objectives were set:

The maximum number of yellow cards a player can receive in a game is 2
Typical : 0,1,2 (most likely to list 1)
Erroneous: 3, -6
Extreme: 0,2

There should be no more than 15 minutes extra time in a game
Typical : 0,1m45,9m23
Erroneous: -6, 15m01
Extreme: 0,15m00

The name of a team should be no longer than 20 characters
Typical : Monster United
Erroneous: Monster and Dagrington League of Gentlefolk
Extreme: Moincicestier United (20 characters!)

Exercise: Test Data
List the typical, erroneous and extreme data for the following:
  • The number of cigarettes currently in a 20 cigarette carton:

Answer:

Typical : 5,16,18 

Erroneous: 21, -7
Extreme: 0 or 20

  • The age of a college teacher:

Answer:

Typical : 28,56,32

Erroneous: 16, 86
Extreme: 21, 68

  • The username for a system that must be of the form <letter><letter><number><number>:

Answer:

Typical : GH24

Erroneous: G678
Extreme: AA00, ZZ99

  • The date for someone's birthday:

Answer:

Typical : 12/07/1987

Erroneous: 31/09/1987, 31/02/1987
Extreme: 31/12/1999, 01/01/2001 (this is harder to specify, it might depend on the age range you allow)

  • Someone's hair colour:

Answer:

Typical : brown, red, black
Erroneous: bicycle
Extreme: n/a (we're not here to judge people!)

  • Does the following calculation work: 14 * 2

Answer:

Typical : 28

Erroneous: 23
Extreme: n/a

  • Number of pages in a book

Answer:

Typical : 24, 500
Erroneous: -9
Extreme: 1 (notice no upper end, this is assuming that it wouldn't be a book without any pages!)

  • Name a date in February:

Answer:

Typical : 23rd, 16th
Erroneous: 30th (you might also mention leap years here)
Extreme: 1st, 28th or 29th (depending on leap years)

Evaluation

The final thing you should do is evaluate how it all went. Remember we are talking about a systems development life cycle here, so if you made any mistakes or things didn't go to plan it's best to make a note of them. Then next time round you won't make the same mistake. However, the main part of the evaluation is to reflect on how successful the operational system is:

  • Review to confirm the new system meets the original objectives
  • Identify any necessary modifications
An example of a Project Evaluation
Objective Complete Notes
Create 3D models of stadia Yes These are all complete and imported
Implement a multiplayer internet game No internet multiplayer is laggy and unplayable. We need to spend more time testing.
Implement Computer player AI Yes AI is implemented, but doesn't offer enough challenge, next time we need to recruit an AI specialist

Skeleton code

The exam questions are very hard to predict and this site is by no means going to give you everything you need for the questions you'll sit. The most important thing you should do is learn how to program, and learn how to program well!

Footnotes