Unit 12: Software Development

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.

Input, process, outputINPUTdata goes ine.g. two numbers typedPROCESSthe program’s instructionse.g. add them togetherOUTPUTresults come oute.g. show the totalMost programs also STORE data, e.g. saving a booking to a file.
Every program takes inputs, processes them and produces outputs.
Three categories of software
CategoryWhat it doesExamples
Application softwarelets users do tasksword processor, spreadsheet, web browser, game
System softwareruns the computer itselfoperating system, device drivers, utilities
Programming softwareused to create other programsIDEs such as Visual Studio, compilers, debuggers
Uses of software programs
Why we develop programsReal examples
Gaming and entertainmentcomputer games, CGI special effects in films, virtual worlds, social media apps
Increasing productivityautomating factory processes, stock control that reorders goods automatically
Information storage and managementbooking systems, customer databases, school registers
Repetitive or dangerous tasksrobot arms on a car production line, robots that defuse bombs or work inside nuclear plants
Solving complex problemsweather 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.

Inputs: barcodes scanned, items weighed, payment card. Outputs: prices on screen, total, receipt, payment request.

Watch

A short, friendly introduction to how computers follow step-by-step instructions.

Watch and think:

  • What everyday task could you write an algorithm for?

Open on YouTube ↗

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 languagesHigh-level languages
Looks likemachine code or short codes (assembly)English words and maths, e.g. If score > 50 Then
Advantagesvery fast; direct control of hardwareeasy to read, write and fix; works on different computers
Disadvantageshard to write and debug; tied to one type of CPUmust be translated; usually a little slower
Procedural and event-driven languages
TypeHow the program runsLanguages
Proceduralinstructions run in order from start to end, using procedures and functionsC, Pascal, COBOL, Python
Event-driventhe program waits for events (a click, a key press, a timer) and runs the code for that eventVisual Basic, VB.NET, VBA, Visual C++
From source code to a program that runsSource codewritten by theprogrammer1 Checksyntax errors foundand reported2 Optimisetidy the code so itruns efficiently3 Translateinto machine code(binary)Executable.exe file the usercan runIf the compiler finds an error, it stops and tells you the line, so you fix it and compile again.
A compiler checks, optimises and translates the whole program into machine code before it runs.
Compilers and interpreters
TranslatorHow it works
Compilertranslates the whole program into machine code before it runs; creates an executable; runs fast; reports all errors after compiling
Interpretertranslates 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.

Watch and think:

  • Give one advantage of each type of language.

Open on YouTube ↗

How source code is turned into something the CPU can run.

Watch and think:

  • Why does a compiled program run without the compiler?

Open on YouTube ↗

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 / techniqueWhat it isVisual Basic example
Command wordsreserved words that tell the computer what to doDim, If … Then, For … Next, MsgBox
Subroutines (procedures and functions)a named block of code that does one job and can be reusedPrivate Sub CalculateTotal()
Basic string handlingworking with text: join, cut, search, change case, lengthname.ToUpper(), name.Length
Basic file handlingopen, read, write and close files so data is kept after the program endsIO.File.AppendAllText("bookings.txt", line)
Data structuresways to organise lots of data, e.g. arrays and recordsDim scores(9) As Integer
Event handlingcode that runs when something happens, e.g. a button clickPrivate 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.

Learning aim A Unit 12 · A · Quality of software programs

The quality of software programs

By the end you can: explain how design and coding techniques affect efficiency, maintainability, portability, reliability, robustness and usability.

Six measures of software qualityEfficiencyuses little CPU time,memory and storageMaintainabilityeasy to fix and change:comments, clear namesPortabilityruns on differentdevices and systemsReliabilitygives accurate,correct outputsRobustnesscopes with bad or extremeinput without crashingUsabilityeasy for the user tolearn and use
Use these six measures whenever you comment on, test or review a program.
Measuring quality
MeasureGood practice that improves itSign of poor quality
Efficiency / performanceloops instead of repeated code; no unnecessary calculations; load data onceslow, freezes, uses lots of memory
Maintainabilitycomments, meaningful names (totalCost not x), indentation, subroutines, constantsnobody can understand or change it safely
Portabilitystandard features; avoid code tied to one deviceonly works on one computer or screen size
Reliabilitytest with normal data; check calculationswrong totals or results
Robustnessvalidate input; handle errors (Try … Catch, Integer.TryParse)crashes when a letter is typed into a number box
Usabilityclear labels, instructions, sensible layout, helpful error messagesusers get confused or make mistakes

Spot the quality problems

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?

Open on YouTube ↗

Learning aim B Unit 12 · B · Software development life cycle

The software development life cycle

By the end you can: describe the stages of the software development life cycle and why it is used.

The software development life cycle1 Assess requirementswhat does the client need?2 Design specificationplan it: inputs, outputs, screens3 Develop codewrite the program4 Testdoes it work and meet needs?5 Maintainfix, update and improvea cycle:maintenance leads tonew requirements
Each stage feeds the next. Real projects often loop back, e.g. a failed test sends you back to development.
Stages of the life cycle
StageWhat happensWhat is produced
Assess requirementstalk to the client and users; find out what the program must dorequirements list, problem definition
Design specificationplan scope, inputs, outputs, processing, user interface and constraintsdesign documents: screens, flowcharts, pseudocode, test plan
Develop codewrite the program from the designworking code with comments
Testcheck it works, meets requirements and is good qualitycompleted test plan, fixes, feedback
Maintainfix bugs found later, update and add featuresnew versions
Different life cycle models
ModelHow it worksGood for
Waterfalleach stage is finished before the next startssmall, clear projects that will not change
Iterative / agilebuild, test and get feedback in short cycles, improving each timeprojects where requirements change
RAD (rapid application development)build prototypes quickly and refine them with the userprograms with lots of user interface

Key terms

Life cycle
the stages used to create and maintain software.
Requirements
what the client needs the program to do.
Iteration
repeating a process to improve it each time.
Prototype
an early, simple version used to get feedback.

Think it through

Why is it risky to start coding before assessing requirements?

You may build the wrong thing, wasting time and money, because you do not know what the client needs.

What is one problem with the waterfall model?

You cannot easily go back: if the client changes their mind late, earlier stages must be redone.

Watch

The stages professional teams follow, and how agile differs from waterfall.

Watch and think:

  • Which stage do you think is skipped most often, and what goes wrong?

Open on YouTube ↗

Learning aim B Unit 12 · B · Designing software

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
PartQuestion it answersExample: a leisure centre class booking program
Intended purposewhat is the program for?to let reception staff book members onto fitness classes and calculate the cost
User requirementswhat must it do for the users?choose a class; enter member type; calculate price with discounts; save bookings; show today’s bookings
Problem definition statementwhat 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 specificationMeaningExample
Scopewhat the program will and will not includebookings and prices; not online payment
Inputsdata entered by the usermember name, member type, class, number of sessions
Outputsresults shown or printedprice, confirmation message, list of bookings
Processingthe main tasks and calculationslook up class price; apply member discount; add to list; save to file
User interfacehow users interactone form with drop-down lists, text boxes and buttons
Constraintslimits on the projectmust 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.

Learning aim B Unit 12 · B · Proposed solution

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 taskInputsProcessingOutputs
Calculate a booking pricemember type, class, sessionslook up price × sessions; apply discountprice shown on the form
Save a bookingname, class, priceadd a line to the bookings file“Booking saved” message
Show today’s bookings(none: button click)read the file; filter today’s datelist of bookings
Annotated screen layout and navigation diagramClass BookingMember nametext boxMember typedrop-down listClassdrop-down listSessionstext boxCalculateSave bookingPrice: £—NavigationSplash / loginBooking formToday’s bookingsExit
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 formAlternative 2: a form per task
Descriptionall inputs and buttons on one screenseparate screens for booking, list and settings, with a menu
Strengthsquick for busy staff; fewer clicksless cluttered; easier to add features later
Weaknessescan look crowded as features growmore navigation; more code to write
Fits the requirements?yes: reception needs speedpartly: 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.

Learning aim B Unit 12 · B · Algorithms

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.

Flowchart symbolsStart / EndInput / OutputProcessDecision?flow lineovalparallelogramrectanglediamond: Yes / No
Five shapes are enough to draw almost any program.
Flowchart: cinema ticket priceStartInput ageage < 16?Yesprice = 4.75Noage >= 65?Yesprice = 6.00Noprice = 9.50Output priceEnd
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’)
counttotaloutput
–0
11
23
36
410
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.

Watch

The flowchart symbols and how to read them.

Watch and think:

  • Which symbol shows a decision?

Open on YouTube ↗

How to dry-run an algorithm with a trace table.

Watch and think:

  • Why is a trace table useful before you write code?

Open on YouTube ↗

Stretch: a longer walk-through of writing clear pseudocode.

Watch and think:

  • How is pseudocode different from real code?

Open on YouTube ↗

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 areaWhat to decideExample
Data structuresvariables, arrays or records to hold the dataarray of 6 class names; record for a booking (name, class, price)
Data storagehow data is kept after the program closestext file bookings.txt, one booking per line
Control structureswhere you need selection and loopsIF for discounts; FOR loop to show all bookings
Data validationchecks that input is sensible before using itsessions must be a whole number from 1 to 10
Error handling and reportingwhat happens when something goes wrongfile missing → friendly message, not a crash
Common validation checks
Validation checkWhat it checksExample
Presencesomething has been enteredmember name is not blank
Typethe right kind of datasessions is a number
Rangewithin sensible limitssessions from 1 to 10
Lengththe right number of charactersmembership number is 6 characters
Lookup / listone of the allowed valuesmember 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 snippetPurposeSource
Integer.TryParsesafely convert text to a whole numberbuilt into VB.NET (Microsoft documentation)
IO.File.AppendAllTextadd a line to a text filebuilt into VB.NET

Test plan with test data

Plan the tests now; fill in actual results later
No.TestTest dataTypeExpected result
1price for an adult, 2 sessionsAdult, Yoga, 2normal£12.00
2highest allowed sessions10boundaryaccepted
3too many sessions11erroneousmessage: “Enter 1 to 10 sessions”
4letters in sessionsabcerroneousmessage, no crash
5blank name(empty)erroneousmessage: “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.

Open on YouTube ↗

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.

The parts of the Visual Studio IDEMenu and toolbar: File · Debug ▶ Start (F5) · BuildToolboxLabelTextBoxButtonComboBoxListBoxCheckBoxForm designer (Form1.vb [Design])txtNamebtnHellolblMessageSolution ExplorerMyProjectForm1.vbProperties(Name) btnHelloText Say helloBackColor …Font …
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
ControlPrefixUseKey properties
Labellblshow text or outputText, Font, ForeColor
TextBoxtxtuser types inputText, MaxLength, PasswordChar, Multiline
Buttonbtnuser clicks to run codeText, Enabled
ComboBox (drop-down list)cbochoose from a list (built-in validation)Items, DropDownStyle, SelectedItem
ListBoxlstshow several itemsItems
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

  1. Create a new Windows Forms App (Visual Basic) called HelloApp.
  2. Add a TextBox (txtName), a Button (btnHello, Text “Say hello”) and a Label (lblMessage).
  3. Double-click the button and type the code above. Run it with F5.
  4. Change the form’s BackColor and the label’s Font in the Properties window.
  5. 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.

Watch

The tools inside an IDE such as Visual Studio.

Watch and think:

  • Which IDE tool helps you find logic errors?

Open on YouTube ↗

Reference: a full Visual Basic course. Dip into the parts you need rather than watching it all.

Watch and think:

  • Find the section on the topic you are working on and try the example.

Open on YouTube ↗

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.

Variables are labelled boxes in memory15ageInteger9.50priceDecimal"Priya"nameStringTruememberBoolean"B"cgradeCharDim price As Decimal = 9.5D → a box called price that can only hold decimal numbers
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 typeHoldsExample
Integerwhole numbersDim seats As Integer = 120
Decimal / Double (real)numbers with a decimal point (Decimal for money)Dim price As Decimal = 4.99D
StringtextDim town As String = "Bedford"
Charone characterDim initial As Char = "J"c
BooleanTrue or FalseDim paid As Boolean = False
Datea date and timeDim today As Date = Date.Today
Operators
OperatorMeaningExample → result
+ − * /add, subtract, multiply, divide7 / 2 → 3.5
\whole-number division7 \ 2 → 3
Modremainder (% in many languages)7 Mod 2 → 1
= <> < <= > >=comparisonage >= 18 → True or False
And Or Notlogicalage >= 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).

Watch

Choosing data types and when to use a constant.

Watch and think:

  • Why is a phone number stored as a string?

Open on YouTube ↗

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

  1. 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).
  2. Add a check box ‘Raining?’ and use And to show “Take a coat” when it is cold and raining.
  3. 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.

Open on YouTube ↗

Selection in Visual Basic, step by step.

Watch and think:

  • What happens if two ElseIf conditions are both true?

Open on YouTube ↗

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.

Counter-controlled and condition-controlled loopsFOR loop: repeat a set number of timescount = 1count <= 5?Yesshow count; count + 1No → endWHILE / DO loop: repeat until a condition changesDim total As Integer = 0Do While total < 20 total = total + 5Loop' runs 4 times: 5, 10, 15, 20Use FOR when you know how many times;use WHILE / DO when you don’t.
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

  1. 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.
  2. Use a Do While loop that doubles a number starting at 1 until it is over 1000. How many loops?
  3. 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.

How many times does For k = 2 To 10 Step 2 run?

5 times: k = 2, 4, 6, 8, 10.

Watch

Stretch: how a function can call itself.

Watch and think:

  • What stops a recursive function running forever?

Open on YouTube ↗

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?
BenefitWhy it matters
Reusewrite once, call many times, e.g. DiscountedPrice from several buttons
Maintainabilitychange the discount rules in one place only
Testingtest each subroutine on its own
Readabilitythe main code reads like a list of steps: Validate(), Calculate(), Save()
Teamworkdifferent 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?

Open on YouTube ↗

How functions take parameters and return values.

Watch and think:

  • What is the difference between a parameter and a return value?

Open on YouTube ↗

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 and a recordArray: classes(0 To 4) As StringYogaindex 0Spinindex 1Pilatesindex 2HIITindex 3Swimindex 4Record (Structure) Booking:memberName = "Priya Shah"className = "Spin"sessions = 3price = 18.00classes(2) is "Pilates"
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 functionWhat it doesExample → result
.Lengthnumber 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

  1. Ask for a first name and surname; show initials in capitals (e.g. “PS”) using Substring and ToUpper.
  2. Store six player names in an array using InputBox in a loop, then show them in a ListBox.
  3. 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.

Watch

Storing lots of data under one name.

Watch and think:

  • What is the index of the third element?

Open on YouTube ↗

Length, substrings, case changes and more.

Watch and think:

  • How would you get the first letter of a name?

Open on YouTube ↗

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.

Writing to and reading from a text fileProgrambooking savedbookings.txtPriya Shah,Spin,3,18.00Tom Bell,Yoga,1,6.00Ana Cruz,Swim,2,6.00Programlist loaded next dayopen, write,closeopen, read,closeData in variables is lost when the program closes; data in a file is kept.
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.

Watch

Keeping data after the program closes.

Watch and think:

  • Why must a file be closed after writing?

Open on YouTube ↗

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.

Three kinds of errorSyntax errorbreaks the rules of the languageDim total As IntegrIDE underlines it; won’t compileRuntime errorcrashes while runningCInt("abc")use validation, Try…CatchLogic errorruns, but gives the wrong resultIf age > 16 (should be >=)find with test data and the debugger
Syntax errors stop the program compiling; runtime errors crash it; logic errors give wrong answers without any warning.
Using the Visual Studio debugger
Debugger toolShortcutUse
BreakpointF9pause the program at a chosen line
Step Into / OverF11 / F10run 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 dataExpectedActualPass / failAction
1Adult, Yoga, 2£12.00£12.00Pass–
210 sessionsacceptedrejectedFailcondition was < 10; changed to <= 10; re-tested: Pass
3abcmessageprogram crashedFailadded Integer.TryParse; re-tested: Pass
Gathering feedback on quality
Feedback questionQuality 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’.

Open on YouTube ↗

The difference between errors that stop a program and errors that give wrong answers.

Watch and think:

  • Which kind of error will the IDE underline for you?

Open on YouTube ↗

Learning aim D Unit 12 · D · Reviewing software

Reviewing the finished program

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 areaQuestions to answerEvidence to use
User requirementsWhich requirements are fully met, partly met or not met? Why?requirements list, test results
Fitness for purposeDoes it solve the client’s problem?problem definition, client feedback
User experienceIs navigation easy? Are messages clear?user feedback, observation
ConstraintsHow did language, time and device limits affect it? How did you work around them?your development log
Qualityreliability, usability, efficiency, maintainability, portabilitytest plan, code comments, feedback
Strengths and improvementsWhat works well? What would you add or change next?all of the above
An evaluation grid helps you review requirement by requirement
RequirementMet?EvidenceComment / improvement
Calculate price with discountsFullytests 1–6 passed–
Save bookingsFullytest 8; file screenshotcould add a backup copy
Print a daily listPartlylist shown on screenprinting 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 purposeweigh how far it meets each requirement, using feedback and constraintscompare 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.