0% found this document useful (0 votes)
16 views163 pages

ITP Student Workbook V2.4

Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
16 views163 pages

ITP Student Workbook V2.4

Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 163

Introduction to Programming

Student Workbook

Page 1 of 163

ITP Student Workbook – V2.3


Modification History

Version Date Revision Description


V1.0 April 2009 For issue
V2 June 2012 Reviewed. Overview and formatting updated.
V2.1 February 2013 Update
V2.2 February 2017 Unit refresh and update to Visual Basic.NET 2015
V2.2 September 2018 Updated TQT
V2.3 September 2018 Updated reference to VLE
V2.4 January 2020 Updated TQT due to change of assessment

© NCC Education Limited 2020

All Rights Reserved

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

ITP Student Workbook – V2.3


ITP Student Guide
CONTENTS
1. Overview and Objectives ............................................................................................... 6
2. Learning Outcomes and Assessment Criteria ............................................................ 6
3. Syllabus ........................................................................................................................... 8
4. Resources...................................................................................................................... 10
4.1. Additional Software Requirements ................................................................... 10
5. Teaching and Learning ................................................................................................ 11
5.1. Lectures ................................................................................................................ 11
5.2. Laboratory Sessions ........................................................................................... 11
5.3. Private Study........................................................................................................ 12
6. Assessment ................................................................................................................... 12
6.1. Design of a Solution for the Assignment ......................................................... 12
6.2. Implementation .................................................................................................... 12
6.3. Testing .................................................................................................................. 12
7. Suggested Further Reading List ................................................................................. 13
Topic 1: Introduction to the IDE, VB Properties and creating a GUI ..................................... 14
1.1. Learning Outcomes ...................................................................................................... 14
1.2. Notes to Teachers and Students................................................................................. 14
1.3. Timings .......................................................................................................................... 15
1.4. Student Manual ............................................................................................................. 17
1.5. Private Study Tasks...................................................................................................... 42
Topic 2: Introduction to Data Types and Sequential Programming ...........................................44
2.1 Learning Outcomes ...................................................................................................... 44
2.2 Notes to Teachers and Students................................................................................. 44
2.3 Timings .......................................................................................................................... 44
2.4 Student Manual ............................................................................................................. 44
2.5 Private Study Tasks...................................................................................................... 58
Topic 3: Introduction to the Programming Construct of Iteration and Fixed Loops..............60
3.1 Learning Outcomes ...................................................................................................... 60
3.2 Notes to Teachers and Students................................................................................. 60
3.3 Timings .......................................................................................................................... 60
3.4 Student Manual ............................................................................................................. 61
3.5 Private Study Tasks...................................................................................................... 73
Topic 4: Introduction to the Programming Construct of Selection ............................................75
4.1 Learning Outcomes ...................................................................................................... 75

Page 3 of 163

ITP Student Workbook – V2.3


ITP Student Guide
4.2 Notes to Teachers and Students................................................................................. 75
4.3 Timings .......................................................................................................................... 75
4.4 Student Manual ............................................................................................................. 75
4.5 Private Study Tasks...................................................................................................... 91
Topic 5: Introduction to Conditional Loops and Data Validation ................................................93
5.1 Learning Outcomes ...................................................................................................... 93
5.2 Notes to Teachers and Students................................................................................. 93
5.3 Timings .......................................................................................................................... 93
5.4 Student Manual ............................................................................................................. 94
5.5 Private Study Tasks.................................................................................................... 107
Topic 6: Project Definition and Design ............................................................................................109
6.1 Learning Outcomes .................................................................................................... 109
6.2 Notes to Teachers and Students............................................................................... 109
6.3 Timings ........................................................................................................................ 109
6.4 Student Manual ........................................................................................................... 110
6.5 Private Study Task...................................................................................................... 124
Topic 7: Case Study: Sample Mid-Course Assignment ...............................................................125
7.1 Learning Outcomes .................................................................................................... 125
7.2 Notes to Teachers and Students............................................................................... 125
7.3 Timings ........................................................................................................................ 125
7.4 Student Manual ........................................................................................................... 126
7.5 Case Study Task ......................................................................................................... 126
Topic 8: Introduction to Arrays ..........................................................................................................131
8.1 Learning Outcomes .................................................................................................... 131
8.2 Notes to Teachers and Students............................................................................... 131
8.3 Timings ........................................................................................................................ 131
8.4 Student Manual ........................................................................................................... 132
8.5 Private Study Tasks.................................................................................................... 141
Topic 9: Introduction to Methods ......................................................................................................142
9.1 Learning Outcomes .................................................................................................... 142
9.2 Notes to Teachers and Students............................................................................... 142
9.3 Timings ........................................................................................................................ 142
9.4 Student Manual ........................................................................................................... 143
9.5 Private Study Tasks.................................................................................................... 150
Topic 10: File IO......................................................................................................................................151

Page 4 of 163

ITP Student Workbook – V2.3


ITP Student Guide
10.1 Learning Outcomes .................................................................................................... 151
10.2 Notes to Teachers and Students............................................................................... 151
10.3 Timings ........................................................................................................................ 151
10.4 Student Manual ........................................................................................................... 152
10.5 Private Study Tasks.................................................................................................... 158
Topic 11: Case Study: Creating a GUI Program that uses Arrays, Procedures and File IO
....................................................................................................................................................................159
11.1 Learning Outcomes .................................................................................................... 159
11.2 Notes to Teachers and Students............................................................................... 159
11.3 Timings ........................................................................................................................ 159
11.4 Student Manual ........................................................................................................... 160
11.5 Case Study Task ......................................................................................................... 160

Page 5 of 163

ITP Student Workbook – V2.3


ITP Student Guide
1. Overview and Objectives
This module makes extensive practical use of the modern programming language Visual Basic
Express to illustrate the classic programming principles of Sequencing, Selection and Iteration
in the context of object oriented computer programming.

2. Learning Outcomes and Assessment Criteria

Learning Outcomes; Assessment Criteria;


The Learner will: The Learner can:
1. Create project documentation. 1.1 Understand why the design, implementation
and testing of a program should be supported
by appropriate documentation
1.2 Create and complete a Project Control Object
Definition Sheet
2. Implement a program that uses data 2.1 Write a working program which accepts and
capture and validation. stores user input
2.2 Write a working program which validates user
input and only accepts expected values
3. Implement a program that uses 3.1 Write a working program that uses sequential
sequential programming with programming
different data types. 3.2 Write a working program which makes use of at
least two different data types

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

ITP Student Workbook – V2.3


ITP Student Guide
6. Implement a program that uses 6.1 Write code that demonstrates how to declare an
arrays array
6.2 Write code that demonstrates how to
manipulate an array
6.3 Write code that demonstrates how to sort an
array
6.4 Identify and document appropriate testing of
arrays

Page 7 of 163

ITP Student Workbook – V2.3


ITP Student Guide
3. Syllabus
Syllabus
Topic Title Proportion Content
No
1 Introduction to 5% • Introduction to Visual Studio
the IDE, VB Community 2015 IDE
Properties and • Introduction to GUI objects and
1 hour of lectures
creating a GUI properties
2 hours of
laboratory • Introduction to creating a GUI
2 hours 15
minutes of private Learning Outcome: 2
study
2 Introduction to 5% • Introduction to programming
data types and • Introduction to objects
sequential
1 hour of lectures • Introduction to variables
programming
2 hours of • Assignment statements
laboratory
• Introduction to data types
2 hours 15
• Arithmetic operations
minutes of private
study
Learning Outcome: 3
3 Introduction to 10% • Introduction to iteration
the • Flow of execution
programming
1 hour of lectures • For loop structure
construct of
iteration and
4 hours of • Variables and loops
laboratory
fixed loops • Nested loops
4 hours 15
minutes of private
Learning Outcome: 4
study
4 Introduction to 10% • If statement structure
the • Comparison operators
programming
1 hour of lectures • If-Else structure
construct of
selection
4 hours of • If – Else – If structure
laboratory
• Compound conditionals
4 hours 15
• Switch statements
minutes of private
study
Learning Outcomes: 2, 4

Page 8 of 163

ITP Student Workbook – V2.3


ITP Student Guide
5 Introduction to 10% • Importance of data validation
conditional • Checking for specific values
loops and data
1 hour of lectures • Checking for a range of values
validation
4 hours of • String comparisons
laboratory
• While loop structure
4 hours 15
• Logical comparisons
minutes of private
study • Multiple conditions
• Do - While loops

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

ITP Student Workbook – V2.3


ITP Student Guide
9 Introduction to 10% • Different method types in VB
Methods (Subs and Functions) and scope
1 hour of lectures • Parameter passing
5 hours of • Return statements
laboratory • Method overloading
5 hours 15
minutes of private
Learning Outcomes: 2, 3, 4, 5, 6
study
10 Introduction to 10% • Files and data storage
File I/O • Writing to files
1 hour of lectures • Reading from files
5 hours of • Exception handling for file I/O
laboratory
5 hours 15
Learning Outcome: 5
minutes of private
study
11 Case Study: 10% • Consolidation of learning from
Creating a GUI topics 1 – 10
program that • Student end of course exam
3 hours of
uses arrays,
laboratory
procedures and
3 hours 30 Learning Outcomes: 1, 2, 3, 4, 5, 6
file I/O
minutes of private
study

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.

4.1. Additional Software Requirements


Students will require access to Visual Studio Community 2015 software. Visual Studio
Community 2015 is available as a free download from Microsoft which means that students
may install the software on their own systems and have no difficulty in transferring their work
between the place of instruction and their homes.

This can be downloaded from:


https://www.visualstudio.com/en-us/products/visual-studio-express-vs.aspx

Page 10 of 163

ITP Student Workbook – V2.3


ITP Student Guide
5. Teaching and Learning

Suggested Learning Hours


Guided Learning Hours Assessment Private Study: Total:
Lectures: Tutorial: Seminar: Laboratory:
9 - - 41 6-hour assignment 44 100

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.

5.2. Laboratory Sessions


During these sessions, students are required to work through practical tutorials and various
exercises. The details of these are provided in this guide and the Student Workbook. Students
will be expected to keep written records of their investigations and solutions to the problems
set.

Page 11 of 163

ITP Student Workbook – V2.3


ITP Student Guide
5.3. Private Study
In addition to the taught portion of the module, students will also be expected to undertake
private study. During this time, students are expected to revise the content of classes and
complete the exercises provided to improve their understanding. Teachers will need to set
deadlines for the completion of exercises and go over the suggested answers, which are
provided in this guide.

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.

6.1. Design of a Solution for the Assignment


The module is not concerned with any formal design skills but students must document a
design of their solution.

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

ITP Student Workbook – V2.3


ITP Student Guide
7. Suggested Further Reading List
A selection of sources of further reading around the content of this topic must be available in
your Accredited Partner Centre’s library. The following is a suggestion of a suitable source:

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

ITP Student Workbook – V2.3


ITP Student Guide
Topic 1: Introduction to the IDE, VB Properties and creating
a GUI

1.1. Learning Outcomes

On completion of this topic, you will be able to:

Use the fundamental facilities of the Visual Studio Community 2015 IDE;

1.2. Notes to Teachers and Students

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.

Concepts introduced in Topic 1 include:

• The VB Integrated Development Environment (IDE)


• How to locate a project on the filing system
• The Toolbox menu
• A VB form
• The Properties menu
• Creating a simple user interface for an application which uses:
o Textbox controls
o Label controls
o ComboBox controls
o RadioButton controls
o CheckBox controls
o GroupBox controls

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

ITP Student Workbook – V2.3


ITP Student Guide
Five important windows are displayed:

The Menu Bar and Toolbar window

The Toolbox window

The Properties window

The Solution Explorer window

The Initial Form window

To see such a screen:

Load up Visual Studio Community 2015.


Close the Start Window.
Go to the top menu.
File – New Project.
Choose the Windows Forms Application Visual Basic option.

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

ITP Student Workbook – V2.3


ITP Student Guide
Laboratory Sessions: 2 hours

Private Study: 2 hours 15 minutes

Page 16 of 163

ITP Student Workbook – V2.3


ITP Student Guide
1.4. Student Manual

We are going to create a simple Visual Basic project that will use several common controls.

1.4.1. Introduction to Visual Studio Community 2015 IDE

Step 1: Set where your projects are to be saved

1. Restart Visual Studio Community 2015 and close the start-up window, giving:

Page 17 of 163

ITP Student Workbook – V2.3


ITP Student Guide
2. Go to top menu; Tools – Options – Projects and Solutions, giving:

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

ITP Student Workbook – V2.3


ITP Student Guide
Step 2: Name a new project

1. Back to the top menu; File – New - Project, giving:

Page 19 of 163

ITP Student Workbook – V2.3


ITP Student Guide
2. Use the menu down the left hand side to make sure that Visual Basic is selected as the
language and that Windows is selected. Then, in the main window, choose Windows Forms
Application, and name the project MyCalendarApp:

Page 20 of 163

ITP Student Workbook – V2.3


ITP Student Guide
3. Check that the Location listed is the directory you chose earlier, and change if needed. Then
click on OK, giving:

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

ITP Student Workbook – V2.3


ITP Student Guide
As briefly mentioned earlier, the IDE consists of several windows:
Solution
Toolbox Explorer

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

ITP Student Workbook – V2.3


ITP Student Guide
The toolbox is a slide-out panel containing all of the components provided by default by Visual
Studio - to begin with only the name of the panel is visible. Click on it, and it’ll bring up the
following options:

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

ITP Student Workbook – V2.3


ITP Student Guide
these are provided - but by default you’ll get access to the most commonly used GUI
components.

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.

So, to sum up the relationship between these various VB elements -

• An application has one or more forms.


• A form has one or more controls.
• A control has many properties.

Let’s put some of this into practise and draw our first VB interface

1.4.2. A First VB Interface


We’ll start by drawing a standard-sized button onto the form. First we make sure the Common
Controls menu has been expanded, and then we double-click on the one that says ‘button’:

Page 24 of 163

ITP Student Workbook – V2.3


ITP Student Guide
Having done this, a standard sized button will appear on our form, with the text Button1
emblazoned across it. It is unlikely that this button will appear where we might want it, and so
we left click and drag it to an appropriate location - near the middle at the bottom seems like
as good a place as any, so that’s where we’ll place it.

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

ITP Student Workbook – V2.3


ITP Student Guide
This changes the name of the button. We will use this when we write VB code for the button.
But it doesn’t change the text displayed on the button which still says Button1. In order to
change the text on the button we need to alter another property: the Text property. Double
click on the Text property and change the text to Press Me :

Page 26 of 163

ITP Student Workbook – V2.3


ITP Student Guide
Once we press Enter, the text on our button control will be updated like so:

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

ITP Student Workbook – V2.3


ITP Student Guide
The MonthCalender control will already work for navigating through the months and picking
up the current date - all of that functionality comes pre-provided by the control. This is the
essence of the .NET class library - it makes things easier for you because it provides a huge
amount of functionality as standard. All you need to do is stitch it all together.

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

ITP Student Workbook – V2.3


ITP Student Guide
This simple example provides you with only a small taster of what’s available in Visual Basic.
Now we’ll look at some of the other properties available in most controls, and what they allow
you to do.

1.4.3. More About Properties


We’ve looked at the name and text properties of controls, but there are many others. We’ll
look at some of the most commonly used ones here.

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

ITP Student Workbook – V2.3


ITP Student Guide
meaning if you resize the application the component will resize with it. Try
docking the button with the bottom area of the application and see what
happens.

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.

Lets make use of this by creating a new GUI application.

Page 30 of 163

ITP Student Workbook – V2.3


ITP Student Guide
1.4.4. Creating a Basic GUI Application
We’re going to use what we have learned so far to create the following GUI:

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.

Step 1: Create a new project

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

ITP Student Workbook – V2.3


ITP Student Guide
Step 2: Change the Form Text

Click on the Form title bar to select it, then change the text property to Holiday Options.

The form title should now say Holiday Options:

Step 3: Add a Title Label

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

ITP Student Workbook – V2.3


ITP Student Guide
will appear and the label will snap back to the smallest size needed to hold that text. Label
sizes change to meet the length and size of the text, unless you alter certain property values
to prevent this.

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

ITP Student Workbook – V2.3


ITP Student Guide
Step 5: Add the Combo Boxes for Month and Day

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

ITP Student Workbook – V2.3


ITP Student Guide
Clicking the icon brings up a secondary window. Type in the months one entry per line. Once
it is completed as in the screen shot below, click OK to close the window.

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.

Step 6: Add the Labels for Destination and Duration

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.

Step 7: Add the Destination and Duration Choices

Page 35 of 163

ITP Student Workbook – V2.3


ITP Student Guide
Customers can only choose one destination, and one duration. We could use a combo box for
this, but to show all options easily, we have chosen to use radio buttons. Radio Buttons are
used when only one of the options can be chosen, and must be grouped together if you want
to have more than one set of radio buttons on a form. Only one radio button in the group can
be selected.

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

ITP Student Workbook – V2.3


ITP Student Guide
Change the text property of the GroupBox to blank (an empty string) as we don’t need to give
it a title because the Destination label is better for this purpose.

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

ITP Student Workbook – V2.3


ITP Student Guide
Click on the form inside the GroupBox control and position the radio button near the top left
hand corner of the GroupBox.

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

ITP Student Workbook – V2.3


ITP Student Guide
Once True has been selected, that radio button will show as checked.

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.

Step 8: Add the Label for Options

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.

Step 9: Add the Option Choices

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

ITP Student Workbook – V2.3


ITP Student Guide
Start by selecting a GroupBox control from the Toolbox window and position it on the form
underneath the Options label, aligning it suitably. After this, select the CheckBox component
and click and drag to place it in the top left hand corner of the GroupBox that you just added.
Then, as you did with the radio buttons, right click and copy it then paste 5 copies and move
them into 2 columns and 3 rows inside the group box and change the text property of each
CheckBox so they match the image below.

As the Options are all optional, we won’t change the checked property for any of them.

Step 10: Add the Submit Button

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

ITP Student Workbook – V2.3


ITP Student Guide
Once it is positioned, go to the Properties window and change the text property to Submit.
Also in the properties window, change the font style to bold and the font size to 12pt.
Congratulations, you should now have a complete interface which looks like this:

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.

1.4.5. Topic Summary


In this topic we have covered the following:

• How to use Visual Studio Community 2015 to create Windows Forms Applications

• How to change the location where projects are saved.

• How to use various Visual Basic controls and change some of their properties.

Page 41 of 163

ITP Student Workbook – V2.3


ITP Student Guide
1.5. Private Study Tasks

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

Add a background image to the HolidayPicker application. Find a suitable, copyright-free


image from the internet and resize the image so that it is the same height and width as your
form, then add it via the appropriate property of the form.

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

ITP Student Workbook – V2.3


ITP Student Guide
Task 5

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

ITP Student Workbook – V2.3


ITP Student Guide
Topic 2: Introduction to Data Types and Sequential
Programming

2.1 Learning Outcomes


On completion of this topic, you will be able to:

• Understand the purpose of the main data types in Visual Basic


• Use the Integer, Double, String and Boolean data types
• Understand the basics of event driven programming
• Write simple event procedures using sequential programming

2.2 Notes to Teachers and Students


This topic introduces the basics of event driven programming. It also introduces the VB
programming language including a few different data types, and the concept of sequential
programming. Arithmetic operators will also be covered.

Concepts introduced in Topic 2 include:

• Naming conventions for GUI controls


• Event procedures in Visual Basic
• How code routines are triggered by events in Visual Basic
• The data types of Integer, Double, String, and Boolean
• How to declare variables
• How to assign values to variables
• How to write simple sequential code to carry out arithmetic tasks
• How to display results of calculations to the user

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

Laboratory Sessions: 2 hours

Private Study: 2 hours 15 minutes

2.4 Student Manual


We are going to learn some of the fundamentals of programming in Visual Basic. This topic
looks at how to write simple sequential programs using variables, and how to trigger the code
we have written via button clicks.

Page 44 of 163

ITP Student Workbook – V2.3


ITP Student Guide
2.4.1 Introduction to Event Driven Programming
2.4.1.1 Setting up the interface
So far we haven’t written any actual code for the programs we have created - in some
programming languages you must first write a chunk of code before you can even get a simple
interface to appear. It is important to realise that in Visual Basic this code is still necessary -
the difference is that the IDE is writing it for you.

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.

So, let’s begin building a simple event driven program.

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

We need to change the following properties to get the appearance correct:

Form Change the text property to ‘My First Event


Driven Application’.
Button Change the text property to ‘Press Me’.
Change the Font property to bold and 10pt.
Label Delete the text in the text property. Change
the Autosize property value to False to
enable resizing of the label.

After doing that, we end up with something that looks similar to this:

Page 45 of 163

ITP Student Workbook – V2.3


ITP Student Guide
2.4.1.2 Naming Conventions
Our application is going to take the text that is present in the textbox area and, when the user
presses the button, transfer it to the label. It will also clear the textbox at this point.

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:

Control Identifier Name of Control


Button cmd cmdPressMe
Label lbl lblOutput
TextBox txt txtInput
Form frm frmMyFirstApplication

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.

2.4.1.3 The Code Window

Page 46 of 163

ITP Student Workbook – V2.3


ITP Student Guide
Now that we’ve got our controls properly named, we can actually add some code to our
application.

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

ITP Student Workbook – V2.3


ITP Student Guide
lblOutput.text = txtInput.text

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

ITP Student Workbook – V2.3


ITP Student Guide
It may be simple, but that’s your first event-driven program right there - an actual, fully
functional event-driven application. Run the program and test the functionality of both buttons.

2.4.2 Introduction to Variables and Scope


In our program above, we manipulated the property values directly without storing them:
once we’d overwritten the value in the label, it was gone forever. However, it is often
necessary for us to store the state of various operations through a program’s lifetime, and it
would be cumbersome if we needed to provide a control to do that every single time.

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:

Dim SomeString as String

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

ITP Student Workbook – V2.3


ITP Student Guide
SomeString = “Hello World!”

This process of storing a value in a variable is known as assignment. Once we have


assigned a value to our variable, we can then use this variable in place of the string itself in
other statements:

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

ITP Student Workbook – V2.3


ITP Student Guide
We can store the previous contents in a variable and then restore it when the undo button is
pressed:

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.

2.4.3 Sequential Programming

Page 51 of 163

ITP Student Workbook – V2.3


ITP Student Guide
All that sequential programming means is the order of execution of a program. For the
programs that we are going to be writing in this topic, execution of code is only one Subroutine
at a time, from first line of code to the last line of code in order (i.e. sequence) when the button
linked to that Subroutine is pressed. In future topics we will see how the order or path of
execution through program code can be altered by selection and looping constructs, but for
now the code you type will run one line after the other, in order.

2.4.4 Other Variable Types and Arithmetic Operators


Strings are used when we need to store text, or other alphanumeric characters (such as phone
numbers), but they are not the only type of variable. The table below shows the most
commonly used variable types in Visual Basic, and describes they type of data they should be
used to store. It also shows how each type of variable can be declared, and how to assign a
value to each type of variable:

Variable Type Type of data stored Example declaration and assignment


String Text/ alphanumeric Dim input As String
Input = “Hello World!”
Integer Whole numbers Dim myNum As Integer
myNum = 15
Double Real numbers (ones with decimal points) Dim pi As Double
pi = 3.14157
Boolean True or False Dim answer As Boolean
answer = true

2.4.4.1 An Event Driven Calculator


We’re going to create a program which uses other types of variable – Integers and Doubles,
and also makes use of arithmetic operators. This is a simple calculator that takes two numbers,
performs the desired arithmetic operation on them, and displays the answer.

Page 52 of 163

ITP Student Workbook – V2.3


ITP Student Guide
Step 1: Open the Calculator project or create it

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

Step 2: Rename the components appropriately

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

ITP Student Workbook – V2.3


ITP Student Guide
The functionality here is very similar to what we did for My First Event Driven Application,
except that we are working with numbers instead of text, and we are pulling information out of
two textboxes rather than just one.

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

We declare them in exactly the same way as we declare strings:

Dim myIntegerNumber as Integer

Dim myRealNumber as Double

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.

Step 3: Add the Code for cmdAdd

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

ITP Student Workbook – V2.3


ITP Student Guide
we need to add in the code which will add the two values together and display the answer
using the lblOutput label. This involves the following:

• Declare a variable to store the answer

• Add numOne and numTwo together and store the result in the answer variable

• Set the Text property of lblOutput to display answer

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

Step 4: Add the Code for cmdDivide

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

ITP Student Workbook – V2.3


ITP Student Guide
Run the program. Now if we enter 12 for the first number and 3 for the second number and
click divide, it will display 3 as the answer.

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.

Step 5: Change the code for cmdAdd to use Double variables

Page 56 of 163

ITP Student Workbook – V2.3


ITP Student Guide
Run the program and test it using whole numbers and numbers with digits after the decimal
point.

Step 6: Change the code for cmdDivide to use Double variables

Run the program and test it using whole numbers and numbers with digits after the decimal
point.

2.4.5 Topic Summary


Programming in Visual Basic (at least at this point) is done through sequential statements of
code that are located within control specific sub-routines. We can declare variables that hold
chunks of data, and the use operators on each of these chunks of data to process them for
output.

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

ITP Student Workbook – V2.3


ITP Student Guide
2.5 Private Study Tasks
Task 1

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:

As an example, someone with a weight of 70 Kilograms and a height of 1 metre 71 centimetres


would have a BMI of 70 / (1.71) 2 which is 70 / 2.9241 which equals 23.9 rounded to one
decimal place. (You do not need to work out how to round the answer to a set number of
decimal places, though you can investigate this if you like.)

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

ITP Student Workbook – V2.3


ITP Student Guide
Create a new project and design and code a program to tell the user the length of the
hypotenuse of a right - angled triangle if they put in the lengths of the other two sides. (Hint:
Look up Pythagoras Theorem, and also how to use the Math.Sqrt function in Visual Basic.)

Page 59 of 163

ITP Student Workbook – V2.3


ITP Student Guide
Topic 3: Introduction to the Programming Construct of
Iteration and Fixed Loops

3.1 Learning Outcomes


On completion of this topic, you will be able to:

• Understand the concept of iteration


• Describe the flow of execution through a fixed loop
• Write simple programs using for loops
• Write simple programs using nested for loops

3.2 Notes to Teachers and Students


This topic introduces the concept of iteration.

Concepts introduced in Topic 3 include:

• Why iteration can be useful


• Fixed loops purpose
• Fixed loops structure
• Using variables to alter the number of times a for loop repeats
• Using nested loops

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

Laboratory Sessions: 4 hours

Private Study: 4 hours 15 minutes

Page 60 of 163

ITP Student Workbook – V2.3


ITP Student Guide
3.4 Student Manual
We are going to learn some of the fundamentals of iteration, and how to use fixed loops. This
topic also looks at how to build up larger strings for outputting to a label, and how to add code
comments.

3.4.1 Introduction to Iteration


In this topic we’re going to look at some of the tools that we have for altering the path of
execution through our programs through the use of what are known as repetition structures.
When writing a program, we usually encounter circumstances when we are doing the same
thing several times - in some circumstances we may know when writing the code how many
times a section should be repeated, and in other circumstances we won’t know until the
program is running. The first set of circumstances can be handled by one type of repetition
structure which will be covered in this topic. The second set of circumstances will be covered
in Topic 5.

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.

3.4.2 The For Loop


The for loop is the first of these repetition structures, and is used when we know how many
times we need to repeat a particular section of code - we may not know it when writing a piece
of code, but we know it when the code is running.

3.4.2.1 Repetition Without For Loops


Let’s take a simple example of calculating the 5 times table from 5 times 1 to 5 times 10 and
displaying the answers on a label.

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

ITP Student Workbook – V2.3


ITP Student Guide
That seems like a lot of work. And the calculations are identical except for the second number
in each multiplication. There must be an easier way of doing this.

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.

Appending Values to Strings and Line Breaks

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

ITP Student Workbook – V2.3


ITP Student Guide
lblOutput.Text = “Your BMI is: “ & bmi

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.

An example of it in use is shown below:

lblOutput.Text = “Your mark for the assignment is: “ & assignmentMark & vbCrLf &

“Your mark for the examination is: “ & examMark

3.4.2.2 For Loop Structure


Our sequential five times table program is not efficient, but it was easy enough to write. But
what if we wanted to print out the five times table up to 5 times 100? There would be lots more
copying and pasting and changing of values, and more chance of missing a number of getting
a line wrong.

For loops make this a much simpler task.

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.

So the procedure breaks down to:

1. Initialise the counter variable


2. If the counter variable is less than or equal to ten
a. Execute the code between the For… and Next lines
Page 63 of 163

ITP Student Workbook – V2.3


ITP Student Guide
b. Go back to 2

If the counter variable is greater than ten, it moves on to the next line of code after the for
loop.

3.4.2.2 Five Times Table Using For Loop


Let’s go back to our five times table example. Could using a for loop make the code more
efficient? Yes, it could.

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?

Declare a variable to store the times table we are using (5).

Declare a variable to store the current answer

Create a loop with a counter that loops from 1 to 10.

Inside the loop:

Calculate the value of the times table value * counter

Append the result to our label

Page 64 of 163

ITP Student Workbook – V2.3


ITP Student Guide
Let’s step through what is happening inside the for loop for a few iterations.

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

ITP Student Workbook – V2.3


ITP Student Guide
3.4.2.3 Power Calculator Example
Let’s look at another mathematical example where a for loop is very useful. This time we will
look at the example of computing the power of one number to another: Xy

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.

We make use of this to calculate a power:

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:

running total is set to the base.

Repeat a number of times equal to the power:

Multiply running total by the base

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:

running total is set to the base (running total = 2)

Repeat 4 times:

1st time: running total = 2 * 2 (4)

2nd time: running total = 4 * 2 (8)

3rd time: running total = 8 * 2 (16)

4th time: running total = 16 * 2 (32)

Page 66 of 163

ITP Student Workbook – V2.3


ITP Student Guide
We go one step too far when we calculate in this way - we actually want to repeat a number
of times equal to the power minus one:

running total is set to the base.

Repeat a number of times equal to the power minus one:

Multiply running total by the base

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

ITP Student Workbook – V2.3


ITP Student Guide
And then the code for the calculate button:

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:

Counter starting value = 1


Counter end value = 3

1st time around the loop: Total = total * base (4 * 4)


1st time around the loop: counter is incremented by one (2)
1st time around the loop: check to see if loop should continue
(yes - will terminate when counter is larger than end value.
Counter is 2, end value is 3)

2nd time around the loop: total = total * base (16 * 4)


2nd time around the loop: counter is incremented by one (3)
2nd time around the loop: check to see if loop should continue
(yes - will terminate when counter is larger than end value.
Counter is 3, end value is 3)

3rd time around the loop: total = total * base (64 * 4)


3rd time around the loop: counter is incremented by one (4)
3rd time around the loop: check to see if loop should continue
(no- will terminate when counter is larger than end value.
Counter is 4, end value is 3)

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

ITP Student Workbook – V2.3


ITP Student Guide
Create the program and test it for yourself.

3.4.3Nested For Loops


It is possible to nest for loops. This is the process of placing one loop inside the body of
another for loop. The result of this is that the inner loop is repeated the number of times
required by the outer loop. We will look at an example of this to see how it works, but it is
largely useful for grid structures and looping over 2D arrays – topics which are beyond the
scope of this unit.

The structure of a nested for loop is shown below.

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

ITP Student Workbook – V2.3


ITP Student Guide
6 2 1
7 2 2
8 2 3
9 2 4
10 2 5
11 3 1
12 3 2
13 3 3
14 3 4
15 3 5
16 4 1
17 4 2
18 4 3
19 4 4
20 4 5

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.

3.4.3.1 Nested For Loop Example


Below is an example of a program with a nested for loop which is used to print out a pyramid
of asterisks (*). The program takes in the height of the pyramid via a textbox, then uses this
variable in the loops.

Page 70 of 163

ITP Student Workbook – V2.3


ITP Student Guide
The outer loop controls how many rows are drawn/ added to the label.

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.

3.4.4 Topic Summary


In this chapter we looked at the concept of repetition, and we looked at one type of
programming structure which can be used to repeat sections of code within our programs.

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

ITP Student Workbook – V2.3


ITP Student Guide
current circumstances of the system. In Topic Five we will look at a different type of looping
structure.

Page 72 of 163

ITP Student Workbook – V2.3


ITP Student Guide
3.5 Private Study Tasks
Task 1

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

ITP Student Workbook – V2.3


ITP Student Guide
Page 74 of 163

ITP Student Workbook – V2.3


ITP Student Guide
Topic 4: Introduction to the Programming Construct of
Selection

4.1 Learning Outcomes


On completion of this topic, you will be able to:

• Understand the concept of selection


• Describe the flow of execution through an if – else statements
• Make use of comparison operators
• Write simple programs using if statements
• Write simple programs using if – else – if statements
• Write simple programs which have if statements that have compound conditions
• Write simple programs which use switch statements

4.2 Notes to Teachers and Students


This topic introduces the concept of selection. Concepts introduced in Topic 4 include:

• Why selection can be useful


• If statement structure
• If – Else statement structure
• If – Else – If structure
• Comparison Operators
• String Comparisons
• Compound conditionals
• Switch statements

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

Laboratory Sessions: 4 hours

Private Study: 4 hours 15 minutes

4.4 Student Manual


We are going to learn some of the fundamentals of selection, and how to use if statements.
We will look at if, if-else, if-else-if structures, and using compound conditionals. We will also
look at the switch statement, which is a different selection structure.

Page 75 of 163

ITP Student Workbook – V2.3


ITP Student Guide
4.4.1 Introduction to Selection
In this chapter we are going to take a look at two new kinds of programming structure - the if
structure and the case structure. Both of these structures fall into the general category of
selection structures - they are used to select between different courses of action depending
on the internal state of the application.

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.

4.4.2 The If Structure


The if structure has the following format:

If comparison_check_is_true Then

‘do the code here

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

Create a new Visual Basic project called AllAboutYou.

Step 2

Set up the interface as follows:

lblAboutYou
chkAnimals

chkBoard

chkTV

chkBooks

cmdPressMe
chkVB

Step 3

Page 76 of 163

ITP Student Workbook – V2.3


ITP Student Guide
We’re going to make use of a variable here to hold the text we will display in lblAboutYou –
this variable is going to be a String. When the button is pressed, we’re going to examine the
checked property of each check box. If it is set as true (as in, the user ticked it) then we add
some text to our String variable describing what they liked. So for the very first check box
(chkAnimals) it would be:

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

ITP Student Workbook – V2.3


ITP Student Guide
4.4.3The If – Else Structure
Often, we want a program to do one thing if a condition is true, and a different thing if the
condition is not met. To do this, we can use the If-Else structure. The If – Else structure has
the following format:

If comparison_check_is_true Then

‘do the code here

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.

Let’s work through this example.

Step 1

Open the AllAboutYou project.

Step 2

Add an Else to the If statement for the chkAnimals check box:

Page 78 of 163

ITP Student Workbook – V2.3


ITP Student Guide
Step 3

Run the program and test it by checking the following boxes.

Page 79 of 163

ITP Student Workbook – V2.3


ITP Student Guide
This should result in the following output:

Step 4

Update the program to add in Else statements for the other four checkboxes.

4.4.4The If – Else – If Structure


In certain situations we don’t just want an ‘If this then do this, else do that’: we want to check
multiple different conditions. We can do this using the If – Else – If structure. This can be
used to chain as many checks together as are required before the final default Else code.

The If – Else structure has the following format:

If comparison_check_is_true Then

‘do the code here

Else If another_check_returns_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

4.4.4.1 If – Else – If Example


Page 80 of 163

ITP Student Workbook – V2.3


ITP Student Guide
Let’s look at an example program using radio buttons which makes use of the If – Else – If
structure.

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

Create a new project called Questionnaire.

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

ITP Student Workbook – V2.3


ITP Student Guide
Add in the code for checking the optFemale and optMale radio buttons. This uses the If –
Else – If structure.

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.

4.4.5 Compound Conditionals


So far, we have only looked at if statements where one condition is checked. It is possible to
check multiple conditions, joining them with and or or logical operators.

Let’s consider the Favourite Programming Language group of checkboxes. In addition to


checking what language is the user’s favourite programming language, we might also be
interested in whether they like Visual Studio Programming Languages. Both C# and VB are
Page 82 of 163

ITP Student Workbook – V2.3


ITP Student Guide
Microsoft Visual Studio programming languages. So we might want a check that says ‘If the
user’s favourite language is C# or if the user’s favourite language is VB, then they like Visual
Studio’.

To do this, we could use the following code:

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.

4.4.5.1 Logical Operators and Truth Tables


The special statement or is used to select an either or relationship within a compound
conditional - we use what is known as a truth table to determine what the effect will be.

Logical Operators and Truth Tables

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

ITP Student Workbook – V2.3


ITP Student Guide
whole to return true. Whereas if we us an And logical operator to join our conditions, both
conditions need to return true in order for the if statement condition as a whole to return true.

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:

4.4.6 Comparison Operators


In the previous examples, our comparison checks have been on the Checked properties of
check boxes or radio buttons. However, we will often want to run comparison checks against
variables such as Strings or Integers or Doubles.

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

Operator Example Will be evaluated to True when…


> a>b a is greater than b
< a<b a is less than b
>= a >= b a is greater than or equal to b
<= a <= b a is less than or equal to b
= a=b a is equal to b
<> a <> b a is not equal to b

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.

4.4.6.1 Primitive Variables Comparison Operators Example


Let’s look at an example of when this might be useful. When scheduling rooms for classes,
some rooms have more PCs than others. Classes should only be assigned to rooms where
there are enough PCs for the group, but they should not be assigned to a classroom that is
far too large for them, as that would not be an efficient use of space.

Classroom Number Number of PCs in Classroom


Y211 12
Y212 15
Y213 16
Y214 20
Y215 25

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

ITP Student Workbook – V2.3


ITP Student Guide
Step 1

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

ITP Student Workbook – V2.3


ITP Student Guide
The first if statement comparison is a less than or equal to comparison check: we are checking
whether the number of students is less than or equal to 12. If this is true, then the class will be
assigned to room Y211.

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.

4.4.6.2 String Variables Comparison Operators Example


Comparing String variables works slightly differently to comparing numeric variables. The
operators in the table will not work for Strings, because Strings are Objects rather than
primitive data types.

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)

Let’s look at an example program.

Step 1

Page 86 of 163

ITP Student Workbook – V2.3


ITP Student Guide
Create a new project called PasswordChecker and set up the GUI so that it resembles the
screen shot below:

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

ITP Student Workbook – V2.3


ITP Student Guide
The screen shot above shows the code for the string comparison check of the userName
variable (which contains the name entered by the user) against the value stored in the
correctName variable. If the userName entered is “Pauline” then the Equals method will return
true and the label will display “The user name is correct”. If any other String is entered, the
Equals method will return false, and the label will display “The user name is incorrect. Please
try again.

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

Case Sensitivity and String Comparisons

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.

Method One: ToUpper

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

ITP Student Workbook – V2.3


ITP Student Guide
Method Two: ToLower

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.

The code for converting a String to lower case is:

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.

4.4.7 Select Case Statements


Page 89 of 163

ITP Student Workbook – V2.3


ITP Student Guide
The last thing we’re going to look at in this topic is the select case structure, which is used to
select between a range of values. It’s essentially a more compact way of implementing a large
If-ElseIf structure. An example Select Case statement is shown below:

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

4.4.8 Topic Summary


In this chapter we looked at the concept of selection, and we looked at programming structures
which can be used to alter the flow of execution through a program based on certain
conditions.

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

ITP Student Workbook – V2.3


ITP Student Guide
4.5 Private Study Tasks
Task 1

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

4. A litre bottle of water

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

ITP Student Workbook – V2.3


ITP Student Guide
Task 5

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

The following options should be supported:

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

Hard Drive (One of) – 1TB, 2TB, 4TB, 6TB, 8TB

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

ITP Student Workbook – V2.3


ITP Student Guide
Topic 5: Introduction to Conditional Loops and Data
Validation

5.1 Learning Outcomes


On completion of this topic, you will be able to:

• Understand the concept of conditional loops


• Describe the flow of execution through a while loop
• Describe the flow of execution through a do – while loop
• Write simple programs using while loops
• Write simple programs which have while loops that have compound conditions
• Write simple programs which use do – while loops
• Understand the importance of data validation
• Avoiding infinite loops

5.2 Notes to Teachers and Students


This topic introduces the concept of conditional loops. This is a different kind of repetition
structure to for loops, which are fixed loops.

Concepts introduced in Topic 5 include:

• Why we sometimes don’t know how many times we need something to be


repeated in a program
• The importance of data validation
• While Loop structure
• Do – While structure
• Dangers of while loops – infinite loops

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

Laboratory Sessions: 4 hours

Private Study: 4 hours 15 minutes

Page 93 of 163

ITP Student Workbook – V2.3


ITP Student Guide
5.4 Student Manual
We are going to learn some of the fundamentals of conditional loops, and how to use while
loops. We will look at while loop and do-while loop structures. We will also look at data
validation, and how conditional loops can be used to validate user input or calculated
variables.

5.4.1 Introduction to Conditional Loops


In this chapter we are going to take a look at two new kinds of programming structure - the
while loop and the do – while loop. Both of these structures fall into the general category of
repetition structures. However, unlike for loops, we don’t know in advance how many times a
conditional loop will be repeated - they are used to select between different courses of action
depending on the internal state of the application. In this way they are also partially selection
structures.

While loops are often used for data validation purposes. We will therefore look at this concept
in this topic.

5.4.2 While Loop Structure


The while loop is another VB repetition structure, but it differs from the for loop in what kinds
of problems it is applied to. A for loop requires you to know in advance how many times you
are going to iterate - that’s not always possible. An application to enter lottery tickets for
example may prompt a user to enter a ticket, take in the numbers, and then ask if they want
to enter another ticket. As computer developers we have no way of knowing that information
except by asking the user. If they say ‘yes’ then we iterate. If they say ‘no’ then we don’t.

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.

The structure of a while loop is as follows:

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

ITP Student Workbook – V2.3


ITP Student Guide
Step 1

Create the user interface so it resembles the screen shot below:

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

ITP Student Workbook – V2.3


ITP Student Guide
Step 3

Run and test the program.

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

ITP Student Workbook – V2.3


ITP Student Guide
Add a counter variable.

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

ITP Student Workbook – V2.3


ITP Student Guide
5.4.3 The Danger of While Loops
While loops are used when we don’t know how many times we are to iterate, and so we
base our iteration on a condition that is evaluated to either true or false.

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

Add the code.

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

ITP Student Workbook – V2.3


ITP Student Guide
Run and test the program.

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.

What happens if it’s a more difficult example?

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

ITP Student Workbook – V2.3


ITP Student Guide
Step 5

Run and test the updated program.

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

End the program.

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:

Page 100 of 163

ITP Student Workbook – V2.3


ITP Student Guide
This is called an infinite loop, and will run until you forcibly quit the application. While it is
running it will take up huge amounts of your processing time and will cause your whole system
to react sluggishly. Such mistakes are very easy to make - if you put a < instead of a >, you
may find yourself in an infinite loop. The important thing is to realise what is going wrong and
check to see where the infinite loop is occurring.

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.

5.4.4 While Loops With Compound Conditions, and Data


Validation
So far, we have only looked at if statements where one condition is checked. It is possible to
check multiple conditions, joining them with and or or logical operators. Refer back to Topic
4 for a discussion of compound conditions and logical operators.

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.

Let’s create an example program.

Step 1

Create a new project called RangeCheck and set up the user interface as shown:

Page 101 of 163

ITP Student Workbook – V2.3


ITP Student Guide
txtNumber

lblOutput

cmdEnter

Step 2

Add the following code to the project:

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?

Page 102 of 163

ITP Student Workbook – V2.3


ITP Student Guide
No, it doesn’t. The reason is because we have not updated the value of num. Unless we
update num we will be stuck in an infinite loop.

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.

Update your code as shown below:

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

Update your code as shown below:

Step 7
Page 103 of 163

ITP Student Workbook – V2.3


ITP Student Guide
Run and re-test your program. It should now work as expected.

5.4.5 Do – While Loops


The last loop we’re going to look at in this topic is the do while loop. A while loop may iterate
zero, one or more times. A do while loop is functionally identical except that it always iterates
at least once. A while loop checks the continuation conditional before it starts to loop - a do
while loop will iterate once and then check the conditional. Both kinds of loop are used for
different kinds of circumstance.

The structure of the do while loop is as follows:

Do

some_code

Loop While condition

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

Create a new project called PasswordCheck.

Step 2

Set up the interface as shown below:

Step 3

Add the following code to the project:


Page 104 of 163

ITP Student Workbook – V2.3


ITP Student Guide
Note that unlike in the String Variables Comparison Operators Example section in Topic
4, we are not checking if the two strings are equal. In this case, we want to loop whilst they
are not equal. In order to do this, we need to add = False after our Equals method call as can
be seen in the code above.

5.4.6 Topic Summary


In this chapter we looked again at the concept of repetition, this time in relation to unbounded
loops. We looked at programming structures which can be used to alter the flow of execution
through a program by repeating a different number of times based on certain conditions.

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.

Page 105 of 163

ITP Student Workbook – V2.3


ITP Student Guide
Page 106 of 163

ITP Student Workbook – V2.3


ITP Student Guide
5.5 Private Study Tasks
Task 1

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:

1 try: “Congratulations: right first time. You win a car.”

2 tries: “Congratulations: right second time. You win a notebook.”

3 tries: “That took 3 tries. Have another go for free.”

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

ITP Student Workbook – V2.3


ITP Student Guide
Modify the program above so that it asks the user to enter in the values for x, y and z. The
program should only accept values between 5 and 15 for x, between 0 and 4 for y, and
between 16 and 20 for z. Add in appropriate data/ input validation for accepting the user
input.

Page 108 of 163

ITP Student Workbook – V2.3


ITP Student Guide
Topic 6: Project Definition and Design

6.1 Learning Outcomes


On completion of this topic, you will be able to:

• Describe the Specification, Design, Implement, Test project development cycle


• Design a program based a project specification
• Implement a project based on a design
• Complete an Object Definition Sheet for simple programs
• Create pseudo code for procedures
• Understand the different types of test data: normal, extreme and exceptional
• Create a test plan with test data that includes all three types of test data
• Test a program using the test plan and fill in a test log to document the results

6.2 Notes to Teachers and Students


This topic introduces the concept of project definition and design. Concepts introduced in
Topic 6 include:

• The multiple stages of Software Development


• Project Specifications
• Program Design
• Program Implementation based on a Design
• Object Definition Sheets
• Pseudo code
• Test plans
• Test data types
• Test logs

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

Laboratory Sessions: 4 hours

Private Study: 4 hours 15 minutes

Page 109 of 163

ITP Student Workbook – V2.3


ITP Student Guide
6.4 Student Manual
We are going to learn some of the fundamentals of project definition and design. This section
covers the software development stages. For the design stage, it covers project specifications,
storyboards and object definition sheets. For the implementation stage it covers how to
translate the design into program code. For the testing stage it covers test data types, test
plans and test logs.

6.4.1 Stages of Software Development


There are various different Software Development Life Cycle models, each of which have their
strengths and weaknesses. As we are writing fairly small programs, most of these are more
detailed than we need. However, even small programs benefit from planning and design. The
stages are:

• Project Specification

• Design

• Implementation

• Testing

Let’s look at each of these in turn.

6.4.2 Project Specification


Project Specification is the process of being sure that we have understood the project brief
before going ahead with writing the code. This involves researching the task, asking additional
questions if needed, and re-writing the requirements in our own words.

The output of this stage is a specification document which lists the features the program must
have.

6.4.2.1 Project Specification Example


Consider Private Study Task 5 from Topic 4. The project brief was as follows:

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

The following options should be supported:

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

ITP Student Workbook – V2.3


ITP Student Guide
Memory (One of) – 2GB DDR3 1333MHz, 4GB DDR3 2000MHz, 4GB DDR4
3000MHz, 8GB DDR4 3400MHz

Hard Drive (One of) – 1TB, 2TB, 4TB, 6TB, 8TB

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.

Shonky Computers Program 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.

9. The program must display a price for each component.

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

ITP Student Workbook – V2.3


ITP Student Guide
11. The program must display a list of the components selected by the user.

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.

6.4.3.1 Logical Design Example


Before we can think about how to design the GUI, we need to think about what components
we need to use, what properties we will need to change from the default settings, and what
procedures we will need to write.

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:

Page 112 of 163

ITP Student Workbook – V2.3


ITP Student Guide
OBJECT DEFINITION SHEET

Non Default Properties at Design Time


Event procedures that have to be written
Obj. Ref. Object Type Property Value Event Procedure
1 Form Name frmShonkyComputers Form_Load ()
Text Shonky Computers
Inc
2 Button Name cmdSubmit cmdSubmit_Click ()
Text Submit Order
3 Label Name Label1 None
Text CPUs:
4 ComboBox Name cboCPU None
Items Intel Pentium G4400,
Intel i3 6100, Intel
Core i5 4430, Intel
Core i7 4790, AMD
A4 6300, AMD A6
7400K, AMD FX
8350
5 Label Name Label2 None
Text Memory:
6 ComboBox Name cboMemory None
Items 2GB DDR3
1333MHz, 4GB
DDR3 2000MHz,
4GB DDR4
3000MHz, 8GB
DDR4 3400MHz
7 Label Name Label3 None
Text HDD:
8 ComboBox Name cboHDD None
Items 1TB, 2TB, 4TB, 6TB,
8TB
9 Label Name Label4 None
Text Software:
10 ComboBox Name cboOS None
Items None, Microsoft
Windows 10,
Microsoft Windows
8.1, Microsoft
Windows 7, Ubuntu
16.04.1 LTS
11 Label Name Label5 None
Text Graphics:
12 ComboBox Name cboGraphics None
Items Sapphire HD 6450,
Gigabyte Radeon RX
460, NVIDIA Quadro
K620

Page 113 of 163

ITP Student Workbook – V2.3


ITP Student Guide
13 Label Name Label6 None
Text Monitor:
14 ComboBox Name cboMonitor None
Items 17” 1080HP, 19”
1080HP, 23” Full HD,
24” Full HD, 27” Full
HD
15 GroupBox Name GroupBox1 None
Font MS Sans Serif, Bold,
10pt
16 CheckBox Name chkPortableHDD None
Text Portable HDD 1TB
17 CheckBox Name chkDVD None
Text DVD Drive
18 CheckBox Name chkInkjet None
Text Inkjet Printer
19 CheckBox Name chkScanner None
Text Scanner
20 CheckBox Name chkCardReader None
Text Card Reader
21 Label Name lblOrderDetails None
Text null

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.

Pseudocode for cmdSubmit_Click

Clear the lblOrderDetails text

Declare CPUchoice, MemChoice, HDDChoice, OSChoice, GraphicsChoice, MonitorChoice,


peripheralChoice as Strings

Declare total as real number and initialise to 0.0

To check which core components have been selected

If the CPU choice is Intel Pentium G4400 Then

set CPUChoice = Intel Pentium G4400

total = total + 40.0

Else If the CPU choice is Intel i3 6100 Then


Page 114 of 163

ITP Student Workbook – V2.3


ITP Student Guide
set CPUChoice = Intel i3 6100

total = total + 60.0

Else If the CPU choice is Intel Core i5 4430 Then

set CPUChoice = Intel Core i54430

total = total + 90.0

Else If the CPU choice is Intel i7 4790 Then

set CPUChoice = Intel i7 4790

total = total + 130.0

Else If the CPU choice is AMD A4 6300 Then

set CPUChoice = AMD A4 6300

total = total + 55.0

Else If the CPU choice is AMD A6 7400 Then

set CPUChoice = AMD A6 7400

total = total + 95.0

Else If the CPU choice is AMD FX 8530 Then

set CPUChoice = AMD FX 8530

total = total + 140.0

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.

If chkPortableHDD is selected Then

peripheralsChoice = peripheralsChoice + Portable External HDD 1TP

total = total + 65.0

End If

If chkDVD is selected Then

peripheralsChoice = peripheralsChoice + DVD Drive

total = total + 35.0

End If
Page 115 of 163

ITP Student Workbook – V2.3


ITP Student Guide
If chkInkjet is selected Then

peripheralsChoice = peripheralsChoice + Inkjet printer

total = total + 145.0

End If

If chkScanner is selected Then

peripheralsChoice = peripheralsChoice + Scanner

total = total + 125.0

End If

If chkCardReader is selected Then

peripheralsChoice = peripheralsChoice + Card Reader

total = total + 15.0

End If

To update the label output to show order summary and total cost

lblOutput Text = CPUChoice + MemChoice + HDDChoice + OSChoice + GraphicsChoice +


MonitorChoice + peripheralsChoice + “ The total cost is: £” + total

6.4.3.2 Physical Design Example


Once we have identified the components we need, we need to decide how to lay them out on
the Form. As we have listed them, we can make sure we have not forgotten anything.

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.

Page 116 of 163

ITP Student Workbook – V2.3


ITP Student Guide
6.4.4 Implemention
Implementation is just a computing term which means “write the code”. You should only do
this once you have finished Designing the program.

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:

• Normal data (valid input)

Page 117 of 163

ITP Student Workbook – V2.3


ITP Student Guide
• Extreme data (data on the boundary between valid and invalid)

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

6.4.5.1 Test Plans


A Test Plan should be drawn up before testing is carried out. A Test Plan is a list of the test
cases we will be using, and the expected result for each test case. The test cases are
numbered, and there are blank columns for the actual results and whether the test passed or
failed. If the expected result and actual result are the same, the program passed the test. If
the actual result differs from what was expected, the program failed the test. This would then
be investigated and the code modified to fix the issue.

An example Test Plan template is shown below:

TEST PLAN

Test Input Expected Output Actual Output Pass/ Fail


Number

Page 118 of 163

ITP Student Workbook – V2.3


ITP Student Guide
For the Shonky Computers example, we might include the following tests:

Test Input Expected Actual Output Pass/ Fail


Number Output

1 cboCPU.SelectedItem = Total is increased


AMD A6 7400 by £95

AMD A6 7400 is
added to the
order summary
list

2 cboMemory.SelectedITem Total is increased


= 4GB DDR4 3000MHz by £55

4GB DDR4
3000MHz is
added to the
order summary
list

3 cboHDD.SelectedItem = Total is increased


1TB by £20

1TB is added to
the order
summary list

4 cboOS.SelectedItem = Total remains the


None same

None is added to
the order
summary list

5 cboGraphics.SelectedItem Total is increased


= NVIDIA Quadro K620 by £130

NVIDIA Quadro
K620 is added to
the order
summary list

6 cboMonitor.SelectedItem Total is increased


= 24 inch Full HD by £130

24 inch Full HD
is added to the
order summary
list

Page 119 of 163

ITP Student Workbook – V2.3


ITP Student Guide
7 cboOS.SelectedItem = null Message
[this means nothing was displayed saying
selected] “You must
choose an
operating
system.”

8 cboGraphics.SelectedItem Message
= null displayed saying
“You must
choose a graphics
card.”

9 chkPortableHDD.Checked Total is increased


= True by £65

Portable External
HDD 1TB is
added to the
order summary
list

10 chkDVD.Checked = False Total stays the


same

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:

Test Input Expected Actual Output Pass/ Fail


Number Output

1 cboCPU.SelectedItem = Total is increased Total is increased Pass


AMD A6 7400 by £95 by £95

AMD A6 7400 is AMD A6 7400 is


added to the added to the order
order summary summary list
list

2 cboMemory.SelectedITem Total is increased Total is increased Pass


= 4GB DDR4 3000MHz by £55 by £55

Page 120 of 163

ITP Student Workbook – V2.3


ITP Student Guide
4GB DDR4 4GB DDR4
3000MHz is 3000MHz is
added to the added to the order
order summary summary list
list

3 cboHDD.SelectedItem = Total is increased Total is increased Pass


1TB by £20 by £20

1TB is added to 1TB is added to


the order the order
summary list summary list

4 cboOS.SelectedItem = Total remains the Total remains the Pass


None same same

None is added to None is added to


the order the order
summary list summary list

5 cboGraphics.SelectedItem Total is increased Total is increased Pass


= NVIDIA Quadro K620 by £130 by £130

NVIDIA Quadro NVIDIA Quadro


K620 is added to K620 is added to
the order the order
summary list summary list

6 cboMonitor.SelectedItem Total is increased Total is increased Pass


= 24 inch Full HD by £130 by £130

24 inch Full HD 24 inch Full HD


is added to the is added to the
order summary order summary
list list

7 cboOS.SelectedItem = null Message Nothing happens Fail


[this means nothing was displayed saying
selected] “You must
choose an
operating
system.”

8 cboGraphics.SelectedItem Message Nothing happens Fail


= null displayed saying
“You must
choose a graphics
card.”

9 chkPortableHDD.Checked Total is increased Total is increased Pass


= True by £65 by £65

Portable External Portable External


HDD 1TB is HDD 1TB is
Page 121 of 163

ITP Student Workbook – V2.3


ITP Student Guide
added to the added to the
order summary order summary
list list

10 chkDVD.Checked = False Total stays the Total stays the Pass


same same

Order summary Order summary


list is unchanged list is unchanged

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:

6.4.6 In Class Exercise


Given the following project brief, create the Specification, Design (layout diagram, Object
Definition Sheet and Pseudo code), Implementation (the actual Visual Studio Program), and
Test Plan. Once the program is completed, test the program and fill in the Test Log. Modify
your program as needed if any tests do not produce the expected results.

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

ITP Student Workbook – V2.3


ITP Student Guide
3: No prize

4: A pencil

5: A pair of shoelaces

6: An activity tracker watch

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.

6.4.7 Topic Summary


In this chapter we looked again at the concept of Project Definition and Design. We looked at
the four stages of Software Development:

• Project Specifications

• Program Design

o Layout Diagrams

o Object Definition Sheets

o Pseudo code

• Implementation

• Testing

o Test data types

o Test plans

o Test logs

Page 123 of 163

ITP Student Workbook – V2.3


ITP Student Guide
6.5 Private Study Task
Given the following project brief, create the Specification, Design (layout diagram, Object
Definition Sheet and Pseudo code), Implementation (the actual Visual Studio Program), and
Test Plan. Once the program is completed, test the program and fill in the Test Log. Modify
your program as needed if any tests do not produce the expected results.

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

Page 124 of 163

ITP Student Workbook – V2.3


ITP Student Guide
Topic 7: Case Study: Sample Mid-Course Assignment

7.1 Learning Outcomes


On completion of this topic, you will be able to:

Understand what you need to know for the final assignment.


Understand what you need to do for the final assignment.

7.2 Notes to Teachers and Students


This topic is a consolidation topic. It does not introduce any new concepts. What it does is
bring together many of the topics covered so far, in one larger case study. This is similar (but
not the same as) the task you will be required to do for the final assignment for this unit. The
actual assignment will depend on the asessment cycle for which you are registered.

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:

Laboratory Sessions: 3 hours

Private Study: 3 hours 15 minutes

Page 125 of 163

ITP Student Workbook – V2.3


ITP Student Guide
7.4 Student Manual
We are going to apply much of what we have learned so far to a large task which includes
planning, design, implementing and testing a program.

7.5 Case Study Task


Project Brief
Gourmet Express provide fresh food, recipes, nutrition plans and fitness plans direct to your
door. They offer a subscription model, with a range of different subscriptions available
depending on family size, main goals of the customer (e.g. healthy eating or sport-specific
nutrition requirements) and cater for various kinds of diets (e.g. gluten free and vegetarian).

All customers must choose which type of nutrition plan they wish to follow, from the following
list:

• Regular healthy eating plan

• Weightlifter eating plan

• Endurance trainer eating plan

• Glute free healthy eating plan

• Gluten free weightlifter eating plan

• Gluten free endurance trainer eating plan

• Vegetarian healthy eating plan

• Vegetarian weightlifter eating plan

• Vegetarian endurance trainer eating plan

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

Page 126 of 163

ITP Student Workbook – V2.3


ITP Student Guide
• 3

• 4

All meal plans come with recipes and nutrition plans.

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.

Customers may optionally select from the following additional services:

• Muscle building fitness plan

• Endurance building fitness plan

• Balanced fitness plan

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.

The costs for the eating plans are as follows:

• Regular healthy eating plan: £50 pcm for each adult, , £35 pcm for each child

• Weightlifter eating plan: £80 pcm for each adult

• Endurance trainer eating plan: £70 pcm for each adult

• 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 weightlifter eating plan: £80 pcm for each adult

• Vegetarian endurance trainer eating plan: £70 pcm for each adult

The costs for the fitness plans are as follows:

• Muscle building fitness plan: £50 pcm

Page 127 of 163

ITP Student Workbook – V2.3


ITP Student Guide
• Endurance building fitness plan: £40 pcm

• Balanced fitness plan: £45 pcm

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.

To do this, you must do the following:

1 Create a Program Specification document

2 Create Layout Diagram(s)

3 Complete an Object Definition Sheet

4 Produce Pseudocode for the program functionality

5 Implement the program

6 Design a Test Plan for the program

7 Complete a Test Log for the program

An Object Definition Sheet Template and a Test Plan Template are provided below

Page 128 of 163

ITP Student Workbook – V2.3


ITP Student Guide
OBJECT DEFINITION SHEET TEMPLATE

Non Default Properties at Design Time


Event procedures that have to be written
Obj. Ref. Object Type Property Value Event Procedure

TEST PLAN TEMPLATE

Page 129 of 163

ITP Student Workbook – V2.3


ITP Student Guide
Test Input Expected Output Actual Output Pass/ Fail
Number

10

11

12

13

14

15

16

Page 130 of 163

ITP Student Workbook – V2.3


ITP Student Guide
Topic 8: Introduction to Arrays

8.1 Learning Outcomes


On completion of this topic, you will be able to:

• Understand the concept of arrays


• Make use of arrays to hold collections of data
• Manipulate arrays using sequential statements
• Step over arrays making use of fixed loops
• Perform calculations making use of arrays
• Write simple programs which make use of arrays

8.2 Notes to Teachers and Students


This topic introduces the concept of arrays. These are data structures that allow collections of
similar data to be stored in an easily manipulated form.

Concepts introduced in Topic 8 include:

• Scale problems associated with variables


• The structure and concept of an array
• Array manipulation
• Arrays and iteration

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

Laboratory Sessions: 5 hours

Private Study: 5 hours 15 minutes

Page 131 of 163

ITP Student Workbook – V2.3


ITP Student Guide
8.4 Student Manual
In this topic we are going to learn about the power of arrays, and how they can be used to
solve a number of programming problems we may not yet be aware we have. We’ll look at
how arrays simplify our programs, and how they make it possible for us to accomplish tasks
that are currently beyond our abilities.

8.4.1 Introduction to Arrays


The variables we have used so far are individual units of data. They are useful, as we have
seen, but they all live an isolated life. They are unconnected to each other, and have no way
of being grouped together into collections of ‘like’ information. In real life we must often deal
with clumps of related data. It’s very useful for us to be able to refer to collections of data with
single lines of code. We do this with the use of an array.

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?

That won’t be fun to code at all, so we need something else.

8.4.2 How Arrays Work


Arrays give us a syntactic way of grouping together sets of like data. In many ways, they
work identically to other variables, except they have an extra set of things we can do to them.
We give them a single name, which is the variable name of the collection. This collection has
a number of compartments, into which are slotted elements. Each compartment has a
numerical address, called an index. We use the index to get the element in that compartment
of the array.

Index Element

0 15

1 90

2 28

Page 132 of 163

ITP Student Workbook – V2.3


ITP Student Guide
3 11

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.

We create an array in Visual Basic like so:

Dim ages(5) As Integer

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!

Let’s look at an example of this in practice.

8.4.3 A worked example


Step 1

Create the user interface so it resembles the screen shot below:

Page 133 of 163

ITP Student Workbook – V2.3


ITP Student Guide
txtAge cmdAdd

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:

Public Class frmAges

Dim age1 As Integer


Dim age2 As Integer
Dim age3 As Integer
Dim age4 As Integer
Dim age5 As Integer

Private Sub cmdAdd_Click(sender As Object, e As EventArgs) Handles cmdAdd.Click


Dim current As Integer
Dim ave As Integer
Dim num As Integer

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

ITP Student Workbook – V2.3


ITP Student Guide
lblAverage.Text = "The average age is " & ave
lblNum.Text = "There are " & num & " age stored"

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:

Public Class frmAges

Dim ages(5) As Integer


Dim counter As Integer

Private Sub cmdAdd_Click(sender As Object, e As EventArgs) Handles cmdAdd.Click


Dim current As Integer
Dim ave As Integer

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

ave = ave / counter

And when we put all of that together:

Public Class frmAges

Dim ages(5) As Integer


Dim counter As Integer

Private Sub cmdAdd_Click(sender As Object, e As EventArgs) Handles cmdAdd.Click


Dim current As Integer
Dim ave As Integer

current = txtAge.Text

ages(counter) = current

Page 135 of 163

ITP Student Workbook – V2.3


ITP Student Guide
counter = counter + 1
ave = 0

For i = 0 To counter
ave = ave + ages(i)
Next

ave = ave / counter

lblAverage.Text = "The average age is " & ave


lblNum.Text = "There are " & counter & " ages stored"

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:

Dim ages(5) As Integer

Into this:

Dim ages(500) As Integer

And that’s the program done.

8.4.4 Calculating from Arrays


The link between for loops and arrays is so powerful that it now lets us do things so much
easier than before. Let’s look at how we might expand our program to find the largest and
smallest number in our array.

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

Page 136 of 163

ITP Student Workbook – V2.3


ITP Student Guide
Our next task is to add in the code to find the largest number. We’ve already got most of
this, because it’s a variation on the loop we’ve already seen. We need a variable that will
keep track of the largest number we’ve found so far (we’ll call it currentLargest) and then
compare that against each element in the array. If we find one that’s bigger, we set
currentLargest to be that instead:

currentLargest = ages(0)

For i = 0 To counter
If ages(i) > currentLargest Then
currentLargest = ages(i)
End If

Next

And then we just need to output it:

lblLargest.Text = "Largest: " & currentLargest

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

Page 137 of 163

ITP Student Workbook – V2.3


ITP Student Guide
5 0

When we add an age at position one, we put in the value:

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.

It’s an easy fix though. We just change our loops a little:

For i = 0 To counter - 1
If ages(i) < currentSmallest Then
currentSmallest = ages(i)
End If

Next

That solves our problem. We end up with the following program:

Public Class frmAges

Dim ages(5) As Integer


Dim counter As Integer

Private Sub cmdAdd_Click(sender As Object, e As EventArgs) Handles cmdAdd.Click


Dim current As Integer
Dim ave As Integer
Dim currentLargest As Integer
Dim currentSmallest As Integer

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

ITP Student Workbook – V2.3


ITP Student Guide
Next

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

ave = ave / ages.Length

lblAverage.Text = "The average age is " & ave


lblNum.Text = "There are " & counter & " ages stored"
lblLargest.Text = "Largest: " & currentLargest
lblSmallest.Text = "Smallest: " & currentSmallest

End Sub
End Class

8.4.5 Sorting Arrays


Arrays are useful as they are, but sometimes we want to be able to put them in order. That’s
very easy to do – we can use the following:

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.

8.4.6 Topic Summary


In this chapter we looked at the power of arrays, and how they make programs much easier
to write. While they do add a certain complexity, the benefits far outweigh the downsides.
There is a hard limit to how effective programs can be before you incorporate arrays. Once
they are mastered you’ll find yourself able to accomplish programming tasks you may never
have previously considered possible.

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

ITP Student Workbook – V2.3


ITP Student Guide
counter variable you use for the loop is just the compartment number – you can treat that like
any other variable.

Page 140 of 163

ITP Student Workbook – V2.3


ITP Student Guide
8.5 Private Study Tasks
Task 1

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.

Page 141 of 163

ITP Student Workbook – V2.3


ITP Student Guide
Topic 9: Introduction to Methods

9.1 Learning Outcomes


On completion of this topic, you will be able to:

• Understand the concept of methods


• Make use of methods to modularise computer code
• Manipulate data with the use of functions and subroutines
• Pass parameters into methods
• Make use of method return values
• Write simple programs which make use of functions

9.2 Notes to Teachers and Students


This topic introduces the concept of methods. These are programming structures that can be
used to simplify code through modularisation. This is an important technique for ensuring
programs are maintainable and generalisable.

Concepts introduced in Topic 9 include:

• 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

Laboratory Sessions: 5 hours

Private Study: 5 hours 15 minutes

Page 142 of 163

ITP Student Workbook – V2.3


ITP Student Guide
9.4 Student Manual
In this topic we are going to learn about methods, and how they can be used to generalise
programs. We’ve been using these all along – every event handler we write is a method.
We’re not stuck with what Visual Basic will auto-generate though – we can use these
throughout the entirety of our programs to good effect. In this chapter we look at subroutines
and functions – these are the two ways Visual Basic gives us to handle methods. The word
method is an object oriented term that encompasses both of these ways of creating modular
units of functionality.

9.4.1 Introduction to Methods


Up until now we’ve been making use of subroutines to handle events in Visual Basic. These
allow us to keep the code that is associated with a particular user action in a single place,
without us having to worry about programs becoming large and unmanageable. In the early
days of programming, source code was often comprised of thousands and thousands of lines
of code where every possible condition had to be checked and rechecked to see if it was
relevant. This code was extremely difficult to write, even more difficult to change, and was all
but impossible to reuse in other programs. These kind of programs are known as monolithic
programs.

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.

Consider the following program:

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:

Private Sub cmdCalculate_Click(sender As Object, e As EventArgs) Handles


cmdCalculate.Click
Dim sum As Integer

sum = txtNum1.Text + txtNum2.Text


Page 143 of 163

ITP Student Workbook – V2.3


ITP Student Guide
If sum Mod 2 = 0 Then
lblOutput.Text = "The sum of these numbers is even"
Else
lblOutput.Text = "The sum of these numbers is odd"
End If

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.

Private Sub cmdCalculate_Click(sender As Object, e As EventArgs) Handles


cmdCalculate.Click
Dim sum As Integer

sum = txtNum1.Text + txtNum2.Text

If sum Mod 2 = 0 Then


lblOutput.Text = "The sum of these numbers is even. " & vbCrLf
Else
lblOutput.Text = "The sum of these numbers is odd. " & vbCrLf
End If

If txtNum1.Text Mod 2 = 0 Then


lblOutput.Text = lblOutput.Text & "The first number is even. " & vbCrLf
Else
lblOutput.Text = lblOutput.Text & "The first number is odd. " & vbCrLf
End If

If txtNum2.Text Mod 2 = 0 Then


lblOutput.Text = lblOutput.Text & "The second number is even. " & vbCrLf
Else
lblOutput.Text = lblOutput.Text & "The second number is odd. " & vbCrLf
End If

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.

Page 144 of 163

ITP Student Workbook – V2.3


ITP Student Guide
What is not so familiar however is the stuff that we’ve ignored up until this point - the things
that drive the power of a subroutine:

Private Sub cmdCalculate_Click(sender As Object, e As EventArgs) Handles


cmdCalculate.Click

End Sub

Subroutines are made up of three parts - a name (cmdCalculate_Click) a signature, and a


handler declaration. We ignore the last bit – it’s not important to us in this course, but you’ll
find out more about it in more advanced programming topics. The signature is the type and
order of parameters that go into the subroutine – in this case, a sender which is of type
object, and e which is of type EventArgs. These are complex data types that we don’t cover
in this course, but they could just as easily be strings, integers and Boolean variables. We’ll
see that in action shortly, The parameters are pieces of information that are sent into the
subroutine to give it all the information it needs to know in order to do its job. It’s important to
note here that the name we give a parameter is not necessarily the same as a variable we
pass into the subroutine elsewhere in the program. It has that name only within the body of
the subroutine.

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:

Private Sub ShowMessage(msg As String)


MsgBox(msg)

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:

Private Sub doCalculations(num As Integer, startText As String)


Dim str As String

If num Mod 2 = 0 Then


str = startText & " is even"
If num Mod 4 = 0 Then
str = str & " and cleanly divisible by four"
Else
str = str & " and not cleanly divisible by four"
End If

Else
str = startText & " is odd"

Page 145 of 163

ITP Student Workbook – V2.3


ITP Student Guide
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

lblOutput.Text = lblOutput.Text & str & vbCrLf

End Sub

When we want to trigger this, then our calculate subroutines becomes much simpler because
we only have the key code elements once:

Private Sub cmdCalculate_Click(sender As Object, e As EventArgs) Handles


cmdCalculate.Click
Dim sum As Integer

sum = txtNum1.Text + txtNum2.Text


lblOutput.Text = ""

doCalculations(sum, "The sum of these numbers")


doCalculations(txtNum1.Text, "The first number")
doCalculations(txtNum2.Text, "The first number")

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.

9.4.3 Functions and Parameters


Functions are stubs of functionality that exist independently until they are executed, just like
subroutines They are used to substantially improve the modularity and maintainability of code.
The only difference between subroutines and functions is that functions not only take in
information, they also provide answers.

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:

Private Function checkIsEven(num As Integer) As Boolean


If num Mod 2 = 0 Then
Return True
Else
Return False
End If

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 –

Page 146 of 163

ITP Student Workbook – V2.3


ITP Student Guide
essentially they become local variables within that function. We saw these in our subroutine
above too. The return type is the type of information that comes out of a 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:

Dim numState As Boolean

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:

Private Function checkIsEven(num As Integer) As Boolean


If num Mod 2 = 0 Then
Return True
Else
Return False
End If

End Function

Private Sub doCalculations(num As Integer, startText As String)


Dim str As String
Dim numState As Boolean

numState = checkIsEven(num)

If numState = True Then


str = startText & " is even"
If num Mod 4 = 0 Then
str = str & " and cleanly divisible by four"
Else
str = str & " and not cleanly divisible by four"
End If

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

lblOutput.Text = lblOutput.Text & str & vbCrLf


Page 147 of 163

ITP Student Workbook – V2.3


ITP Student Guide
End Sub

And then we can add new functions to generalise it even further still:

Private Function addTextToString(str As String, newstr As String) As String


str = str & newstr

Return str
End Function

Private Sub doCalculations(num As Integer, startText As String)


Dim str As String
Dim numState As Boolean

str = lblOutput.Text + startText


numState = checkIsEven(num)

If numState = True Then


str = addTextToString(str, " is even")
If num Mod 4 = 0 Then
str = addTextToString(str, " and cleanly divisible by four")
Else
str = addTextToString(str, " and not cleanly divisible by four")
End If

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

str = addTextToString(str, vbCrLf)

lblOutput.Text = str

End Sub

And then even further still!

Private Function checkIsCleanlyDivisible(num As Integer, div As Integer) As


Boolean
If num Mod div = 0 Then
Return True
Else
Return False
End If

End Function

Private Sub doCalculations(num As Integer, startText As String)


Dim str As String
Dim numState As Boolean

str = lblOutput.Text + startText


numState = checkIsCleanlyDivisible(num, 2)

If numState = True Then

Page 148 of 163

ITP Student Workbook – V2.3


ITP Student Guide
str = addTextToString(str, " is even")
If checkIsCleanlyDivisible(num, 4) Then
str = addTextToString(str, " and cleanly divisible by four")
Else
str = addTextToString(str, " and not cleanly divisible by four")
End If

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

str = addTextToString(str, vbCrLf)

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:

Private Function checkIsCleanlyDivisible(num As Integer, div As Integer) As


Boolean
If num < 0 Then
Return False
End If

If num Mod div = 0 Then


Return True
Else
Return False
End If

End Function

And when you change it in this one place, it’s changed for every single part of the program!
That’s powerful.

Page 149 of 163

ITP Student Workbook – V2.3


ITP Student Guide
9.5 Private Study Tasks
For each of these tasks, make use of the number program that has been constructed as part
of this chapter.

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.

Page 150 of 163

ITP Student Workbook – V2.3


ITP Student Guide
Topic 10: File IO

10.1 Learning Outcomes


On completion of this topic, you will be able to:

• Understand the concept of file IO


• Make use of methods to read and write sequential files
• Manipulate files with the use of the .NET File IO routines
• Make use of the platform UI for file dialogs
• Handle file errors with conditional logic

10.2 Notes to Teachers and Students


This topic introduces the concept of file Input and Output, or File IO. These are the routines
that are used to save and read data from computer programs into persistent files. These come
in two varieties – sequential files and random access files. We will not be looking at the latter
type in this module.

Concepts introduced in Topic 10 include:

• 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

Laboratory Sessions: 5 hours

Private Study: 5 hours 15 minutes

Page 151 of 163

ITP Student Workbook – V2.3


ITP Student Guide
10.4 Student Manual
In this topic we are going to learn about file IO, and how it can be used to implement data
persistence in a computer program. Up until this point, we have largely been playing around
with Visual Basic – we have covered a large number of the fundamental building blocks, but
we could not have written the vast majority of real world applications simply because we had
no way of storing data between executioins. We are going to address that limitation in this
topic.

10.4.1 An Introduction to File IO


To begin with, let’s look at how we write to a file from VB .NET. We refer to this as stream
based IO because data gets written in a stream – from start to finish. A stream is written
sequentially from the first piece of data to the last piece of data. The process of writing a
stream of data to a file follows a simple structure:

1. We open a connection to a file.


2. We write some data to the file
3. We close the file.

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

Public Class frmFileIO

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:

Page 152 of 163

ITP Student Workbook – V2.3


ITP Student Guide
txtData

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.

10.4.2 Saving Data


Before we can do anything, we need to declare the variable that will hold our StreamWriter.
We’ll do this in the method stub for the save button:

Private Sub cmdSave_Click(sender As Object, e As EventArgs) Handles cmdSave.Click


Dim myWriter As StreamWriter

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:

Private Sub cmdSave_Click(sender As Object, e As EventArgs) Handles cmdSave.Click

Page 153 of 163

ITP Student Workbook – V2.3


ITP Student Guide
Dim myWriter As StreamWriter

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:

Private Sub cmdSave_Click(sender As Object, e As EventArgs) Handles cmdSave.Click


Dim myWriter As StreamWriter

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.

Private Sub cmdSave_Click(sender As Object, e As EventArgs) Handles cmdSave.Click


Dim myWriter As StreamWriter

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.

10.4.3 Reading from a File


Reading from files is a very similar procedure, which involves the same steps, although it
requires a selection of different objects. We use the File class as before, but instead of a
StreamWriter we are going to make use of an object called a StreamReader, and instead of
WriteLine we use a method called ReadToEnd:

Private Sub cmdOpen_Click(sender As Object, e As EventArgs) Handles cmdOpen.Click


Dim myReader As StreamReader

Page 154 of 163

ITP Student Workbook – V2.3


ITP Student Guide
myReader = File.OpenText("example.txt")
txtData.Text = myReader.ReadToEnd
myReader.Close()

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:

Private Sub cmdOpen_Click(sender As Object, e As EventArgs) Handles cmdOpen.Click


Dim myReader As StreamReader

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.

10.4.4 File Choosers


There are legitimate reasons why we might want to hard-code a file name into an application
– we might want to be keeping an internal log of errors, for example. For most systems
though we’ll want to allow the user to give us filenames and use those instead. You wouldn’t
be happy if you bought a word-processor that could only handle a single file called
example.txt.

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:

Page 155 of 163

ITP Student Workbook – V2.3


ITP Student Guide
Dim dialog As OpenFileDialog

dialog = New OpenFileDialog()

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

If selected = True Then


filename = dialog.FileName

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:

Private Sub cmdOpen_Click(sender As Object, e As EventArgs) Handles cmdOpen.Click


Dim myReader As StreamReader
Dim dialog As OpenFileDialog
Dim selected As Boolean
Dim filename As String
dialog = New OpenFileDialog()

selected = dialog.ShowDialog

If selected = True Then


filename = dialog.FileName

If File.Exists(filename) Then
myReader = File.OpenText(filename)
txtData.Text = myReader.ReadToEnd
myReader.Close()
End If
Else
MsgBox("No such file")

End If End Sub

We can do a very similar thing for saving a file, except we make use of the SaveFileDialog
class instead of OpenFileDialog:

Private Sub cmdSave_Click(sender As Object, e As EventArgs) Handles cmdSave.Click


Dim myWriter As StreamWriter
Page 156 of 163

ITP Student Workbook – V2.3


ITP Student Guide
Dim dialog As SaveFileDialog
Dim selected As Boolean
Dim filename As String

dialog = New SaveFileDialog()

selected = dialog.ShowDialog

If selected = True Then


filename = dialog.FileName

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.

Page 157 of 163

ITP Student Workbook – V2.3


ITP Student Guide
10.5 Private Study Tasks
For each of these tasks, make use of the number program that has been constructed as part
of this chapter.

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.

Page 158 of 163

ITP Student Workbook – V2.3


ITP Student Guide
Topic 11: Case Study: Creating a GUI Program that uses
Arrays, Procedures and File IO

11.1 Learning Outcomes


On completion of this topic, you will be able to:

Understand what you need to know for the final assignment.


Understand what you need to do for the final assignment.

11.2 Notes to Teachers and Students


This topic is a consolidation topic. It does not introduce any new concepts. What it does is
bring together many of the topics covered so far, in one larger case study. This is similar (but
not the same as) the task you will be required to do for the final assignment, The actual
assignment will depend on the asessment cycle for which you are registered.

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:

Laboratory Sessions: 3 hours

Private Study: 3 hours 30 minutes

Page 159 of 163

ITP Student Workbook – V2.3


ITP Student Guide
11.4 Student Manual
We are going to apply much of what we have learned so far to a large task which includes
planning, design, implementing and testing a program.

11.5 Case Study Task


Project Brief
Warrior Fitness gym is looking to identify individuals to enter and sponsor for an Iron Man
triathlon in Seattle. They have a number of great athletes who attend their training facilities,
and want to identify which members have the best potential to do well in the Iron Man triathlon.

The triathlon involves the following three events:

• A 2.4 mile swim

• A 112 mile bicycle ride

• A marathon (26.22 mile) run

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.

Event Minimum time


2.4 mile swim 40 minutes
112 mile bicycle ride 260 minutes
26.22 mile run 125 minutes

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.

To do this, you must do the following:

8 Create a Program Specification document

9 Create Layout Diagram(s)


Page 160 of 163

ITP Student Workbook – V2.3


ITP Student Guide
10 Complete an Object Definition Sheet

11 Produce Pseudocode for the program functionality

12 Implement the program

13 Design a Test Plan for the program

14 Complete a Test Log for the program

An Object Definition Sheet Template and a Test Plan Template are provided below

Page 161 of 163

ITP Student Workbook – V2.3


ITP Student Guide
OBJECT DEFINITION SHEET TEMPLATE

Non Default Properties at Design Time


Event procedures that have to be written
Obj. Ref. Object Type Property Value Event Procedure

TEST PLAN TEMPLATE

Page 162 of 163

ITP Student Workbook – V2.3


ITP Student Guide
Test Input Expected Output Actual Output Pass/ Fail
Number

10

11

12

13

14

15

16

Page 163 of 163

ITP Student Workbook – V2.3


ITP Student Guide

You might also like