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

From Wikibooks, open books for an open world
< A-level Computing‎ | AQA
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 Computer Science. It aims to fit with the AQA GCE A-Level Computer Science 2015 syllabus but is not endorsed by AQA. It should be useful as a revision guide or to find alternative explanations to the ones in your textbook. If you haven't heard of an A-Level then this book probably won't be of much interest to you but you can find out about them at Wikipedia.

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


2015 A-level

Paper 1

Paper 2

Non-exam assessment – the computing practical project

Programming

Accepted languages

A-Level Projects can be written in any language.

Old Specification

AS modules

A2 modules


How to read the book

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

Specification link

What the specification says you must learn for each chapter

Examples

Example questions and how to solve them

Questions

Questions to test yourself, click below

Answer :

to check if you were right

Extension

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

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

Word - meaning

Unit 1 - Summary

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

Definitions

Unit 1 definition list

The examination

Problem solving

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

Introduction to principles of computation

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

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

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

Decomposition

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

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

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

  1. repeat for

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

Pattern recognition

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

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

The face was automatically detected by pattern recognition

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

Pattern generalisation and abstraction

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

Algorithm design

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

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

Answer :

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

Answer :

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

with seed values

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

Answer :

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

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

Limits?

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

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

Answer :

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

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

console.writeline("hello")

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

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

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

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

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

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

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

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

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

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

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

References

Stages of problem solving

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

Understand the problem

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

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

Define the problem

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

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

For example:

Example: Defining the problem (Football game)

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

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

Define boundaries

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

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

Plan solution

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

Check solution

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

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

Top-down design and Step-wise refinement

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

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


Example: Making Pancakes

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

  • Make some pancakes

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

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

Each of these tasks can then be broken down further:

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

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

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

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

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

Answer :

Your answer probably won't be the same as this as the question is open to interpretation, but hopefully it'll be similar:
  • Make First Person Shooter
  1. Create graphics
    1. Characters
    2. Guns
    3. Maps
    4. Interface
  2. Create sounds
    1. Music
    2. SFX
  3. Create AI
    1. Non-playable characters
    2. Monsters

Stages of problem solving

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

Understand the problem

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

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

Define the problem

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

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

For example:

Example: Defining the problem (Football game)

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

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

Define boundaries

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

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

Plan solution

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

Check solution

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

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

Structure charts

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

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

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:

dim num1, num2 as integer

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

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

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

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

Create structure charts for the following code:

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

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

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

Answer :

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

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

Create structure charts for the following code:

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

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

function divBy3(x)
  return x + 1
end function

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

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

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

Answer :

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

Finite state machines

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

Consider an elevator :

[picture of elevator to be inserted here]


Possible states of the system:

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


[picture of states inserted here]


The transitions and their inputs:

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

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

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

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

[picture of state transition diagram to be inserted here]


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

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


A finite state automata accepting binary input

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

110011001
001110011

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

110011011

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

Exercise: Finite State Automaton

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

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

Linear Search

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

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

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

which can be directly translated to Python:

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

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

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

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

Here is the Python code:

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

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

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

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

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

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

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

  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

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

Answer :

5

And how many when searching for "Camel"?

Answer :

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

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

Answer :

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

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

Answer :

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

Binary Search

Binary Search
Class Search algorithm
Data structure Array
Worst case performance O(log n)
Best case performance O(1)
Average case performance O(log n)
Worst case space complexity O(1)

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

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

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

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

Exercise:Linear vs Binary Search

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

Answer :

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

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

Answer :

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

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

Answer :

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

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

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


Fundamentals of programming

Fundamentals of programming

Features of Imperative High Level Languages

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

Use the following appropriately.

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

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

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

Boolean operators NOT, AND, OR

Logical bitwise operators NOT, AND, OR, XOR

Set operators Union, difference, intersection, membership

Built-in functions

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


The Role of Variables

Recognise the different roles a variable can take:

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

Understand the structured approach to program design and construction.

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

Arrays

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

Variables

questions

Introduction

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

module module1
  sub main()

  end sub
end module

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

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

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

If you are using Visual Studio then you can make the program run by pressing F5 or hitting the Run button that looks a little like this: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:

VB.NET Python
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()
1         name = "Peter"
2         age = 29
3         print("Hello " + name + " you are " + str(age) + " years old")
4         print("This also means you are " + str(age * 12) + " months old")
5         print("Bye " + name + "!")

you might be expecting both programs to print out:

Hello name you are age years old

But instead they say:

  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 friendly programs!

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

  1. dim is a variable declaration, creating a temporary data store, a variable, and calling it name It also makes sure that whatever goes into name will be a string by setting it to as string
  2. We declare another variable called age and make sure it is stored as an integer (a whole number)
  3. The variable name that we created earlier is now assigned a value and as it's a string we better use speech marks - "Peter"
  4. The variable age that we created earlier is now assigned a value and as it's an integer we better not use speech marks - 29
  5. This line writes things to the screen, starting with the text "Hello " which attaches that variable we saw earlier to, but instead of putting the variable name, it puts the contents of the variable ("Hello Peter"), then it attaches some more text ("Hello Peter you are ") and adds another variable, age. Even though age is an integer we can stick it together with a string ("Hello Peter you are 29"). Then finally it uses the ampersand once more to attach the final piece of text ("Hello Peter you are 29 years old)
  6. This line works in pretty much the same way, but it does a calculation, working out the age in months. Computers are like giant calculators 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 multiplied by y = " & x * y)
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 *

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

  1. dim is a variable declaration, creating a temporary data store, a variable, and calling it name It also makes sure that whatever goes into name will be a string by setting it to as string
  2. We declare another variable called age and make sure it is stored as an integer (a whole number)
  3. We create a temporary data store, a variable name called name and assign a value and as it's a string we better use speech marks1 - "Peter"
  4. We create a temporary data store, a variable name called age and assign 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. To add the integer variable we convert it to a string using the built-in string function and this ("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.
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 Python we simply create it with a meaningful name.

Most programming languages have rules about identifiers: they generally have to use only Alphanumeric characters (a..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:

Notes

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

Comments

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

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


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

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

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

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

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

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

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

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


Python example

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

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

Inputs and outputs

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

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

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

Outputs

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

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

Let's see an example of this in action:

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

This would output the following:

  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.

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

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

will produce the output:

  Blank.svg Code Output
Down arrow Hexagonal Icon.svg

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


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

print("This output will", end="")
print(" all appear ", end="")
print("on the same line.", end="")
  Blank.svg Code Output
Down arrow Hexagonal Icon.svg

This output will all appear on the same line.


Extension: Console methods in VB.NET

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

console.

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

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

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

Find out more about the console command on the MSDN website

Inputs

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

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

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

dim name as string   'declare a variable called name
console.write("Please insert your name:") ' write "Hello" and the name to the screen
name = console.readline() 'assign the user's input into the variable name
console.writeline("Hello " & name) ' write "Hello" and the name to the screen
  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


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

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

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

  Blank.svg Code Output
Down arrow Hexagonal Icon.svg

Please enter your name:
Alice
Hello Alice


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

Answer :

  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:

John
16

Answer :

  Blank.svg Code Output
Down arrow Hexagonal Icon.svg

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


Whoops! Fix this:

Answer :

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

Arithmetic operators

Arithmetic Operation - is a function which can perform one of the following tasks: adding, subtracting, multiplying and dividing


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


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

+   Addition
-   Subtraction
*   Multiplication
/   Division
\   Integer division
Mod Remainder Division
^   Exponentiation
&   String concatenation

7 + 2     produces 9
7 - 2     produces 5
7 * 2     produces 14
7 / 2     produces 3.5
7 \ 2     produces 3
7 Mod 2   produces 1
7 ^ 2     produces 49
"7" & "7" produces "77"

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

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

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


First, we set the total Sales to 3142.51.

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

Why the funny symbols?

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

Addition

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

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

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

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

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

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

Subtraction

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

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

Multiplication

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

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

Division

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

Normal

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

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

Integer division

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

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

Remainder Division

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

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

Exponentiation

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

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

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

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

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

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

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

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

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

This is because .

BODMAS

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

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

For example:

console.writeline( (3+4)/7 )
console.writeline( 3+4/7 )
console.writeline( 3+4/7-1 )
  Blank.svg Code Output
Down arrow Hexagonal Icon.svg

1
3.57142857
2.57142857


If in doubt use the brackets!

Built-in data types

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

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

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

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

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

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

  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


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

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

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

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

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

Relational operators

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

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

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

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

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

we will get an error message similar to this:

  Blank.svg Code Output
Down arrow Hexagonal Icon.svg

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


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

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

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

  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
Example: Multiple Ifs versus Nested Ifs

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

VB.NET

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

Python 3

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

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

VB.NET

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

Python 3

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

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

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

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

  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.

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

This is a much shorter way of writing:

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

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

Case Statement

CASE-IF-THEN-END flowchart.svg

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

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


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

Think carefully before you answer each of these.

Answer :

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


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

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

While speedNow < maxSpeed And pedalDown
   console.writeline(speedNow)
   speedNow = speedNow + 1
End While
console.writeline("MAXSPEED!")
  Blank.svg Code Output
Down arrow Hexagonal Icon.svg

0
1
2
3
...
119
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.

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

For example:

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

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

Answer :

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

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

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

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

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

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

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

Extension: Parameters vs Arguments

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

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

The output would be:

  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 these limited datatypes aren't enough and a programmer wants to build their own datatypes. Just as an integer is restricted to "a whole number from -2,147,483,648 through 2,147,483,647", user-defined datatypes have limits placed on their use by the programmer.

Enumerated, subrange, sets

Enumerated

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

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

dim cardset as string
cardset = spade

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

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

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

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

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

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

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

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

Answer :

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

Answer :

  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, characterclass (barbarian, wizard, elf), gold, gender

Answer :

Enum type
   WIZARD
   BARBARIAN
   ELF
End Enum

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

Answer :

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

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

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

Extension: Object Orientation

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

File handling

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

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

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

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

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

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

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

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

Reading files

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

Example: Reading from a text file

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

VB.NET

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

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

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

        filereader.Close()
    End Sub
End Module

The above code would produce the following:

  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.


Python 3

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

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

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

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

The above code would produce the following:

  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.

Example: Writing to a text file

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

VB.NET

This time we are using the StreamWriter:

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

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

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

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


Python 3

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

textToFile = input()

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


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

VB.NET answer

Answer :

Imports System.IO

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

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

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

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

filewriter.Close()

Python 3 answer

Answer :

textToFile = ""

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

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

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

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

Answer :

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

CSV

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

ID, name, DoB, Comment
1, Peter, 12/12/12, Nice person
2, Simon, 13/13/13, "Must try harder, or he will fail"

This would produce:

ID name DoB Comment
1 Peter 12/12/82 Nice person
2 Simon 13/09/73 Must try harder, or he will fail

You might notice that .csv files are very simple and don't store any information on datatypes or style. So if you were to save your spreadsheet in Microsoft Excel as a .csv file you would lose all this information. In general .csv files are a small and simple way to transfer data.

Exercise: CSV
write a CSV file to hold the following table structure
POBOX Company Description
223 Computering Co. badly spelt, slight smell.
657 Acme Deals in everything.

Answer :

POBOX,Company,Description
223,Computering Co.,"badly spelt, slight smell"
657,Acme,Deals in everything.

File of records

When stored as (.csv), each line of a file is a data record. Each record consists of one or more fields, separated by commas. You should be able to move data between a 2d array and a csv file. The following code gives you an example of how to do this.

Example: Writing to a text file

Creating a .csv file from a 2d array.

Python 3

This example uses ",".join(inner). Join is a method of a string in python. It takes an array of strings and joins them into a single string using (in this case) a comma as glue. Note that if your array contains any non-string data types, this will not work and you will need to convert the elements of your array into strings first.

# mainArray contains the headers and 3 records for a database

mainArray = [["Name","Age","Favourite Fruit"],
             ["Alice","23","Apple"],
             ["Bob","34","Banana"],
             ["Claire","45","Cherry"]]

outputArray = []    #empty array. Each element will contain one line of csv data

for inner in mainArray:
    csvLine = ",".join(inner)       #each inner array (record) is turned into a single string
    csvLine = csvLine+"\n"          #a newline character is added to the end
    outputArray.append(csvLine)     #the finished string is appended to the output array

outFile = open("C:\database.csv",mode="w")
outFile.writelines(outputArray)     #outputArray written in one go to C:\database.csv
outFile.close()

Reading a .csv file into a 2d array

Python 3

Note that readlines() reads a text file into a one dimensional array of text. Each line from the original text file becomes a unique element in that array and includes the \n character from the end of each line.

inFile = open("database.csv",mode="r")
csvLines = inFile.readlines()   #csv file read into a 1d array
inFile.close()

mainArray = []                  #empty array defined        

for line in csvLines:
    line = line.strip()         #removes \n character from end of line
    inner = line.split(",")     #line is split into an array "inner"
    mainArray.append(inner)     #inner array appended into mainArray
Exercise: CSV File access
Write a program that asks you for the names, email and mobile phone number of your friends then writes them into a csv file.

Python 3 answer

Answer :

looping = ""
outputArray = []

while looping != "n":
    forename = input("Forename :")
    surname = input("Surname  :")
    email = input("Email    :")
    mobile = input("Mobile   :")

    csvLine = forename + "," + surname + "," + email + "," + mobile + "\n"
    outputArray.append(csvLine)
    
    looping = input("Hit enter to add another, enter n to stop")

op = open("friends.csv",mode="w")
op.writelines(outputArray)
op.close()
Write a program that reads the .csv file from the question above into a 2d array.

Python 3 answer

Answer :

inFile = open("friends.csv",mode="r")
csvLines = inFile.readlines()
inFile.close()

friends = []

for line in csvLines:
    line = line.strip()
    innerArray = line.split(",")
    friends.append(innerArray)
Extension: CSV Files

Write a program which extends the tasks above allowing you to maintain a friends list. You could include features such as searching for, adding, editing and deleting friends.

Extension: XML

A lot of modern programs and data formats such as LibreOffice and .odf use XML to store data, then compress the data to make the files smaller. XML is very similar to HMTL and SVG in that is uses tags, but the great thing about it is that you define what each tag is. Take a look at this example:

<?xml version="1.0"?>
<school>
  <class name="UCOM2">
    <student>
      <name>Omer</name>
      <age>12</age>
    </student>
    <student>
      <name>Sandra</name>
      <age>12</age>
    </student>
  </class>
</school>

XML has become increasingly important, especially with regards to the internet, if you want to learn more you can check out the tutorial at w3schools.

However there are people who hate XML: the files it makes are generally quite large, having to store all that tag information and when the internet is involved speed is often of the essence. A leaner way of sending data from one place to another is JSON which you can also find out about at w3schools.


Validation

Error types

When you write a program it often won't work as you expect. It might not compile, it might crash when you run it, or it might give you the wrong result. These are all errors with your code and we can place them into 3 different error categories:

  • Compilation Errors
  • Run-time Errors
  • Logic Errors

Let's take a look at what each of them mean.

Compilation (Syntax) error

You have probably met this error a lot, when you try and run your program it won't compile, giving you an error message. If you are using something like Visual Studio it will even underline the problem code with a blue squiggly line. There is a problem with the structure, or syntax, of the code that you have written. This might be a situation where you have forgotten to add a closing bracket or you have misspelt a key word. Take a look at this example:

For x = 1 two 9
  console.WriteLine(x)
Next

You should be able to see that in line 1 the programmer has misspelt the word to. This code won't work at all.

Run-time error

Sometimes you will have a program that compiles fine, but breaks when you actually run it. For example this code here:

Dim x as integer = 0
Dim total as integer = 0
While x < 5
  total = total + 1
Loop

The programmer has created an infinite loop, and the value of total will head towards infinity, eventually breaking the program.

Logic (Semantic) error

A logic error is when a program compiles, doesn't crash, but the answers that it gives are incorrect. The logic, semantics or meaning, conveyed by the code is wrong. Take a look at the next example:

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:

6 Console.Writeline("Total = " & Price + (Price * Tax))
Exercise: Exception Handling

Name and give examples of the three error types in programming code:

Answer :

  • Compilation (Syntax)
  • Logic (Symantic)
  • Runtime

What error is in the following code, how would you fix it:

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: Exception Handling
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 it ChocAverage().

Try to stick to one naming convention

If you are using lots of variable names and function names, stick to a single style for naming them. If you use lots of different conventions things are going to look ugly. Wikipedia guidance

For example:

  • firstName, lastName, calculateDoB, numLegs
  • FirstName, LastName, CalculateDoB, NumLegs
  • First_Name, Last_Name, Calculate_DoB, Num_Legs

Don't make your names too long

Long variables can be very hard to read and much easier for you to make mistakes when writing them, try to shorten things where possible.

For example:

Too Long Just Right
ThisIsYourFirstName FirstName
the_value_of_a_chocolate_bar ChocVal

Indent your work

A lot of programming environments help to indent your code automatically and you should be able to find one for the language you are using. Indenting helps people to read and understand your code quickly as it clearly shows the structure of functions, procedures, selection and iteration statements. For example the following is very hard to read:

int main(int argc, char *argv[])
{
...
while (x == y) {
something();
somethingelse();
if (some_error)
do_correct();
else
continue_as_usual();
}
finalthing();
...
}

If you indent it is becomes much easier to read:

int main(int argc, char *argv[])
{
    ...
    while (x == y) {
        something();
        somethingelse();
        if (some_error)
            do_correct();
        else
            continue_as_usual();
    }
    finalthing();
    ...
}

Use comments where necessary

Some of the best written code doesn't need comments because if you have structured it correctly and used all the proper naming conventions it should be pretty easy to read. However for the code you are writing you should put some comments to explain what each section does.

'this function takes an array of prices and outputs the average
function calculateAverage(num1(20) as integer)
{
    'add all the numbers together
    while ...
          ...
          ...
    end while
    
    console.writeline(average)
}

The advantages of the structured approach

  • Easy to read and fix code
  • Problems broken down into easy to manage chunks
  • procedures / functions are reusable, you can use them in different projects.
  • You can test modules individually
Exercise: Structured programming
sub calcEverything(byref a as integer, byref b as integer, byref c as integer)
  dim total, avg as integer
  total = a + b + c
  console.writeline("the total of inputs = " & total)
  avg = total / 3
  console.writeline("the average of inputs = " & avg)
end sub

What might be considered wrong about the use of the subroutine above? How could it be fixed?

Answer :

The sub routine is performing multiple function: it calculates the total AND the average. Functions/procedures should only perform one task at a time. You could replace the above with two subroutines:

  • calcAvg(...)
  • calcTotal(...)

List three reasons for using functions and procedures to structure your code

Answer :

  • You can re-use the code
  • You can test parts of the code individually
  • The code is easier to read and understand
dim ppdpdp as string
dim cheesy as integer
console.write("hello, please insert your name: ")
ppdpdp = console.readline()
console.write("hello, please insert your age: ")
cheesy = console.readline
if ppdpdp = "Dave" then
if cheesy = 23
console.write("daisy, daisy...")
else
console.write("I'm sorry dave")
end if
else
console.write("Get off my spaceship")
end if

Give three structured programming techniques that could be used to improve the code above:

Answer :

  • proper use of indentation
  • sensible variables names (why on earth have they used cheesy to store the age, why not use age?)
  • use comments

Modulo arithmetic

Modular arithmetic is all about finding the remainder from long division (MOD), and the total number of times that a number goes into a division (DIV). Let's take a look at a quick example of 10 divided by 7 (you might want to remind yourself about long division):

    1 r 3
 7)10
    7
    3

Hopefully that wasn't too hard. We now need to introduce some terminology, MOD and DIV:

  • MOD = finds the remainder from long division i.e. 10 MOD 7 = 3
  • DIV = finds the number of divides in long division i.e. 10 DIV 7 = 1
Exercise: MOD and DIV
Try these examples, working out the MOD and DIV of each: 7 / 2

Answer :

MOD = 1 DIV = 3

17 / 5

Answer :

MOD = 2 DIV = 3

8 / 2

Answer :

MOD = 0 DIV = 4

6 / 9

Answer :

MOD = 6 DIV = 0 (9 does not divide into 6 at all!)

Now try these explicit calculations: 11 MOD 8

Answer :

= 3

8 MOD 4

Answer :

= 0

6 DIV 5

Answer :

= 1

600 DIV 20

Answer :

= 30

Hopefully you are now pretty good with MOD and DIV, but what exactly is the point of all this? A very common example in past exam paper has been using the MOD and DIV to work out a binary equivalent of a denary number.

Example: Converting Denary to Binary using DIV
sub convertDtoB(byVal base10 as integer)
  dim base2(7) as integer 'create an array to store the binary
  dim temp as integer = base10
  for i = 7 to 0 step -1 'loop through each binary bit starting from the biggest value
    base2(i) =  temp \ (2^i)  'temp DIV 2^i
    temp = temp MOD 2^i
  next
  console.write(base10 & " in binary = ")
  for i = 7 to 0 step -1 'loop through each binary bit starting from the biggest value
    console.write(base2(i))
  next
end sub

Try the code out and see if it works. Try to write a trace table and see how it works for the number 67 (again another popular question in exams):

Answer :

base10 temp 2^i i base2
0 1 2 3 4 5 6 7
67 67
128 7 0
3 64 6 1
32 5 0
16 4 0
8 3 0
4 2 0
1 2 1 1
0 1 0 1

Output:

67 in binary = 01000011

Another common use is in finding out whether a number is odd or even using the MOD function. We know that MOD returns the remainder from a division sum. So for example 4 MOD 2 = 0, 5 MOD 2 = 1, 6 MOD 2 = 0 and so on. By modding something with 2 we can work out whether it is odd or not due to the return value.

Example: Finding out if a number is Odd using MOD
Dim testNum as Integer
Dim temp as Integer
console.writeline("please insert a number to test:")
testNum = console.readline()
If testNum MOD 2 = 0 Then
  Console.Writeline("The number is even")
Else
  Console.Writeline("The number is odd")
End If

Logical bitwise operators

As you have probably discovered already, converting a positive binary number into a negative binary number involves changing bits. As does converting a capital ASCII letter into a lower case ASCII letter. How exactly does a computer perform this action? The answer lies with bitwise operators:

Bitwise Operator NOT() AND() OR() XOR()
Description invert input where exactly two 1s where one or more 1s where exactly one 1
Input 01001010 01001010 01001010 01001010
Input 11110000 11110000 11110000
Output 10110101 01000000 11111010 10111010

So how can we use these for useful tasks in a computer? If we look closer at the examples above we can see that setting Input 2 bits to 1s or 0s has a direct inpact on the Output. We'll call Input 2 a mask, and we apply this mask to change the values in Input 1 in certain ways. Consider these questions about Masks:

  • If we have an AND mask bit as 0 what is the output in all cases?
  • If we have an AND mask bit as 1 what is the output in all cases?
  • If we have an OR mask bit as 0 what is the output in all cases?
  • If we have an OR mask bit as 1 what is the output in all cases?
  • If we have an XOR mask bit as 0 what is the output in all cases?
  • If we have an XOR mask bit as 1 what is the output in all cases?

In summary:

AND OR XOR
0 clears the value retains the value retains the value
1 retains the value sets the value inverts the value
uses setting chosen bits to 0 setting chosen bits to 1 inverting chosen bits, finding differences between bit sets
Exercise:Bitwise operators
So know we know how each Bitwise Operator works we can use them with masks to calculate things: Input data 11011011, I want an output with bits 4 and 5 set to 0 and I don't care about the others. (???00???)

Answer :

By using an AND I can set bits to 0 and keep other bits. The mask I need is :11100111

Input data 11011011, I want an output with bits 1 and 8 set to 1 and I don't care about the others. (1??????1)

Answer :

By using an OR I can set bits to 1 and keep other bits. The mask I need is :10000001

Input data 11011011, I want an output with bits 3,4,5,6 set to 1, bits 1 and 8 set to 0 and I don't care about the others. (0?1111?0)

Answer :

AND: 01111110 followed by
OR: 00111100

Alternatively:

XOR: 10100101

This might all sound a little academic, what are the actual practical uses of this? Take a look at the following:

Example: Turning a positive binary integer into a negative

We are going to convert the number 37 into -37

37 = 00100101

1. Flip the number by XORing it

    00100101
 XOR11111111
  = 11011010

2. Add 1

  11011010
+ 00000001
  11011011 = -37
Example: Finding a lowercase ASCII letter

We are going to find out the how to convert any Upper case ASCII value into its lower case equivalent. First lets find out the difference between two letters, we'll look at 'P' and 'p', and 'A' and 'a':

P: 01010000
p: 01110000
A: 01000001
a: 01100001

You can probably work out the difference by looking at them, but let's use a XOR to make sure:

    01010000 (P)
XOR 01110000 (p)
    00100000 (difference)
    01000001 (A)
XOR 01100001 (a)
    00100000 (difference)

We can clearly see that it is the 6th bit that defines whether a number is upper case (not set) or lower case (set). Now let's apply this rule to see if it works:

If given the letter g what is the upper case ASCII value?
g = 01100111
We know that all we have to do is get rid of the 6th bit.  But how can we perform this?
By using an AND mask, to return all the bits excluding the 6th:
    01100111 (g)
AND 11011111(mask)
    01000111 (G)
Exercise: Masks
For the example above we can also do this by using a XOR, can you find out how?

Answer :

    01100111 (g)
XOR 00100000(mask)
    01000111 (G)

What about converting an upper-case letter into a lower-case letter, try with X (01011000), you can't use AND what can you use?

Answer :

   01011000(X)
OR 00100000 (mask)
   01111000(x)

Programming

You can program logical bitwise operators to change the case of letters and even encrypt messages. Unfortunately it isn't always possible to play around with binary digits and you may have to work with decimals instead. Let's take a look an an example using an AND:

We know that 3 = 011 and 5 = 101.  If we AND the two together we get:
011 (3)
101 (5)
===
001 (1)

Let's check:

Console.Writeline(3 AND 5)
  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

Basic set understanding

Sets describe collections of things or values, such as numbers, animals or people.

In a set, each value occurs only once. For example, the value fox will occur only once in the set of animals. Just as the value 3 occurs only once in the element of all natural numbers, N.

The cardinality of a set refers to the number of elements it contains.

An empty set is written ∅ and its cardinality is 0.

Sets may be finite or infinite. For example, the set of people currently alive in the world will be finite, but the set of N is infinite.

A set may be countable or uncountable. A countable set is a set, whose elements can be matched with the set of natural numbers. In other words, it is possible to count the elements one-by-one. If a set is finite, it will always be countable. The best example of an uncountable set is R. It is impossible to match each element of R with an element of N. This is because there are not enough elements in N to match each one with an element of R.


Membership ∈ and its reverse ∉:

x ∈ S, x is an element of S.


Examples:

  • x ∈ ℕ, meaning that x is an element of the set of natural numbers. For example, 3 ∈ ℕ. Whereas 3.5 ∉ ℕ
  • x ∈ Q, meaning that x is an element of the set of rational numbers. Whereas pi ∉ Q
  • x ∈ WorkingDays, meaning that x is an element of the set of all WorkingDays. For example, Monday ∈ WorkingDays. Whereas Saturday ∉ WorkingDays
  • x ∈ WeekendDays, meaning that xis an element of the set of all WeekendDays. For example, Saturday ∈ WeekendDays. Whereas Monday ∉ WeekendDays


Questions relating to membership and basic understanding

Using set notation, state that Sunday is a weekend day.

Answer :

Sunday ∈ WeekendDays

Using set notation, state that Monday is not a weekend day.

Answer :

Monday ∉ WeekendDays

What is the cardinality of the set WeekendDays.

Answer :

2

Let set A be the set of all atoms in the world. Which of the following words can be used to describe this set? Countable, uncountable, finite, infinite.

Answer :

Countable, finite.

Let set P be the set of all prime numbers. Which of the following words can be used to describe this set? Countable, uncountable, finite, infinite.

Answer :

Countable, infinite.


Union

The union of two sets:

A ∪ B, meaning that all elements of the set A form a union with all of the elements in set B. This is a set comprehension, since this generates a new set.


Examples:

  • Q ∪ Irrational Number Set, meaning that all numbers in the set of rational numbers form a union with the set of all irrational numbers. This set comprehension generates the set of real numbers.
  • WorkingDays ∪ WeekendDays, meaning that all of the working days (elements of WorkingDays) form a union with weekend days (elements of WeekendDays). This set comprehension generates the set of WeekDays.
  • {1, 2} ∪ {2,3,4} = {1,2,3,4} (notice that only once instance of 2 is in the resulting set)
  • {1, 2, green} ∪ {red, white, green}={1, 2, red, white, green}
  • {1, 2} ∪ {1, 2} = {1, 2}
Questions relating to union

Let A = {0,2,4,6,8,10,12}

and B = {0,3,6,9,12}.

Write out all elements of A ∪ B

Answer :

{0,2,3,4,6,8,9,10,12}

{3,4} ∪ B

Answer :

={0,3,4,6,9,12}.

A ∪ {7,13,red}

Answer :

={0,2,4,6,7,8,10,12,13,red}.

B ∪ B

Answer :

={0,3,6,9,12}.


Intersection

The intersection of two sets:

A ∩ B, meaning that the set A and set B form an intersection. The generated set will be ∅, if the two sets share no elements.


Examples:

Let A be the set of numbers which are divisible by 3 and B the set of numbers divisible by 4.

  • A ∩ B, meaning that A and B form an intersection, which generates a set, which contains all of the numbers divisible by 3 and 4.
  • WorkingDays ∩ WeekendDays, meaning that WorkingDays and WeekendDays form an intersection, which is ∅

Now let A be the set of all A-level students who take computer science and B the set of all A-level students who take mathematics.

  • A ∩ B, meaning that A and B form an intersection, which generates a set, which contains all students who take both computer science and mathematics.
  • {1, 2, 3} ∩ {2, 3, 4} = {2, 3}
  • {1, 2, 3} ∩ {bear,hen,squirrel} = Ø (this means an empty set)
  • {cat, dog, canary} ∩ {wolf, canary, whale, cat} = {cat, canary}
Questions relating to intersection

As above,

let A = {0,2,4,6,8,10,12}

and B = {0,3,6,9,12}.

A ∩ B =

Answer :

{0,6,12}

A ∩ {goat,4,6,9} =

Answer :

{4,6}

A ∩ {goat,3,9} =

Answer :

It has no intersected values (Ø)

B ∩ {3,5,7,9,11} =

Answer :

{3,9}


Difference \

A \ B, meaning that the set A and set B form a set difference. This will generate a set, which contains the elements of A, which are NOT also in B.

The difference of two sets:

Examples:

  • R \ Q, meaning that R and Q form a set difference. This will generate the set of irrational numbers.

Let A be the set of all A-level students who take computer science and B the set of all A-level students who take mathematics.

  • A \ B, meaning that A and B form a set difference. This will generate the set of all computer science students, who do not also take mathematics.
  • {1, 2, 3} ∩ {2, 3, 4} = {2, 3}
  • {1, 2, 3} ∩ {bear,hen,squirrel} = Ø (this means an empty set)
  • {cat, dog, canary} ∩ {wolf, canary, whale, cat} = {cat, canary}


Questions relating to difference

As above,

let A = {0,2,4,6,8,10,12}

and B = {0,3,6,9,12}.

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

A ∖  B    =

Answer :

{2,4,8,10}

B ∖  A    =

Answer :

{3,9}

B ∖  {1,2,3,5,7,11}    =

Answer :

{0,6,9,12}

A ∖  {0,1,2,3,5,8,13}    =

Answer :

{4,6,10,12}

Proper Subsets

S ⊂ T, meaning that S is a proper subset of T, such that all elements in S are also elements of T. However, there will need to be at least one element in T, which is not in S.

Examples:

  • N ⊂ Z, meaning that the set of natural numbers is a proper subset of the set of integers. In other words, all natural numbers are also integers. There are some elements in Z, which are not in N - these are the negative integers.
  • Z ⊂ Q, meaning that the set of integers is a proper subset of the set of rational numbers. In other words, all integers are also rational numbers. But there are rational numbers which are not integers.


Questions relating to proper subsets

As above,

let A = {0,2,4,6,8,10,12}

and B = {0,3,6,9,12}.

Is A a proper subset of B, so that we can write A ⊂ B? Explain your answer.

Answer :

No, because there are elements in the set B which are not in the set A. In other words we can find an element, for which x ∈ B and x ∉ A

Relating to the above definitions for A, define a set which is a proper subset of A.

Answer :

Any valid answer, for example {0,2,12} or {8,12}

Subsets

A ⊆ B, meaning that A forms a subset of B. In other words, A could be identical to B, but does not have to be!

Examples:

Let A be the set of all students in 6th form and B the set of all students taking computer science.

  • A ⊆ B, meaning that A forms a subset of B. In other words, all students in the 6th form could be taking computer science. In which case the two sets would be the same, but they may not be!

Now let A be all of the students present in school and B the set of students currently in the assembly hall.

  • A ⊆ B, meaning that A forms a subset of B. In other words, all students currently in present in school may all be located in the assembly hall, but they may not be!


Questions relating to subsets

Let A be all students who sit the A-level exam in computer science. Let B be all the students who gain a 'B' grade or above in the A-level computer science exam.

Is B a subset of A? Explain your answer.

Answer :

Yes, because it may be the case that all students who sit the exam will also gain grade 'B' or above.

Let A be the set of customers in a restaurant. Let B be the set of all the vegetarian customers in the restaurant.

Is B a subset of A? Could A be a subset of B? Could A be a proper subset of B? Explain your answer.

Answer :

B is a subset of A since every vegetarian customer is a customer. A could be a subset of B, because it may be the case that all customers present are also vegetarian. It cannot be a proper subset, since A contains B.

Fundamentals of data representation

From the Specification : Binary number system

Pure Binary Representation of Denary Integer

  • Describe the representation of unsigned denary integers in binary. Perform conversion from denary to binary and vice-versa.

Binary Arithmetic

  • Add two binary numbers and multiply two binary numbers.

Representation of signed integers by Two’s Complement

  • Describe the use of Two’s Complement to perform subtraction. Convert a denary integer into Two’s Complement and vice versa.

The Concept of Number Bases: Denary, Binary and Hexadecimal

  • Describe the conversion of a denary integer to hexadecimal form and vice versa. Describe the use of hexadecimal as shorthand for binary.

Integers and Numbers with a Fractional Part

  • Draw a distinction between integers and numbers with a fractional part in a computer context.Describe how an unsigned denary number with a fractional part is represented in fixed-point form in binary.
From the Specification : Information Coding Schemes

Describe standard coding systems for coding character data.

  • Understand ASCII
  • Understand Unicode

Differentiate between the character code representation of a denary digit and its pure binary representation. Error checking and correction

  • Parity bits, Hamming code.

Gray coding

  • Describe Gray coding. Explain why and where it is used.
From the Specification : Representing Images, Sound and other data

Images

Describe how bit patterns may represent other forms of data including graphics and sound.
Bitmapped Graphics
  • Bitmaps: resolution, colour depth and simple bitmap file calculations.
Vector Graphics
  • Vector graphics: drawing list – objects and their properties.
Compare bitmaps to vector graphics; advantages, disadvantages.
The need for compression and basic techniques for compression.

Sound files

The need for compression and basic techniques for compression.
Sampled Sound and Nyquist-theorem
  • Sampling resolution, sampling rate.
Sound Synthesis
  • Describe MIDI and its advantages for storing sound digitally.
Streaming audio
  • Explain what it is and why it is used.
Analogue and Digital Data. Analogue and Digital Signals
  • Differentiate between analogue and digital data and analogue and digital signals.
Analogue to Digital Converter
  • (ADC) Describe the principles of operation of an analogue to digital converter.

Bit patterns in a computer

Bits and Bytes

The language that a computer understands is very simple, so simple that it only has 2 different numbers: 1 and 0. This number system is called Binary. This is because 1 represents high voltage and 0 to represent low voltage.

A 1 or 0 is called a Bit which is short for BInary DigiT. This is the fundamental unit of information.

Everything you see on a computer, images, sounds, games, text, videos, spreadsheets, websites etc. Whatever it is, it will be stored as a string of ones and zeroes.

monochrome image of a smiley face

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


Byte - a standard unit to measure computer memory, usually consisting of a group of 8 bits. e.g. 10101011



Exercise: Bit patterns in a Computer

How do computers store data?

Answer :

as binary values, using a pattern of 1s and 0s

What sort of data can be stored in binary?

Answer :

  • Video
  • Sound
  • Picture
  • Text
  • Code
  • Spreadsheet
  • Game
  • etc

What does the following binary string represent: 10011100

Answer :

This could be anything:

  • sound data
  • picture data
  • text ASCII for œ
  • unsigned integer = 156
  • video data
  • etc

How many bits in a byte?

Answer :

8, but it is originally the amount of bits used to represent a character

How many bits in 7 bytes?

Answer :

7 * 8 = 56

How many different patterns can be made from 4 bits?

Answer :

24 = 16 different patterns or combinations can be created

Minimum and Maximum Number vs. Number of Different Values

From the Specification : Binary number System - Unsigned binary

Know that in unsigned binary the minimum and maximum values for a given number of bits, n, are 0 and 2n -1 respectively.

A common question that you'll need to know the answer to, and one that many people get wrong, is a question about the minimum and maximum denary value you can store in a set number of binary digits.

If I were to have 3 binary digits, the minimum value I could store would be 0002 = 0. Whereas, the maximum value that I could store would be 1112, this equates to 4 + 2 + 1 = 710. So for 3 binary digits the range of numbers I can store is 0 (minimum) to 7 (maximum).

From the Specification : Units of information - Bits and bytes

Know that the 2n different values can be represented with n bits.

A similar, but different question, is how many different binary patterns (and therefore values) can you represent with a set number of binary digits. If I were to be asked how many binary patterns can be represented from 3 binary digits, then we have 8 options:

# 000
# 001
# 010
# 011
# 100
# 101
# 110
# 111

We could count these all out and write down: "There are 8 different values 3 binary digits can take". But this isn't very clever, what is you wanted to find out the range and maximum values for 34 bits, you can't be expected to write them all out.

We are looking for a rule to save us the job and stop us making mistakes. Can you work out a rule in terms of for:

Maximum denary value of binary digits:

Number of different values/binary patterns for binary digits:


Example

2 bits can be configured in 22 = 4 different ways. 3 bits can be configured in 23 = 8 different ways.

2 bits 3 bits
00

01

10

11

000

001

010

011

100

101

110

111

Min = 0 Min = 0
Max = 22-1 = 3 Max = 23-1 = 7
22 = 4 23=8
4 combinations 8 combinations


Exercise: Max and range of binary numbers

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

4

Answer :

Maximum :

Range :

5

Answer :

Maximum :

Range :

8

Answer :

Maximum :

Range :

10

Answer :

Maximum :

Range :

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

Answer :

highest address :

Different number of addresses :

This is a very popular exam question!

Denary, Binary and Hexadecimal number systems

Before we jump into the world of number systems we'll need a point of reference, I recommend that you copy the following table that you can refer to throughout this chapter to check your answers.

Hexadecimal Binary Denary
0 0000 0
1 0001 1
2 0010 2
3 0011 3
4 0100 4
5 0101 5
6 0110 6
7 0111 7
8 1000 8
9 1001 9
A 1010 10
B 1011 11
C 1100 12
D 1101 13
E 1110 14
F 1111 15
10 0001 0000 16

Denary/Decimal

Denary is the number system that you have most probably grown up with. It is also another way of saying base 10. This means that there are 10 different numbers that you can use for each digit, namely:

0,1,2,3,4,5,6,7,8,9

Notice that if we wish to say 'ten', we use two of the numbers from the above digits, 1 and 0.

Thousands Hundreds Tens Units
10^3 10^2 10^1 10^0
1000 100 10 1
5 9 7 3

Using the above table we can see that each column has a different value assigned to it. And if we know the column values we can know the number, this will be very useful when we start looking at other base systems. Obviously, the number above is: five-thousands, nine-hundreds, seven-tens and three-units.

5*1000 + 9*100 + 7*10 + 3*1 = 597310

Binary

You should know denary pretty well by your age, but there are different base systems out there, and the most important one for computing is the binary base system. Binary is a base-2 number system, this means that there are two numbers that you can write for each digit:

0, 1

With these two numbers we should be able to write (or make an approximation) of all the numbers that we could write in denary.

One-hundred and twenty-eights Sixty-fours Thirty-twos Sixteens Eights Fours Twos Units
2^7 2^6 2^5 2^4 2^3 2^2 2^1 2^0
128 64 32 16 8 4 2 1
0 1 1 0 1 0 1 0

Using the above table we can see that each column has a value assigned to it that is the power of two (the base number!), and if we take those values and the corresponding digits we can work out the value of the number: 1*64 + 1*32 + 1*8 + 1*2 = 106.

If you are asked to work out the value of a binary number, the best place to start is by labelling each column with its corresponding value and adding together all the columns that hold a 1. Let's take a look at another example:

000111112
128 64 32 16 8 4 2 1
0 0 0 1 1 1 1 1

So now all we need to do is to add the columns containing 1s together: 1*16 + 1*8 + 1*4 + 1*2 + 1*1 = 31

Exercise: Binary

Convert the following binary numbers into denary

000011002

Answer :

128 64 32 16 8 4 2 1
0 0 0 0 1 1 0 0
8+4 = 1210

010110012

Answer :

128 64 32 16 8 4 2 1
0 1 0 1 1 0 0 1
64 + 16 + 8 + 1 = 8910

000001112

Answer :

128 64 32 16 8 4 2 1
0 0 0 0 0 1 1 1
4 + 2 + 1 = 710

010101012

Answer :

128 64 32 16 8 4 2 1
0 1 0 1 0 1 0 1
64 + 16 + 4 + 1 = 8510

How do we tell if a binary number is odd?

Answer :

Its right most digit is a one

Is there a short cut to working out a binary number that is made of solid ones, such as: 011111112

Answer :

Yes, take the first 0's column value and minus one

128 64 32 16 8 4 2 1
0 1 1 1 1 1 1 1
= 128 - 1 = 127 = 64 + 32 + 16 + 8 + 4 + 2 + 1
000011112 = 16 - 1 = 15 = 8 + 4 + 2 + 1
000001112 = 8 - 1 = 7 = 4 + 2 + 1

If we were to use octal, a base 8 number system, list the different numbers each digit could take:

Answer :

0, 1, 2, 3, 4, 5, 6, 7

Max and range

A common question that you'll need to know the answer to, and one that many people get wrong, is a question about the maximum denary value you can store in a set number of binary digits, or alternatively, the range of values that you can store in a set number of binary digits. Read carefully, these are not the same thing.

Consider the following example:

If I were to have 3 binary digits, the maximum value that I could store would be 1112, this equates to 4 + 2 + 1 = 710.

If I were to be asked, the range of numbers then we have 8 options:

# 000
# 001
# 010
# 011
# 100
# 101
# 110
# 111

We could count these all out and write down: "There are 8 different values 3 binary digits can take". But this isn't very clever, what is you wanted to find out the range and maximum values for 34 bits, you can't be expected to write them all out. We are looking for a rule to save us the job and stop us making mistakes. Can you work out a rule in terms of for:

Maximum denary value of binary digits:

Number of different values for binary digits:

Exercise: Max and range of binary numbers

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

4

Answer :

Maximum :

Range :

5

Answer :

Maximum :

Range :

8

Answer :

Maximum :

Range :

10

Answer :

Maximum :

Range :

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

Answer :

highest address :

Different number of addresses :

This is a very popular exam question!

Hexadecimal

You may notice from the table that one hexadecimal digit can represent exactly 4 binary bits. Hexadecimal is useful to us as a shorthand way of writing binary, and makes it easier to work with long binary numbers.

Hexadecimal is a base-16 number system which means we will have 16 different numbers to represent our digits. The only problem being that we run out of numbers after 9, and knowing that 10 is counted as two digits we need to use letters instead:

0,1,2,3,4,5,6,7,8,9,A,B,C,D,E,F

We can do exactly the same thing as we did for denary and binary, and write out our table.

16^5 16^4 16^3 16^2 16^1 16^0
1 048 576 65536 4096 256 16 1
0 0 3 4 A F

So now all we need to do is to add the columns containing values together, but remember that A = 10, B = 11, C = 12, D = 13, E = 14, F = 15.

3*4096 + 4*256 + (A)10*16 + (F)15*1 = 1348716

You might be wondering why we would want to use hexadecimal when we have binary and denary, and when computer store and calculate everything in binary. The answer is that it is entirely for human ease. Consider the following example:

Error messages are written using hex to make it easier for us to remember and record them
Representation Base
EFFE11 base-16 hexadecimal
15728145 base-10 denary
111011111111111000010001 base-2 binary

All the numbers are the same and the easiest version to remember/understand for humans is the base-16. Hexadecimal is used in computers for representing numbers for human consumption, having uses for things such as memory addresses and error codes. NOTE: Hexadecimal is used as it is shorthand for binary and easier for people to remember. It DOES NOT take up less space in computer memory, only on paper or in your head! Computers still have to store everything as binary whatever it appears as on the screen.

Exercise: Hexadecimal

Convert the following Hex numbers into decimal/denary:
A1

Answer :

16  1
 A  1

16 * 10 + 1 * 1 = 16110

FF

Answer :

16  1
 F  F

16 * 15 + 1 * 15 = 25510

0D

Answer :

16  1
 0  D

16 * 0 + 1 * 13 = 1310

37

Answer :

16  1
 3  7

16 * 3 + 1 * 7 = 5510

Why would we use the Hexadecimal system?

Answer :

Hexadecimal is used for humans, it is easier to understand and write

Name a use of the hexadecimal system

Answer :

Hexadecimal is used for error message codes and memory addresses

Converting Between Bases

The sum that you saw previously to convert from hex to denary seemed a little cumbersome and in the exam you wouldn't want to make any errors, we therefore have to find an easier way to make the conversion.

Since 4 binary bits are represented by one hexadecimal digit, it is simple to convert between the two. You can group binary bits into groups of 4, starting from the right, and adding extra 0's to the left if required, and then convert each group to their hexadecimal equivalent. For example, the binary number 0110110011110101 can be written like this:

0110 1100 1111 0101

and then by using the table above, you can convert each group of 4 bits into hexadecimal:

0110 1100 1111 0101
  6    C    F    5

So the binary number 0110110011110101 is 6CF5 in hexadecimal. We can check this by converting both to denary. First we'll convert the binary number, since you already know how to do this:

32768 16384 8192 4096 2048 1024 512 256 128 64 32 16 8 4 2 1
0 1 1 0 1 1 0 0 1 1 1 1 0 1 0 1

By multiplying the columns and then adding the results, the answer is 27893.

Notice that the column headings are all 2 raised to a power, , , , , and so on. To convert from hexadecimal to denary, we must use column headings that are powers with the base 16, like this:

4096 256 16 1
6 C F 5

(You should memorize the values A-F)

Totalling them all up gives us 27893, showing that 0110110011110101 is equal to 6CF5.

To convert from denary to hexadecimal, it is recommended to just convert the number to binary first, and then use the simple method above to convert from binary to hexadecimal.

In summary, to convert from one number to another we can use the following rule: Hexadecimal <-> Binary <-> Denary

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 - using Fixed Point notation

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

From the Specification : Introduction to Principles of Computation

Know how numbers with a fractional part can be represented in:

  • fixed point form in binary in a given number of bits
  • floating point form in binary in a given number of bits.

Be able to convert for each representation from:

  • decimal to binary of a given number of bits
  • binary to decimal of a given number of bits.

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

10 1
1 2 . 7 5

As you can see, the column headings have been extended to and . We can do the same thing in binary with the column headings , , and so on. The number 12.75 in 8 bit binary with 4 bits after the binary point is therefore 8 + 4 + 0.5 + 0.25:

8 4 2 1
1 1 0 0 . 1 1 0 0

Notice that for the same number of bits after the point, the binary fraction provides less accuracy. It can only take 4 different values, whereas the decimal number can have 100 different values with two digits. You'll see in a moment how this can cause trouble.

Example: converting decimal to binary decimal using fixed point notation

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

8 4 2 1
0 1 1 0 . 0 0 1 0

This seems simple enough as 6.125 = 4 + 2 + 0.125, but what about this more interesting number: 6.4

8 4 2 1
0 1 1 0 . 0 1 1 0

But this doesn't look right?! This number isn't correct as it only reaches 4 + 2 + 0.25 + 0.125 = 6.375, we need more bits for the binary fraction places. However, a computer might restrict you to the number of bits you can use, so we'll use the number closest to the one we were aiming for. You could feel a bit annoyed at this, but don't worry, you make this compromise every time you try to represent with the decimal factions, 0.33333333.

So you might ask how a computer does complicated mathematics if it struggles so hard with fractions. The answers we have looked at so far have only used one byte, computers can use far more space than this. They can also manipulate the number of bits they have been given in two ways:

  • increase the number of bits to increase range of number
  • increase number of bits after the decimal point to increase accuracy

In practice they will also use clever techniques such as floating point numbers (see below).

Exercise: converting from denary to binary fractions

Now try some questions yourself and see how you get on. Remember, where there aren't enough bits for the decimal place, write down the number closest to your target number. In each case use 8 bits for the binary with four bits after the decimal point:

7.5

Answer :

0111.1000

4.5625

Answer :

0100.1001

1.6

Answer :

0001.1010 (this is the closest we are going to get)

3.3333333

Answer :

0011.0101 (this is the closest we are going to get)

Try and convert these binary fractions into denary:

0111.0100

Answer :

7.25

1011.1001

Answer :

11.5625 (notice that we treated this as a positive number, some of you might already know about twos complement, if you haven't heard about it before, don't worry, we'll get there very soon)
To interpret it as a two's complement number let's flip it: 0100.0111 = 4 + 0.25 + 0.125 + 0.0625 = -4.4375

If I want to increase the range of numbers stored in a fixed point binary number, what should I do?

Answer :

Increase the number of bits before the decimal point

If I want to increase the accuracy of numbers stored in a fixed point binary number, what should I do?

Answer :

Increase the number of bits after the decimal point

Two's complement

Nearly all computers work purely in binary. That means that they only use ones and zeros, and there's no - or + symbol that the computer can use. The computer must represent negative numbers in a different way.

We can represent a negative number in binary by making the most significant bit (MSB) a sign bit, which will tell us whether the number is positive or negative. The column headings for an 8 bit number will look like this:

-128 64 32 16 8 4 2 1
MSB LSB
1 0 1 1 1 1 0 1

Here, the most significant bit is negative, and the other bits are positive. You start with -128, and add the other bits as normal. The example above is -67 in denary because: (-128 + 32 + 16 + 8 + 4 + 1 = -67)

-1 in binary is 11111111.

Note that you only use the most significant bit as a sign bit if the number is specified as signed. If the number is unsigned, then the msb is positive regardless of whether it is a one or not.

Signed binary numbers

If the MSB is 0 then the number is positive, if 1 then the number is negative.

0000 0101 (positive)
1111 1011 (negative)
Method: Converting a Negative Denary Number into Binary Twos Complement

Let's say you want to convert -35 into Binary Twos Complement. First, find the binary equivalent of 35 (the positive version)

32  16   8   4   2   1 
 1   0   0   0   1   1

Now add an extra bit before the MSB, make it a zero, which gives you:

64 32  16   8   4   2   1 
 0  1   0   0   0   1   1

Now 'flip' all the bits: if it's a 0, make it a 1; if it's a 1, make it a 0:

64 32  16   8   4   2   1 
 1  0   1   1   1   0   0

This new bit represents -64 (minus 64). Now add 1:

64 32  16   8   4   2   1 
 1  0   1   1   1   0   0
                      + 1
 1  0   1   1   1   0   1

If we perform a quick binary -> denary conversion, we have: -64 + 16 + 8 + 4 + 1 = -64 + 29 = -35

Converting Negative Numbers

To find out the value of a twos complement number we must first make note of its sign bit (the most significant, left most bit), if the bit is a zero we work out the number as usual, if it's a one we are dealing with a negative number and need to find out its value.

Method 1: converting twos complement to denary

To find the value of the negative number we must find and keep the right most 1 and all bits to its right, and then flip everything to its left. Here is an example:

1111 1011 note the number is negative
1111 1011 find the right most one

1111 1011 
0000 0101 flip all the bits to its left

We can now work out the value of this new number which is:

128  64  32  16   8   4   2   1 
  0   0   0   0   0   1   0   1
                      4   +   1 = −5   (remember the sign you worked out earlier!)
Method 2: converting twos complement to denary

To find the value of the negative number we must take the MSB and apply a negative value to it. Then we can add all the heading values together

1111 1011 note the number is negative
-128  64  32  16   8   4   2   1 
   1   1   1   1   1   0   1   1
-128 +64 +32 +16  +8      +2  +1 = -5

How about a more complex example?

Method 1: converting twos complement to denary
1111 1100 note the number is negative 

1111 1100 find the right most one

1111 1100
0000 0100 flip all the bits to its left
128  64  32  16   8   4   2   1 
  0   0   0   0   0   1   0   0
                      4         = −4   (remember the sign you worked out earlier!)
Method 2: converting twos complement to denary

To find the value of the negative number we must take the MSB and apply a negative value to it. Then we can add all the heading values together

1111 1100 note the number is negative
-128  64  32  16   8   4   2   1 
   1   1   1   1   1   1   0   0
-128 +64 +32 +16  +8  +4          = -4

So we know how to work out the value of a negative number that has been given to us. How do we go about working out the negative version of a positive number? Like this, that's how...

Method 1: converting twos complement to binary

Take the binary version of the positive number

0000 0101 (5)
0000 0101 find the right most one

0000 0101 
1111 1011 flip all the bits to its left

So now we can see the difference between a positive and a negative number

0000 0101 (5)
1111 1011 (−5)
Method 2: converting twos complement to binary

Take the binary version of the positive number

starting with -128, we know the MSB is worth -128. We need to work back from this:

-128  64  32  16   8   4   2   1 
   1   1   1   1   1   0   1   0   
-128 +64 +32 +16  +8      +1      = -5
0000 0101 (5)
1111 1011 (−5)
Exercise: two's complement numbers

Convert the following two's complement numbers into denary:

0001 1011

Answer :

(positive number) 27

1111 1111

Answer :

(negative number) 0000 0001 = -1

0111 1101

Answer :

(positive number) 125

1001 1001

Answer :

(negative number) 0110 0111 = -103

1011 1000

Answer :

(negative number) 0100 1000 = -72

81 (hexadecimal)

Answer :

(using 4 bits for each HEX char) 1000 0001

(negative number) -> 0111 1111 = -127

A8 (hexadecimal)

Answer :

(using 4 bits for each HEX char) 1010 1000

(negative number) -> 0101 1000 = -88

Convert the following numbers into negative numbers written in binary

0000 0001

Answer :

1111 1111

0110 0000

Answer :

1010 0000

0111 1111

Answer :

1000 0001

12 (denary)

Answer :

0000 1100 = +12 -> 1111 0100 = -12

67 (denary)

Answer :

0100 0011 = +67 -> 1011 1101 = -67

34

Answer :

0010 0010 = +34 -> 1101 1110 = -34

34 (hexadecimal)

Answer :

(using 4 bits for each HEX char) 0011 0100 = +52 -> 1100 1100 = -54

7E (hexadecimal)

Answer :

(using 4 bits for each HEX char) 0111 1110 = +126 -> 1000 0010 = -126

Binary Subtraction