ITP Student Workbook V2.4
ITP Student Workbook V2.4
Student Workbook
Page 1 of 163
The copyright in this document is vested in NCC Education Limited. The document must not be
reproduced by any means, in whole or in part, or used for manufacturing purposes, except with the
prior written permission of NCC Education Limited and then only on condition that this notice is
included in any such reproduction.
Published by: NCC Education Limited, The Towers, Towers Business Park, Wilmslow Road,
Didsbury, Manchester M20 2EZ, UK.
Tel: +44 (0) 161 438 6200 Fax: +44 (0) 161 438 6240 Email: [email protected]
http://www.nccedu.com
Page 2 of 163
Page 3 of 163
Page 4 of 163
Page 5 of 163
4. Implement a program that uses 4.1 Write a working program that uses a for loop
iteration and selection constructs. construct.
4.2 Write a working program that uses an if – else
construct
4.3 Identify and document appropriate testing of
loops and selection statements
5. Implement a program that uses file 5.1 Write code that demonstrates how to output data
i/o. to an external file.
5.2 Write code that demonstrates how to read in and
store data from an external file.
5.3 Identify and document appropriate testing of file
input/ output
Page 6 of 163
Page 7 of 163
Page 8 of 163
Learning Outcomes: 2, 4
6 Project 10% • Specification, design,
Definition and implementation, test cycle
Design • Project Brief to Specification
1 hour of lectures
4 hours of • Object Definition Sheets
laboratory • Debugging and testing
4 hours 15
minutes of private
Learning Outcome: 1
study
7 Case Study: 10% • Consolidation of learning from
Creating a GUI topics 1 – 6
program that • Student mid-course assignment
3 hours of
uses sequence,
laboratory
selection and
3 hours 15 Learning Outcomes: 1, 2, 3, 4
iteration
minutes of private
study
8 Introduction to 10% • Benefits of arrays
Arrays • Declaring arrays
1 hour of lectures • Initialising and filling arrays
5 hours of • Accessing and changing values
laboratory in arrays
5 hours 15 • Manipulating arrays using for
minutes of private loops
study
• Sorting arrays
Learning Outcomes: 4, 6
Page 9 of 163
4. Resources
Lecturer Guide: This guide contains notes for lecturers on the organisation of each topic,
and suggested use of the resources. It also contains all of the suggested
exercises and model answers.
Student Workbook: This guides the student through the module and presents details of the
tasks they should undertake during the laboratory sessions. It also
included the exercises which have been provided for private study time.
Page 10 of 163
The class time for this module is mostly made up of laboratory sessions. This is because the
module has a very practical focus. Each topic will also have an introductory lecture session.
All lessons will take place in the computer laboratory.
A major role of the teachers for this module will be as trouble shooters as the students work
their way through the self instructional student text. Hence it is vital for you to prepare by
working through the student workbook yourself.
It should be made clear to students that they keep a reasonably detailed record of their
progress through the student workbook. This record should include all details of their solutions
of all the set exercises and the private study work.
Great stress should be put on the testing of solutions. Students should test even the most
trivial solutions by writing down what they expect from a particular test and reporting as to
whether the solution produced the expected result. If the answer is no, then there should be
some record of the remedial action they had to take. These records are not for assessment
but it is important that students learn that it is good practice to record the actions taken.
5.1. Lectures
It is suggested that you prepare an introductory lecture to each topic. To help with this
preparation there are notes before the start of each topic in this Lecturer Guide. You will be
presenting the basic knowledge required for the topic during this time and students are
expected to take notes. Students should then work through the associated notes in the Student
Workbook under the supervision and guidance of the lecturer.
Page 11 of 163
6. Assessment
This module will be assessed by means of an assignment, based on the assessment criteria
given above and students will be expected to demonstrate that they have met the module’s
learning outcomes. Sample papers are available through the NCC Education Virtual Learning
Environment (http://vle.nccedu.com/login/index.php) for your reference.
The assignment will only require the knowledge and skills exposed in Topics 1 to 7. Please
refer to the Academic Handbook for the programme for further details.
In Topic 6, students are introduced to the Object Definition Sheet together with a minimalist
approach to design. If students follow this approach and make some supporting notes, then
that should be sufficient for this introductory module.
6.2. Implementation
Pseudocode or flowcharts for algorithms are not required but if students or teachers find them
helpful then they may of course be added. However, some description is expected that
indicates the logic that will direct how they program each procedure. In addition, program code
should contain sensible comments. It is not unreasonable that the pre-description and the
program comments should be similar.
6.3. Testing
This is mentioned in Topic 6. It is important that the design of tests and the carrying out of
testing should appear in a separate part of the documentation.
For example, if a TextBox has been programmed to only accept numeric data then the design
of the testing should simply indicate what test data will be entered, including some non-
numeric data, and also indicate the results expected. Finally exemplar screen shots that it has
all really happened should also be given. Note that not every possible screen shot is required,
but rather a few to show good faith.
Page 12 of 163
McGrath, M. (2016). Visual Basic in easy steps. 4th Edition. Leamington Spa: In Easy Steps
Limited.
ISBN-10: 1840787015
ISBN-13: 978-1840787016
Page 13 of 163
Use the fundamental facilities of the Visual Studio Community 2015 IDE;
This topic introduces the Visual Studio Community 2015 IDE. It also introduces the VB toolbox
and some commonly used components and their properties, and looks at how to create a
basic graphical user interface (GUI) program.
Visual Studio Community 2015 provides the programmer with an Integrated Development
Environment (IDE). This consists of a number of windows as shown below.
Page 14 of 163
By default, the Toolbox window will not be open when you open up your project. To open it,
click on the Toolbox option in the menu running down the left hand side of the screen, then
click the pin icon to pin the Toolbox menu in place.
1.3. Timings
The approximate amount of time that you can expect to spend on each type of activity in this
topic is as follows:
Lectures: 1 hour
Page 15 of 163
Page 16 of 163
We are going to create a simple Visual Basic project that will use several common controls.
1. Restart Visual Studio Community 2015 and close the start-up window, giving:
Page 17 of 163
3. Note the Visual Studio projects location. In the example above, Visual Studio has chosen
C:\Users\Pauline\Documents\Visual Studio 2915\Projects. You will have a similar location
chosen by Visual Studio. Change this location by either typing the location where you want
your projects to be saved, or by clicking on the button with the three dots to the right of the
location window and browsing to a suitable folder. (If you are working on more than one
computer it is wise to save your work on a Flash (USB) drive.)
Page 18 of 163
Page 19 of 163
Page 20 of 163
Now that we have a new project set up, let’s take a closer look at the Visual Studio IDE.
Visual Studio Community 2015 is an Integrated Development Environment (IDE) – from one
application, you can write the code, compile the code, execute the program, and test the
results. In years gone by, it was common practise for developers to write code in one
application and then compile it from the command line. The development of the IDE has led
to a great saving in time and frustration.
Page 21 of 163
Form
Designer Properties
Along the top of the IDE are the standard menu options and action buttons - we will have
cause to explore these as we go on through the module, but we can leave them aside for now
and concentrate on the key areas of the interface.
The biggest window is the form design window, and this is where you do most of your work
when setting up an interface. The grey box within the form design window is the layout of an
actual windows application. It doesn’t do anything, or have anything on it, but that’s an
application nonetheless. Within Visual Basic, this application window is known as a form. A
windows application is made up of one or more forms.
The solution explorer provides you with an easy way to navigate through complicated VB
applications. In many cases, a VB application will have more than one form, and the solution
explorer provides a simple way for you to move between these as you need to.
Page 22 of 163
Click on the Common Controls option from the menu. This is where most of the components
you will be using in your projects can be found:
The Common Controls provide you with most of the things that you can drag onto your
windows application. There are many more components that aren’t seen here - hundreds of
Page 23 of 163
In Visual Basic, each of these GUI components is known as a control, and a Visual Basic
form is made up of one or more controls.
VB offers two ways for you to incorporate a control onto your forms - you can click on the
control in the toolbox and then draw it onto the form in the standard way by clicking the start
point then dragging the mouse to size it, according to your desires for size and positioning.
Alternatively, you can just double click on one of the options and it will draw a standard sized
control onto your form.
Once you’ve drawn a control onto the form, you can left-click on it and drag it to wherever
you wish. You can also resize it through the usual mouse interactions.
It is worth noting at this point that a form itself is also a control - it’s a control that holds other
controls. The implications of this should become clear as we proceed through the module to
the later weeks.
The properties window is used to configure the specific details about controls. We can
choose the size and positioning of these when we draw them, but there are usually many
other aspects that we want to be able to change. For example, if we draw a button onto a
form, we will want to be able to change the text on that button. It is the properties window
that allows us to do this.
A property is a configurable element of data that goes along with a control. A control has
many properties, each of which can be changed to alter the look or behaviour of that control.
Let’s put some of this into practise and draw our first VB interface
Page 24 of 163
All of the standard controls we’ll be discussing in the next few weeks are drawn this way.
Some of the more advanced controls work differently, and we’ll discuss these as time goes
on.
The text Button1 looks quite ugly there, and so we so we should change it to something
better. It doesn’t really matter to what we want to change it just now, so let’s change it to the
words Press Me.
In order to do this we need to make use of the properties window. First we ensure that the
button is selected on the form by left clicking on it - the properties window is control specific -
it will display the properties of the control with which you are currently working
There are a huge number of these properties, and not all of them are interesting to us. At
the moment, there is only one that we want, and it’s called Text. The Text property contains
the text that is displayed across the button - changing this property will change what is
written. The properties are displayed as a pair of columns - the text at the left of the column
is the name of the property, and the text at the right is what is known as its value. At the
moment, the text property has a value of ‘Button1’.
The properties window shows the properties for the currently selected object. Select Button1
by clicking on it. An outline with small squares will appear around it, showing that it is the
currently selected object, as seen in the screen shot above. Once the button is selected,
double-click on the Name property and it will let you type something else in its place:
Page 25 of 163
Page 26 of 163
The form itself also has properties - let’s get rid of that ugly ‘Form1’ across the top. Click on
the form itself to bring up the properties window for the form, and then change its text property
to something more suitable:
The controls aren’t all so basic - there are some very complicated, very powerful controls
available even in the default toolkit. So let’s pick one of these and place it onto our form.
Double-click on the control called MonthCalendar, and then drag the control it creates to a
suitable position. You’ll find that you can’t resize this control, but that’s okay - its specialised
functionality makes resizing it problematic, so the VB designers simply disallowed it:
Page 27 of 163
Now that we have an application, we need to see it in action. We now go through a process
called compilation to turn our efforts into something that can be understood by the Common
Language Runtime. There is a button on the toolbar that looks like a play button - this is the
button that compiles and executes your program:
Clicking this button will (after a few seconds) cause your application to appear. You’ll be
able to flick through the months on the calendar - you’ll even be able to press the button
(although nothing will actually happen because we haven’t added any program code yet).
It’s a fully functioning Visual Basic program in every way that matters.
Page 28 of 163
Many controls share properties - any control that displays text on it will have a Text property,
for example. Some controls though have specialised properties that don’t exist on other
controls. We’ll be seeing some of these through the coming weeks and months.
In this chapter, we’re going to look at some common properties you might expect to see, and
what they actually do:
Property Function
(Name) The name property is vital, and we’ll be changing it on every control that we
add to a form. The name of a control is a unique identifier that lets you refer to
it within code - more on this next week.
BackColor This is the background colour for the control. Changing this property will give
you a range of options as to what colours your control could be. Changing it to
Red for our button would change the background colour to red, but the text
would still be in black.
BackgroundImage This property lets you set an image to act as the background for a component -
you can have a button that has no text, but instead has an image. Changing the
property allows you to browse for the appropriate image.
Dock If you want a component to be flush with some area of the form, you can choose
to ‘dock’ it. Clicking on the property will bring up the choice of five areas.
Select one of these and the component will resize itself and ‘lock’ to the area,
Page 29 of 163
Enabled If you wish a control to be made unusable for a time, then you can set its enabled
property to false - it will still be drawn, but it will be non-functional. You can
re-enable it by setting it to true.
Font You can change the font of any control that displays text by changing this
property. Clicking on the property brings up a smaller subset of font properties
allowing you to precisely configure the font.
ForeColor For our button, this is the colour of the text - we can change this in the same
way we change the BackgroundColor.
Visible Set this property to false if you want the control to disappear - it’ll still be there,
it just won’t be seen. Set it back to true if you want it to reappear.
TabStop In most applications you can press ‘tab’ to step over each of the controls until
you find the one you want. If you want the controls of your application to
behave similarly, you set this property to ‘true’. Otherwise you set it to false.
TabIndex The TabIndex determines in which order you tab through controls - it’s just an
integer number. When you press tab, VB looks for the control on the form that
has the next highest TabIndex. If there is none, it moves to the control that has
the lowest TabIndex.
Page 30 of 163
This will allow us to use the Button control we have already used, and introduce us to some
other commonly used controls such as labels, text boxes, combo boxes, radio buttons, check
boxes and group boxes.
If you already have a project open, go to File – Close Solution. If not, open up Visual Studio
Community 2015, close the Start Page, then go to File – New – Project. Select Visual Basic
as the language and Windows Forms Application as the type, and change the name of the
project to HolidayPicker. Note that you should never have spaces in your project name. Also
ensure that the Location is suitable and browse to a different folder or drive if required.
Page 31 of 163
Click on the Form title bar to select it, then change the text property to Holiday Options.
It makes sense to start adding components from the top and work our way down. The first
component we need to add is a Label, which will be used to display the title Holiday Planner.
Labels are used whenever we need to display text that we do not want the user to be able to
change.
To add a label, click on the Label control in the list of Common Controls, then click and drag
to position it in an appropriate position on the form.
The black box in the screen shot above is what you see when you are clicking and dragging
to position the control on the form. Once you release the left mouse button, the text Label1
Page 32 of 163
Now change the text property to Holiday Planner. When we do this, the text remains very
small because the default font is MS Sans Serif 8.25pt. In the properties window for the control,
select the Font property and click on the icon to the right of it with the three dots:
This brings up a secondary window. Use this window to change the font style to bold and the
font size to 14pt.
Once you click OK the label should change to look like the one in the example screen shot.
Step 4: Add the labels and textboxes for the name and email
Add two additional labels using the same method as above. You can right or left-align these
so they match up – as they are labels to go with textboxes which will be to the right of them,
right-aligning the labels will look best. When placing the second label, a blue line will show
you when they are aligned:
Next, we need to add two Textbox controls to the right of these labels. We want these to line
up both horizontally and vertically with the labels. Blue and purple lines will help us to identify
when we have them positioned neatly in relation to both the labels and the other textbox
control.
Page 33 of 163
Combo Boxes are drop down lists of options from which the user can select one item. We
want to line these up with the textbox for entering the user’s name. Add both of these to the
form, using the little white boxes to resize them (e.g. make them less wide) if required.
Once we have them positioned, we need to change the text property for the first one to Month
and for the second one to Day. Once we have done so, the form will look like this:
However, if we run the program (by pressing the Start button) we will see that there are no
months or dates listed.
We need to add a list of Months, and a list of dates to the appropriate combo boxes. To do
this for the Month combo box, select the control, then in the properties window select the Items
property and click on the icon with the three dots which appears when you select it.
Page 34 of 163
Run the program again, and this time the list of months will appear in the drop down menu,
and you will be able to select one.
Repeat this process for the Days, putting in 1 to 31 on separate lines for the items.
For this step, we add two new Label controls. Use the blue and purple lines to check that they
are aligned with each other, and with any other components you wish to align them vertically
with. Change the text properties to Destination and Duration and change the font properties
to font style bold and font size 14pt.
Page 35 of 163
To begin then, we need to add two GroupBox controls to the form. The GroupBox control is
not found in the Common Controls list. The easiest way to find it is to click on the All Windows
Forms menu above the Common Controls item in order to expand it.
Once this has been expanded, we can click on the GroupBox component to select it.
Select GroupBox by clicking on it, then click and drag to position it, lining it up with the left
hand side of Destination. Use the small white squares to resize the box so it is large enough
to hold two columns of 3 radio buttons, but does not get too close to the left hand edge of the
Duration label.
Page 36 of 163
We can now add radio buttons to our group box. Note that when you are adding a lot of controls
of the same type, it can be easiest to add one control then select it, right click and copy and
paste, then align them all as required and change the text properties.
In the Toolbox window, scroll dow to the Common Controls menu option, click it to expand the
list, then select RadioButton.
Page 37 of 163
As noted above, the easiest way to get all 6 is to right click on the radio button, then choose
Copy from the menu that appears.
After choosing Copy, right click on the form and select Paste. The radio button will not be
pasted where you clicked, but just select it then drag it to where you want to position it.
Do this until you have 6 radio buttons in 2 columns and 3 rows, and change the text property
of each as shown below.
Note that none of the radio buttons are currently selected. Select the top radio button, with the
text London, and go to the Properties window. Scroll to the Checked property, and select
True from the drop down menu.
Page 38 of 163
Note that you cannot set the Checked property to True for more than one radio button in the
group. Try changing the Checked property to True for Edinburgh. It will let you do so, but
immediately sets the property for London back to false, so only Edinburgh is checked. Set it
back to London as being selected, as it is usual practice for the top left hand option to be the
one selected by default.
Now that we have the group box of radio button options set up for the Destination, follow the
same process to set up the Duration group box of radio buttons so that they appear as shown
below.
For this step, we add a new Label control. Use the blue and purple lines to check that it is
suitably aligned with any other components you wish to align it vertically with. Change the text
property to Options and change the font properties to font style bold and font size 14pt.
As with the Destination and Duration choices, we are going to use a GroupBox control to
keep things neat. However, we are going to use CheckBox controls for the options. Check
boxes are used when you want the user to be able to select multiple options: the choices are
not mutually exclusive. In this case, we want the user to be able to select as many of the
options as they wish.
Page 39 of 163
As the Options are all optional, we won’t change the checked property for any of them.
Our final step is to add the Submit button. From the Toolbox window, select the Button control
and click and drag to position it on the form below the Options GroupBox.
Page 40 of 163
When you run the program by pressing the Start button, you will be able to select different
destinations and durations, and check as many or as few options as you like. You will also be
able to select different months and days. The program won’t do anything when you press the
Submit button, because we haven’t learned how to add any code yet. But we’ll get to that later
on.
• How to use Visual Studio Community 2015 to create Windows Forms Applications
• How to use various Visual Basic controls and change some of their properties.
Page 41 of 163
Some of these tasks involve experimenting with properties which were mentioned in this topic
but which we did not use in the Holiday Picker task. You should be able to identify what to use
by referring to the properties table.
Task 1
Change the background colour of the HolidayPicker application we have just created to the
ControlDark option using the properties menu.
Task 2
Task 3
Change the font colour of the Submit button in the HolidayPicker application to red.
Task 4
Create a new Visual Basic Windows Forms Application project called CakeChooser. Set up
the interface so that it looks like this:
Page 42 of 163
Create a new Visual Basic Windows Forms Application project called Calculator. Set up the
interface so that it looks like this:
Page 43 of 163
2.3 Timings
The approximate amount of time that you can expect to spend on each type of activity in this
topic is as follows:
Lectures: 1 hour
Page 44 of 163
In general, programming takes the form of collections of related statements of code that are
executed one after another - these statements are like sentences to be translated into actions
for the computer. In Visual Basic, these statements are compiled into a format that the
Common Language Runtime (CLR) can understand - this format is called intermediate
language. The CLR then executes this intermediate language, which causes the computer
to perform the actions you have requested.
The path of execution through a program is the order in which statements are executed - in
later topics we’ll see ways in which we can alter the path of execution based on conditions
that we specify.
Step 1
Create a new Visual Basic Windows Forms Application called MyFirstEventDrivenApp and
store it in a suitable location.
Step 2
We need to create an appropriate interface, and so we will create a form that has a textbox, a
label, and a button. It doesn’t matter how these are arranged - just that they are present on
the form.
Step 3
After doing that, we end up with something that looks similar to this:
Page 45 of 163
All of this is handled through a few lines of code, but first we need to talk about a property that
we only briefly touched upon last week - it’s the name property.
Every control has a name, and that name is how we refer to it in code. Visual Basic will
automatically provide you with a name when you create the control, but it’s not very
memorable. The name of the button by default is Button1, which is fine if you have only one
button on the form - if you have ten, it’s easy to forget what Button5 does and Button6 does.
So instead we provide the controls with meaningful names.
Additionally, it is the convention in Visual Basic to use a naming convention when changing
the names of controls - this allows us to differentiate between controls drawn onto a form, and
other data constructs (more on this later). We identify a control by prefixing its name with a
specific three letter identifier:
As we introduce new controls, we’ll also introduce their identifier and use them within the
example code.
Step 4
We need to change the name property of each of the controls to something appropriate - the
names indicated above are good enough for that, so those are the ones we use.
Page 46 of 163
Step 5
First you select a control - in this case, we’ll select the button. Then double-click on it, and it
will open up the code window for that control:
What appears contains a lot of generated code. This is code that Visual Studio creates for
you. We’ll return to the meaning of some of these things later, but for now we’re more
interested in doing what we need to do next.
The important part of the code here is the part marked as private sub cmdPressMe_Click -
but don’t worry about the stuff that’s in the brackets - it doesn’t matter to us just yet:
This marks what is known as a subroutine - a little piece of code that exists independently in
the program until someone tells Visual Basic to execute it. You can see the name of our
control is built into the subroutine, as is the word ‘Click’. Visual Basic has set this subroutine
to execute whenever anyone clicks on the cmdPressMe button. Add in another button and
double click on it, and you’ll get a different subroutine - in this way you can add different
functionality to different controls. But we’ll get to that later.
For now we want our functionality. This is a two step process - first we want to put the contents
of the textbox into the label, and then we want to clear the textbox.
The text in the textbox is stored in a property called text, as we’ve already seen - and we know
our textbox is called txtInput, because that’s what we changed the name property to. We
can use a special dot notation to say to Visual Basic ‘I want the value of this property in this
control':
txtInput.text
We can type that into our code window, but all that will happen is that we’ll confuse Visual
Basic. We need to provide instructions to Visual Basic as to what we want to happen.
The text of a label is also stored in a property called text, and we know the label is called
lblOutput:
lblOutput.text
So we want the text property of the lblOutput control to be the same as the text property of the
txtInput control. We can accomplish this using a special symbol called an operator. In this
case, it’s an equals sign:
Page 47 of 163
We’ll talk more obout operators later in this topic, but for now that’s step one accomplished.
Step two involves us clearing the text property of the txtInput control. We use the equals
operator for this also:
txtInput.text = “”
Step 6
Add the three lines of code to the cmdPressMe subroutine so that it looks like this:
And with these two lines of code, we’ve completed the functionality for the application as we
can clearly see when we compile and run the program by pressing the Start button:
Step 7
Now that we’ve got the basic functionality implemented, let’s add another button (called
cmdClear), and double click on it to get the code window. We’ll make this button clear the text
from our label:
lblOutput.text = “”
You’ll see that VB provides you with a different subroutine for this button, so you end up with
the following code in your code window:
Page 48 of 163
All programming languages offer the facility for creating variables - in Visual Basic they exist
without being linked to any control. There are many different kinds of data, and so there are
many different kinds of variable to store data. We’ll look at the most familiar kind now - the
string. A string is a collection of alphanumeric characters - just like the text property of a
component.
Each variable has a name (just like a VB control), and it also has a value (which is what the
variable contains). We can use the variable name wherever we would normally use its value
- it’s like algebra when you used the letter x to represent an unknown value, except that it’s
easier because the value isn’t unknown - you set it yourself. Variables then are boxes in the
computer's memory, each of which is given a name by which your program can refer to
them. Each box has a name, and a type which indicates what the contents of the box are.
Your program will have no way of storing information for any length of time without these
boxes, and so it is important to make use of them wisely. There are many different types for
variables, and each type indicates the kind of information that can be contained within the
box.
That may sound intimidating, so it’s best explained with an example. We use the following
method to declare a variable in Visual Basic:
The ‘dim’ stands for ‘dimension’ and it’s a holdover from the very first incarnations of the
basic programming language from the 1960s. The second word of the statement
(SomeString) gives the name of the variable, and the fourth word (String) gives the type of
the variable.
Now that we have a variable, we can set its value using the equals operator:
Page 49 of 163
lblOutput.text = SomeString
Step 8
Let’s modify our first program to make use of a variable in the PressMe button to show it in
action:
The variable acts as a container for the data, and we can then use that variable later without
knowing explicitly what is contained within.
All controls and variables in Visual Basic have what is known as a scope, and that scope
relates to where you can make use of it within the program. By default, all controls in VB (at
least, the ones you draw through the IDE) have a class-wide scope - that means you can
use them in any subroutine, as we saw with lblOutput. We made use of lblOutput in the
PressMe subroutine, and also in the Clear subroutine.
However, the variable defined in cmdPressMe_Click has what is known as local scope - it
exists only as long as the subroutine is executing. If you try to use inputText in another
subroutine, your program will no longer compile. You could create the variable again, but it
would be a different variable and not simply a new reference to the first variable. The
contents of a variable are inaccessible when it is out of scope.
This is done for a good reason - it stops variable naming clashes in large programs, and it
ensures that when you are finished using a variable, it no longer takes up memory in the
system. But it can be inconvenient. For example, let’s look at implementing some undo
functionality in our program - at the moment, whenever the text in lblOutput is overwritten, it
is gone forever.
Step 9
Page 50 of 163
Step 10
And then we provide an undo button (called cmdUndo, naturally) that restores the text to the
label:
Step 11
This still will not work because the variable inputText has local scope and is inaccessible in
cmdUndo_Click. This is why undoText is underlined in red in the code window: the compiler
knows it cannot be accessed from this Subroutine. If we want this to work, we must move the
variable declaration outside of the subroutine and give it class-wide scope. This means that
the variable for which we need access from more than one Sub must be declared inside the
class but outside of the Subroutines:
In this way it can be used in all of the subroutines for that form. But be warned! Class-wide
scope should be avoided where possible because it leads to bad program design. You’ll learn
more about this in the program design topic.
Page 51 of 163
Page 52 of 163
If you completed Task 5 of Topic 1 then you already have a Calculator project with the interface
set up as below:
If you have done this, then once you have opened it you are ready to move on to Step 2.
However, if you did not complete Task 5 for Topic 1 you will need to create a new project
As Topic 1 did not include writing any code, we did not bother to change to name property of
any of the GUI controls. As a result, all the components will have default names i.e. Button1,
Button2, Button3, Button4. This is not useful when it comes to writing the code – how will we
remember what Button3 is supposed to do? We need to give the controls suitable names.
Rename the controls as shown in the image below. Remember that this is following our
naming convention for controls of having a prefix which is a shortened version of the control
type, followed by a word which describes what the control is for.
txtNum1
txtNum2
lblAnswer
cmdMultiply
cmdAdd
cmdDivide
cmdSubtract
Page 53 of 163
We need to learn a little more about a new kind of variable now - or rather, we need to learn
about two kinds of variables. The first of these is the Integer, and the second of these is the
Double. They are in the table of variables in the above section, but now we need to make use
of them.
An Integer holds whole numbers, and nothing else. A Double holds real numbers (numbers
with a decimal point) and nothing else. An integer cannot hold a real number and a real
number can only hold an integer if it has a decimal point in it (such as 10.0).
The difference comes in how we use the equals operator - with a string we surround the text
to be assigned in quotation marks. We don’t do that with numbers:
myIntegerNumber = 10
myRealNumber = 11.1232
Other than that, the process is the same - the variable is a label that points to some value that
is either hard-coded in the program or obtained from the user’s interactions with our controls.
Let’s create the calculator using Integers and see what happens.
We need to pull the information out of the two textboxes and store each item in a separate
variable. So we need to double click on the cmdAdd button to bring up it’s Subroutine, then
declare and initialise two variables as shown below:
Even though the text property is a string, Visual Basic will handle the job of converting it into
a number for you.
Run the program and see what happens when we type in 12 and 4 as the two numbers and
click the Add button. Nothing happens! This doesn’t mean we haven’t stored the values. But
Page 54 of 163
• Add numOne and numTwo together and store the result in the answer variable
Update the cmdAdd to add in these extra steps. It will now look like the code shown below:
Run your program again, and the program should add the two numbers together and display
the answer in the label area once you click the Add button.
Arithmetic Operators
The code above makes use of an arithmetic operator. In this case it is the + sign. The table
below shows the other main arithmetic operators which we will use in Visual Basic:
Operation Operator
Addition +
Subtraction -
Multiplication *
Division /
Remainder mod
We’re going to leave two of these for you to work out, so we’re going to skip subtract and move
on to divide. The code for this will be exactly the same as for cmdAdd, except we will use the
/ operator rather than the +. However, it also helps us see why Doubles can be useful.
Remember that you can reuse variable names from the cmdAdd Sub because they are local
variables.
Double click on the cmdDivide button and add the following code:
Page 55 of 163
This is fine when working with whole numbers that divide equally, but what happens if we want
to divide 10 by 4, for example?
10 divided by 4 should be 2.5, so why is our calculator only showing 2? It’s because we are
using the Integer data type. This can only store whole numbers. The result of the calculation
is therefore ‘cut off’ before the decimal point and the fraction is not stored.
Calculators are more useful if they can calculate values to several decimal places. In order to
do this, we need to use the Double data type rather than Integer to store the numbers and the
answer.
Page 56 of 163
Run the program and test it using whole numbers and numbers with digits after the decimal
point.
Controls and variables in VB each have a name, and this name is how they are referenced to
in code. Controls have a naming convention that goes with them that helps the developer
differentiate between different types of controls, and between controls and variables within the
program.
Variables must have a data type, and each data type is designed to store a different kind of
data. Variables also have scope. Variables declared inside of a Subroutine have local scope
and can only be used by that Subroutine. Variable declared inside the Class but outside of the
Subroutines have global scope and can be used by all Subroutines in the program. Only make
variables global if you need to be able to access them from more than one Subroutine.
Page 57 of 163
Update the Calculator application to add in the functionality for Subtraction and Multiplication.
Task 2
Create a new project and design and code a program which will add 5 whole numbers together
and display the answer. You should store each of the numbers entered in a variable of an
appropriate type, including the answer.
Task 3
Create a new project and design and code a program which asks the user to enter in any
phrase they like. This phrase should be stored in a variable of an appropriate type. The
program should then display the phrase to the user.
Task 4
Create a new project and design and code a program which asks the user to enter their height
in metres and their weight in kilograms. The program should then calculate the user’s body
mass index and display this figure for them. The formula for calculating Body Mass Index is:
Task 5
Create a new project and design and code a program which will enable the user to covert
between pounds and kilograms. The user should be prompted to enter in a weight in
kilograms. The program should then calculate the equivalent weight in pounds, store this
answer, then display it to the user. 1 Kilogram = 2.2 Pounds
Task 6
Create a new project and design and code a program to covert between miles and
kilometres. 1 miles = 1.61 kilometres.
Task 7
Page 58 of 163
Page 59 of 163
3.3 Timings
The approximate amount of time that you can expect to spend on each type of activity in this
topic is as follows:
Lectures: 1 hour
Page 60 of 163
We can handle repetition in the first case through the use of repeated sequential code
statements - it’s a big hassle, but it’s an option we have available to us. On the other hand, in
the second situation we can’t simply hard-code the repetition since by definition we don’t know
how many times we need to repeat the code.
Visual Basic provides a range of repetition structures to deal with these situations - these
structures take the responsibility for handling repetition out of your hands and place it in the
hands of the computer - a much more desirable state of affairs.
To do this using sequential programming we would need to have a separate line of code for
each calculation. An example program is shown below:
Page 61 of 163
There is, but before we get to that, we need to take a small tangent to discuss three new things
in this program: code comments, line breaks and appending values to Strings.
Code Comments
You will have noticed that there are three lines of code in the program above which are in
green. These are not actually code, and are ignored by the compiler. Code comments are
used by the programmer to explain what the code in the line or section below the comment
are designed to do. It is good practice to add code comments so that another developer, or
your Lecturer, can understand what you are trying to do. It is also useful if you go back to a
program you wrote earlier, or did not complete in one sitting, to refer back to.
To add a code comment, use the single apostrophe symbol ‘. Everything after this on that line
will then appear in green (unless you have chosen different settings in Visual Studio
Community 2015) and ignored by the compiler.
So far, we have just been outputting variables to labels, for example in the miles to kilometres
and BMI calculator programs from the previous topic. This can be adequate for some
programs, but often you will want to output more detailed information. For example it would
have been useful to be able to display “Your BMI is: “ plus the BMI.
To append additional information on to a String or label we just use the ampersand (&) symbol
like so:
Page 62 of 163
Note that as bmi is a variable name it does not need to be inside quotation marks.
When you want data displayed over multiple lines, you need to also put in line breaks,
otherwise the width of the form will be what dictates where lines split and it is unlikely to be
well formatted.
The line break symbol is vbCrLf which is short for Visual Basic Carriage Return Line Feed.
lblOutput.Text = “Your mark for the assignment is: “ & assignmentMark & vbCrLf &
The for loop looks like this in its most basic form:
Note that we use a variable called counter - this is our counter variable and it tells us how
many times the loop has executed (or in proper programming terms, how many times the
loop has iterated). As we did not declare it outside of the for loop, it is local to the for loop
and can only be accessed by the code inside the for loop structure.
counter = 1 to 10 has two parts to it. counter = 1 sets the starting value of the counter to 1. It
tells the program what value to start the loop from. We often want loops to start counting
from 1, but they don’t have to. We could start our loop at 0, or -5, or 143, or any other Integer
value. In this case though, we want to start at 1. The second part, to 10, tells the loop the
value at which we want to stop repeating. After the counter gets to 10, we want the program
to move on to the next line of code underneath the Next keyword. Next tells the compiler to
go back to the start of the for loop and check the value of counter against the end value, and
to repeat if the counter is less than or equal to the end value.
If the counter variable is greater than ten, it moves on to the next line of code after the for
loop.
Firstly, we won’t need to declare ten Integer variables to store our results. We can add the
results of each calculation to our label each time around the loop.
What is our algorithm or list of steps for writing this program using a for loop?
Page 64 of 163
The first time around the loop the value of counter is 1. This is not greater than 10, so the loop
runs. The program calculates the value of table (5) * counter (1) and stores the result (5) in
the answer variable. It then adds “five times 1 is 5” to the label.
The second time around the loop the value of counter is 2. This is not greater than 10, so the
loop runs. The program calculates the value of table (5) * counter (2) and stores the result (10)
in the answer variable. It then adds “five times 2 is 10” to the label.
The third time around the loop the value of counter is 3. This is not greater than 10, so the
loop runs. The program calculates the value of table (5) * counter (3) and stores the result (15)
in the answer variable. It then adds “five times 3 is 15” to the label.
This process continues until the counter is 11, at which point the program moves on to the
next line of code after the loop, which is to end the Subroutine.
Create this program and run it. You should get the following output:
Page 65 of 163
The first number (the one we want to raise to a power) is called the base. The power itself is
properly called an exponent, but we’ll just refer to it as a power. You may already be familiar
with how to calculate this by hand, but we’ll briefly go over it anyway to ensure we’re all using
the same technique.
We obtain a power by multiplying the base by itself a number of times - so to get 3 to the
power of 3 we calculate 3 * 3 * 3, which gives us 27. To calculate 2 to the power of 4, it’s 2 *
2 * 2 * 2, which is 16.
Multiplication operators are commutative, which means that a * b is the same as b * a, and a
* b * c is the same regardless of the order in which the terms are multiplied.
2 to the power of 4 = 2 * 2 * 2 * 2
2*2*2*2=4*2*2
4*2*2=8*2
8 * 2 = 16
We maintain a running total of what the current total of our calculation is, and then multiply
that running total by the base for each step of the power. We can translate this into a formal
english description as follows:
This doesn’t quite work when we follow it through. Let’s look at what happens when we
compute two to the power of four:
Repeat 4 times:
Page 66 of 163
This structure will work for calculating any power to any base - and it is based on repetition.
However, although we don’t know when a program is being written what powers people will
want to compute, we can prompt them for that information and then store it in Integer
variables.
When calculating the power by hand, we can work out in our head how many times we’ve
repeated a section of code - Visual Basic on the other hand can’t do that - we need to
explicitly tell it how it can tell how many times it has repeated, and this is done through a
counter variable. We set this to some starting value, and then we say ‘repeat this code
until the counter variable reaches a certain value’. As soon as VB knows what to use for a
counter variable, it will increment it by one every time it repeats the code.
So let’s look at a program that will calculate this value for us. First the interface:
txtBase
txtPower
lblResult
cmdCalculate
Page 67 of 163
The counter variable we are using is called counter. In the for loop, we first set this to a
starting value (1) and then say ‘repeat this code until the value of counter has exceeded the
value of power - 1’.
So let’s go through the code and see step by step what will happen if a user comes along
and enters a base of 4 and a power of 4. When we get to the for loop for the first time:
The result is that we have the value 256 in our total (which is correct) after our loop has iterated
a total of three times:
Page 68 of 163
Notice that the for loop counter variable names have been changed to i and j. We can use
any name we want for the loop counters but due to variable scope we cannot use the same
name for the inner loop counter variable as we use for the outer loop counter. It has become
standard practice to use i and j for the outer and inner loops.
In the example above the code will run in the following sequence:
Step Outer loop counter (i) value Inner loop counter (j) value
1 1 1
2 1 2
3 1 3
4 1 4
5 1 5
Page 69 of 163
Create a new project with a nested for loop as shown above. Add code to the inner for loop
which will print out the value of i followed by the value of j. Compare it with the table above.
Page 70 of 163
The first inner loop controls how many initial blanks are printed for each line. [We need this or
we would get all the asterisks starting at the left hand side and would end up with a right angled
triangle rather than a pyramid.]
The second inner loop controls how many stars are printed on the line.
A new line command is then placed after the second inner for loop to ensure the next time the
outer loop runs the next row of stars is placed on a new line.
The for loop is used to repeat a determinate number of times - we must know how many times
we are going to iterate.
The for loop can be used whenever we need a section of code to be repeated a fixed number
of times. This can either be something known by the programmer (e.g. in the times table
example where we knew we wanted to loop 10 times) or a value entered by the user at run
time (e.g. for the pyramid program where the user chooses the height).
For loops are only one family of such structures – in the next topic we’ll look at selection
structures and how they allow us to select between a range of actions depending on the
Page 71 of 163
Page 72 of 163
Create a new project and design and code a program which asks the user to enter in a phrase,
and also to enter in the number of times they want the phrase repeated. The phrase should
then be displayed via a label, repeated the requested number of times.
Task 2
Create a new project and design and code a program that loops 10 times and outputs to a
label “The counter is now at [counter_value]” (i.e. the first message should read, “The counter
is now at 1”, the second message should read “The counter is now at 2”, and so on.
Task 3
Create a new project and design and code a program which does the countdown from 10 to 0
for a rocket launch. After reaching 0, the program should display “We have lift-off”. [Hint: To
count down rather than up, you will need to research how to use the Step property of for
loops.]
Task 4
Create a new project and design and code a program which prints out all of the even numbers
between 2 and 40 inclusive. [Hint: again, the Step property is useful for this task.]
Task 5
Create a new project and design and code a program which will print out a times table for
which ever times table the user chooses. The code for this will be very similar to the example
we worked through in the lab, except that rather than hard coding if for the five times table,
you need to alter it so that the user can choose which times table they want displayed.
Task 6
Create a new project and design and code a program to draw a rectangle of asterisks. The
user should enter how many rows and how many columns of asterisks they want the
rectangle to have. For example, entering 4 for rows and 30 for columns would result in the
following output:
Page 73 of 163
4.3 Timings
The approximate amount of time that you can expect to spend on each type of activity in this
topic is as follows:
Lectures: 1 hour
Page 75 of 163
Check boxes and Radio buttons are good GUI components to use when demonstrating
selection. This topic will assume you are familiar with their properties and how to group them
using group boxes, so refer back to Topic 1 if you need a refresher on them.
If comparison_check_is_true Then
End If
The “comparison_check_is_true” is a conditional check which returns either true or false. We’ll
have cause to return to this idea in a little while, but for now let’s work through an example of
how we make use of it.
Step 1
Step 2
lblAboutYou
chkAnimals
chkBoard
chkTV
chkBooks
cmdPressMe
chkVB
Step 3
Page 76 of 163
Add in the code above. Run the program and check what happens when the animals box is
ticked, and what happens when it is not ticked.
Notice here in our if statement we are using the same = operator that we normally use to set
the value of something. The difference here is the context: when we are putting one value
into a property or a variable, it is an assignment operation. In an if statement, it is an evaluation
operation - it checks to see if the left hand side of the operator is the same as the right hand
side. This can be quite confusing, but it will become second nature after a while.
We are trying to determine here if the checked property of chkAnimals is set to true. If it is
(and only if it is), we add some text to our aboutYou variable. If it is not set to true (as in, it’s
false) then nothing happens. The code within the if structure is executed only if the condition
evaluates to true.
Step 4
Complete the program by adding in the If statements for the other checkboxes. Put them in
the order they are listed on the form. Run the program and see what happens when you tick
various combinations of the check boxes.
Page 77 of 163
If comparison_check_is_true Then
Else
‘do the code in this part if the comparison check returned false
End If
Let’s look at this using our previous AllAboutYou program. At the moment, if you completed
it as per Step 4 of the previous section, it will print out statements for all the things you have
checked, but it does not print out statements for the things you did not check. We can
change this so that if you do not check something, it adds a line saying that you do not like
that item.
Step 1
Step 2
Page 78 of 163
Page 79 of 163
Step 4
Update the program to add in Else statements for the other four checkboxes.
If comparison_check_is_true Then
‘do this code instead. This will only be checked if the previous if statement check returned
‘false
Else
‘do the code in this part if both comparison checks returned false
End If
We follow a very similar structure for our radio buttons as we did for the check boxes - they
too have a checked property that is either true or false, and we follow our path of execution
dependant on what the value is.
There is a difference though - we must examine all checkboxes because any one of them
may be ticked. With radio buttons within a particular group, we only need to check until we
find one that is selected - we don’t need to check any further because only one in a group
can ever be selected at once. The If – Else _ If structure is perfect for this.
Step 1
Step 2
Set up the GUI so that it has a similar layout and the same controls as shown in the screen
shot below. Remember to set the Checked property to True for one (and only one) radio
button in each radio button group.
Step 3
Page 81 of 163
The structure is hopefully self-explanatory - we follow through each of the conditions until we
find one that evaluates to true. We then stop checking - this is more efficient than checking
every one of them, especially if a group contains a large number of check boxes.
We can extend an if-else-if structure indefinitely - we can have as many Else If lines as are
needed. For example, we can have six for the Continent check:
We can also break it down into a simple ‘this or that’ using if and else. For example because
we have only the two options ‘male’ and ‘female’ for gender, then we could write it as:
Step 4
Add in the code for the remaining two groups of radio buttons: Age and Favourite
Programming Language. Run and test your programs to check they work as expected.
This is an example of what is called a compound conditional - in it we are basing the execution
of the code on a number of different conditionals that are linked together. This can get really,
really complicated really quickly - in this particular case it’s moderately simple. It means if
optCSharp is checked, or optVB is checked, then execute the code. The result is that if either
of them are checked, the same piece of code will be executed.
Logical Operators are operators which allow a program to make a decision based on multiple
conditions. With multiple conditions, it may be that you require all conditions to be true in order
for the if statement check as a whole to return true. Or it may be that you only require one of
the checks to return true in order for the if statement check as a whole to return true. There
are various logical operators, but the only two we need to concern ourselves with just now are
Or and And.
Logical operators have Truth Tables associated with them. A truth table is a breakdown of a
logic function which lists the output conditions for each possible set of inputs. We will look at
the truth tables for And and Or based on two inputs (conditions):
OR
Condition A Condition B Result
False False False
False True True
True True True
True True True
AND
Condition A Condition B Result
False False False
False True False
True True False
True True True
We can see from the above truth tables that if we use an Or logical operator to join our
conditions, only one condition needs to return true in order for the if statement condition as a
Page 83 of 163
For example, if we reopen the AllAboutYou project we could add the following compound
conditional statement to check whether the person ticked all the boxes and therefore likes
everything:
In order to do this, we need to make use of comparison operators. There are six of these
symbols that are used for the comparison of primitive data types (especially numerical data
types):
These comparison operators do exactly what they say they do – they compare one value
against another. In such comparisons, the term on the left hand side is known as the left hand
value, and the term on the right hand side is the right hand value.
Given the above information, we want to create a program which will take in the number of
students in the class, and then indicate which room the class should be scheduled for.
Page 84 of 163
Create a new project called ClassAllocation and set up the GUI so that it is similar to the
screen shot below:
txtNumStudents
lblRoom
cmdFindClassroom
Step 2
Double click on the Find Classroom button and add in the following code to check which
room should be allocated:
This code makes use of several of the comparison operators we saw in the table, and also
makes use of compound conditional statements.
Page 85 of 163
The next elseif comparison is a compound conditional. The first comparison check is to check
whether the number of students is greater than 12 and the second check is to identify whether
the number of students is less than or equal to 15. This will only return true if the number of
students meets both of these conditions, i.e. it must be greater than 12 and also less than or
equal to 15. So only groups with 13, 14 or 15 students will return true for this elseif statement.
The third check is an equivalence check. Does the number of students equal 16? This will only
return true if there are exactly 16 students in the class.
The fourth selection statement in the chain is another compound conditional. The first part
identifies whether the number of students is greater than 16, and the second part identifies
whether the number of students is less than or equal to 20. This will only return true if the
number of students meets both of these conditions, i.e. it must be greater than 16 and also
less than or equal to 20. So only groups with between 17 and 20 students will return true for
this elseif statement.
The fifth selection statement in the chain is another compound conditional. The first part
identifies whether the number of students is greater than 20, and the second part identifies
whether the number of students is less than or equal to 25. This will only return true if the
number of students meets both of these conditions, i.e. it must be greater than 20 and also
less than or equal to 25. So only groups with between 21 and 25 students will return true for
this elseif statement.
The final else statement will be executed only if all the above statements proved false. In this
case, the number must be greater than 25, and therefore there are no suitable classrooms.
Instead, we must use the equivalence methods provided by the String data type to do our
comparisons.
The first of these methods is Equals(), and takes a single String parameter which is the String
to check against:
If aString.Equals(“This”)
Or
If aStringVariableName.Equals(anotherString)
Step 1
Page 86 of 163
txtName
txtPassword
lblResult
cmdLogin
Step 2
Double click the Log In button and add the following code:
In this program, we want to check the username and password entered by the user against
the correct username and password. If they are correct, we will let them know. If one or both
are wrong, we will also let them know.
Page 87 of 163
Step 3
Run and test the program. Check it for correct and incorrect user names. Also test the user
name with all capitals, all lower case, and the case actually used in the variable (first letter
capitalised and the rest in lower case).
From the testing you have carried out in step 3, you have probably found that “pauline”,
“PAULINE” and various other combinations of the word with different capitalisations e.g.
“PauLinE” return false despite containing the correct letters in the correct order. This is
because an upper case A is not the same as a lower case a, and so on for all letters. Different
unicode values are used to represent them.
For passwords we usually insist on case sensitivity. In this case the .Equals() method is
suitable to use.
However, if you want to allow for someone to enter the correct word and ignore the case used,
then there are different methods we can use to achieve this.
If we convert the value entered by the user to upper case, and compare it against the upper
case version of the word, they will be able to enter in the user name in any case they like and
as long as they get the correct letters in the correct order, it will be accepted as equivalent to
the user name.
To do this, we need to change the code so that the correctName is set to “PAULINE”, and add
a line to convert the userName to userName.ToUpper()
Step 4
Update the code from Step 3 as explained above. It should now resemble the code below:
Page 88 of 163
Similar to ToUpper, Strings have a ToLower method which converts a String all into lower
case. We can use this in the same manner as ToUpper. Rather than storing the correct
username in capitals, we store it all in lower case letters. Then we convert the value entered
by the user into lower case before the if statement check.
userName = userName.ToLower()
Step 5
Change your program from Step 4 so that it converts the user’s name to lower case and
compares it against the correctName variable which should also be stored all in lower case
letters.
Step 6
Add in the code to check the password. Remember that passwords should be case sensitive.
Your program should tell the user whether the username was correct, and should also tell the
user whether or not the password was correct. Run and test the program.
You can see from the example that the comparison must be against a variable. In this case,
we are comparing against an Integer variable. With Integers, we can check against a single
value (e.g. Case 4), a range of values (e.g. Case 1 to 3) or a list of values (e.g. Case 8, 9,
10).
If statements allow us to only execute a section of code if a particular condition applies. If Else
statements allow us to say what to do if the condition applies, and what to do if the condition
does not apply. If – ElseIf statements allow us to chain two or more if statements together,
optionally with a default Else statement at the end.
Logical operators and and or enable us to use compound conditional statements. Truth tables
can be used to work out the output from combining multiple conditions using and or or logical
operators.
Select Case statements are a slightly different type of selection structure which can offer a
slightly more compact representation compared to a large chain of If-ElseIf statements, but
has the same impact on the flow of execution through a program.
Combined with repetition statements, selection structures allow you enormous flexibility as to
how your program executes. Togeger they represent the first real plateau in your programming
skills: you can now write a whole range of applications that may have seemed impossible only
a few weeks ago.
Page 90 of 163
Create a new project and design and code a program which takes in the mark achieved by a
student, between 0 and 100, in an exam. The program should display a message telling the
user what grade the student has achieved. The grade boundaries are as follows:
A = 70+
B = 60 – 69
C = 50 – 59
D = 40 – 49
F = 0 – 39
Task 2
Extend the program above so that a message is also displayed to the user. The messages
are as follows:
A: “Congratulations! An excellent result.”
B: “Very well done. A very good result.”
C: “Well done. A satisfactory result.”
D: “Not too bad. You need to do a bit more work to improve.”
F: “Unfortunately you will need to re-sit.”
Task 3
Create a new project and design and code a program which prompts the user to enter in a
number between 1 and 6 to win a prize. The prizes are as follows:
1. A sheet of paper
2. A car
3. A pair of slippers
5. A 52” LCD TV
6. An umbrella
Task 4
Create a new project and design and code a program which will tell the user whether the
number they have entered is a multiple of 3 or not. The program should prompt the user to
enter in a whole number and store it in a variable. The program must then check whether the
number is a multiple of 3. If the number is perfectly divisible by 3 then display a message
saying that the number is a multiple of 3. If it is not, then display a message telling the user
that the number is not a multiple of 3. [Hint: Remember the mod arithmetic operator. This can
be used in a comparison check to identify whether a number is a multiple of 3 or not (or any
other number).]
Page 91 of 163
‘Shonky Computers Inc’ would like you to develop an application that allows interested users
to design their ideal computer system. Users should be able to choose from a range of
processors, peripherals and bundled software.
You should give each of the components a price of their own - it doesn’t matter if it’s realistic.
Upon designing their dream computer, the user should be able to press a button that
summarises their choice, and provides the total they have to pay.
CPU (One of) – Intel Pentium G4400, Intel i3 6100, Intel Core i5 4430, Intel Core i7
4790, AMD A4 6300, AMD A6 7400K, AMD FX 8350
Memory (One of) – 2GB DDR3 1333MHz, 4GB DDR3 2000MHz, 4GB DDR4
3000MHz, 8GB DDR4 3400MHz
Software (One of) – None, Microsoft Windows 10, Microsoft Windows 8.1, Microsoft
Windows 7, Ubuntu 16.04.1 LTS
Graphics (One of) – Sapphire HD 6450, Gigabyte Radeon RX 460, NVIDIA Quadro
K620
Monitor (One of) – 17” 1080HP, 19” 1080HP, 23” Full HD, 24” Full HD, 27” Full HD
Peripherals (Any number of) – Portable External HDD 1TB, DVD Drive, Inkjet
printer, scanner, card reader
Exactly which controls you use to design your user interface is up to you.
Task 6
Rewrite the program from Task 2 using a Select Case statement rather than a series of If –
ElseIf statements.
Page 92 of 163
5.3 Timings
The approximate amount of time that you can expect to spend on each type of activity in this
topic is as follows:
Lectures: 1 hour
Page 93 of 163
While loops are often used for data validation purposes. We will therefore look at this concept
in this topic.
While loops do not have a counter - instead they have a continuation condition which is
evaluated every time around the loop. If we want to maintain a count of iterations, we must
keep our own counter that is incremented every time around the loop.
While (some_condition)
code_goes_in_here
End While
Let’s take a fairly abstract example to see this in action - a pair of numbers which are increased
by different values each time around the loop. We’ll loop until the second number is no longer
bigger than the first number - in that way, we’ll see what value they have when they intersect.
Page 94 of 163
txtNum1
txtNum1Mod
txtNum2
txtNum2Mod
lblDisplay
cmdGo
Step 2
Write the code to increase each number by it’s modifier until number 1 is no longer larger than
number 2.
We make use of a comparison operator here called the greater than operator, which is the >
symbol - we want the while loop to continue while number one is greater than number two.
There is a corresponding less than operator that is the < symbol:
Page 95 of 163
Entering the values 100 (incremented by 10) and 20 (incremented by 12) tells us that the
numbers will be 500 when they intersect:
Step 4
Page 96 of 163
A while loop does not have any counter variable - if we want to know when they will intersect,
we need to modify the code slightly to provide our own counter:
This gives us an indication of how long it takes for the two to intersect:
Page 97 of 163
What happens if it is never evaluated to false? Let’s look and see. We’re going to use
another comparison operator, which is does not equal. It looks like a greater than and less
than operator back to back: <>
Step 1
Create a suitable interface for this test program. All it needs is a button and a label.
Step 2
In this instance, we are going to loop while x is not equal to 10. Whilst it is not equal to 10,
we will add 4 to the value of x.
The loop here will continue as long as x does not equal ten. Due to the way the code works,
x will never equal ten - it will be 1, then 5, then 9, and then 13, and then increasingly large
values. The while loop will never terminate naturally.
Step 3
Page 98 of 163
In this circumstance, Visual Basic will continue on for a few seconds before it panics and
throws what is known as an exception:
An exception indicates an exceptional circumstance in the running of the program that Visual
Basic was unable to compensate for. In this case it’s because the number being stored in X
became so big that VB couldn’t deal with it.
Step 4
Change the code inside the while loop so that while x is not equal to x, the value of x is set to
x:
Page 99 of 163
This number never gets too big for VB, because it never increases. In this situation, the button
can be pressed, the loop will begin... and then nothing. The application will stop responding.
Step 6
Open up your task manager by pressing and holding down Ctrl + Alt + Del then choosing Task
Manager from the options list. (This may take some time depending on how long the program
has been running and how powerful your pc is.)
You will see that your short VB program is using up significant amounts of your CPU power
and a very large percentage of your computer’s memory. It may not exactly resemble the
screen shot below as it depends on your system and what other processes and applications
you have running:
You can end the program by selecting it in Task Manager and pressing End Task.
Alternatively, you can end the program by pressing the red Stop button in Visual Studio.
Data Validation
Let’s look at an example of a while loop with a compound condition. This example is going to
look at how to ensure the user enters a valid value into the program. This process of
ensuring the data is valid is known as data validation. It is, more specifically, a subset of
data validation known as input validation. Input validation is very important in programming
to ensure that the values entered by the user are valid. For example, for the first private
study task in Topic 4, the valid range of exam marks was between 0 and 100. Input
validation could be used there to ensure the program does not allow the user to enter values
below 0 or over 100, as these are not possible results from the exam.
Step 1
Create a new project called RangeCheck and set up the user interface as shown:
lblOutput
cmdEnter
Step 2
Note that this code introduces us to a new control: the InputBox. This is a pop up message
box which cannot be ignored. This is not good Event-Driven programming practice, as we
should let the user dictate the flow of execution based on how they interact with the controls.
However, if they continually get user input incorrect, it can be useful to use the InputBox to
keep reminding them of the correct range of values until they enter a suitable value.
Step 3
Run the program and see what happens when you type in another invalid number. If you
again enter a number that is lower than 10 (e.g. 8) or greater than 50 (e.g. 786), a new
InputBox will appear asking you the same question.
Step 4
Enter a valid number (e.g. 48). This should stop the InputBox appearing again, right?
The InputBox method returns the value entered, but we need to store it in a variable in
order to make use of it. In this case, we need to store the output in num.
Step 5
Run and re-test your updated program. Now when you enter a value between 10 and 50 into
the InputBox, no more input boxes appear. However, the original textbox still contains the
original (incorrect) value entered into the textbox, and the label is not displaying anything.
We can fix these things by adding in code after the while loop to clear the contents of the
textbox, and to display the number entered on the label.
Step 6
Step 7
Page 103 of 163
Do
some_code
The sole difference between while and do-while loops is the fact that the former may never
iterate if the condition is unmet, and the latter will always iterate at least once regardless of
the condition.
Let’s look at an example of a do-while loop in practice. For our example, we’re going to use
an InputBox to get a password from the user before we will store their data.
Step 1
Step 2
Step 3
While loops allow us to only execute a section of code whilst a particular condition applies. If
the condition never applies (e.g. the while loop condition is to loop while X is greater than 10,
but the starting value of X is 2) then the while loop never executes. While loops are also in
danger of looping forever (infinite loops) if the condition is always met. This is most likely to
happen if you forget to ensure that somewhere inside the while loop structure you update the
value of one or more of the variables on which the condition is based. For example, in our
example of looping whilst X is greater than 10, we should have code inside the while loop that
reduces the value of X so that it will fall below 10 after a certain number of loops.
Logical operators and and or enable us to use compound conditional statements in our while
loops.
While loops are useful for data validation, specifically input validation, to ensure that the data
entered into the program falls within the range of values we expect.
Do – While Loops function in largely the same way as While loops. The difference is that the
condition is checked at the end of the loop, not the beginning. This means that a Do-While
loop will execute at least once. This can be useful for data validation, and in certain other
circumstances.
Combined with bounded repetition (for loops), and selection structures (if statements),
conditional loops allow you enormous flexibility as to how your program executes. You are
now equipped to solve about 80% of programming problems, though not in the most efficient
manner.
Create a new project and design and code a program which asks the user to enter the number
50, and which will keep asking them to do so until they enter 50. Once they have entered 50,
display the message “Goodbye” on a label.
Task 2
Extend the program above so that it uses a counter to track how many tries it takes before
the user correctly enters 50. When they enter 50, display a message telling them how many
tries it took for them to enter the value 50.
Task 3
Create a new project and design and code a program which asks the user to guess the number
between 1 and 6. You should either hard-code the number to be guessed (e.g. 3, or 4, or any
value between 1 and 6) or you can investigate how to generate a random number between 1
and 6.
Task 4
Extend the program above so that it displays a different message depending on how many
tries it took for the user to guess the correct value:
4 – 6 tries: “That took a more tries than average. Better luck next time.”
7+ tries: “You must have guessed the same incorrect number more than once to need this
many tries!”
Task 5
Create a new project and design and code a quiz program which asks the user a geography
question with a one word answer (e.g. “What is the capital of France?”). The program should
use a Do While Loop and InputBox to prompt the user for an answer until they get the correct
answer. When they have answered correctly, display a message telling them it is correct, and
how many tries it took for them to get the correct answer.
Task 6
Create a new project and design and code a program which has three integer variables, x, y
and z. Set x to 5, y to 1 and z to 10 When the user presses the Go button, the program
should loop whilst x is greater than y and x is less than z. Inside the loop, 2 should be added
to the value of x. Once the loop has completed, display the current value of x via a label.
Task 7
Page 107 of 163
6.3 Timings
The approximate amount of time that you can expect to spend on each type of activity in this
topic is as follows:
Lectures: 1 hour
• Project Specification
• Design
• Implementation
• Testing
The output of this stage is a specification document which lists the features the program must
have.
‘Shonky Computers Inc’ would like you to develop an application that allows interested users
to design their ideal computer system. Users should be able to choose from a range of
processors, peripherals and bundled software.
Upon designing their dream computer, the user should be able to press a button that
summarises their choice.
CPU (One of) – Intel Pentium G4400, Intel i3 6100, Intel Core i5 4430, Intel Core i7
4790, AMD A4 6300, AMD A6 7400K, AMD FX 8350
Page 110 of 163
Software (One of) – None, Microsoft Windows 10, Microsoft Windows 8.1, Microsoft
Windows 7, Ubuntu 16.04.1 LTS
Graphics (One of) – Sapphire HD 6450, Gigabyte Radeon RX 460, NVIDIA Quadro
K620
Monitor (One of) – 17” 1080HP, 19” 1080HP, 23” Full HD, 24” Full HD, 27” Full HD
Peripherals (Any number of) – Portable External HDD 1TB, DVD Drive, Inkjet
printer, scanner, card reader
Exactly which controls you use to design your user interface is up to you.
Based on this project brief, what must the program include? The list of requirements is known
as the Specification.
1. The program must allow the user to choose one, and only one, option from the
following list of CPU chips: Intel Pentium G4400, Intel i3 6100, Intel Core i5 4430, Intel
Core i7 4790, AMD A4 6300, AMD A6 7400K, AMD FX 8350
2. The program must allow the user to choose one, and only one, option from the
following list of RAM types: 2GB DDR3 1333MHz, 4GB DDR3 2000MHz, 4GB DDR4
3000MHz, 8GB DDR4 3400MHz
3. The program must allow the user to choose one, and only one, option from the
following list of hard disk drives: 1TB, 2TB, 4TB, 6TB, 8TB
4. The program must allow the user to choose one, and only one, option from the
following list of operating systems: None, Microsoft Windows 10, Microsoft Windows
8.1, Microsoft Windows 7, Ubuntu 16.04.1 LTS
5. The program must allow the user to choose one, and only one, option from the
following list of graphics cards: Sapphire HD 6450, Gigabyte Radeon RX 460, NVIDIA
Quadro K620
6. The program must allow the user to choose one, and only one, option from the
following list of monitor types: 17” 1080HP, 19” 1080HP, 23” Full HD, 24” Full HD, 27”
Full HD
7. The program must allow the user to choose any number of the following peripherals:
Portable External HDD 1TB, DVD Drive, Inkjet printer, scanner, card reader
8. The program must display the component lists for the user to select from.
10. The program must calculate the cost of the computer system by adding the prices of
each of the components selected.
Page 111 of 163
12. The program must display the total price to be paid by the user.
6.4.3 Design
At the specification stage we are interested in what the program should do. At the design
stage, we are interested in how the specification can be implemented.
There are two different types of design involved in creating a graphical Visual Basic program.
One is creating the physical design – what the program’s graphical user interface (GUI) will
look like. The second is creating the logical design – how the program will be structured.
For all components where the user must choose one, and only one, option, suitable
components for this would include ComboBoxes or RadioButton Groups. As there are five
long lists to choose from, ComboBoxes are the better choice in terms of taking up less space
on the form and being visually less busy and confusing. It would also be useful to have a label
above each ComboBox to indicate what it is for. As we won’t be updating these when the
program is running, we can get away with leaving the names as the default values e.g. Label1,
Label2, etc.
For the peripherals, the user should be able to choose any, some or all of these. For this option
it would be best to use CheckBoxes. A GroupBox is not essential but is good design and will
make it clear that the check boxes belong to one group, not multiple groups. As this won’t be
changed when the program is running, we can leave it with the default name i.e. GroupBox1.
We need to let the user enter their selection. A Button would be the best option for this.
We need to display a list of the components ordered. A Label is the best option for this.
We need to display the total cost of the order. Again, a Label is the best option for this. We
can use the same label as for the list of components.
We can summarise our design using an Object Definition Sheet. An example Object
Definition Sheet for the ‘Shonky Computers’ project is shown below:
The Object Definition Sheet lets us specify what controls we need and what properties we
need to set for them. It also shows us what procedure(s) we need. However, it doesn’t show
what the procedures should do. For that task, we can use pseudocode.
Pseudocode is a list of instructions, like a recipe. When the button is pressed the program
needs to check each Combo Box to find out what is selected, add the component name to the
summary list, and add the price of the component to the total price for the order. It then needs
to check all the Check Boxes to see which of them have been selected and add the selected
ones to the summary list and the prices to the order total.
End If
…This would be done for the other five Combo Boxes too
To check the peripherals, we would need to use separate if statements as they are not
mutually exclusive.
End If
End If
Page 115 of 163
End If
End If
End If
To update the label output to show order summary and total cost
An example design is shown below. You can use pen and paper, or any graphics application.
You can also try designing the form in Visual Studio, not adding any code until you are happy
with the layout.
If your design is detailed enough and complete (i.e. it includes all the requirements in the
Specification) then the implementation stage should be straightforward.
Firstly, create the Form using the physical design diagram you created. If you used Visual
Studio to create this, you will already have added the controls to the form.
Secondly, update the names, text, and other properties of each control to the settings listed
in the Object Definition Sheet.
Thirdly, add in the code for the procedure(s) using the pseudo code. This will require a little
bit of modification to turn it into VB code, but the steps should be clear from the pseudo
code.
6.4.5 Testing
Testing is the process of checking that your program functions as expected. Unless a program
is very simple, it is not possible to exhaustively test a program with all possible options. We
therefore draw up test cases which cover three different types of tests:
• Exceptional data (invalid data outwith normal bounds, wrong data type, etc)
As the program we have designed above is solely based on ComboBoxes and CheckBoxes,
it minimises the chances of the user entering invalid data. This is good practice in
programming: limit the opportunities for the user to put in incorrect data.
We could check what happens if a certain CPU is selected, what happens if one of the
ComboBox choices has been left blank when the user presses the Submit button, and so on
for the other selection choices. The only invalid data in this case is when options have been
left blank.
TEST PLAN
AMD A6 7400 is
added to the
order summary
list
4GB DDR4
3000MHz is
added to the
order summary
list
1TB is added to
the order
summary list
None is added to
the order
summary list
NVIDIA Quadro
K620 is added to
the order
summary list
24 inch Full HD
is added to the
order summary
list
8 cboGraphics.SelectedItem Message
= null displayed saying
“You must
choose a graphics
card.”
Portable External
HDD 1TB is
added to the
order summary
list
Order summary
list is unchanged
Tests 1 to 6 and 9 – 10 test normal data: these are inputs we would expect.
Tests 7 and 8 test exceptional data. Our programs should be designed to cope with situations
like this, so the expected output is that a message will tell the user to choose an item from the
combo box.
We don’t know what the program will do until we run it and test it using each test case in turn.
When we do that, we can fill in the remaining two columns of the table, and out Test Plan
becomes a completed Test Log:
Under normal conditions, the program functions as expected. However, when nothing is
chosen for the Graphics Card or the Operating System, the program does nothing: it just lets
the user order without selecting those core components.
At this stage, we go back to the code and realise we didn’t include an Else statement to cover
nothing being selected. We therefore update the code to add a final Else statement for the OS
Combo Box which will display a message saying “You must choose an Operating System”,
and do the same for all the Combo Boxes. An example of the adjusted code for the Operating
System combo box is shown below:
Project Brief
Lucky Prizes Inc. would like you to create a program which prompts the user to enter in a
number between 1 and 6 to win a prize. The prizes are as follows:
1: No prize.
2: No prize
Page 122 of 163
4: A pencil
5: A pair of shoelaces
The user should be asked to type in the number. Once they have entered the number a
message should be displayed telling them what they have won. If they entered a value that
was not one of the six listed, a message should be displayed telling that they need to enter a
value between 1 and 6.
• Project Specifications
• Program Design
o Layout Diagrams
o Pseudo code
• Implementation
• Testing
o Test plans
o Test logs
Project Brief
Create a new project and design and code a program which takes in the mark achieved by a
student, between 0 and 50, in a coursework assignment. The mark should be typed in by the
user. Once the user has entered the mark, the program should display a message telling the
user what grade the student has achieved. The grade boundaries are as follows:
A = 35+
B = 30 – 34
C = 25 – 29
D = 20 – 24
F = 0 – 19
In addition to displaying the grade achieved, a feedback message should also be displayed.
The messages are as follows:
A: “Congratulations! An excellent result.”
B: “Very well done. A very good result.”
C: “Well done. A satisfactory result.”
D: “Not too bad. You need to do a bit more work to improve.”
F: “Unfortunately you will need to re-sit.”
7.3 Timings
The approximate amount of time that you can expect to spend on each type of activity in this
topic is as follows:
All customers must choose which type of nutrition plan they wish to follow, from the following
list:
All customers must choose the number of adults to be fed on the plan, from the following
options:
• 1
• 2
• 3
• 4
All customers must choose the number of children to be fed on the plan, from the following
options:
• 1
• 2
• 4
The plan cannot be sold only for children. The program must therefore check that at least one
adult is selected. In addition, children can only be added to the regular, gluten free or
vegetarian healthy eating plans. Children cannot be included on a weightlifter or endurance
training eating plan. If such a selection is made, the customer must be told to change their
options.
Once the choices have been completed, the monthly costs should be calculated, and a
summary list of the chosen items and the monthly subscription cost should be displayed
The customer should then be asked to enter their address details (house number, street name,
town, postcode) and their credit card number. Credit card numbers are 16 digits long and
should be entered with no spaces between numbers.
Once the address and card details have been accepted, a confirmation message should be
displayed, detailing plan chosen, the number of adults and children it covers, and the monthly
charge.
• Regular healthy eating plan: £50 pcm for each adult, , £35 pcm for each child
• Gluten free healthy eating plan: £55 pcm for each adult, £40 pcm for each child
• Gluten free weightlifter eating plan: £85 pcm for each adult
• Gluten free endurance trainer eating plan: £75 pcm for each adult
• Vegetarian healthy eating plan: £50 pcm for each adult, £35 pcm for each child
• Vegetarian endurance trainer eating plan: £70 pcm for each adult
Task List
Given the above project brief, your job is to plan, design, implement and test a program which
meets the conditions given in the project brief.
An Object Definition Sheet Template and a Test Plan Template are provided below
10
11
12
13
14
15
16
8.3 Timings
The approximate amount of time that you can expect to spend on each type of activity in this
topic is as follows:
Lectures: 1 hour
Arrays are conceptually linked lists of data – instead of having multiple pieces of data, we have
a single container that contains a number of different compartments. We slot each data
element into one of these compartments. Arrays have a single data type – they can hold lots
of pieces of data, but each piece of data must be of the same type.
The benefit of arrays comes from when we’re dealing with lots of otherwise unconnected
variables that refer to the same thing. Let’s say we had ten integer variables, each keeping
track of someone’s age. Or twenty strings, each representing the name of a book. We might
want to find the largest age in our program, or see if a book with a particular name is present.
That’s very difficult to do with lots of individual variables, but much easier to do with an array.
To store five ages, we’d need five integer variables. We’d need to check each against the
others to see which was the largest. That might be okay for five, but what about ten? Or fifty?
Or a thousand?
Index Element
0 15
1 90
2 28
4 19
5 20
Sometimes we’ll want to refer to the whole collection – we’ll see some examples of that in the
future. More usually, we want to refer to individual elements.
Ages is the name of the array, and it has six compartments, each of which can hold an integer.
Why six? That’s because in Visual Basic we put the highest index value of the array between
the brackets when we create it. This is called its Upper Bound. We make use of the
assignment operator to put numbers into the array in particular compartments.
ages(0) = 15
This will put the value 16 into compartment zero. We can keep pacing through the array, fitting
data into each compartment as necessary:
ages(0) = 15
ages(1) = 90
ages(2) = 28
ages(3) = 11
ages(4) = 19
ages(5) = 20
This might not seem like much of an improvement over individual variables, but we’ll get to
that. The real power of arrays comes with how easily they work with the programming
structures we’ve been learning about. It’s important to note that we’re looking at them with
integers here, but they can be used for any data type we’ve already seen. An Array can be
used for strings, numbers, buttons, checkboxes – anything!
lblNum lblAverage
Step 2
For our first effort here, we’re going to try to create this program using individual variables.
When we add an age, we’ll look for the next variable that we have empty, and put it in there.
Then we’ll calculate the number, and the average:
current = txtAge.Text
If age1 = 0 Then
age1 = current
num = 1
ave = age1
ElseIf age2 = 0 Then
age2 = current
num = 2
ave = (age1 + age2) / num
ElseIf age3 = 0 Then
age3 = current
num = 3
ave = (age1 + age2 + age3) / num
ElseIf age4 = 0 Then
age4 = current
num = 4
ave = (age1 + age2 + age3 + age4) / num
ElseIf age5 = 0 Then
age5 = current
num = 5
ave = (age1 + age2 + age3 + age4 + age5) / num
End If
Page 134 of 163
End Sub
End Class
It’s not bad, but let’s say you now want to do five hundred ages.
Step 3
Let’s look at how we’d do it with arrays. First we’ll need a counter that keeps track of how
many ages we’ve added, and we use that to put the age into the next empty compartment of
the array:
current = txtAge.Text
ages(counter) = current
counter = counter + 1
End Sub
End Class
This only does part of the program though – the second part is calculating the average. For
that, we’ll use a for loop – step over each compartment, adding it to a running total, and then
dividing that total by our counter:
ave = 0
For i = 0 To counter
ave = ave + ages(i)
Next
current = txtAge.Text
ages(counter) = current
For i = 0 To counter
ave = ave + ages(i)
Next
End Sub
End Class
Step 4
Okay, that program is a little more complicated, but here’s the clever part – what happens if
you want this program to handle five hundred ages? You just change this:
Into this:
Step 1
We need to modify our interface to add in labels for the largest and smallest. We’ll call these
lblLargest and lbSmallest:
Step 2
currentLargest = ages(0)
For i = 0 To counter
If ages(i) > currentLargest Then
currentLargest = ages(i)
End If
Next
No matter how many ages we have in the program, it’ll always tell us what the largest one is.
Step 3
What about the smallest number? This does not work in exactly the same way:
currentSmallest = ages(0)
For i = 0 To counter
If ages(i) < currentSmallest Then
currentSmallest = ages(i)
End If
Next
When we run this, we find that the smallest number is always zero. That’s because all of our
elements in the array are zero unless we put something in to them, and when we added an
element we increased the counter by one. Our code searching for the largest and smallest
is always checking one empty element, which isn’t quite what we want.
Step 4
Let’s look at how to fix our final issue by examining what’s causing it. We begin with a
counter of 0, and an array of six elements. It looks like this:
Index Element
0 0
1 0
2 0
3 0
4 0
Index Element
0 15
1 0
2 0
3 0
4 0
5 0
At this point our counter becomes one, because that’s the next index into which we’re going
to put a number. But now let’s look at what happens with our loop.
It begins with 0, and goes to counter. In a for loop in Visual Basic, the bounds are
inclusive. To counter includes the counter. For 0 to 1 gives us zero and one even though
we only have one compartment filled in our array.
For i = 0 To counter - 1
If ages(i) < currentSmallest Then
currentSmallest = ages(i)
End If
Next
current = txtAge.Text
ages(6) = 10
ages(counter) = current
counter = counter + 1
ave = 0
For i = 0 To counter - 1
ave = ave + ages(i)
Page 138 of 163
currentLargest = ages(0)
For i = 0 To counter - 1
If ages(i) > currentLargest Then
currentLargest = ages(i)
End If
Next
currentSmallest = ages(0)
For i = 0 To counter - 1
If ages(i) < currentSmallest Then
currentSmallest = ages(i)
End If
Next
End Sub
End Class
Array.Sort (ages)
That means Visual Basic will do it for us. That’s very useful for certain kinds of programming
tasks, such as finding the median value in a list.
Arrays are made up of indices, which allow us to access individual compartments, and data
within those compartments. We call those elements. When we want data out of an array, we
use its variable name and the index of the element we wish to access. Other than that, we
can use the same operators we’ve been using throughout the course.
The true effectiveness of arrays is unlocked in conjunction with loops – these let us step over
each of the elements in turn and perform a comparison or assignment. By making clever
use of loops you can step over each element, or every other element, or more interesting
patterns. You can double the values. You can refer to the next and previous elements. The
Page 139 of 163
Making use of the age adding program from this chapter, add new functionality that will find
the median age in the list. For this you will need to sort the array and find the mid-point. If
there is no clear mid-point, you must take the two vales to either side of the mid-point and
average them. You’ll only be able to do this properly when the array is fully filled, so include
a check for that. Output this along with the other values in the application.
Task 2
Modify the ages program so that it asks for a name as well as an age, and stores the name
in a second array of strings. When showing the largest and smallest ages, it should also
display the name of the associated person.
Task 3
The current age program will crash if you try to add more ages than the array will support.
Add a check in the add method that will make sure you can’t put more elements into the array
than it’s been set up to handle.
Task 4
Add new functionality to the age program so that it calculates the sum of the ages and outputs
that as a new value.
Task 5
Add a new button and textbox to the age program. When the user presses this button, it will
search through the array for the numerical value entered in the textbox. If it is present, the
application should say ‘found’.
Task 6
Modify the program in task five so that it also shows how many times the age is to be found
in the array.
• Generalisation
• The concept of a subroutine
• The concept of a function.
• Implementation of subroutines and functions in Visual Basic.
9.3 Timings
The approximate amount of time that you can expect to spend on each type of activity in this
topic is as follows:
Lectures: 1 hour
It was rapidly realised that this was not a solution that would scale up to difficult programming
tasks, and the concept of modular programs become popular. In modular programs,
individual ‘packages’ of functionalty are implemented. Each takes in information that defines
its context, and many provide information back that show the product of the functionality.
txtNum1
txtNum2
lblOutput
cmdCalculate
The intention of this program is to allow the user to enter two numbers, and find out if the sum
is odd or even. You may remember we had to do that in the previous chapter:
End Sub
Let’s say that we also want it to give us the odd and even status of each of the numbers that
went into the sum.
End Sub
This is ok, but we will have problems if we want to expand the program much further. Let’s
imagine that we’re busy writing this program and someone comes and tells us ‘I want to know
if they are odd and even, and if they are odd I want to know if they are divisible by three with
no remainder’.
Suddenly a task that was pretty easy becomes one of serious re-engineering. Then let’s
imagine the client makes more requests. Every single adjustment needs us to go back and
change three parts of the program to do what we want.
9.4.2 Subroutines
Subroutines are self-contained parcels of functionality that are executed only when triggered
externally. When we double click on a button in the Visual Studio IDE to enter the code
window, it creates a code stub for a subroutine - all the code we want associated with that
button goes into that code stub. This by now should be a familiar process.
End Sub
There is absolutely nothing to stop us creating our own subroutines within a Visual Basic
program - the only thing we have to remember is that we can only send information into a
subroutine. We cannot pull information out except by making use of some bad programming
techniques. Let’s say for example that we want to write a subroutine that displays a simple
message box - we just add the following code to our project:
End Sub
We can then make use of this function anywhere in our program by calling it, making use of
its name and a parameter that we provide:
ShowMessage("This is a test!")
It’s really that simple, but it becomes useful when we have a task that needs us to do a number
of things together, and then when that thing needs to be done several times in the same
program. We’ve got exactly such a scenario as in our example above. We can write a
subroutine that does all the work for us, and suddenly everything becomes less awkward to
do:
Else
str = startText & " is odd"
End If
End Sub
When we want to trigger this, then our calculate subroutines becomes much simpler because
we only have the key code elements once:
End Sub
As a general rule, if we repeat code we probably want to look at alternative options – either
loops or functions, depending on how often we’ll be doing it and how varied the situations are
under which it’ll be done.
Functions are identified by name, as with variables and subroutines. They also have a return
type and a list of parameters. Let’s look at a simple example of a function that takes a
number and gives us back ‘true’ if it’s even and ‘false’ if it isn’t:
End Function
Functions communicate with other pieces of VB code by means of the parameters and return
types of the function. The parameters are variables that are passed into the function –
Functions may only return one type of data, but they can take any number of parameters.
As with subroutines we can make use of a function by calling it by name within the body of
another piece of code. The only difference is that we need to ‘catch’ whatever data may
come out of it:
numState = checkIsEven(num)
We assign the return value of the function to a variable of the appropriate type (in this case, a
boolean). We use the return keyword within the code of our function to indicate when we
want to send some information out of it – as soon as we do this, the function stops executing
and control returns to the code that just called the function. Any code that exists after the
return statement has been executed will be unreachable and never executed.
Functions do not need to have a return type or any parameters. For a function that does not
return a value, we simply leave off as a return type. If we have no parameters, we leave the
function brackets empty.
We can make use of our new function to simplify our code a little more:
End Function
numState = checkIsEven(num)
Else
str = startText & " is odd"
If num Mod 3 = 0 Then
str = str & " and cleanly divisible by three"
Else
str = str & " and not cleanly divisible by three"
End If
End If
And then we can add new functions to generalise it even further still:
Return str
End Function
Else
str = addTextToString(str, " is odd")
If num Mod 3 = 0 Then
str = addTextToString(str, " and cleanly divisible by three")
Else
str = addTextToString(str, " and not cleanly divisible by four")
End If
End If
lblOutput.Text = str
End Sub
End Function
Else
str = addTextToString(str, " is odd")
If checkIsCleanlyDivisible(num, 3) Then
str = addTextToString(str, " and cleanly divisible by three")
Else
str = addTextToString(str, " and not cleanly divisible by four")
End If
End If
lblOutput.Text = str
End Sub
This doesn’t just make the code more readable, it makes it more amenable to change. If
someone later says ‘If a number is negative, it should always count as even’, you can do that:
End Function
And when you change it in this one place, it’s changed for every single part of the program!
That’s powerful.
Task 1
Instead of detecting whether a number is cleanly divisible by three, your program should detect
if a number is a prime number, and output that information instead.
Task 2
Instead of detecting whether a number is cleanly divisible by four, your program should
instead detect if a number is a power of two, and output that information instead.
Task 3
Add in a third textbox for a third number, and adapt the program accordingly.
Task 4
Add an error handling subroutine that you use on each textbox before you extract its value.
It should check to see if a textbox is empty. If it is, set its contents to zero.
Task 5
Add a function that allows the user to specify a set of three numbers, an operation to
perform, and then does that rather than the addition operator. These should include
addition, subtraction, multiplication, and division.
Task 6
Create a function that calculates the power of the first number to the second, adding on the
third. Add this as an option to the function from task five.
• File IO
• Writing files
• Reading Files
• The File Chooser.
10.3 Timings
The approximate amount of time that you can expect to spend on each type of activity in this
topic is as follows:
Lectures: 1 hour
We will need to make use of a number of .NET’s underlying File IO architecture elements for
this, and so we must make use of the System.IO package. This must be imported into your
program before special code systems will be recognised. We do this by adding an import to
the very top of our program, outside of any other code:
Imports System.IO
End Class
In order to use the File IO mechanisms present in VB .NET, we must make use of some
special code packages provided by the framework. We use these in much the same way as
we do for any other kind of data type – it’s just that these are objects. A full discussion of
this topic is outside the scope of this module, but you don’t need to know the specifics in
order to make use of the tools.
The first of these objects is called File. The second is called StreamWriter. Let’s look at
how we might develop a simple text editor in Visual Basic. This is a form that contains a
multiline textbox, and the buttons for saving and loading files:
cmdOpen
cmdSave
Before we can open a file, we must have a file to open. For that reason we will begin with
the save functionality.
End Sub
We give this variable a starting value in a slightly unusual way. We make use of a method
(as we saw in the last chapter) that is defined inside the File class. This creates the object we
can use as the basis of our StreamWriter variable. It works like this:
myWriter = File.CreateText("example.txt")
End Sub
This tells Visual Basic to create the connection between your program and a file, in its working
directory, called example.txt. You can make use of relative or absolute addressing as is
convenient for your filenames.
Once we have this reference to the underlying file, we can tell our myWriter variable to start
putting information into the file, like so:
myWriter = File.CreateText("example.txt")
myWriter.WriteLine(txtData.Text)
End Sub
Finally, once we have finished writing text into the file we close our StreamWriter so that the
underlying operating system knows we’re done with it. Many operating systems prohibit
multiple programs making use of the same file at the same time.
myWriter = File.CreateText("example.txt")
myWriter.WriteLine(txtData.Text)
myWriter.Close()
End Sub
Once you’ve run this program, put some text in the textbox and hit save, you should look in
the working directory for the project. You’ll find in there a new text file, called example.txt, that
contains the contents of the textbox. If you run the program again, type in some text and then
hit save, you’ll find that it overwrites the old one with your new data. Sometimes we don’t
want that – sometimes we want to add to what’s already there. For that, you replace the
CreateText method with the AppendText method. It otherwise works in exactly the same way.
If you just want to write a line without a linebreak, you can use the Write method rather than
WriteLine.
End Sub
Unlike with StreamWriter, StreamReader will expect the file to be there. It won’t create one if
no file exists. If the file does not exist, it will cause an error.
Where we would create a file using CreateText for saving, we instead use a method called
OpenText for loading. It takes the same parameter (the name of the file). Instead of using
WriteLine, we use a method called ReadToEnd which starts reading the file in, a character a
time, and returns it as a String. When we’re done, we Close the StreamReader just as we do
with the StreamWriter.
It may not seem like much, but this means that we now have the ability to save data out to
files, and then read it back in – we’re no longer constrained by the lifetime of a program when
it comes to persisting data. But we shouldn’t congratulate ourselves too much just yet – most
programs won’t crash if you try to load a file that isn’t there, and ours should be no exception.
We need to add a little bit of error handling in here to make things work a little better:
If File.Exists("example.txt") Then
myReader = File.OpenText("example.txt")
txtData.Text = myReader.ReadToEnd
myReader.Close()
Else
MsgBox("No such file")
End If
End Sub
Now when the program tries to load a file that doesn’t exist, it’ll tell us.
The first and most obvious way to permit this is to allow the user to enter the filename into a
textbox. However, that’s more trouble than we’d like – the user might need to write a long
pathname, and we’d need to do all kinds of validation to make sure the filename was correct
and that the user had typed anything at all. As far as is possible, we want the computer to
do all the work for us.
Most real applications have a more elegant solution – allow the user to browse to a directory
and choose a file. Visual Basic lets us do that, making use of a new type of variable called
an OpenFileDialog. We declare this in a slightly different way:
When we have this then we can show a dialog to let the user browse around the file system:
Once the user has opened up this dialog, there are certain things we need to know. We need
to know if they selected a file, or hit cancel. As such, when the dialog is shown it will give us
back a boolean – true indicated they selected something, false indicated they didn’t.
selected = dialog.ShowDialog
End If
If they selected something, it’ll be held in dialog.FileName. And then instead of having a
hard-coded name, we can let them decide:
selected = dialog.ShowDialog
If File.Exists(filename) Then
myReader = File.OpenText(filename)
txtData.Text = myReader.ReadToEnd
myReader.Close()
End If
Else
MsgBox("No such file")
We can do a very similar thing for saving a file, except we make use of the SaveFileDialog
class instead of OpenFileDialog:
selected = dialog.ShowDialog
myWriter = File.CreateText(filename)
myWriter.WriteLine(txtData.Text)
myWriter.Close()
End If
End Sub
The only significaint difference between the two, in this program, is the text that they show on
their buttons and the way they behave for selection and creation of files.
With these tools, the world of File IO is now open for you to explore.
Task 1
Create a function in this program called SaveText. Move all the code for writing to a file into
this, passing the filename and text to be written as parameters.
Task 2
Add a txtTitle textfield to this form. Using two separate files (one called title.txt for the title),
save the contents of txtTitle and txtData so that they are opened and saved at the same time.
Task 3
Add a new new textfield to this project. The textfield will allow the user to set a number, and
this is the number of times the contents of of txtData will be written to the file.
Task 4
Making use of the DeleteFile method of File, add a button and dialog that allows the user to
select a file and delete it.
Task 5
Remove the save and open buttons from your form. Remove the title textbox too. Replace it
with a textbox that permits the user to enter a filename.
Task 6
Modify the txtData control so that it behaves like a typewriter. Whenever anyone types in the
textbox, have it write the current contents to the filename set in the textfield you put in for task
five, and then clear the text.
Task 7
Add in some error checking for your application, making sure that it does not try to save text
if no filename has been set. It should also not save text if the filename exists before your
application starts writing text to it.
11.3 Timings
The approximate amount of time that you can expect to spend on each type of activity in this
topic is as follows:
In order to identify potential athletes, they need a program to enter the personal bests for all
three events for the best athletes at their gym.
The program should store the name of each athlete, and also their best time for each of the
three events. The times should be entered in minutes. It should then calculate the lowest total
time for all athletes.
All times should be stored as doubles to allow suitable precision. The minimum times for each
event are listed below – times lower than these should not be accepted by the program.
If values lower than the above are entered for an event, the user should be told the value is
invalid and asked to re-enter the time for the event.
Once the lowest total times have been calculated, the three lowest total times should be
displayed, alongside the names of the athletes with the lowest total times for the three events.
These three names and times should then be written out to a file, called IronManTriathletes.txt.
Task List
Given the above project brief, your job is to plan, design, implement and test a program which
meets the conditions given in the project brief.
An Object Definition Sheet Template and a Test Plan Template are provided below
10
11
12
13
14
15
16