BTEC First in Information and Creative Technology: how programs work, how to design them, and how to develop, test and review your own program in Visual Basic.
Read the lesson, study the diagrams, watch the video, then open the matching workbook section.
Learning aim A Unit 12 · A · Why is software used?
Why is software used?
By the end you can: explain what software is, the main categories of software, and why organisations and people develop programs.
A software program is a set of instructions that tells a computer’s processor (CPU) what to do, step by step. Hardware cannot do anything useful without software. Programs turn inputs into useful outputs, quickly, accurately and without getting tired.
Every program takes inputs, processes them and produces outputs.
Three categories of software
Category
What it does
Examples
Application software
lets users do tasks
word processor, spreadsheet, web browser, game
System software
runs the computer itself
operating system, device drivers, utilities
Programming software
used to create other programs
IDEs such as Visual Studio, compilers, debuggers
Uses of software programs
Why we develop programs
Real examples
Gaming and entertainment
computer games, CGI special effects in films, virtual worlds, social media apps
Increasing productivity
automating factory processes, stock control that reorders goods automatically
Information storage and management
booking systems, customer databases, school registers
Repetitive or dangerous tasks
robot arms on a car production line, robots that defuse bombs or work inside nuclear plants
Solving complex problems
weather forecasting, route planning, medical scans
In the real world: a cinema booking app
Inputs: the film, time and number of seats chosen. Processing: check which seats are free, calculate the price and discounts. Outputs: the ticket and a confirmation email. Storage: the booking is saved so nobody else can buy the same seat.
Key terms
Software program
a set of instructions a computer follows.
Input
data that goes into a program.
Process
what the program does with the data.
Output
the result the program produces.
Think it through
Give one reason a factory uses software to control robots.
Robots can repeat the same task accurately for hours, and can do dangerous jobs, which increases productivity and safety.
Name the inputs and outputs of a supermarket self-checkout.
Learning aim A Unit 12 · A · Programming languages
Programming languages and compiling
By the end you can: describe high-level and low-level languages, procedural and event-driven languages, and why programs are compiled.
The only language a CPU understands is machine code: binary 1s and 0s. Every other language has to be translated first.
Low-level and high-level languages
Low-level languages
High-level languages
Looks like
machine code or short codes (assembly)
English words and maths, e.g. If score > 50 Then
Advantages
very fast; direct control of hardware
easy to read, write and fix; works on different computers
Disadvantages
hard to write and debug; tied to one type of CPU
must be translated; usually a little slower
Procedural and event-driven languages
Type
How the program runs
Languages
Procedural
instructions run in order from start to end, using procedures and functions
C, Pascal, COBOL, Python
Event-driven
the program waits for events (a click, a key press, a timer) and runs the code for that event
Visual Basic, VB.NET, VBA, Visual C++
A compiler checks, optimises and translates the whole program into machine code before it runs.
Compilers and interpreters
Translator
How it works
Compiler
translates the whole program into machine code before it runs; creates an executable; runs fast; reports all errors after compiling
Interpreter
translates and runs one line at a time; good for testing; stops at the first error; the interpreter is needed every time
Program design methods include top-down design (break the problem into smaller parts), flowcharts, pseudocode and screen designs. You will use all of these in learning aim B.
Key terms
Machine code
binary instructions the CPU can run directly.
Source code
the program written by the programmer in a high-level language.
Compiler
translates all the source code into machine code before it runs.
Event-driven
a program that responds to user actions such as clicks.
Think it through
Why do programmers usually write in high-level languages?
They are easier to read, write and debug, so programs are built faster and with fewer mistakes, and they can run on different computers.
Why is Visual Basic called an event-driven language?
Its code runs in response to events, such as the user clicking a button or changing a drop-down list.
Watch
Why we write in high-level languages and what machine code is.
Learning aim A Unit 12 · A · Characteristics of software programs
Constructs and techniques: the building blocks of programs
By the end you can: identify command words, subroutines, string handling, file handling, data structures and event handling in a program.
All programming languages are built from the same kinds of building blocks. When you look at someone else’s program (as in Assignment 1), find these and say what each one does.
Constructs and techniques
Construct / technique
What it is
Visual Basic example
Command words
reserved words that tell the computer what to do
Dim, If … Then, For … Next, MsgBox
Subroutines (procedures and functions)
a named block of code that does one job and can be reused
Private Sub CalculateTotal()
Basic string handling
working with text: join, cut, search, change case, length
name.ToUpper(), name.Length
Basic file handling
open, read, write and close files so data is kept after the program ends
IO.File.AppendAllText("bookings.txt", line)
Data structures
ways to organise lots of data, e.g. arrays and records
Dim scores(9) As Integer
Event handling
code that runs when something happens, e.g. a button click
Private Sub btnSave_Click(…) Handles btnSave.Click
Reading a program: an annotated example
' Program: cinema ticket price (event-driven)
Private Sub btnPrice_Click(sender As Object, e As EventArgs) Handles btnPrice.Click ' event handling
Const ADULT_PRICE As Decimal = 9.5D ' a constant
Dim age As Integer = CInt(txtAge.Text) ' input + data type
Dim price As Decimal
If age < 16 Then ' selection
price = ADULT_PRICE / 2
Else
price = ADULT_PRICE
End If
lblPrice.Text = "Price: " & price.ToString("C") ' output + string handling
End Sub
Comments (after the apostrophe) are ignored by the computer but explain the code to people.
Key terms
Construct
a building block of a language, e.g. a loop or IF.
Reserved word
a word with a special meaning in the language that cannot be used as a variable name.
Subroutine
a named section of code that performs one task.
Event
something that happens, such as a click, that the program reacts to.
Links to your assignment: 1A.1 / 2A.P1
For each program your teacher gives you, explain its purpose and identify the constructs and techniques it uses, like the annotated example above.
Think it through
Find two constructs in the cinema example and say what each does.
Selection (If … Else) chooses the child or adult price; a constant (ADULT_PRICE) stores a value that does not change; event handling runs the code when the button is clicked.
Why would a booking program need file handling?
So bookings are saved permanently and can be loaded again after the program closes.
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
Dim a As Integer = TextBox1.Text
Dim b As Integer = TextBox2.Text
Label1.Text = a * 1.2 + b * 1.2
End Sub
No comments, meaningless names, the 1.2 is repeated and unexplained, and typing a letter crashes it.
Improved: name the controls (txtPrice, btnTotal), use a constant VAT_RATE, add comments, and validate the inputs with Integer.TryParse so a wrong entry shows a friendly message instead of crashing.
Key terms
Maintainability
how easily code can be understood and changed later.
Robustness
how well a program copes with unexpected or extreme input.
Portability
how easily a program runs on different hardware or operating systems.
Usability
how easy a program is for its users.
Links to your assignment: 2A.M1 / 2A.D1
Comment on the quality of one program using these six measures, suggest improvements and draw a flowchart of the improved processing. For Distinction, discuss strengths and weaknesses in a balanced way.
Think it through
Why do comments improve maintainability?
They explain what the code does and why, so the original programmer or someone new can change it safely later.
A program crashes when a user types ‘ten’ instead of 10. Which quality measure is weak and how do you fix it?
Robustness: validate the input (e.g. Integer.TryParse) and show a helpful message instead of crashing.
Watch
How programmers make code robust and maintainable.
Watch and think:
Which quality measures does defensive programming improve?
Requirements, problem definition and design specification
By the end you can: describe the purpose and user requirements from a brief, write a problem definition statement and outline a design specification.
Your assignment brief describes a client and a problem. Before designing anything, show that you understand what the program is for and who will use it.
Understanding the brief
Part
Question it answers
Example: a leisure centre class booking program
Intended purpose
what is the program for?
to let reception staff book members onto fitness classes and calculate the cost
User requirements
what must it do for the users?
choose a class; enter member type; calculate price with discounts; save bookings; show today’s bookings
Problem definition statement
what is the problem now, and how will software help?
bookings are written on paper, prices are worked out by hand and mistakes are common; a program will speed this up and reduce errors
The design specification
Design specification
Meaning
Example
Scope
what the program will and will not include
bookings and prices; not online payment
Inputs
data entered by the user
member name, member type, class, number of sessions
Outputs
results shown or printed
price, confirmation message, list of bookings
Processing
the main tasks and calculations
look up class price; apply member discount; add to list; save to file
User interface
how users interact
one form with drop-down lists, text boxes and buttons
Constraints
limits on the project
must be written in Visual Basic; four weeks to develop; runs on reception PCs; no internet connection
Key terms
Brief
the client’s description of the problem and what they want.
User requirement
something the program must do for its users.
Problem definition statement
a short description of the current problem and how software will solve it.
Constraint
a limit, e.g. time, language, device or cost.
Links to your assignment: 1B.2 / 2B.P2
Describe the purpose and user requirements for the program in your brief. Use your own words, and do not copy the brief: show you understand it.
Think it through
What is the difference between the purpose and the user requirements?
The purpose is the overall aim of the program; the user requirements are the specific things it must do for its users.
Give two constraints that could affect a student’s program.
The programming language available (Visual Basic), the time before the deadline, the computers it must run on, or no access to a database.
Designing the solution: tasks, screens, navigation and alternatives
By the end you can: describe the main program tasks, design screen layouts and navigation, and compare alternative solutions.
Your proposed solution shows the client what the program will look like and how it will work, before any code is written.
Describing the main program tasks (input–process–output)
Main task
Inputs
Processing
Outputs
Calculate a booking price
member type, class, sessions
look up price × sessions; apply discount
price shown on the form
Save a booking
name, class, price
add a line to the bookings file
“Booking saved” message
Show today’s bookings
(none: button click)
read the file; filter today’s date
list of bookings
Label every control and say what type it is. A navigation diagram shows how screens link together.
Alternative solutions
Good designers consider more than one idea, then choose and justify the best. You can offer alternatives for the screen layout, navigation, algorithms, data structures or control structures.
Comparing alternatives (and justifying the choice)
Alternative 1: one form
Alternative 2: a form per task
Description
all inputs and buttons on one screen
separate screens for booking, list and settings, with a menu
Strengths
quick for busy staff; fewer clicks
less cluttered; easier to add features later
Weaknesses
can look crowded as features grow
more navigation; more code to write
Fits the requirements?
yes: reception needs speed
partly: more than the client needs now
Key terms
Screen layout
a labelled sketch of a form or screen.
Navigation diagram
a diagram showing how screens link together.
Prototype
an early version used to try out a design.
Alternative solution
a different way to meet the same requirements.
Links to your assignment: 2B.M2 / 2B.D2
Merit needs alternative solutions and a detailed design using a range of tools. Distinction needs you to justify your decisions: how each one meets the purpose and user requirements, and how constraints affected it.
Think it through
Why should screen layouts be shown to the client before coding?
The client can give feedback and spot problems early, when changes are quick and cheap.
Give one advantage of a drop-down list over a text box for ‘member type’.
Users can only choose valid options, so typing mistakes are impossible (built-in validation) and it is quicker.
Algorithms: pseudocode, flowcharts and trace tables
By the end you can: write algorithms as pseudocode and flowcharts, and check them with a trace table.
An algorithm is a set of step-by-step instructions to solve a problem. Designing the algorithm first means you solve the problem before worrying about the exact code.
Five shapes are enough to draw almost any program.A decision has exactly two exits, Yes and No. Follow the arrows with test values to check the flowchart works.
The same algorithm in pseudocode
INPUT age
IF age < 16 THEN
price ← 4.75
ELSE IF age >= 65 THEN
price ← 6.00
ELSE
price ← 9.50
END IF
OUTPUT price
Pseudocode is structured English: no exact syntax, but clear enough to turn into code.
Checking with a trace table
total ← 0
FOR count ← 1 TO 4
total ← total + count
NEXT count
OUTPUT total
A trace table records each variable as the algorithm runs (a ‘dry run’)
count
total
output
–
0
1
1
2
3
3
6
4
10
10
Key terms
Algorithm
step-by-step instructions to solve a problem.
Pseudocode
structured English used to plan code.
Flowchart
a diagram of an algorithm using standard symbols.
Trace table
a table used to follow the values of variables through an algorithm.
Links to your assignment: 2A.M1 / 2B.P3
Assignment 1 Merit asks for a flowchart of the improved program; your design needs algorithms as flowcharts and/or pseudocode.
Think it through
Using the flowchart, what price does a 70-year-old pay? A 16-year-old?
70: age ≥ 65, so £6.00. 16: not under 16 and not 65 or over, so £9.50.
Why must a decision box have two exits?
A decision is a Yes/No question, so the algorithm needs a path for each answer.
Learning aim B Unit 12 · B · Proposed solution · test plan · constraints
Data, validation, error handling, predefined code and test plans
By the end you can: plan data structures and storage, validation, error handling, predefined code and a test plan with test data.
Planning the data and checks
Design area
What to decide
Example
Data structures
variables, arrays or records to hold the data
array of 6 class names; record for a booking (name, class, price)
Data storage
how data is kept after the program closes
text file bookings.txt, one booking per line
Control structures
where you need selection and loops
IF for discounts; FOR loop to show all bookings
Data validation
checks that input is sensible before using it
sessions must be a whole number from 1 to 10
Error handling and reporting
what happens when something goes wrong
file missing → friendly message, not a crash
Common validation checks
Validation check
What it checks
Example
Presence
something has been entered
member name is not blank
Type
the right kind of data
sessions is a number
Range
within sensible limits
sessions from 1 to 10
Length
the right number of characters
membership number is 6 characters
Lookup / list
one of the allowed values
member type is Adult, Junior or Senior (drop-down)
Predefined code
Reusing code (from the language’s libraries, your teacher, or the internet) saves time, but you must have permission and list the source in your design and in a comment in the code.
A predefined code table
Predefined function or snippet
Purpose
Source
Integer.TryParse
safely convert text to a whole number
built into VB.NET (Microsoft documentation)
IO.File.AppendAllText
add a line to a text file
built into VB.NET
Test plan with test data
Plan the tests now; fill in actual results later
No.
Test
Test data
Type
Expected result
1
price for an adult, 2 sessions
Adult, Yoga, 2
normal
£12.00
2
highest allowed sessions
10
boundary
accepted
3
too many sessions
11
erroneous
message: “Enter 1 to 10 sessions”
4
letters in sessions
abc
erroneous
message, no crash
5
blank name
(empty)
erroneous
message: “Enter the member’s name”
Key terms
Validation
automatic checks that input is sensible.
Normal / boundary / erroneous data
typical valid data / data at the edge of the allowed range / invalid data.
Predefined code
code that already exists and can be reused with permission.
Test plan
a list of tests with test data and expected results.
Links to your assignment: 1B.3 / 2B.P3
Your design must include a problem definition statement, a proposed solution, a list of any predefined functions/subroutines and a test plan.
Think it through
Why test with boundary data?
Mistakes often happen at the edges, e.g. using < instead of <=, so testing exactly at the limit catches them.
Why should you list the source of predefined code?
To show which parts are not your own work, give credit, and help anyone maintaining the program.
Watch
Validation, verification and keeping data accurate.
Watch and think:
Give an example of a range check and a presence check.
Learning aim C Unit 12 · C · Developing software · Event handling
The development environment, forms and events
By the end you can: use an IDE to create a form, set properties of controls, and write event-handling code for inputs and outputs.
You will develop programs in Visual Basic .NET using Visual Studio (Community edition is free). Choose Windows Forms App (.NET Framework) – Visual Basic when you create a project.
Drag controls from the Toolbox onto the form, set their properties, then double-click a control to write its event code.
Common controls. Name them with a prefix, e.g. btnCalculate, so code is readable
Control
Prefix
Use
Key properties
Label
lbl
show text or output
Text, Font, ForeColor
TextBox
txt
user types input
Text, MaxLength, PasswordChar, Multiline
Button
btn
user clicks to run code
Text, Enabled
ComboBox (drop-down list)
cbo
choose from a list (built-in validation)
Items, DropDownStyle, SelectedItem
ListBox
lst
show several items
Items
Public Class Form1
' Event handler: runs when the user clicks btnHello
Private Sub btnHello_Click(sender As Object, e As EventArgs) Handles btnHello.Click
Dim name As String = txtName.Text ' INPUT from a text box
lblMessage.Text = "Hello, " & name & "!" ' OUTPUT to a label
MessageBox.Show("Welcome to programming") ' OUTPUT in a message box
End Sub
End Class
Press F5 to build and run. Stop with the red square, or by closing the form.
Try it: your first form
Create a new Windows Forms App (Visual Basic) called HelloApp.
Add a TextBox (txtName), a Button (btnHello, Text “Say hello”) and a Label (lblMessage).
Double-click the button and type the code above. Run it with F5.
Change the form’s BackColor and the label’s Font in the Properties window.
Build an .exe: Build → Build Solution, then find it in the project’s bin\Debug folder.
No Visual Studio at home? Console versions of the practicals run in your browser at dotnetfiddle.net (choose VB.NET).
Key terms
IDE
integrated development environment: editor, designer, compiler and debugger in one.
Control
an object on a form, such as a button or text box.
Property
a setting of a control, e.g. Text or BackColor.
Event handler
a subroutine that runs when an event happens.
Think it through
What is the difference between the (Name) and Text properties of a button?
(Name) is what the code uses to refer to it (btnSave); Text is what the user sees on the button (“Save”).
Why is the code inside btnHello_Click not run when the program starts?
It is an event handler: it only runs when the Click event happens.
Learning aim C Unit 12 · C · Constructs and techniques · data types
Variables, constants, data types and operators
By the end you can: declare variables and constants with suitable data types, use assignment, arithmetic and logical operators, and explain local and global scope.
A variable has a name, a data type and a value that can change while the program runs. A constant’s value cannot change.
Data types
Data type
Holds
Example
Integer
whole numbers
Dim seats As Integer = 120
Decimal / Double (real)
numbers with a decimal point (Decimal for money)
Dim price As Decimal = 4.99D
String
text
Dim town As String = "Bedford"
Char
one character
Dim initial As Char = "J"c
Boolean
True or False
Dim paid As Boolean = False
Date
a date and time
Dim today As Date = Date.Today
Operators
Operator
Meaning
Example → result
+ − * /
add, subtract, multiply, divide
7 / 2 → 3.5
\
whole-number division
7 \ 2 → 3
Mod
remainder (% in many languages)
7 Mod 2 → 1
= <> < <= > >=
comparison
age >= 18 → True or False
And Or Not
logical
age >= 13 And age <= 19
&
join strings (concatenate)
"Hi " & name
Public Class Form1
Const VAT_RATE As Decimal = 0.2D ' constant: never changes
Dim basketTotal As Decimal = 0 ' GLOBAL: usable by every subroutine in the form
Private Sub btnAdd_Click(sender As Object, e As EventArgs) Handles btnAdd.Click
Dim itemPrice As Decimal = CDec(txtPrice.Text) ' LOCAL: only exists inside this sub
basketTotal = basketTotal + itemPrice ' assignment
lblTotal.Text = (basketTotal * (1 + VAT_RATE)).ToString("C")
End Sub
End Class
Key terms
Variable
a named storage location whose value can change.
Constant
a named value that cannot change while the program runs.
Local variable
exists only inside the subroutine where it is declared.
Global variable
declared outside subroutines; available throughout the program.
Think it through
Which data type would you use for a phone number, and why not Integer?
String: phone numbers start with 0, may contain spaces or +, and are never used in calculations.
What is 17 Mod 5 and 17 \ 5?
17 Mod 5 = 2 (the remainder); 17 \ 5 = 3 (whole-number division).
Learning aim C Unit 12 · C · Constructs: sequence, selection
Sequence and selection
By the end you can: write programs that use sequence, If…Then…Else, ElseIf, nested If, logical operators and Select Case.
Sequence means instructions run one after another, in order. Selection means the program chooses which instructions to run, depending on a condition.
' Login check: sequence then selection
Dim attempt As String = txtPassword.Text
If attempt = "Lantern42" Then
MessageBox.Show("Access granted")
Else
MessageBox.Show("Access denied")
End If
Set the text box’s PasswordChar property to * to hide what is typed.
' Grade bands with ElseIf
Dim mark As Integer = CInt(txtMark.Text)
If mark >= 70 Then
lblGrade.Text = "Distinction"
ElseIf mark >= 55 Then
lblGrade.Text = "Merit"
ElseIf mark >= 40 Then
lblGrade.Text = "Pass"
Else
lblGrade.Text = "Not yet achieved"
End If
Conditions are checked from the top; the first true one runs and the rest are skipped.
' Select Case: neater than many ElseIfs when checking one value
Select Case cboDay.Text
Case "Saturday", "Sunday"
lblRate.Text = "Weekend rate"
Case "Monday", "Tuesday", "Wednesday", "Thursday", "Friday"
lblRate.Text = "Weekday rate"
Case Else
lblRate.Text = "Choose a day"
End Select
Try it: selection practice
Make a form that asks for a temperature in °C and says “Freezing” (below 0), “Cold” (0–10), “Mild” (11–20) or “Hot” (above 20).
Add a check box ‘Raining?’ and use And to show “Take a coat” when it is cold and raining.
Write a Select Case that turns a number 1–7 into a day name, with Case Else for invalid numbers.
Key terms
Sequence
instructions carried out in order.
Selection
choosing a path depending on a condition.
Nested If
an If statement inside another If.
Select Case
selection that compares one value against several cases.
Think it through
In the grade code, what is shown for a mark of 55? Why is the order of the ElseIfs important?
Merit. If the Pass check (>= 40) came first, 55 would wrongly show Pass, because the first true condition wins.
Write a condition that is true for ages 13 to 19 inclusive.
age >= 13 And age <= 19
Watch
The three building blocks of every program.
Watch and think:
Give one example of each construct from a program you have written.
Learning aim C Unit 12 · C · Constructs: iteration, recursion
Iteration: counter-controlled and conditional loops, and recursion
By the end you can: use For…Next, Do While, Do…Loop Until and nested loops, and explain recursion.
Iteration repeats code instead of copying it out many times, which makes programs shorter and easier to maintain.
' Counter-controlled: a times table
lstTable.Items.Clear()
For i As Integer = 1 To 12
lstTable.Items.Add(i & " x 7 = " & (i * 7))
Next
' Conditional: keep asking until the PIN is right (max 3 tries)
Dim tries As Integer = 0
Dim pin As String
Do
pin = InputBox("Enter your PIN")
tries = tries + 1
Loop Until pin = "2468" Or tries = 3
If pin = "2468" Then MessageBox.Show("Unlocked") Else MessageBox.Show("Locked out")
Do … Loop Until always runs at least once; Do While … Loop may not run at all.
Recursion
A recursive function calls itself on a smaller version of the problem, and must have a base case that stops it.
Function Factorial(n As Integer) As Integer
If n <= 1 Then Return 1 ' base case: stop
Return n * Factorial(n - 1) ' calls itself with a smaller n
End Function
' Factorial(4) = 4 × 3 × 2 × 1 = 24
Try it: loops practice
Show the numbers 1 to 8, one per line, in a multiline text box; then change it to show the running total after each number.
Use a Do While loop that doubles a number starting at 1 until it is over 1000. How many loops?
Use a nested loop to draw a 5 × 5 square of * characters.
Key terms
Iteration
repeating a set of instructions.
Counter-controlled loop
repeats a fixed number of times (For … Next).
Conditional loop
repeats while or until a condition is true (Do While, Do … Loop Until).
Recursion
a subroutine that calls itself, with a base case to stop.
Think it through
What would happen if a Do While loop’s condition never became false?
It would loop forever (an infinite loop) and the program would freeze.
Learning aim C Unit 12 · C · Constructs: subroutines/functions/procedures
Subroutines, functions and procedures
By the end you can: write procedures (Sub) and functions (Function) with parameters and return values, and explain why they improve programs.
A subroutine is a named block of code that does one job. A procedure (Sub) does a task; a function does a task and returns a value.
Public Class Form1
' Function: returns the price after discount
Private Function DiscountedPrice(price As Decimal, memberType As String) As Decimal
Select Case memberType
Case "Junior" : Return price * 0.5D
Case "Senior" : Return price * 0.7D
Case Else : Return price
End Select
End Function
' Procedure: clears the form ready for the next booking
Private Sub ClearForm()
txtName.Clear()
cboClass.SelectedIndex = -1
lblPrice.Text = ""
End Sub
Private Sub btnCalculate_Click(sender As Object, e As EventArgs) Handles btnCalculate.Click
Dim total As Decimal = DiscountedPrice(6D * CInt(txtSessions.Text), cboMember.Text)
lblPrice.Text = total.ToString("C")
End Sub
End Class
Why use subroutines?
Benefit
Why it matters
Reuse
write once, call many times, e.g. DiscountedPrice from several buttons
Maintainability
change the discount rules in one place only
Testing
test each subroutine on its own
Readability
the main code reads like a list of steps: Validate(), Calculate(), Save()
Teamwork
different programmers can write different subroutines
Key terms
Procedure
a subroutine that performs a task (Sub).
Function
a subroutine that returns a value (Function … As type).
Parameter
a value passed into a subroutine.
Return value
the result a function sends back.
Think it through
What is the difference between a procedure and a function?
A function returns a value to the code that called it; a procedure just carries out a task.
What would DiscountedPrice(10, "Junior") return?
5 (half price for a junior).
Watch
Why programs are split into procedures and functions.
Watch and think:
Why can’t one subroutine see another’s local variables?
Learning aim C Unit 12 · C · Data structures · string handling
Data structures and string handling
By the end you can: use one-dimensional arrays, records (user-defined types) and string-handling functions.
An array stores many values of the same type under one name. A record groups different fields about one thing.
Dim classes() As String = {"Yoga", "Spin", "Pilates", "HIIT", "Swim"}
For i As Integer = 0 To classes.Length - 1 ' loop through every element
cboClass.Items.Add(classes(i))
Next
Structure Booking ' a record / user-defined type
Dim memberName As String
Dim className As String
Dim sessions As Integer
Dim price As Decimal
End Structure
Dim todaysBookings As New List(Of Booking) ' a list of records
Arrays in VB start at index 0.
Basic string handling
String function
What it does
Example → result
.Length
number of characters
"Bedford".Length → 7
.ToUpper() / .ToLower()
change case
"yoga".ToUpper() → "YOGA"
.Substring(start, length)
part of a string (first character is 0)
"Bedford".Substring(0, 3) → "Bed"
.IndexOf(text)
position of text, or −1 if not found
"Bedford".IndexOf("ford") → 3
.Trim()
remove spaces at the start and end
" Ali ".Trim() → "Ali"
.Split(",")
break into an array of parts
"Spin,3,18".Split(",") → {"Spin","3","18"}
&
join strings
"Mr " & "Lee" → "Mr Lee"
Try it: strings and arrays
Ask for a first name and surname; show initials in capitals (e.g. “PS”) using Substring and ToUpper.
Store six player names in an array using InputBox in a loop, then show them in a ListBox.
Compare two words and show them in alphabetical order (hint: use ToUpper first so case does not matter).
Key terms
Array
a data structure holding many values of the same type, accessed by an index.
Index
the position of an element in an array (starting at 0 in VB).
Record / structure
a user-defined type grouping related fields of different types.
String handling
working with text: length, case, substrings, searching, splitting.
Think it through
What does "Software".Substring(4, 4) return?
"ware" (start at index 4, take 4 characters).
Why use an array instead of six separate variables?
One name, and a loop can process every element, so the code is shorter and easy to change if there are more items.
Learning aim C Unit 12 · C · File handling · annotation · compiling
File handling, validation, error handling and compiling
By the end you can: open, read, write and close text files, validate input, handle errors so the program does not crash, comment the code and compile an executable.
File handling stores data permanently. Each line can hold one record, with fields separated by commas.
Imports System.IO
' WRITE: add one booking to the end of the file (creates it if needed)
Private Sub SaveBooking(line As String)
Using writer As New StreamWriter("bookings.txt", True) ' open, True = append
writer.WriteLine(line) ' write
End Using ' close (automatically)
End Sub
' READ: show every booking in a ListBox
Private Sub LoadBookings()
lstBookings.Items.Clear()
If Not File.Exists("bookings.txt") Then Exit Sub ' error handling: no file yet
Using reader As New StreamReader("bookings.txt") ' open
Do While Not reader.EndOfStream
lstBookings.Items.Add(reader.ReadLine()) ' read
Loop
End Using ' close
End Sub
Validation and error handling
Dim sessions As Integer
If txtName.Text.Trim() = "" Then ' presence check
MessageBox.Show("Please enter the member's name.") : Exit Sub
End If
If Not Integer.TryParse(txtSessions.Text, sessions) Then ' type check
MessageBox.Show("Sessions must be a whole number.") : Exit Sub
End If
If sessions < 1 Or sessions > 10 Then ' range check
MessageBox.Show("Enter between 1 and 10 sessions.") : Exit Sub
End If
Try
SaveBooking(txtName.Text & "," & cboClass.Text & "," & sessions)
Catch ex As IOException ' error handling
MessageBox.Show("The booking could not be saved. Check the file is not open.")
End Try
Validation stops bad data getting in; Try…Catch stops unexpected errors from crashing the program.
Annotate your code with comments explaining what each part does and why. It shows the assessor your understanding (2C.P4 asks for commentary throughout) and makes the code maintainable. Finally, compile the program into an executable (Build → Build Solution) so the client can run it without Visual Studio.
Key terms
File handling
opening, reading, writing and closing files.
Append
add to the end of a file without deleting what is there.
Exception
an error that happens while the program runs.
Executable
a compiled program file (.exe) users can run.
Links to your assignment: 1C.4 / 2C.P4 / 2C.M3
Develop a program for the brief with a user interface (inputs and outputs), a range of constructs and techniques, and commentary throughout. For Merit it must be fully functional and meet the brief.
Think it through
Why must a file be closed after use?
So the data is fully written and the file is released for other programs; Using … End Using closes it automatically.
What is the difference between validation and error handling?
Validation checks input is sensible before it is used; error handling deals with problems that happen while running, such as a missing file.
Learning aim C Unit 12 · C · Testing and refining the software
Testing, debugging, feedback and refining
By the end you can: test a program against the test plan and requirements, find and fix errors with the debugger, gather feedback and refine the program.
Syntax errors stop the program compiling; runtime errors crash it; logic errors give wrong answers without any warning.
Using the Visual Studio debugger
Debugger tool
Shortcut
Use
Breakpoint
F9
pause the program at a chosen line
Step Into / Over
F11 / F10
run one line at a time
Locals / Watch window
–
see the value of variables while paused
Error List
–
every syntax error with its line number
Recording test results (with evidence screenshots)
No.
Test data
Expected
Actual
Pass / fail
Action
1
Adult, Yoga, 2
£12.00
£12.00
Pass
–
2
10 sessions
accepted
rejected
Fail
condition was < 10; changed to <= 10; re-tested: Pass
3
abc
message
program crashed
Fail
added Integer.TryParse; re-tested: Pass
Gathering feedback on quality
Feedback question
Quality measure
Did it give the right price every time?
reliability
Was it easy to use without help? Were the messages clear?
usability
Was it quick to respond and load the bookings?
efficiency / performance
Could another programmer understand and change the code?
maintainability
Did it run on the reception PC as well as yours?
portability
Refine the program using test results and feedback, then re-test, because one change can break something else. Record every change, update your design documents, and add any new predefined code to your sources table.
In the real world: cash machines paying out too much
A software fault in a bank’s cash machines once let customers withdraw more money than they had, and the bank lost a great deal before it was fixed. Thorough testing with erroneous and boundary data is how such faults are found before users find them.
Key terms
Debugging
finding and fixing errors.
Breakpoint
a marker that pauses the program at a line.
Functional testing
checking every feature works as required.
Refine
improve the program based on testing and feedback.
Links to your assignment: 1C.5 / 2C.P5 / 2C.M4 / 2C.D3
Pass: test against your plan and the requirements and repair faults. Merit: gather feedback on usability and quality and use it to improve. Distinction: refine the program taking account of code quality and user feedback.
Think it through
Which is harder to find, a syntax error or a logic error? Why?
A logic error, because the program still runs; you only notice from wrong results, so you need good test data and the debugger.
Why re-test after fixing a fault?
To prove the fix worked and that it did not break anything else.
Watch
How to plan tests and choose test data.
Watch and think:
Give normal, boundary and erroneous data for ‘age 16 to 65’.
By the end you can: review a finished program against user requirements, fitness for purpose, user experience, constraints and quality, and recommend improvements.
What a good review covers
Review area
Questions to answer
Evidence to use
User requirements
Which requirements are fully met, partly met or not met? Why?
requirements list, test results
Fitness for purpose
Does it solve the client’s problem?
problem definition, client feedback
User experience
Is navigation easy? Are messages clear?
user feedback, observation
Constraints
How did language, time and device limits affect it? How did you work around them?
What works well? What would you add or change next?
all of the above
An evaluation grid helps you review requirement by requirement
Requirement
Met?
Evidence
Comment / improvement
Calculate price with discounts
Fully
tests 1–6 passed
–
Save bookings
Fully
test 8; file screenshot
could add a backup copy
Print a daily list
Partly
list shown on screen
printing not added because of time; next version
Moving up the grades
Pass (explain)
Merit (review the extent)
Distinction (evaluate)
explain how the program meets the requirements and purpose
weigh how far it meets each requirement, using feedback and constraints
compare the final program with the initial design and code quality, justify every change, recommend further improvements
Key terms
Fitness for purpose
whether the program does the job it was made for.
User experience
how it feels to use the program.
Evaluation
a balanced judgement with evidence and conclusions.
Recommendation
a justified suggestion for future improvement.
Links to your assignment: 1D.6 / 2D.P6 / 2D.M5 / 2D.D4
Review your own program for the brief. Use your test results, feedback log and design changes as evidence.
Think it through
Why should a review mention requirements that were NOT met?
It is honest and shows judgement; explaining why (e.g. a constraint) and how to fix it is what higher grades reward.
What is the difference between reviewing and evaluating?
A review describes how well it meets needs; an evaluation weighs strengths and weaknesses with evidence, compares with the design, justifies changes and reaches conclusions.