Jump to content

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

75% developed
From Wikibooks, open books for an open world

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

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

Authors

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

Contributors and proof readers

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

Thanks for helping out!

Book Overview

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

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


A-level

Paper 1 Index

Paper 2 Index

Non-exam assessment

Programming

Accepted languages

A-Level Projects can be written in any language.

Old Specification (up to 2017)

AS modules

A2 modules


How to read the book

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

Specification link

What the specification says you must learn for each chapter


Examples

Example questions and how to solve them


Questions

Questions to test yourself, click below

Answer:

to check if you were right

Extension

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


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

Word - meaning


Unit 1 - Summary

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

Definitions

Unit 1 definition list

The examination

Problem solving

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

Introduction to principles of computation

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

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

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

Decomposition

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

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

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

  1. repeat for

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

Pattern recognition

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

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

The face was automatically detected by pattern recognition

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

Pattern generalisation and abstraction

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

Algorithm design

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

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

Answer:

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

Can you spot a pattern in this set of numbers?

Answer:

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

with seed values

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

Answer:

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

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

Limits?

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

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

Answer:

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

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

console.writeline("hello")

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

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

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

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

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

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

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

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

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

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

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

References

Stages of problem solving

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

Understand the problem

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

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

Define the problem

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

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

For example:

Example: Defining the problem (Football game)

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

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

Define boundaries

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

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

Plan solution

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

Check solution

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

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

Top-down design and Step-wise refinement

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

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


Example: Making Pancakes

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

  • Make some pancakes

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

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

Each of these tasks can then be broken down further:

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

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

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

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

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

Answer:

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

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

Stages of problem solving

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

Understand the problem

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

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

Define the problem

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

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

For example:

Example: Defining the problem (Football game)

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

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

Define boundaries

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

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

Plan solution

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

Check solution

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

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

Structure charts

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

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

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

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

dim num1, num2 as integer

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

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

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

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

Create structure charts for the following code:

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

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

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

Answer:

Selection

Structure Chart representation of the selection code

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

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

Iteration

Structure Chart of the code to the left

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

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

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

Create structure charts for the following code:

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

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

function divBy3(x)
  return x + 1
end function

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

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

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

Answer:

Decision tables

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

The four quadrants
Conditions Condition alternatives
Actions Action entries

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

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

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

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

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

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

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

What happens when:

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

Answer: Keep Playing and give them some extra time

Exercise: Decision Tables

Create a decision table for the following program in an office email system

  • Send email when Recipient address present, subject present, before 5:30pm
  • If after 5:30pm then put in pending folder
  • If Recipient address missing or subject message, give warning message

Answer:

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

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

Describe the use of Decision Tables

Answer:

Determine logical conditions and consequential actions.


Finite state machines

Finite state machines

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

Consider an elevator :

Possible states of the system:

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


[picture of states inserted here]


The transitions and their inputs:

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

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

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

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

[picture of state transition diagram to be inserted here]


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

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


A finite state automata accepting binary input

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

110011001
001110011

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

110011011

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

Exercise: Finite State Automaton

For the FSM above which of these inputs are valid:

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

Answer:

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

For the FSM above which of these inputs are valid:

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

Answer:

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

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

Answer:

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

  • Tim
  • Grit
  • Grrrrrim

Answer:

Mealy Machines

Mealy Machine - an FSM with outputs

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

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

000101010

It outputs

000010101

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

Exercise: Mealy Machines

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

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

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

Answer:

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

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

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

Answer:

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

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

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

State transition tables

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

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

Create a state transition table for the following FSM:

Answer:

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

Create a state transition table for the following FSM:

Answer:

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


Draw the FSM for the following state transition table:

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

Answer:

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


Draw the FSM for the following state transition table:

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

Answer:

Algorithm design

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


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

Sequence

performing or operating each step consecutively in the order they arise

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

int main() {

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

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

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

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

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

}

Selection

Selection is choosing a step

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

Repetition

A sequence of steps that loop until a requirement is met

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


Trace tables

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


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

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

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

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

To do this we create a trace table:

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

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

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

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

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

So we should construct the following table:

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

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

Answer:

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

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

For x = 0 to 6
Exercise: Trace tables

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

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

Dim op As String = ""

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

Console.Write(op)
Console.ReadLine()

Answer:

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

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

Dim num As Integer = 239938

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

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


What does the above code do?

Answer:

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


Complete the trace table for the following code:

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

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

Answer:

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


What function does the above code perform?

Answer:

It finds the highest value in an array of values


Pseudo code

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

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

Example: Pseudocode

Below is an example of a pseudocode algorithm

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

Converting this into VB.NET, we get:

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

Structured English

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

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

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

What are the rules when writing pseudocode?

Answer:

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

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

Answer:

Pseudocode cannot create executable code, whilst javascript can.

For the following pseudocode write a VB.NET equivalent:

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

Answer:

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

Write pseudocode for the following problem:

Find the average of 4 numbers and display it

Answer:

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

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


Searching and sorting

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

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

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

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

which can be directly translated to Python:

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

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

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

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

Here is the Python code:

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

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

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

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

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

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

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

   Code Output

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

   Code Output

What are you searching for: z
-1

Exercise: Linear Search

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

Answer:

5

And how many when searching for "Camel"?

Answer:

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

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

Answer:

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

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

Answer:

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

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

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

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

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

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

Exercise:Linear vs Binary Search

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

Answer:

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

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

Answer:

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

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

Answer:

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

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

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


Fundamentals of programming

Fundamentals of programming

Features of Imperative High Level Languages

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

Use the following appropriately.

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

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

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

Boolean operators NOT, AND, OR

Logical bitwise operators NOT, AND, OR, XOR

Set operators Union, difference, intersection, membership

Built-in functions

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

Recognise the different roles a variable can take:

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

Understand the structured approach to program design and construction.

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

Arrays

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

Variables

questions

Introduction

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

module module1
  sub main()

  end sub
end module

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

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

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

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

You should get the following output:

   Code Output
Hello World!


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

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

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

We'll take a look at each line:

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

This should output the following:

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

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

Exercise: Hello World!

Create a short program to write the following to the screen, replacing the name Dave with your own name (unless it also happens to be Dave):

   Code Output
Dear Teacher,

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

Yours Sincerely,
Dave

Answer:

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

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

Variables

Let's take a look at this program:

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

you might be expecting both programs to print out:

Hello name you are age years old

But instead they say:

   Code Output

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

What friendly programs!

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

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

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

Dim identifierName As datatype

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

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


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

identifierName = 7

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

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

Producing:

   Code Output

The value stored in identifierName is: 7


Exercise: Variables

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

Answer:

dim name as string
dim age as integer
name = "Syeda"
age = 31
console.writeline("Hello " & name & " you are " & age & " years old")
console.writeline("This also means you are " & age * 12 & " months old")
console.writeline("This also means you are " & age * 365 & " days old")
console.writeline("This also means you are " & age * 365 * 24 & " hours old")
console.writeline("This also means you are " & age * 365 * 24 * 60 & " minutes old")
console.writeline("This also means you are " & age * 365 * 24 * 60 * 60 & " seconds old")
console.writeline("Bye " & name & "!")
console.readline()

Give a good reason why you made age a variable in the previous code

Answer:

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

What will the following code output:

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

Answer:

   Code Output

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

A couple of things to note here:

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


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

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

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

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

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


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

identifierName = 7

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

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

Producing:

   Code Output

The value stored in identifierName is: 7


Notes

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

Comments

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

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


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

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

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

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

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

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

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

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


Python example

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

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

Inputs and outputs

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

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

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

Outputs

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

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

Let's see an example of this in action:

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

This would output the following:

   Code Output

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


Notice the difference between a writeline and a write command.

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

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

will produce the output:

   Code Output

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


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

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

This output will all appear on the same line.


Extension: Console methods in VB.NET

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

console.

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

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

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

Find out more about the console command on the MSDN website

Inputs

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

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

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

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

Please insert you name: Ali
Hello Ali


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

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

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


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

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

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

   Code Output

Please enter your name:
Alice
Hello Alice


Exercise: Inputs and Outputs

What does the following code output:

console.writeline("The ")
console.write("Cat")
console.write("sat ")
console.writeline("on ")
console.writeline("the " & "mat")

Answer:

   Code Output

The
Catsat on
the mat

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

Answer:

   Code Output

The average age
of a combat soldier in Vietnam was 19

Write code to display the following to the screen:

   Code Output

My favourite colours:
Red
Blue

Answer:

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

What would the following look like:

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

for the input:

John
16

Answer:

   Code Output

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


Whoops! Fix this:

Answer:

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

Arithmetic operators

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


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

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

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

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

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


First, we set the total Sales to 3142.51.

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

Why the funny symbols?

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

Addition

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

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

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

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

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

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

Subtraction

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

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

Multiplication

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

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

Division

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

Normal

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

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

Integer division

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

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

Remainder Division

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

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

Exponentiation

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

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

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

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

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

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

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

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

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

This is because .

BODMAS

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

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

For example:

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


If in doubt use the brackets!

Built-in data types

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

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

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

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

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

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

   Code Output

hello Barry! you are 56 years old

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

Assignments

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

  • Integers, Bytes, Real, Singles, Doubles = Plain assignment without speech marks
exampleNumber = 7.65
  • Boolean = Plain assignment without speech marks
paidMember = TRUE
  • String, Char = Assignment with speech marks
name = "Henry"
  • Date = Assignment with speech marks
doB= "12/12/45"
Exercise:Data types

Using the correct datatype declare variables for a person's:

  • Age
  • Name
  • Gender
  • Height (metres)
  • Date of Birth
  • License (Do they have a driving license?)

Answer:

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


Write assignment statements for the following variables using yourself as an example:

  • Name
  • Age
  • Gender

Answer:

name = "Peter" 'we must use speech marks for text, so we don't mistake the value for a variable
age = 56 'we don't need speech marks for numbers
gender = "m"

Which of the following declarations are correct, which are wrong and why?

dim colour as string
dim wheelNum as integer
dim topSpeed as single
dim hasElectricWindows as char

Answer:

dim colour as string 'CORRECT, also we could use a single to store the frequency
dim wheelNum as integer 'CORRECT
dim topSpeed as single 'WRONG, we don't need such precision, an integer would do
dim hasElectricWindows as char 'WRONG, a boolean would work better

Which of the following assignments are correct, which are wrong and why:

name = Pete
age = "34"
height = twenty
electricWindow = True

Answer:

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

Answer:

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

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

   Code Output

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

Answer:

dim num1, num2, num3 as single 'NOT integer, we need decimal numbers!  You can use different identifiers
console.write("Please insert number 1:")
num1 = console.readline()
console.write("Please insert number 2:")
num2 = console.readline()
console.write("Please insert number 3:")
num3 = console.readline()
console.writeline("multiplied together = " & num1 * num2 * num3)
console.writeline("added together = " & num1 * num2 * num3)
console.readline()
Extension: Strongly and weakly typed languages

You don't need to know this part for the exam, but it should help you understand why we need to convert.

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

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

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

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

Constant definitions

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

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

3.14

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

Exercise: Constants

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

   Code Output

Insert radius: 5
area = 78.5398163
circumference = 31.4159265

Answer:

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


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

   Code Output

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

Answer:

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

Answer:

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

When is it suitable to use a constant?

Answer:

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

Selection

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

IF Statement

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

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


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

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

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

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

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

Relational operators

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

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

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

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

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

we will get an error message similar to this:

   Code Output

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


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

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

Write a single IF statement for the following:

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

   Code Output

What eyes have thee?
Green
Thou art a Goblin?

Alternatively:

   Code Output

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

Answer:

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

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


   Code Output

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


   Code Output

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


   Code Output

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


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

Answer:

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


Now for some very simple AI:

   Code Output

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

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

Answer:

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

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

VB.NET


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

Python 3


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

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

VB.NET


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

Python 3


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

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

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

Write nests of IF statements for the following:

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

   Code Output

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

It should also handle:

   Code Output

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

Answer:

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


Create a login screen to do the following:

   Code Output

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

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

Answer:

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


Extension: Single line IF statements

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

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

This is a much shorter way of writing:

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

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

Case Statement

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

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

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

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

Between 4 and up to 8


Exercise: Case statements

Create a program where someone types in the name of an animal and it outputs the sound the animal makes. The animals it should handle are:

  • Pig - Oink
  • Cow - Moo
  • Bear - Grr
  • Sheep - Baa
  • Tiger - Grr
  • everything else - Meow

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

Answer:

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


You are now going to use a case statement to create an electronic piano.

Note Frequency
A 220.00
B 246.94
C 261.63
D 293.66
E 329.63
F 349.23
G 392.00

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

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

Remember to make sound you use:

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

Answer:

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

Iteration

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

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

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

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


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

Think carefully before you answer each of these.

Answer:

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


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

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

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

0
1
2
3
...
119
MAXSPEED!


Exercise: While Loops

Write a program that counts from 20 to 60 inclusive like so:

   Code Output

20
21
22
...
60

Answer:

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


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

   Code Output

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

Answer:

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


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

Answer:

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

While Do

The while loop: For example:

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

0
1
...
118
119

Do While Loop

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

Do
increase speed
While not top speed
End

Visual Basic handles this with some slight syntax differences

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

This is great for young students:

   Code Output

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

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

   Code Output

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

Exercise: Do While and While Do

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

Answer:

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

Be careful when you use each loop!

For Loop

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

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

It is far easier to use in vb

For speed = 0 to 120
	drive()
Loop

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

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

display:

   Code Output

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

Exercise: For loops

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

Answer:

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


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

   Code Output

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

Answer:

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


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

Answer:

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


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

   Code Output

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

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

Answer:

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

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

  • While Do
  • Do While
  • For

Click here to learn more

Loopy Loops (Nested Loop)

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

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

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

   Code Output

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

Exercise: Loopy loops

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

   Code Output

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

Answer:

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


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

Answer:

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

Built-in functions

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

Arithmetic functions

You'll have to be familiar with several

Round

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

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

Truncation

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

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

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

Extension: Random numbers

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

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

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

randomNumber = rndGen.Next(5,10)

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

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

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

Answer:

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


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

        Loop
    End Sub
Exercise: Arithmetic function

What does the following code output:

dim num1 as single = 12.75
dim num2 as single = 12.499
dim total as single

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

Answer:

   Code Output

24


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

Answer:

Math.Truncate(input)


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

   Code Output

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

Answer:

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

String handling functions

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

Length

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

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

22


Position

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

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

23

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

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

25

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

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

0


Substring

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

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

567890


Concatenation

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

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

Hello Charles. How are you today?


String conversion functions

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

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

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

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

34

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

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

34.3 34


Exercise: String functions

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

   Code Output

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

Answer:

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


Some people have stupidly typed their firstname and their surname into a database, write some code to display the first name, then their surname

Dim name as string = "Elizabeth Sheerin"
   Code Output

Input: Elizabeth Sheerin
Firstname: Elizabeth
Surname: Sheerin

Answer:

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

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

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

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

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


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

dim phonenum as string = "(01234)567890"

Write some code to output the number without brackets:

   Code Output

Input: (01234)567890
Output: 01234567890

Answer:

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

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

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


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

dim phonenum as string = "01234567890"

This should then be output as:

   Code Output

Input: 01234567890
Output: (01234)567890

Answer:

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


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

   Code Output

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

Answer:

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


Extension: REGEX

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

   Code Output

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

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

[A-Z][a-z]+

Breaking apart the rule:

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

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

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

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

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

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

Boolean "or"

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

Grouping

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

Quantification

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

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

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

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

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

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

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

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

to/from integer, real, date/time.

One-dimensional arrays

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

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

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

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

You can pick out individual items by using their index

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

Would output:

   Code Output

Gertrude
Barry


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

friends(0) = console.readline()
Exercise: One-Dimensional Arrays

Declare an array listing 5 animals in a zoo (aardvark, bear, cuckoo, deer, elephant) in alphabetical order:

Answer:

dim zooanimals() as string = {"aardvark","bear","cow","deer","elephant"}

Write code to output the first and last animal

Answer:

console.writeline(zooanimals(0))
console.writeline(zooanimals(4))

Someone has accidentally eaten the cuckoo, let the user add a new third animal and print them all out:

   Code Output

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

Answer:

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

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

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

Would print out:

   Code Output

Barry
Aubrey
Gertrude


To overwrite something, you treat it like a variable:

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

Would output:

   Code Output

Barry
Peter
Gertrude


Exercise: One-Dimensional Arrays

What is the output of the following code:

dim primes() as integer = {2,3,5,7,11,13,17,19,23}
dim count = 8
While count >= 0
  console.write(primes(count) & ", ")
  count = count - 1
end while

Answer:

   Code Output

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


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

Answer:

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


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

   Code Output

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

Answer:

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


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

Answer:

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

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

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

The above code would output:

   Code Output

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

Uses

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

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

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

For example:

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

dim fib(30) as integer
'initiate the first two values
fib(0) = 0 
fib(1) = 1
for x = 0 to 28
  fib(x+2) = fib(x) + fib(x+1)
next
console.writeline("The first 31 fibonacci numbers are:")
for y = 0 to 30
  console.write(fib(y) & ",")
next
Exercise: Calculating with arrays

Update the above code to allow the user to input a number, then the program to store and display that many fibonacci numbers. Test it for 10 and 1000

Answer:

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

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

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

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

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

   Code Output

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

Exercise: Searching arrays

Why do we have attendance.length - 1 in the above code?

Answer:

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

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

Answer:

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

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


Functions and procedures

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

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

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

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

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

Declarations

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

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

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

Function printNumber() as Integer
	return number1
End Function

Calls

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

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

Parameters (and Arguments)

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

Extension: Parameters vs Arguments

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

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

The output would be:

   Code Output

4


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

The output would be:

   Code Output

Mounir is 17 years old


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

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

   Code Output

16


Exercise: Functions and Procedures

What is the difference between a function and procedure?

Answer:

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


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

Answer:

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


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

Answer:

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


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

   Code Output

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

Answer:

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


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

For the procedure above list:

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

Answer:

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

ByRef

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

Dim number1 as integer = 123

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

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

The output would be:

   Code Output

123
124
124


ByVal

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

Dim number1 as integer = 123

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

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

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

   Code Output

123
124
123


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

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

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

Answer:

   Code Output

7


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

Answer:

   Code Output

15


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

What is the output of the above code?

Answer:

   Code Output

hello - goodbye
hello - hello


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

Answer:

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

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

Global and local variables

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

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

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


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

Take a look at this example:

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

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

What would the output be?

   Code Output

123
234
123


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

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

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

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

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

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

Answer:

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

Answer:

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

Answer:

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


List the global and local variables for the following. What will be the output for input 16:

Module calcAge
	Sub Main()
		dim age as integer
		console.writeline("age?")
		age = console.readline()
		printMonths(age)
		printDays(age)
	End Sub
	Dim months as integer
	Sub printDays(a)
		Dim d as integer
		d = a * 365
		console.writeline(d)
	End Sub
	Sub printMonths(a)
		months = a * 12
		console.writeline(months)
	End Sub
End Module

Answer:

Locals: age, d

Globals: months

   Code Output

age?
16
192
5840

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

Answer:

Make the months variable a local variable by putting it inside the printMonths(a) sub routine, if you leave it as a global variable it will be taking up memory even when you don't need it.

List the Global and Local variables in the following code, list the output:

Module greetings
	Dim q as integer = 6
	Sub sayGoodbye()
		for y = 1 to q
			console.write("bye,")
		loop
	End Sub
	Sub sayHello()
		dim q as integer = 4
		if q =< 4 then
			console.write("hi,")
		else
			console.write("hello,")
		endif
	End Sub
	Sub Main()
		console.writeline(q)
		sayHello()
		sayGoodbye()
		console.writeline(q)
	End Sub
End Module

Answer:

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

Globals: q (on line 2)

   Code Output

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

Two-dimensional arrays

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

Dim friends(6) As String

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

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

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

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

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

Dim grid(4,4) As String

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

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

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

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

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

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

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

Answer:

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

Answer:

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

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

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

Answer:

sub display(checkBoard())
for x = 1 to 3
   for y = 1 to 3
      console.write(checkBoard(x,y))
   Next
   console.writeline()
Next

Declare a chessBoard (8*8 squares), programmatically colour it in with b for black and w. You might want to look for a pattern in the colour assignments for the checker board above and make friends with the MOD function

You might also go a little loopy trying to answer this question

Answer:

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

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

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

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

Using the following two-dimensional array, grid(4,4):

  • Write code to output the name CRAIG
  • Insert MARY on row 2 (the third row)
  • Overwite STEVE with SAM

Answer:

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

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

Noughts and Crosses

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

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

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

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

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

  'main game function call to go here
end sub

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

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

		Console.WriteLine()
	Next
End Sub

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

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

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

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

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

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

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

Finally we'll bring everything together

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

	game(board)
	console.readline()
End Sub

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

		move(b, togo)
		display(b)
	Loop While Not (win(b, togo)) And Not (drawn(b))
End Sub
Exercise: More Two-Dimensional arrays

Fix the program above so that an incorrect move allows the user to try again:

   Code Output

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

Answer:

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


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

Answer:

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

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

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


User-defined data types

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

Enumerated, subrange, sets

Enumerated

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

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

dim cardset as string
cardset = spade

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

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

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

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

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

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

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

dim ManUvChelsea as Result
ManUvChelsea = Result.Win
Console.Writeline("ManU scored " & ManUvChelsea & " points" )
Exercise: Enumerated types

Declare an enum called months that holds the months along with how many days in each for a non-leap year

Answer:

Enum months
   January = 31
   February = 28
   March = 31
   April = 30
   May = 31
   June = 30
   July = 31
   August = 31
   September = 30
   October = 31
   November = 30
   December = 31
End Enum

What would the following code do:

Enum DayOfWeek
    Monday = 1
    Tuesday = 2
    Wednesday = 3
    Thursday = 4
    Friday = 5
    Saturday = 6
    Sunday = 7
End Enum

Answer:

   Code Output

Records and Fields


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

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

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

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

For the following input:

   Code Output

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

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

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

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

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

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

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

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

Exercise: Records

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

Answer:

Enum type
   WIZARD
   BARBARIAN
   ELF
End Enum

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

Creates 2 characters, Gandolf and Conan using the player record

Answer:

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

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

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

Extension: Object Orientation

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

File handling

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

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

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

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

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

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

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

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

Reading files

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

Example: Reading from a text file

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

VB.NET

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

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

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

        filereader.Close()
    End Sub
End Module

The above code would produce the following:

   Code Output

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


Python 3

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

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

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

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

The above code would produce the following:

   Code Output

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


Writing files

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

Example: Writing to a text file

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

VB.NET

This time we are using the StreamWriter:

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

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

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

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


Python 3

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

textToFile = input()

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


Exercise: Reading and Writing Files

write code to save a shopping list typed in by a user (they finish typing the list by entering a blank line) to a file called specified by the user

VB.NET answer

Answer:

Imports System.IO

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

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

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

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

filewriter.Close()

Python 3 answer

Answer:

textToFile = ""

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

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

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

textFile = open(filename,"w")
textFile.write(textToFile)
textFile.close()

What does the extension of a file change about a file?

Answer:

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

CSV

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

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

This would produce:

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

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

Exercise: CSV

write a CSV file to hold the following table structure

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

Answer:

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


File of records

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

Example: Writing to a text file

Creating a .csv file from a 2d array.

Python 3

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

# mainArray contains the headers and 3 records for a database

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

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

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

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

Reading a .csv file into a 2d array

Python 3

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

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

mainArray = []                  #empty array defined        

for line in csvLines:
    line = line.strip()         #removes \n character from end of line
    inner = line.split(",")     #line is split into an array "inner"
    mainArray.append(inner)     #inner array appended into mainArray
Exercise: CSV File access

Write a program that asks you for the names, email and mobile phone number of your friends then writes them into a csv file.

Python 3 answer

Answer:

looping = ""
outputArray = []

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

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

op = open("friends.csv",mode="w")
op.writelines(outputArray)
op.close()

Write a program that reads the .csv file from the question above into a 2d array. Python 3 answer

Answer:

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

friends = []

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

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

Extension: XML

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

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

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

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


Validation

Error types

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

  • Compilation Errors
  • Run-time Errors
  • Logic Errors

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

Compilation (Syntax) error

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

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

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

Run-time error

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

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

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

Logic (Semantic) error

A logic error is when a program compiles, doesn't crash, but the answers that it gives are incorrect. The logic, semantics or meaning, conveyed by the code is wrong. Take a look at the next example:

Dim Price as decimal = 45.99
Dim Tax as decimal = 0.20

Console.Writeline("Price {{=}} " & Price)
Console.Writeline("VAT {{=}} " & Price * Tax)
Console.Writeline("Total {{=}} " & Price + Tax)

In the above example you would expect it to print out:

   Code Output
Price = 45.99
VAT = 9.198
Total = 55.188

But because there is a logic error on line 6, it prints:

   Code Output
Price = 45.99
VAT = 9.198
Total = 46.19

To fix it, you have to fix the logic of the code and change line 6 to:

Console.Writeline("Total = " & Price + (Price * Tax))
Exercise: Exception Handling

Name and give examples of the three error types in programming code:

Answer:

  • Compilation (Syntax)
  • Logic (Symantic)
  • Runtime


What error is in the following code, how would you fix it:

dim x as integer
do until x > 5
  x = 1
  x = x + 1
loop

Answer:

There is a Runtime error. x will never be greater than 5, since line 3 gives x the value of 1, thus, the loop will always end in 2 and the loop will never end. This could be fixed by moving the x = 1 instruction outside the loop, between line 1 and 2.


What error is in the following code, how would you fix it:

dim n as sting
console.writeline("enter your name")
n = console.readline

Answer:

The first line has a compilation (syntax) error. dim n as sting should read dim n as string


What error is in the following code, how would you fix it:

Dim names() As String = {"Harry", "Dave", "Princess", "Nicky"}
'print all the names
For x = 1 to 3
   Console.Writeline("name " & x & " = " & names(x))
Next

Answer:

The third line has a Logic (semantic) error. For x = 1 to 3 should read For x = 0 to 3


What error is in the following code, how would you fix it:

Dim names() As Sting = {"Harry", "Dave", "Princess", "Nicky"}
Dim y As Integer
y = Console.Readline()
'print some of the names
For x = 0 to y
   Console.Writeline("name " & x & " = " & names(x))
Next

Answer:

Line 1 has a compilation error, Sting should read String. There is also a potential Runtime error on line 5, if the user inputs a value of y that is greater than 3 then the code will break. Errors like these can be solved in a number of ways, we are going to look at one now.


Catching errors

Dim age as integer
console.writeline("How old are you?")
age = console.readline()
console.writeline("What is your name?")

For the above code we can easily break it if we type the following:

   Code Output

How old are you?
cabbages!

The reason, as you should already be aware, is that variable age is an integer and you are trying to save the string cabbages into an integer. It's like trying to fit a cannon into a camel, they just aren't compatible, and VB will definitely complain ruining all your code. What is needed is a way in which we can stop or catch these errors, we are going to take a look at try and catch.

Dim age as integer
console.writeline("How old are you?")
Try
  age = console.readline()
Catch ex As Exception
  console.writeline(ex.message)
End Try
console.writeline("What is your name?")

This will deal with the issue:

   Code Output

How old are you?
Socrates!
Conversion from string "Socrates!" to type 'Integer' is not valid.
What is your name?

Letting us know that you're put a string in when it was expecting an integer. The program doesn't crash.

Exercise: Exception Handling

Use a try and catch to avoid the issue of a person inputting a value for y that would break the array.

Dim names() As String = {"Harry", "Dave", "Princess", "Nicky"}
Dim y As Integer
y = Console.Readline()
'print some of the names
For x = 0 to y
   Console.Writeline("name " & x & " = " & names(x))
Next

Answer:

Dim names() As String = {"Harry", "Dave", "Princess", "Nicky"}
Dim y As Integer
y = Console.Readline()
'print some of the names
Try
   For x = 0 to y
      Console.Writeline("name " & x & " = " & names(x))
   Next
Catch ex As Exception
   console.writeline("Looks like we're exceeded our array index")
   console.writeline(ex.message)
End Try


The role of variables

As we have seen variables can play a very important role in creating programs and especially when executing loops. The roles of these variables can be categorised into several types:

Type Description Examples
fixed value A variable that is given a value that then does not change for a duration of a loop This might be an upper or lower bounds that the array is tending towards
stepper A variable used to move through an array or other data structure, often heading towards a fixed value and stepping through elements in an array Stepping through the values in an array, or outputting a certain number of lines of text
most recent holder A variable used to record the last thing inserted by a user or the latest value being read from an array input = console.readline() or getting the next value from an array
gatherer A variable that accumulates or tallies up set of data and inputs. It is very useful for calculating totals or totals that will be used to calculate averages. the total of ages of students in a class, the scores or batsmen in a cricket game, tally UMS points for an A-Level student or tell you the combined price of all the objects in your shopping basket
Example: fixed value / stepper / most recent holder
dim fixedvalue as integer = 10
for stepper = 1 to fixedvalue
  console.writeline("the stepper value is : " & stepper & " and the fixed value is : " & fixedvalue)
next

in the above code it is easy to see the use of a fixed value and a stepper. Let's look at a more complicated example:

dim totalnum as integer = 10
dim t as integer = 0
dim input as integer
console.writeline("The following loop will collect 10 values and gather them together:")
for x = 1 to totalnum
  console.writeline("the stepper value is : " & x & " the fixed value is : " & totalnum )
  console.writeline("please insert a value:")
  input = console.readline()
  t = t + input 
  console.writeline("so far we have gathered numbers totalling:" & t)
next

In the above code you can see the various roles of variables in collecting together 10 inputs and adding them all together (gathering):

Variable Role
totalnum fixed value
x stepper
t gatherer
input most recent holder
Type Description Examples
most wanted holder A variable that keeps track of the lowest or highest value in a set of inputs calculating the top scorer in a football team, the lowest score in an exam and the highest number of pied wag tails seen by a bird watcher in a particular year
follower used to keep check of a previous value of a variable, so that a new value can be compared followers are often used when sorting arrays, in routines such as bubble or insertion sort
temporary A variable used for storing something for a very short period of time temporary variables are often used for swapping values between other variables
transformation used to store the result of a calculation involving more than one variable transformation variables are used to calculate such things as compound interest
Example:most wanted holder / transformation / follower / temporary
dim scores() as integer = {12,32,43,2,11,23,7,9}
dim mostwantedholder as integer = 0
for c = 0 to 7
  if scores(c) > mostwantedholder then
    mostwantedholder = scores(c)
  end if 
next
console.writeline("the highest score is: " & mostwantedholder)

In the code above you can see the use of the most wanted holder to store the maximum value from an array of numbers. As you cycle through each item in the array (using the stepper c), you update the mostwantedholder to store the maximum value that you come across. Let's take a look at a more complex example

dim scores() as integer = {12,32,43,2,11,23,7,9}
dim temp, prev as integer
dim arLen as integer = 7
dim mostwantedholder as integer = 0

for c = 1 to arLen
  prev = scores(c-1)
  if prev > scores(c) then
    temp = prev
    prev = scores(c)
    scores(c) = temp
  end if
next

The code above describes a single pass of bubble sort. Using the temporary variable, temp, we bubble the largest array value to the top of the array, by comparing the current array value (scores(c)) and the follower prev. In summary:

Variable Role
temp temporary
prev follower
arLen fixed value
c stepper

Finally let's look at an example of a transformation, we have used lots of loops so far, but variables certainly aren't only used in loops:

Const pi as single = 3.14
dim r as single
dim a, c as single
console.write("insert the radius: ")
r = console.readline()
a = pi * r * r
console.writeline("area = " & a)
c = 2 * pi * r
console.writeline("circumference = " & c)

In the code above there are two transform variables a and c.

Exercise: Role of Variables
dim numCats as integer = 9
for x = 1 to numCats
  console.writeline("cat number :" & x & " says meow!")
next

For the above code name the role of each of the following variables:

Variable Role
x
numCats

Answer:

Variable Role
x stepper
numCats fixed value
dim total, highest, avg, current as integer = 0
dim max as integer = 10
console.writeline("insert " & max  & " numbers:")
for count = 1 to max
  current = console.readline()
  total = total + current
  avg = total / count
  if current > highest then
    highest = current
  end if
next

For the above code name the variables that act as a:

Role Variable
transformation
most wanted holder
most recent holder
gatherer
fixed value
stepper

Answer:

Role Variable
transformation avg
most wanted holder highest
most recent holder current
gatherer total
fixed value max
stepper count
Extension: Other Roles

The roles you see here are included in the syllabus and it is very likely that they will be examined. There are several other roles out there which aren't covered here, these include:

  • one-way flag
  • organizer
  • container
  • walker

You can find out more about them here

Fundamentals of structured programming

You should already have seen how you can use structure tables, structure charts, hierarchy charts and procedures/functions in breaking down a complex task. This section will look at how to write the best formed and most readable code we can.

If you want to be a good programmer (and get good marks in the exam) then you have to make sure that your code is easily read by other people. There are several things you should try and do when coding:

Use procedures that execute a single task

Each procedure / Function does a single thing, such as calculate the current health of a player in a game. This means you can then use them as building blocks to build bigger solutions. If you make your procedures / functions do too many things at once, then they are very hard to re-use in different projects and difficult to test.

Use procedures/functions with interfaces

  • Breaks the problem into chunks
  • You can test each separately
  • You can reuse code

Use sensible variable datatypes

Make sure that the datatype you use are sensible. You will get marked down for using the wrong datatypes in your database tables and variables.

For example: If you are recording the total number of chocolate bars in a shop you don't need to use a Long or Float, you can only have whole numbers of chocolate bars and it is unlikely you'll have over a few million items. Use an Integer!

Meaningful identifier names

When you are declaring parts of your program and you return to the code some time later, you want to be able to understand what each variable, procedure and function does without having to trace out the code. The easiest way to start doing this is to name them correctly:

Use sensible variable names

If you are using variables to store things they must have a name that makes sense so you know what it does when you read its name in your code.

For example: If you are recording the total number of chocolate bars in a shop you don't want to use a name like variable1. What does variable1 mean? Use a sensible name such as NumChoc.

Use sensible Function/Procedure names

If you are creating subroutines to process things in your code make sure you give them a sensible name so that people know what they are doing when they see them in the code.

For example: If you have written a piece of code to calculate the average price of a chocolate bar then don't call it FunctionA(), what does FunctionA() mean?! Call it ChocAverage().

Try to stick to one naming convention

If you are using lots of variable names and function names, stick to a single style for naming them. If you use lots of different conventions things are going to look ugly. Wikipedia guidance

For example:

  • firstName, lastName, calculateDoB, numLegs
  • FirstName, LastName, CalculateDoB, NumLegs
  • First_Name, Last_Name, Calculate_DoB, Num_Legs

Don't make your names too long

Long variables can be very hard to read and much easier for you to make mistakes when writing them, try to shorten things where possible.

For example:

Too Long Just Right
ThisIsYourFirstName FirstName
the_value_of_a_chocolate_bar ChocVal

Indent your work

A lot of programming environments help to indent your code automatically and you should be able to find one for the language you are using. Indenting helps people to read and understand your code quickly as it clearly shows the structure of functions, procedures, selection and iteration statements. For example the following is very hard to read:

int main(int argc, char *argv[])
{
...
while (x == y) {
something();
somethingelse();
if (some_error)
do_correct();
else
continue_as_usual();
}
finalthing();
...
}

If you indent it is becomes much easier to read:

int main(int argc, char *argv[])
{
    ...
    while (x == y) {
        something();
        somethingelse();
        if (some_error)
            do_correct();
        else
            continue_as_usual();
    }
    finalthing();
    ...
}

Use comments where necessary

Some of the best written code doesn't need comments because if you have structured it correctly and used all the proper naming conventions it should be pretty easy to read. However for the code you are writing you should put some comments to explain what each section does.

'this function takes an array of prices and outputs the average
function calculateAverage(num1(20) as integer)
{
    'add all the numbers together
    while ...
          ...
          ...
    end while
    
    console.writeline(average)
}

The advantages of the structured approach

  • Easy to read and fix code
  • Problems broken down into easy to manage chunks
  • procedures / functions are reusable, you can use them in different projects.
  • You can test modules individually
Exercise: Structured programming
sub calcEverything(byref a as integer, byref b as integer, byref c as integer)
  dim total, avg as integer
  total = a + b + c
  console.writeline("the total of inputs = " & total)
  avg = total / 3
  console.writeline("the average of inputs = " & avg)
end sub

What might be considered wrong about the use of the subroutine above? How could it be fixed?

Answer:

The sub routine is performing multiple function: it calculates the total AND the average. Functions/procedures should only perform one task at a time. You could replace the above with two subroutines:

  • calcAvg(...)
  • calcTotal(...)

List three reasons for using functions and procedures to structure your code

Answer:

  • You can re-use the code
  • You can test parts of the code individually
  • The code is easier to read and understand
dim ppdpdp as string
dim cheesy as integer
console.write("hello, please insert your name: ")
ppdpdp = console.readline()
console.write("hello, please insert your age: ")
cheesy = console.readline
if ppdpdp = "Dave" then
if cheesy = 23
console.write("daisy, daisy...")
else
console.write("I'm sorry dave")
end if
else
console.write("Get off my spaceship")
end if

Give three structured programming techniques that could be used to improve the code above:

Answer:

  • proper use of indentation
  • sensible variables names (why on earth have they used cheesy to store the age, why not use age?)
  • use comments


Modulo arithmetic

Modular arithmetic is all about finding the remainder from long division (MOD), and the total number of times that a number goes into a division (DIV). Let's take a look at a quick example of 10 divided by 7 (you might want to remind yourself about long division):

    1 r 3
 7)10
    7
    3

Hopefully that wasn't too hard. We now need to introduce some terminology, MOD and DIV:

  • MOD = finds the remainder from long division i.e. 10 MOD 7 = 3
  • DIV = finds the number of divides in long division i.e. 10 DIV 7 = 1
Exercise: MOD and DIV

Try these examples, working out the MOD and DIV of each:

7 / 2

Answer:

MOD = 1 DIV = 3

17 / 5

Answer:

MOD = 2 DIV = 3

8 / 2

Answer:

MOD = 0 DIV = 4

6 / 9

Answer:

MOD = 6 DIV = 0 (9 does not divide into 6 at all!)

Now try these explicit calculations:

11 MOD 8

Answer:

= 3

8 MOD 4

Answer:

= 0

6 DIV 5

Answer:

= 1

600 DIV 20

Answer:

= 30

Hopefully you are now pretty good with MOD and DIV, but what exactly is the point of all this? A very common example in past exam paper has been using the MOD and DIV to work out a binary equivalent of a denary number.