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

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

Contents

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 Computing. It aims to fit in with the AQA GCE A-Level Computing 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 Computing students have.

AS modules

A2 modules

Programming

Accepted languages (please note that support for PHP, C and C# at AS Level was withdrawn in 2011)

A2 Projects can be written in any language.

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.

x=\frac{-b \pm \sqrt {b^2-4ac}}{2a}

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

  1. b^2
  2. 4ac
  3. b^2-4ac
  4. \sqrt {b^2-4ac}
  5. -b + \sqrt {b^2-4ac}
  6. 2a
  7. x=\frac{-b + \sqrt {b^2-4ac}}{2a}
  8. repeat for -b - \sqrt {b^2-4ac}

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:

1, 4, 7, 10, 13, 16, 19, 22, 25,

This is pretty easy with number sets, the above has the patternn = (n * 3) - 2. 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 patterns 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?
0, 1, 1, 2, 3, 5, 8, 13, 21, 34, ...

Answer :

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

F_n = F_{n-1} + F_{n-2},\!\,

with seed values

F_1 = 0,\; F_2     = 1

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 finished 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.

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.

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.

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.

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.

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
CPT-Structured Chart Data Couple.svg Data Couple Data being passed from module to module that needs to be processed.
CPT-Structured Chart Flag.svg 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:

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()
  dim num1 as integer
  dim num2 as integer
  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 :

CPT-Structured-Chart-Q1.svg

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
 
sub countdown(a)
  return a - 1
end sub
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 :

CPT-Structured-Chart-Q2.svg

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

Example of a simple finite state machine
p = start state
a = transition
q = accept state

A finite state machine consists of states, inputs and outputs. The number of states is fixed; when an input is executed, the state is changed and an output is possibly produced. Finite state machines are widely used when designing computer programs, but also have their uses in engineering, biology, linguistics and other sciences thanks to their ability to recognise sequences.

A finite state machine expressed visually is a State transition diagram. It is used to show all the states, inputs and outputs. Each state is represented with a circle, and each transition with an arrow. Transitions are labelled with an input that causes a transition and possibly an output that results from it. A double circle signifies the accept state. Not all FSMs will have an accepting state and it is possible they could run for ever

A finite state machine can be with or without outputs:

Finite state automaton

Finite State Automaton - an FSM with no outputs


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 one, 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

CPT-FSM-abcd.svg

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)

CPT-FSM-0123456789+-.svg

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 :

CPT-FSM-FSA-Banana.svg

Draw a finite state automata that will accept the words:

  • Tim
  • Grit
  • Grrrrrim

Answer :

CPT-FSM-FSA-Grim.svg

Mealy Machines

Mealy Machine - an FSM with outputs


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

CPT-FSM-Mealy-01.svg

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
CPT-FSM-Mealy-02.svg

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:

CPT-FSM-01.svg

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:

DFAexample.svg

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:

CPT-FSM-Mealy-01.svg

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 :

CPT-FSM-FSA-Traffic.svg

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 :

Deterministicfiniteautomaton.svg

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

CPT-Sequence-diagram.svg

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")

Assignment

Assigning a value to a variable

Dim x, y, sum as integer
x = 5
y = 15
sum = x + y

Selection

Selection is choosing a step

If-Then-Else-diagram.svg
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

Do-while-loop-diagram.svg
While-loop-diagram.svg
CPT-For-loop-diagram-complex.svg
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.

Dim y as integer = 3
For x = 1 to 4
	y = y + x
Loop
Console.writeline(y)

To do this we create a trace table:

x y output
1 3
2 4
3 6
4 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 35/7 = 5. 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 reckon 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

Bubble Sort

A bubble sort, a sorting algorithm that continuously steps through a list, swapping items until they appear in the correct order.

Bubble sort is a simple sorting algorithm that works by repeatedly stepping through the list to be sorted, comparing each pair and swapping them if they are in the wrong order. The pass through the list is repeated until no swaps are needed, which indicates that the list is sorted. The algorithm gets its name from the way larger elements "bubble" to the top of the list. It is a very slow way of sorting data and rarely used in industry. There are much faster sorting algorithms out there such as insertion sort and quick sort which you will meet in A2.

Bubble-sort.gif

Step-by-step example

Let us take the array of numbers "5 1 4 2 8", and sort the array from lowest number to greatest number using bubble sort algorithm. In each step, elements written in bold are being compared.

First Pass:
( 5 1 4 2 8 ) \to ( 1 5 4 2 8 ), Here, algorithm compares the first two elements, and swaps them since 5 > 1
( 1 5 4 2 8 ) \to ( 1 4 5 2 8 ), It then compares the second and third items and swaps them since 5 > 4
( 1 4 5 2 8 ) \to ( 1 4 2 5 8 ), Swap since 5 > 2
( 1 4 2 5 8 ) \to ( 1 4 2 5 8 ), Now, since these elements are already in order (8 > 5), algorithm does not swap them.
The algorithm has reached the end of the list of numbers and the largest number, 8, has bubbled to the top. It now starts again.

Second Pass:
( 1 4 2 5 8 ) \to ( 1 4 2 5 8 ), no swap needed
( 1 4 2 5 8 ) \to ( 1 2 4 5 8 ), Swap since 4 > 2
( 1 2 4 5 8 ) \to ( 1 2 4 5 8 ), no swap needed
( 1 2 4 5 8 ) \to ( 1 2 4 5 8 ), no swap needed
Now, the array is already sorted, but our algorithm does not know if it is completed. The algorithm needs one whole pass without any swap to know it is sorted.
Third Pass:
( 1 2 4 5 8 ) \to ( 1 2 4 5 8 )
( 1 2 4 5 8 ) \to ( 1 2 4 5 8 )
( 1 2 4 5 8 ) \to ( 1 2 4 5 8 )
( 1 2 4 5 8 ) \to ( 1 2 4 5 8 )
Finally, the array is sorted, and the algorithm can terminate.

Pseudocode implementation

The algorithm can be expressed as:

procedure bubbleSort( A : list of sortable items )
  do
    swapped = false
    for each i in 1 to length(A) - 1 inclusive do:
      if A[i-1] > A[i] then
        swap( A[i-1], A[i] )
        swapped = true
      end if
    end for
  while swapped
end procedure

Exercise: Bubble Sort

We will now look at an example in Visual Basic using an array of people's heights. The following data set is being passed:

height
1 98
2 12
3 99
4 54
  Sub bubbleSort(ByRef height() As integer)
        Dim swapped As Boolean
        Dim temp As integer
        'sort the elements
        Do
            swapped = False
            For Count = 1 To MaxSize - 1
 
                If height(Count + 1) < height(Count) Then
                    temp = height(Count)
                    height(Count) = height(Count + 1)
                    height(Count + 1) = temp
                    swapped = True
                End If
            Next
        Loop Until swapped = False
 
        'Print out the elements
        For Count = 1 To MaxSize
            Console.WriteLine(Count & ": " & height(Count))
        Next
    End Sub
Construct a trace table for the above code:
Swapped Count MaxSize Temp height
1 2 3 4
False 4 null 98 12 99 54

Answer :

Swapped Count MaxSize Temp height
1 2 3 4
False 4 null 98 12 99 54
True 1 98 12 98
2
True 3 99 54 99
False 1
True 2 98 54 98 99
3
False 1
2
3
What does the above code output?

Answer :

1: 12
2: 54
3: 98
4: 99

Show the following lists after one pass of bubble sort:

Sort into alphabetical order:

Henry, Cat, George, Mouse

Answer :

Cat, George, Henry, Mouse

Sort into alphabetical order:

G, C, N, A, P, C

Answer :

C, G, A, N, C, P

Sort into numerical order:

12, 56, 0, 23, 10

Answer :

12, 0, 23, 10, 56

Show the following after 2 passes

Sort into alphabetical order:

Emu, Shrike, Gull, Badger 

Answer :

Emu, Gull, Badger, Shrike (Pass 1)
Emu, Badger, Gull, Shrike (Pass 2)

Sort into numerical order:

99, 45, 32, 56, 12

Answer :

45, 32, 56, 12, 99 (Pass 1)
32, 45, 12, 56, 99 (Pass 2)

Let's look at a more complicated example, an array of structures, TopScores. The following data set is being passed:

TopScores
Name Score
1 Michael 45
2 Dave 78
3 Gerald 23
4 Colin 75
  Sub bubbleSort(ByRef TopScores() As TTopScore)
        Dim swapped As Boolean
        Dim temp As TTopScore
        'sort the elements
        Do
            swapped = False
            For Count = 1 To MaxSize - 1
 
                If TopScores(Count + 1).Score > TopScores(Count).Score Then
                    temp.Name = TopScores(Count).Name
                    temp.Score = TopScores(Count).Score
                    TopScores(Count).Score = TopScores(Count + 1).Score
                    TopScores(Count).Name = TopScores(Count + 1).Name
                    TopScores(Count + 1).Name = temp.Name
                    TopScores(Count + 1).Score = temp.Score
                    swapped = True
                End If
            Next
        Loop Until swapped = False
 
        'Print out the elements
        For Count = 1 To MaxSize
            Console.WriteLine(Count & ": " & TopScores(Count).Name & " " & TopScores(Count).Score)
        Next
    End Sub
Exercise: Bubble Sort (Harder)
Draw a trace table to see if it works:
Swapped Count MaxSize Temp TopScores
name score 1 2 3 4
name score name score name score name score
False 1 4 null null Michael 45 Dave 78 Gerald 23 Colin 75
 

Answer :

Swapped Count MaxSize Temp TopScores
name score 1 2 3 4
name score name score name score name score
False 1 4 null null Michael 45 Dave 78 Gerald 23 Colin 75
True 1 4 Michael 45 Dave 78 Michael 45
True 2 4
True 3 4 Gerald 23 Colin 75 Gerald 23
False 1 4
True 2 4 Michael 45 Colin 75 Michael 45
True 3 4
False 1 4
False 2 4
False 3 4

The output should be:

1: Dave 78
2: Colin 75
3: Michael 45
4: Gerald 23

Linear Search

The following pseudo code describes a typical variant of linear search, where the result of the search is supposed to be either the location of the list item where the desired value was found; or an invalid location -1, to indicate that the desired element does not occur in the list.

For each item in the list:
    if that item has the desired value,
        stop the search and return the item's location.
Return ''-1''
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
  If x = 10 Then
    console.writeline(-1)
  End If
Next

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

  Blank.svg Code Output
Down arrow Hexagonal Icon.svg

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

  Blank.svg Code Output
Down arrow Hexagonal Icon.svg

What are you searching for: z
-1

Exercise: Linear Search

"Cat","Mouse","Frog","Lion","Panda","Llama","Bee"

For the array above, how many searches would it take to find the following data:

"Panda"

Answer :

5

"Camel"

Answer :

7 and still it wouldn't find it!

For an n length list of items, what is the maximum number of searches it would take to see if an item is there or not?

Answer :

n. This is seen as very slow, there is a faster ways of searching called binary search that you will learn about in A2, however, the data must be ordered first.

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
Extension: Binary Search

Linear search isn't very fast, for example if you had 1,000,000,000 names in a database and you searched for "Miles", four things might happen:

  • Miles is at the beginning of the database and you find him quickly
  • Miles is in the middle of the database and you find him in around 500,000,000 searches
  • Miles is at the end of the database and it takes you a long time to find him

Or

  • Miles isn't in your list and it will take 1,000,000,000 comparisons to prove this!

The worst case scenario is 1,000,000,000 searches. The average case 500,000,000. There must be a faster way. There is!

If your data is sorted then you can perform a Binary Search. This involves splitting the data into half. For example, let's search for Miles again in a much smaller list:

{"Ali","Bernie","Claire","Mohammed","Peter", "Simon", "Yvonne"}
  • We compare Miles to the middle name, "Mohammed", Miles is before Mohammed in the alphabet so we know that Miles won't be in the right hand side of the list, we can 'throw it away'
{"Ali","Bernie","Claire","Mohammed","Peter", "Simon", "Yvonne"}
  • We split this new list in half and compare Miles with the new middle name, "Bernie", Miles is later in the alphabet than 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", 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 we use large lists. For example, our 1,000,000,000 item list would only take a maximum of 30 searches using Binary Search! It's very useful to have sorted data.

You will learn more about binary search and the speed of algorithms in A2

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:Media-playback-start-green.svg

You should get the following output:

  Blank.svg Code Output
Down arrow Hexagonal Icon.svg

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:

  1. module module1
    
  2.   sub main()
    
  3.     console.writeline("Hello there, my name is Peter and my age is 29")
    
  4.     console.writeline("6 * 6 = " & 6 * 6)
    
  5.     console.readline()
    
  6.   end sub
    
  7. 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:

  Blank.svg Code Output
Down arrow Hexagonal Icon.svg

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):
  Blank.svg Code Output
Down arrow Hexagonal Icon.svg

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

Yours Sincerely,
Dave

Answer :

  1. module module1
    
  2.   sub main()
    
  3.     console.writeline("Dear Teacher,")
    
  4.     console.writeline("My name is Dave and this homework is too easy.")
    
  5.     console.writeline("2 + 2 = " & 2 + 2) 'bonus points for using a sum!
    
  6.     console.writeline("")
    
  7.     console.writeline("Yours Sincerely,")
    
  8.     console.writeline("Dave")
    
  9.     console.readline()
    
  10.   end sub
    
  11. 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:

  1.         Dim name As String
    
  2.         Dim age As Integer
    
  3.         name = "Peter"
    
  4.         age = 29
    
  5.         Console.WriteLine("Hello " & name & " you are " & age & " years old")
    
  6.         Console.WriteLine("This also means you are " & age * 12 & " months old")
    
  7.         Console.WriteLine("Bye " & name & "!")
    
  8.         Console.ReadLine()
    

you might be expecting it to print out:

Hello name you are age years old

But instead it says:

  Blank.svg Code Output
Down arrow Hexagonal Icon.svg

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

What a friendly program! Let's break it 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 and you can perform all the sums you can perform on your little pocket calc performed and far far more using them!
  7. The great things about variables is that we can use them again and again, here we say "Bye " and using an ampersand 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..Z0..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:

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

Producing:

  Blank.svg Code Output
Down arrow Hexagonal Icon.svg

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 :

  1. dim name as string
    
  2. dim age as integer
    
  3. name = "Syeda"
    
  4. age = 31
    
  5. console.writeline("Hello " & name & " you are " & age & " years old")
    
  6. console.writeline("This also means you are " & age * 12 & " months old")
    
  7. console.writeline("This also means you are " & age * 365 & " days old")
    
  8. console.writeline("This also means you are " & age * 365 * 24 & " hours old")
    
  9. console.writeline("This also means you are " & age * 365 * 24 * 60 & " minutes old")
    
  10. console.writeline("This also means you are " & age * 365 * 24 * 60 * 60 & " seconds old")
    
  11. console.writeline("Bye " & name & "!")
    
  12. 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:
  1. dim x, y as integer
    
  2. x = 45
    
  3. y = 9
    
  4. console.writeline("The sum of x + y = " & x + y)
    
  5. console.writeline("y goes into x " & x / y & " times")
    
  6. console.writeline("x times y = " & x * y & " times")
    
  7. console.readline()
    

Answer :

  Blank.svg Code Output
Down arrow Hexagonal Icon.svg

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 *

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)

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). 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:

  Blank.svg Code Output
Down arrow Hexagonal Icon.svg

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


Notice the difference between a writeline and a write command.

Extension: Console methods

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
  Blank.svg Code Output
Down arrow Hexagonal Icon.svg

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 )
  Blank.svg Code Output
Down arrow Hexagonal Icon.svg

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


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 :

  Blank.svg Code Output
Down arrow Hexagonal Icon.svg

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 :

  Blank.svg Code Output
Down arrow Hexagonal Icon.svg

The average age
of a combat soldier in Vietnam was 19

Write code to display the following to the screen:

  Blank.svg Code Output
Down arrow Hexagonal Icon.svg

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:

Nobby
16

Answer :

  Blank.svg Code Output
Down arrow Hexagonal Icon.svg

Enter your name: Nobby
Enter your age: 16
Hello 16. You are Nobby 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

Operator - a programming device that performs a function on one or more inputs, for example arithmetic operators (+,-,/,*)


Visual Basic .NET provides 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. The Dim operator creates the variable.

  1.  Dim Commission As Single
    
  2.  Dim Sales As Single
    
  3.  Sales = 3142.51
    
  4.  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:

 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"

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

 Dim x As Integer = 54
 x += 89       ' result is 143
 x += 7       ' result is 150

It also works with Strings as a concatenation operator.

 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"

Subtraction

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

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

Multiplication

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

 Dim x As Integer
 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:

 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.

Integer division

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

 Dim x As Integer
 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." Examples:

 Dim x As Integer
 x = 7 Mod 2  ' Results in 1.
 x = 25 Mod 4 ' Results in 1.

Exponentiation

This is raising a number to a power. For example 7^2 in VB .Net code is:

 Dim x As Integer
 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.

 Dim x As Single
 x = 7 ^ 0.5 ' Results in a number around 2.645.

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.)

 Dim x As Integer
 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 is the can be calculated by raising the number to the power of 1/n:

 Dim x As Single
 Dim n As Single
 n = 7
 x = 2 ^ (1 / n)

This is because x ^ \frac{1}{n} = \sqrt[n]{x}.

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 )
  Blank.svg Code Output
Down arrow Hexagonal Icon.svg

1
3.57142857
2.57142857


If in doubt use the brackets!

Built-in data types

All programming languages have built in data types that are used when declaring variables (though not all programming languages have variables - don't worry about this yet though!). Some very 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:

  Blank.svg Code Output
Down arrow Hexagonal Icon.svg

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 driver 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 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:

  Blank.svg Code Output
Down arrow Hexagonal Icon.svg

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. Strongly means that you can't add a string to a integer, even if the string contains a number. Weakly typed allows 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)
  Blank.svg Code Output
Down arrow Hexagonal Icon.svg

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:

  Blank.svg Code Output
Down arrow Hexagonal Icon.svg

Insert radius: 5
area = 78.5398163
circumference = 31.4159265

Answer :

  1. const pi as single = 3.14
    
  2. dim r as single
    
  3. console.write("Insert radius: ")
    
  4. r = console.readline()
    
  5. console.writeline("area = " & pi * r * r)
    
  6. console.writeline("circumference= " & 2 * pi * r)
    
  7. 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

  Blank.svg Code Output
Down arrow Hexagonal Icon.svg

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 :

  1. const VAT as single = 0.175
    
  2. dim price1, price2 as single
    
  3. console.write("Insert price of item 1: ")
    
  4. price1 = console.readline()
    
  5. console.write("Insert price of item 2: ")
    
  6. price2 = console.readline()
    
  7. console.writeline("item 1 = " & price1 & " + " & price1 * VAT & " VAT = £" & price1 * (VAT + 1))
    
  8. console.writeline("item 2 = " & price2 & " + " & price2 * VAT & " VAT = £" & price2 * (VAT + 1))
    
  9. 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

If-Then-Else-diagram.svg

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
If name = "Queen" Then
	console.writeline("Hello your Majesty")
Else
	console.writeline("Get to the back of the queue!")
End If

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

If name = "Queen" Then
	console.writeline("Hello your Majesty")
End If

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

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
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:

  Blank.svg Code Output
Down arrow Hexagonal Icon.svg

What eyes have thee?
Green
Thou art a Goblin?

Alternatively:

  Blank.svg Code Output
Down arrow Hexagonal Icon.svg

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>

  Blank.svg Code Output
Down arrow Hexagonal Icon.svg

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


  Blank.svg Code Output
Down arrow Hexagonal Icon.svg

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


  Blank.svg Code Output
Down arrow Hexagonal Icon.svg

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:

  Blank.svg Code Output
Down arrow Hexagonal Icon.svg

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

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:

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

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.

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

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

name = "Queen" age = 18
name = "Quentin" age = 28
name = "Queen" age = 17
name = "Aashia" age = 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.

  Blank.svg Code Output
Down arrow Hexagonal Icon.svg

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

It should also handle:

  Blank.svg Code Output
Down arrow Hexagonal Icon.svg

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:

  Blank.svg Code Output
Down arrow Hexagonal Icon.svg

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.

If(input >= 18,console.writeline("drink beer"),console.writeline("drink cola"))

This is a much shorter way of writing:

If input >= 18 then
  console.writeline("drink beer")
Else
  console.writeline("drink cola")
End if

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

CASE-IF-THEN-END flowchart.png

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
  Blank.svg Code Output
Down arrow Hexagonal Icon.svg

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
  Blank.svg Code Output
Down arrow Hexagonal Icon.svg

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


A computer game example would be increasing the speed of a car while the accelerator is pressed down and until you hit its top speed.

dim maxSpeed as integer = 120
dim curSpeed as integer = 0
dim pedalPress as boolean = True
 
While curSpeed <= maxSpeed And pedalPress = True
   console.writeline(curSpeed)
   curSpeed = curSpeed + 1
End While
console.writeline("MAXSPEED!")
  Blank.svg Code Output
Down arrow Hexagonal Icon.svg

0
1
2
3
...
120
MAXSPEED!


Exercise: While Loops
Write a program that counts from 20 to 60 inclusive like so:
  Blank.svg Code Output
Down arrow Hexagonal Icon.svg

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:
  Blank.svg Code Output
Down arrow Hexagonal Icon.svg

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

While-loop-diagram.svg

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
  Blank.svg Code Output
Down arrow Hexagonal Icon.svg

0
1
...
118
119

Do While Loop

Do-while-loop-diagram.svg

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:

  Blank.svg Code Output
Down arrow Hexagonal Icon.svg

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:

  Blank.svg Code Output
Down arrow Hexagonal Icon.svg

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

CPT-Programming-FOR-Loop.svg

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:

  Blank.svg Code Output
Down arrow Hexagonal Icon.svg

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:

  Blank.svg Code Output
Down arrow Hexagonal Icon.svg

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!".

  Blank.svg Code Output
Down arrow Hexagonal Icon.svg

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

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!

  Blank.svg Code Output
Down arrow Hexagonal Icon.svg

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:

  Blank.svg Code Output
Down arrow Hexagonal Icon.svg

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

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 :

  Blank.svg Code Output
Down arrow Hexagonal Icon.svg

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:
  Blank.svg Code Output
Down arrow Hexagonal Icon.svg

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))
  Blank.svg Code Output
Down arrow Hexagonal Icon.svg

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,"."))
  Blank.svg Code Output
Down arrow Hexagonal Icon.svg

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"))
  Blank.svg Code Output
Down arrow Hexagonal Icon.svg

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"))
  Blank.svg Code Output
Down arrow Hexagonal Icon.svg

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)
  Blank.svg Code Output
Down arrow Hexagonal Icon.svg

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?")
  Blank.svg Code Output
Down arrow Hexagonal Icon.svg

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)
  Blank.svg Code Output
Down arrow Hexagonal Icon.svg

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)
  Blank.svg Code Output
Down arrow Hexagonal Icon.svg

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:
  Blank.svg Code Output
Down arrow Hexagonal Icon.svg

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 fistname as string = "Elizabeth Sheerin"
  Blank.svg Code Output
Down arrow Hexagonal Icon.svg

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:

  Blank.svg Code Output
Down arrow Hexagonal Icon.svg

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:

  Blank.svg Code Output
Down arrow Hexagonal Icon.svg

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:
  Blank.svg Code Output
Down arrow Hexagonal Icon.svg

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 letters or spaces, and it should start with a capital letter:

  Blank.svg Code Output
Down arrow Hexagonal Icon.svg

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:

  Blank.svg Code Output
Down arrow Hexagonal Icon.svg

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:
  Blank.svg Code Output
Down arrow Hexagonal Icon.svg

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:

  Blank.svg Code Output
Down arrow Hexagonal Icon.svg

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:

  Blank.svg Code Output
Down arrow Hexagonal Icon.svg

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 :

  Blank.svg Code Output
Down arrow Hexagonal Icon.svg

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:

  Blank.svg Code Output
Down arrow Hexagonal Icon.svg

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:

  Blank.svg Code Output
Down arrow Hexagonal Icon.svg

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.

F_n = F_{n-1} + F_{n-2},\!\,
A tiling with squares whose sides are successive Fibonacci numbers in length

For example:

0,1,1,2,3,5,8,13,21,34,55,89,144, ...

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:

  Blank.svg Code Output
Down arrow Hexagonal Icon.svg

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)

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

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

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

The output would be:

  Blank.svg Code Output
Down arrow Hexagonal Icon.svg

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:

  Blank.svg Code Output
Down arrow Hexagonal Icon.svg

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:

  Blank.svg Code Output
Down arrow Hexagonal Icon.svg

16


Exercise: Functions and Procedures

What is the difference between a function and procedure?

Answer :

Functions return values, Procedures don't

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:

  Blank.svg Code Output
Down arrow Hexagonal Icon.svg

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:

  Blank.svg Code Output
Down arrow Hexagonal Icon.svg

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:

  Blank.svg Code Output
Down arrow Hexagonal Icon.svg

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 :

  Blank.svg Code Output
Down arrow Hexagonal Icon.svg

7

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

Answer :

  Blank.svg Code Output
Down arrow Hexagonal Icon.svg

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 :

  Blank.svg Code Output
Down arrow Hexagonal Icon.svg

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:

  1. Module Glocals
    
  2. 	Dim number1 as integer = 123
    
  3.  
    
  4. 	Sub Main()
    
  5. 		console.writeline(number1)
    
  6. 		printLocalNumber()
    
  7. 		printGlobalNumber()
    
  8. 	End Sub
    
  9.  
    
  10. 	Sub printLocalNumber
    
  11. 		Dim number1 as integer = 234
    
  12. 		console.writeline(number1)
    
  13. 	End Sub
    
  14.  
    
  15. 	Sub printGlobalNumber
    
  16. 		console.writeline(number1)
    
  17. 	End Sub
    
  18. End Module
    

What would the output be?

  Blank.svg Code Output
Down arrow Hexagonal Icon.svg

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 a 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:
  1. Module calcAge
    
  2. 	Sub Main()
    
  3. 		dim age as integer
    
  4. 		console.writeline("age?")
    
  5. 		age = console.readline()
    
  6. 		printMonths(age)
    
  7. 		printDays(age)
    
  8. 	End Sub
    
  9. 	Dim months as integer
    
  10. 	Sub printDays(a)
    
  11. 		Dim d as integer
    
  12. 		d = a * 365
    
  13. 		console.writeline(d)
    
  14. 	End Sub
    
  15. 	Sub printMonths(a)
    
  16. 		months = a * 12
    
  17. 		console.writeline(months)
    
  18. 	End Sub
    
  19. End Module
    

Answer :

Locals: age, d

Globals: months

  Blank.svg Code Output
Down arrow Hexagonal Icon.svg

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:
  1. Module greetings
    
  2. 	Dim q as integer = 6
    
  3. 	Sub sayGoodbye()
    
  4. 		for y = 1 to q
    
  5. 			console.write("bye,")
    
  6. 		loop
    
  7. 	End Sub
    
  8. 	Sub sayHello()
    
  9. 		dim q as integer = 4
    
  10. 		if q =< 4 then
    
  11. 			console.write("hi,")
    
  12. 		else
    
  13. 			console.write("hello,")
    
  14. 		endif
    
  15. 	End Sub
    
  16. 	Sub Main()
    
  17. 		console.writeline(q)
    
  18. 		sayHello()
    
  19. 		sayGoodbye()
    
  20. 		console.writeline(q)
    
  21. 	End Sub
    
  22. End Module
    

Answer :

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

Globals: q (on line 2)

  Blank.svg Code Output
Down arrow Hexagonal Icon.svg

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

CPT-arrays-2d-names.svg

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

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:
  Blank.svg Code Output
Down arrow Hexagonal Icon.svg

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 thee 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 :

  Blank.svg Code Output
Down arrow Hexagonal Icon.svg

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:

  Blank.svg Code Output
Down arrow Hexagonal Icon.svg

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, class (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.class = type.WIZARD
 
Dim Conan As player
Conan.name = "Conan"
Conan.health = 100
Conan.gold = 30
Conan.gender = "m"
Conan.class = 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. 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:

  Blank.svg Code Output
Down arrow Hexagonal Icon.svg

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, this time 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
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

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()
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

Read/write records from/to a file

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:

  1. Dim Price as decimal = 45.99
    
  2. Dim Tax as decimal = 0.20
    
  3.  
    
  4. Console.Writeline("Price {{=}} " & Price)
    
  5. Console.Writeline("VAT {{=}} " & Price * Tax)
    
  6. Console.Writeline("Total {{=}} " & Price + Tax)
    

In the above example you would expect it to print out:

  Blank.svg Code Output
Down arrow Hexagonal Icon.svg

Price = 45.99
VAT = 9.198
Total = 55.188

But because there is a logic error on line 6, it prints:

  Blank.svg Code Output
Down arrow Hexagonal Icon.svg

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:

  1. Console.Writeline("Total = " & Price + (Price * Tax))
    
Exercise: Validation

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:

  1. dim x as integer
    
  2. do until x > 5
    
  3.   x = 1
    
  4.   x = x + 1
    
  5. 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:

  1. dim n as sting
    
  2. console.writeline("enter your name")
    
  3. 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:

  1. Dim names() As String = {"Harry", "Dave", "Princess", "Nicky"}
    
  2. 'print all the names
    
  3. For x = 1 to 3
    
  4.    Console.Writeline("name " & x & " = " & names(x))
    
  5. 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:

  1. Dim names() As Sting = {"Harry", "Dave", "Princess", "Nicky"}
    
  2. Dim y As Integer
    
  3. y = Console.Readline()
    
  4. 'print some of the names
    
  5. For x = 0 to y
    
  6.    Console.Writeline("name " & x & " = " & names(x))
    
  7. 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:

  Blank.svg Code Output
Down arrow Hexagonal Icon.svg

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:

  Blank.svg Code Output
Down arrow Hexagonal Icon.svg

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: Validation
Use a try and catch to avoid the issue of a person inputting a value for y that would break the array.
  1. Dim names() As String = {"Harry", "Dave", "Princess", "Nicky"}
    
  2. Dim y As Integer
    
  3. y = Console.Readline()
    
  4. 'print some of the names
    
  5. For x = 0 to y
    
  6.    Console.Writeline("name " & x & " = " & names(x))
    
  7. Next
    

Answer :

  1. Dim names() As String = {"Harry", "Dave", "Princess", "Nicky"}
    
  2. Dim y As Integer
    
  3. y = Console.Readline()
    
  4. 'print some of the names
    
  5. Try
    
  6.    For x = 0 to y
    
  7.       Console.Writeline("name " & x & " = " & names(x))
    
  8.    Next
    
  9. Catch ex As Exception
    
  10.    console.writeline("Looks like we're exceeded our array index")
    
  11.    console.writeline(ex.message)
    
  12. 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 a 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 harder 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 is 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(\overline{P}) AND(P.Q) OR(P+Q) XOR(P \oplus Q)
Description invert input where exactly two 1s where one or more 1s where exactly one 1
Input P 01001010 01001010 01001010 01001010
Input Q 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 all 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)
  Blank.svg Code Output
Down arrow Hexagonal Icon.svg

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:

  Blank.svg Code Output
Down arrow Hexagonal Icon.svg

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

Sets describe collections of things such as numbers or people. For the exam you need to be familiar with the following terminology:

  • Membership
  • Union
  • Difference
  • Intersection

For the following examples we are going to use two sets. To define a set use the curly brackets {} and place all values of that set inside them.

Set A: All even naturals up to and including 12 = {0,2,4,6,8,10,12}
Set B: Natural multiples of 3 up to and including 12 = {0,3,6,9,12}

Membership

Membership defines what is contained in a particular set, it makes claims as to a particular things set membership. Set membership means "is an element of" and is written by ∈. The reverse "is NOT an element of" is written by ∉. Let's take a look at some examples:

Monday ∈ WeekDays (Monday is an element of WeekDays)
Monday ∉ Colours   (Monday is NOT an element of Colours)

Let us take a look at the two sets we are using as examples:

  • 0 ∈ A
  • 2 ∈ A
  • 0 ∈ B
  • 6 ∈ A AND 6 ∈ B
  • 7 ∉ B
  • 89 ∉ A

Union

The union of two sets:
~A \cup B

When we have sets we often want to perform actions on them, for example trying to find all the unique members contained in two sets. The union(∪) of A and B, denoted by A ∪ B, is the set of all things which are members of either A or B. It is similar to the boolean function OR. The union command allows us to perform this action:

  • {1, 2} ∪ {2,3,4} ={1,2,3,4}. (notice that we don't count 2 twice)
  • {1, 2} ∪ {red, white} ={1, 2, red, white}.
  • {1, 2, green} ∪ {red, white, green} ={1, 2, red, white, green}.
  • {1, 2} ∪ {1, 2} = {1, 2}.
Exercise: Union

Let us take a look at the two sets we are using as examples:

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}.

Difference

The difference of two sets:
A \setminus B

Difference(\) is used to work out the members unique to one set, members that are not also in the other set. It is similar to the boolean function NAND. A \setminus B = \{ x\in A \, | \, x \notin B \}. . Meaning elements that are members of A but not members of B. Let us look at some examples:

  • {1,2,3} ∖ {2,3,4}   =   {1}
  • {2,3,4} ∖ {1,2,3}   =   {4}
Exercise: Difference

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,1,2,3,5,8,13}    =

Answer :

{4,6,10,12}

Intersection

The intersection of two sets:
~A \cap B

We use intersection(∩) to find out all the elements that are members of one set, and also at the same time members of another set. It is similar to the boolean function AND. : xAB = xA AND xB. Let us look at some examples:

  • {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}
Exercise: Intersection
Let us take a look at the two sets we are using as examples: 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}

Programming

Not every programming language offers the ability to perform set theory calculations out of the box. In Visual Basic it has only been available since VB.NET 2008, using the LINQ libraries that you have to import to get it working:

Imports System.Linq
Imports System.Xml.Linq
 
Module Module1
    Sub Main()
 
    Dim A() As Integer = {0,2,4,6,8,10,12}
    Dim B() As Integer = {0,3,6,9,12}
 
    Dim unionAB = A.Union(B)
    Console.WriteLine("Union of A and B:")
    For Each n In unionAB
       Console.WriteLine(n)
    Next
 
    Dim differenceAB = A.Except(B) 'Except performs the same function as Difference
    Console.WriteLine("Difference of A and B:")
    For Each n In differenceAB
       Console.WriteLine(n)
    Next
 
    Dim intersectAB = A.Intersect(B)
    Console.WriteLine("Intersection of A and B:")
    For Each n In intersectAB
       Console.WriteLine(n)
    Next
 
    End Sub
End Module

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

The language that a computer understands is very simple, so simple that it only has 2 different numbers: 1 and 0. This is called Binary. 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

Bit - a standard unit to measure computer memory, consisting of of a value that is either 1 or 0


Byte - a standard unit to measure computer memory, consisting 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

How many bits in a 7 bytes?

Answer :

7 * 8 = 56

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 n for:

Maximum denary value of n binary digits:

Number of different values for n binary digits:

Exercise: Max and range of binary numbers

Give the maximum value and number of different values for the following n binary digits:

4

Answer :

Maximum : 2^n - 1 = 2^4 - 1 = 16 - 1 = 15

Range : 2^n = 2^4 = 16

5

Answer :

Maximum : 2^n - 1 = 2^5 - 1 = 32 - 1 = 31

Range : 2^n = 2^5 = 32

8

Answer :

Maximum : 2^n - 1 = 2^{8} - 1 = 256 - 1 = 255

Range : 2^n = 2^{8} = 256

10

Answer :

Maximum : 2^n - 1 = 2^{10} - 1 = 1024 - 1 = 1023

Range : 2^n = 2^{10} = 1024

For an address bus with 6 wires, what is the highest address that can be given, how many addresses can accessed?

Answer :

highest address : 2^n - 1 = 2^6 - 1 = 64 - 1 = 63

Different number of addresses : 2^n = 2^6= 64

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, 1 = 2^0, 2 = 2^1, 4 = 2^2, 8 = 2^3, and so on. To convert from hexadecimal to denary, we must use column headings that are powers with the base 16, like this:

16^3=4096 16^2=256 16^1=16 16^0=1
6 C F 5

5 \times 1 = 5

15 \times 16 = 240 (You should memorize the values A-F)

12 \times 256 = 3072

6 \times 4096 = 24576

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

CPT-Numbers-Conversion.svg
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.

Rotate right arithmetically.svg

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

So far we have only looked at whole numbers (integers), we need to understand how computers represent fractions.

You should have learned at Primary School how a decimal fraction works:

10 1 \frac {1}{10} \frac {1}{100}
10^1 10^0 10^{-1} 10^{-2}
1 2 . 7 5

As you can see, the column headings have been extended to 10^{-1}=\frac {1}{10} and 10^{-2}=\frac {1}{100}. We can do the same thing in binary with the column headings 2^{-1}=\frac {1}{2}, 2^{-2}=\frac {1}{4}, 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 \frac {1}{2} \frac {1}{4} \frac {1}{8} \frac {1}{16}
2^3 2^2 2^1 2^0 2^{-1} 2^{-2} 2^{-3} 2^{-4}
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

We are going to convert the number 6.125 into a binary fraction by using the grid below

8 4 2 1 \frac {1}{2} \frac {1}{4} \frac {1}{8} \frac {1}{16}
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 \frac {1}{2} \frac {1}{4} \frac {1}{8} \frac {1}{16}
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 \frac {1}{3} 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 that you will meet in A2.

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.1001 (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 = -54

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
  0001 0010 (10)
- 1110 0001 (-31)

Answer :

They have tried to trick you. What is the a 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:

   0001 0010 (10)
 + 0001 1111 (31)
   0011 0001 = 49
(¹)  ¹¹ ¹¹     the one carried over the bit 9 is ignored

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 a 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 (+6)

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

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.svg LINEAR B SYLLABLE B008 A D800, DC00
U+1D11E GClef.svg 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 measily 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 eigth 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 column one 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 column one 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 column one 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 column one 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 a 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 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 1 bit.png 2 bit.PNG 4 bit.png
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
2^1=2 2^2=4 2^4=16
Colour depth 8 bit 24 bit
Example 8 bit.png Truecolor.png
Description close to reality hard to see any difference between reality
Number of colours
per pixel
2^8=256 2^{24}=16777216

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 :

2^8 = 256

To represent 1024 colours per pixel, what colour depth would I need?

Answer :

2^{10} = 1024

For an image of 30 by 40 pixels, what would the file sizes be for the following colour depths:

4 bits

Answer :

30 * 40 * 4 = 4800 bits

6 bits

Answer :

30 * 40 * 6 = 7200 bits

2 bits

Answer :

30 * 40 * 2 = 2400 bits

How many colours can each pixel store if it has a colour depth of 4bits?

Answer :

2^4 = 16 colours

How many bits does the colour depth have to be if we want to store 64 colours per pixel?

Answer :

6 as: 2^6 = 64 colours

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: 2^3 = 8 colours
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 Svg example1.svg Svg example4.svg ExempleSimple.svg
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:

CPT-Graphics-VectorList1.svg

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 :

CPT-Graphics-VectorList2.svg

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:

CPT-sound-physical-manifestation.svg

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.

Sampled.signal.svg
Zeroorderhold.signal.svg
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 a 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
CPT-sound-ADCDAC-Q.svg

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 Convert 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
CPT-Sound-SamplingRate.svg CPT-Sound-SamplingRate-1.svg CPT-Sound-SamplingRate-2.svg CPT-Sound-SamplingRate-3.svg CPT-Sound-SamplingRate-4.svg
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,000Hz (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,000Hz. 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,000Hz
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, effecting 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,000Hz
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,000Hz

Why might a song recorded with the following settings:
Sample Rate = 22,000Hz
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
CPT-sound-grid.svg

Answer :

CPT-sound-grid2.svg

Sample the sound wave below and convert it into binary form: