Vous êtes sur la page 1sur 44

Software Design and

Development
Programming With
Booklet 1
Contents

Content coverage of units.............................................................................................3


Introduction....................................................................................................................4
Programming in Visual Basic........................................................................................4
The Visual Basic Screen...............................................................................................5
Introduction to Visual Basic...........................................................................................6
Variables......................................................................................................................14
Input – Process – Output.............................................................................................17
Using arithmetic operators..........................................................................................19
Testing.........................................................................................................................23
Program Design – Designing the HCI.........................................................................26
Program Design – Designing the Code......................................................................35
Selection – Simple Conditional Statements................................................................37
Selection – Multiple Conditions...................................................................................43
Selection – Methods for Data Input.............................................................................46
Iteration – Fixed Loops................................................................................................52
Iteration – Conditional Loops......................................................................................61

Content coverage of units


Items in italics are in both National 4 and National 5 courses. Items in
bold are only in National 5 courses.

Booklet 1 coverage Booklet 2 coverage – additional items


Computational • expressions to assign • expressions to return values using
constructs values to variables arithmetic operations (mod)
• expressions to return • use of selection constructs
values using arithmetic including simple and complex
operations (+, -, *, /, ^) conditional statements and logical
• execution of lines of operators (AND, OR, NOT)
code in sequence • pre-defined functions (with
demonstrating input – parameters)
process – output
• use of selection
constructs including
simple conditional
statements
• iteration and repetition
using fixed and
conditional loops
Data types and • String • Character
structures • numeric (integer and • Boolean variables
real) variables • 1-D arrays
Testing and • normal, extreme and • syntax, execution and logic errors
documenting exceptional test data in programs
solutions • readability of code • readability of code (meaningful
(internal commentary, identifiers, indentation)
meaningful variable
names)
Algorithm • input validation
specification

Design • contemporary design


notations notations
• graphical to illustrate
selection and iteration
• pseudocode to
exemplify
programming
constructs

Introduction
A program is a list of instructions that cause a computer to perform a useful task, such
as:
• playing a game,
• doing a calculation,
• drawing a graphic,
• sending e-mail or
• managing files on a network.

In fact, everything you ever do on a computer works by running a program!


A program can be quite small – something designed to add two numbers together, or it
can be a large application, such as Microsoft Word.

Programming in Visual Basic


You are going to write programs using Visual Basic which comes with its own
development environment.

Visual Basic is a programming language that allows you to


define the HCI (Human Computer Interface – like the one shown opposite), and then
write the program.

Visual Basic is an event driven language. This means that it reacts to events such as
clicking a button, loading a form, selecting an option etc.

These events are similar to the event blocks in Scratch, ie the code will only run when
this event takes place.

The Visual Basic Screen


There are 2 main working areas in Visual Basic.

Form Area (Design View)


This is where you will create your screen layouts for the user.

Code View
This is where you will type the lines of programming instructions.

Solution Explorer
To move between the object window and the code window you
can use the View Designer and View Code buttons in the solution explorer.

Introduction to Visual Basic


This lesson will cover:
• The Visual basic environment, including
• Setting up VB for the first time
• Starting a new project
• Changing object properties
• Creating a simple program to display a welcome message

Setting Up VB
From the Start button…

When Visual Studio first opens…


Your screen should look like this…

Starting a new project


Select New Project from the File menu. The following dialogue box will appear.

Creating the HCI


The first program you are going to create is a simple one that will display a welcome
message when the user clicks a button.

For our first simple program, the only objects we want to add are a button and a label.

We put objects on a form first by double clicking the icon on the toolbox or by dragging
and dropping them onto the form.

Add one label and one button to your form.

Changing object properties


Object Properties
You may have noticed when you added each of your objects, the properties window
changed to display the name and related properties for that object.

There are many properties associated with each of the objects in VB, such as font style,
colour, size, whether that object is visible or not. These can be changed when you are
designing your user interface (by selecting the object through clicking it or from the drop
down list in the properties window) or through programming code.

• Select label1 by clicking on it once.


• Scroll to the Text property in the Properties box and type in Click the button to
see a message. Press return.
• Change the text property of the button to click here
• Change the text property of the form to My First VB Program.

Your form should now look something like this.

Entering your code


• Double click the Click button to take you to the code view window.

• Now enter the following line within the Button1_Click event (remember to leave the
existing VB code as it is).

Public Class Form1

Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As


System.EventArgs) Handles Button1.Click

MsgBox("Welcome, this is my first VB program")

End Sub
End Class

Saving your program


There are a number of files associated with your solution. Visual Basic organises it all in
a folder for you.

• To save you must select Save All from the File menu.

• The following dialogue box will appear. Check everything matches what is shown
below then Click Save.

Running your program


1. To run your program, clicking on the Start Debugging icon on the Visual Basic
toolbar.

1. Test your program works by clicking on the Click Here on your form. You should get
a message box something like this…

1. Stop the program by clicking on stop debugging button icon.

Understanding the code

Changing the look of your form and objects


We can make the user interface look better by changing the colours and fonts used.

• Make sure you are in Form View


• To Change the Font of your Label1, select the label by clicking it once, look for the
Font property and click on the box to the right .

• Select a font and font size of your choice and click OK


• To make your text appear on two lines as shown above set the AutoSize property of
the label to False and resize your label to suit.

• Make changes to the other objects on your form…

• Try changing BackColor of the Form


• You can change the colour of the text of an object by selecting ForeColor.

Note: you may have to adjust the positioning of your objects if you change their sizes.

• Save any changes to your project. Remember to select SAVE ALL (you do not
need to change the filename).
Introduction to VB Task – Bad Joke
Create a program that will reveal the punchline of a joke when a button is clicked. Make
sure that you –

• Change the text properties of the form, and any labels and buttons
• Change the font and text alignment properties of the label
• Change the autosize property of the label if necessary
• Change the backcolour property of the form
• Include a relevant picture if you have time (follow the steps in the extension task)

Your end result should look something like this…

Introduction to VB Extension Task – Entering pictures or images


Relevant pictures can be used to improve the look of your form.

• Open your bad joke task.


• Insert a picture box onto the new form.

• You will notice a little arrow toward the top right of the picturebox. Click this and
adjust the SizeMode property to StretchImage (this will help ensure the image you
import fits).
• Then select Choose Image. The Select Resource dialogue box will appear.

• Click on Local Resource and then Import.


• Your “My Pictures” directory will appear. If you don’t have a suitable image, look in
the Our School area. Select a suitable image then click OK.

Variables
This lesson will cover –
• What a variable is
• Expressions to assign values to variables
• readability of code (meaningful variable names)
• Data types (string, and numeric (integer and real) variables)
Task 1 – String Variables
Adapt the simple message program created in the last chapter so that it asks for the
user’s name and include this in the welcome message. Follow the instructions
numbered at the bottom of the page.

Screen Layout Design

Program Code
Public Class Form1

Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs)


Handles Button1.Click

Dim Name as String

Name = textbox1.text

MsgBox("Welcome " & Name & ", this is my first VB program.")))


End Sub
End Class

• Open the My First VB program you created earlier.


• Add a new label and a textbox to your form in the positions shown above.
• Change the text property of the new label to read Please enter your name.
• Adapt the instruction text in lable1 to instruct the user to enter their name.
• Go to Code view make the changes to the code shown in the box above.
• Run the program and enter your name to test that it works. The end result should
now look something like this…

Task 2 – Whole Numbers (Integers)


Create a program that asks for a user’s name and age and displays a message
including this information.

This program will have the following variables:

Variable Name Data Type


Name String
Age Integer

Some of the code for this program is shown below. Fill in the missing parts and run it to
check that your program is working.

Program Code
Public Class Form1
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As
System.EventArgs) Handles Button1.Click

Dim Name as String


Dim        as          

Name =             .text

     =              

MsgBox("Hello " & Name & “                 ” Age)

End Sub
End Class

Task 3 – Real Numbers (Single)


Adapt the program so that it asks the user for their height in m and includes this in the
message.

Add the following variable to the program.

Variable Name Data Type


Height Single

Make any other necessary changes.

Variables extension task


Create a program that asks the user for their favourite colour, shoe size and favourite
band and displays this information as 3 separate message boxes.

Input – Process – Output


This lesson will cover –
• Understanding of execution of lines of code in sequence demonstrating Input –
Process – Output

Sequence of Instructions (Input – Process – Output)

You may have already noticed that, just as blocks in the same stack in scratch are
executed in sequence, one after the other, so are the lines of code in a VB program.
Therefore the order that we write our program in is very important.

Most programs follow a basic Input à Process à Output Model (ie they take data in from
the user, do something with it and then give them something back out).

INPUT is the data flowing into the system from outside.

PROCESSING is the action of manipulating the input into a more useful form (ie doing
something with the data that has been entered).
Output is the information flowing out of the system, normally presented in a user-
friendly way.

It is a good idea when developing a program to spend a bit of time thinking about your
inputs, process and outputs before you start to implement, or even design you
program.

Imagine you were asked to create a program to calculate the area of a rectangle.

Program Inputs
For this to work we would need to get the user to input the dimensions of the rectangle,
ie the length and breadth.

Program outputs
Although the next step in the IPO model is process, it is sometimes good to think about
our outputs first so that we can then understand what we need to do in the middle.

We can see that we need to display the area. This is the only output we are asked for.

Program Process
Now that we know what our program takes in and what it gives out we need
to think about what it had to do in the middle in order to get the outputs.

This is easy – we had to multiply length and breadth to get area!

We can now rewrite these to give us a better understanding of what our program will do

Create a program that –


• Asks the user to enter length and breadth
• Calculates the area (by multiplying length and breadth)
• Displays the area

Input à Process à Output Tasks


Task 1 – Average
Write down the inputs, process, and outputs for a program that will find the average of 3
numbers.

Task 2 – Area of a Square


Write down the inputs, process, and outputs for a program that works out the area of a
square (note: if you later go on to implement this program in VB you use the ^ symbol
to raise the power).

Task 3 – Volume of Cuboid


Write down the inputs, process, and outputs for a program that works out the volume of
a cuboid.
Task 4 – Average Test Mark
Write down the inputs, process, and outputs for a program that takes in a pupils mark in
3 tests out of 20 and calculates and displays their average test mark as a percentage.

Using arithmetic operators


This lesson will cover –
• Expressions to return values using arithmetic operations (+,-,*,/,^)
• readability of code (Internal commentary )

Arithmetic Operators
Simple calculations play a big part in programming. For example keeping count of a
user’s score/lives, working out total costs, counting how many times something
happened, increasing/reducing font size, etc.

The arithmetic operators you will use are –

Arithmetic operation Symbol


Addition +
Subtraction -
Multiplication *
Division /
Raise the power ^

Readability of Code – Internal Commentary


All programs should start with an explanation of what they are about. This helps to
make your code more readable. Readability means how easy it is for you, or any other
programmer looking at your code to understand it.

It is good practice to include the following 4 lines at the beginning of any program.

line 1 – short description of the program


line 2 – your name
line 3 – the date
line 4 – what the program is saved as

As these lines should be ignored by the computer you need to make this clear so start
each line with ‘ (it is on the same key as the @ symbol)
e.g. ‘ this program finds the volume of a cuboid

Sometimes programmers may also use internal comments through their program code
to explain a piece of complex or confusing code.
Task 1 – Adding two numbers
Create a program which will add 2 numbers together and display the answer in a
message box.

Screen Layout Design

Design Code in Visual Basic


Main Steps Private Sub Button1_Click(…)
• Declare variables 'This program adds together two
• RECEIVE numbers FROM numbers
KEYBOARD ' written by ………
• SET sum TO FirstNumber + ' on ……………
SecondNumber ' saved as Booklet 1 xxxxxxxxxxx
• SEND sum TO DISPLAY

Refinements Dim FirstNumber As Integer


2.1 RECEIVE FirstNumber FROM Dim SecondNumber As Integer
KEYBOAD Dim Sum As Integer
2.2 RECEIVE SecondNumber FROM
KEYBOARD FirstNumber = TextBox1.Text
SecondNumber = TextBox2.Text

Sum = FirstNumber + SecondNumber

MsgBox("Total is " & Sum)

End Sub

• Create the above HCI (you can choose which fonts, colours, etc to use).
• Double click on button1 to enter the code window.
• Enter the VB code above. Correct any errors that you have made. The first 4 lines
of this code are know as internal comments.
• Start debugging and run some initial tests to make sure the program works as
expected

If your program does not give the outputs you expect, look carefully at your code to see
if you have made any errors not shown in the error list.

Arithmetic Operators Tasks


Create, run and test the following programs. Remember to include internal comments
at the start of each program.

Task 2 – Adding 3 numbers


Create a program that takes in 3 numbers from the user, adds these together, then
displays the total.

Task 3 – Wage Calculator


Create a program to work out how much a person is paid. It will ask them their hourly
rate, how many hours they work and then display their total wage.

Task 4 – Year you were born


Create a program that will ask you what year you were born then calculate how old they
will be in 2050 (hint: this task will involve a subtraction).

Task 5 – CD Cost Calculator


Create a program to work out the cost of one CD-R sold as part of a bulk pack (eg how
much for 1 CD-R from a pack of 100). The program should take in how many CDs are
in the pack and what the bulk price is.

Task 6 – Area of a Square


Create a program to work out the area of a square (remember to use the ^ symbol to
raise the power. You have already thought about the inputs, process and output for this
program in task the last unit).

Arithmetic Operators Extension Task – Calculator


Create a program that will act as a very simple calculator. It will take in two numbers
and add, subtract, multiply or divide them depending which button you click.

Screen Layout Design


Design Code in Visual Basic
Main Steps – Add Buttion Private Sub Button1_Click(…)
• Declare variables 'this subprogram adds two numbers
• RECEIVE numbers FROM together
KEYBOARD
• SET solution TO FirstNumber + Dim FirstNumber As Integer
Secondnumber Dim SecondNumber As Integer
• SEND sum TO DISPLAY Dim Solution As Single

Refinements FirstNumber = TextBox1.Text


2.1 RECEIVE firstNumber FROM SecondNumber = TextBox2.Text
KEYBOAD
2.2 RECEIVE secondNumber FROM Solution = FirstNumber +
KEYBOARD SecondNumber

TextBox3.Text = Solution 'answer


will be displayed in a text box

End Sub

• Create the above HCI (you can choose which fonts, sizes and colours to use)
• Double click the Add button and enter the code above
• Double click the other buttons in turn to generate the code for these action events
and copy and paste the code, editing the text where necessary to reflect the
operation being carried out
• Run the program with some initial test data to ensure it works. Remember to try
Add, Subract, Multiply and Divide. Put in different values such as 0, -1 and 100. You
should know what the correct answer should be in order to check the results. Use a
test table to record your results.

Testing
This lesson will cover –
• The importance of testing
• normal, extreme and exceptional test data
• debugging common errors
Testing
Simply finishing keying in a program does not mean that you have finished the task.
Imagine paying for software that hadn’t been tested – you wouldn’t be very happy
when it started giving you the wrong results or crashing!

You have already run some initial tests on your programs you created in the previous
chapter to check they are working, but how much thought did you put into the numbers
you chose to test with? Software development companies spend a great deal of time
(and money) testing their programs to ensure that they do what they are supposed to
do and there are no errors in the code.

Programmers will think carefully about their chosen test data and ensure that they
have tested their program under normal, extreme and exceptional conditions.

• Normal test data represents normal working conditions; it is data within the
expected range.
• Extreme test data tests that program can handle data on the limits of what is
considered normal; it is data just on the boundaries.
• Exceptional test data checks that a program can cope with unexpected data
without crashing; it is data you wouldn’t expect to be entered. (Note: at this stage
your programs will usually crash when you enter exceptional test data.)

Before testing your program it is good practice to calculate your expected results
before you run your program.

Task 1 – Testing your program


Open Arithmetic operators Task 1 – Adding Two Numbers. Copy the following test table
in your jotter.

Number 1 Number 2 Expected output Actual output


Normal 10 25 35
Extreme -32768 32768 0
Exceptional A % Error

Now run the program using the test data above. Record the answers your program
gives you in the last column. If your program works correctly then the actual output
should equal the expected output.

Testing Tasks
Come up with suitable normal, extreme and exceptional test data for the following
programs. Write your test plan, along with your expected outputs into your jotter.

• A program that asks for a user’s test mark out of 45 and calculates their percentage.

• a program that takes in two whole numbers, each between 1 and 10, adds them
together and displays the result.

• A program that asks the


• to enter their name and date of birth and displays a welcome message.

• A program that asks the user to enter any letter of the alphabet in lower case and
displays the character in upper case.

• A program that asks the user to enter the month they were born as a number (eg
March = 3).

Testing Extension Task 1


Create suitable test data (inclduing normal, extreme and exceptional test data) for the
tasks you created in the arithmetic operators unit. Run your programs with your test
data and record your results. Fix any errors that you find as a result of testing.

Testing Extension Task 2 – Common Errors


Look at the common errors described below.

Common VB Errors
• Forgetting to declare variables (usually ones like total, area, etc)
• Spelling mistakes in variable/object names
• Spaces in variable names
• Deleting End Sub from the end of an event
• Deleting End Class from the end of your program
• Code in the wrong event (eg in Form_Load instead of button_click)
• Referring to the wrong objects (eg textboxes 1,2 and 3 are not in the order you
think they are)
• Assignment statement is the wrong way around (eg answer = textbox3.text
instead of textbox3.text = answer)

Solving Common VB Errors


• Always have the error list visible
• Double click the error(s) shown in the error list in order
• If you can’t find the error on this line you have been taken to when you double
click the error, check the line above.

Work with a partner or group to discuss:

• what affect each of the errors would have on a program and

• the steps you would take to solve each of the errors.

• If you have time, create a help guide with relevant screen shots for solving these
common VB errors.
Program Design – Designing the HCI
This lesson will cover –
• Understanding the importance of designing the user interface
• Different methods for receiving data from the keyboard
• Different methods for displaying information to the screen
• Designing user friendly programs
• Adding clear and quit buttons to programs

Input and Output Methods


Up until now, all variables have been given a value via a text box and most outputs have
been displayed using a message box.

In this lesson you are going to investigate different methods for receiving inputs and
displaying outputs.

The main methods for receiving data from the keyboard in VB include
• Text boxes
• Input boxes

The main methods for displaying information to the screen are


• Text boxes
• Message boxes
• Labels
• Listboxes

Designing the interface


Before programmers start to create their programs they usually spend some time
thinking about how their program will look and how it will work. How the program will
look is the user interface. This is how the user will interact with the computer.

When designing your user interface you should always consider your target audience
(who will be using your program) and try to make your program as user friendly as
possible.

Task 1 – Using Input boxes


Create a simple program that will generate User IDs for employees.

Screen layout design


Design Code in Visual Basic
• Declare variables Dim forename As String
• RECEIVE forename FROM Dim surname As String
KEYBOARD Dim userID As String
• RECEIVE surname FROM
KEYBOARD forename = InputBox("Please
• SET userID TO surname + forename enter employee’s forename",
• SEND userID TO DISPLAY “Enter Forename”)
surname = InputBox("Please
enter employee’s surname",
“Enter Surname”)

userID = surname + forename

MsgBox(forename & “ “ & Surname &


& "’s ID is " & userID)

Understanding the code

userID = InputBox(“Please enter employee’s forename”. “Enter Forename”)

This will result in the following dialogue box

User friendly programs – user friendly input prompts


A ‘user friendly’ program is one that is easy to use. When designing your program you
should try to ensure that the user interface is as user friendly as possible.

You should always try to ensure your user knows how to use your program and what is
required of them. For example, including labels on your form telling the user what the
program will do and how to get started (like we did in the program above). Also, if you
are asking the user to enter data, the user should understand exactly what is being
asked of them.

Look at these two input boxes. The first one lets the user know they have to enter a
number but does not give the user any information about what kind of number should be
entered. Is it an integer? What are the limits?

In the second input box the user is given clear instructions about the number type and
size.

Task 2 – Using a Listbox


Listboxes are useful when there are several lines of text to be shown (for example what
if the network manager wanted to input a group of users and get their user IDs).

• Change the last line of code from

MsgBox(foremane & “ “ & surname & & "’s ID is " & userID)

To

Listbox1.items.add(foremane & “ “ & surname & & "’s ID is " & userID)

• Run your program to test that it is working. You should notice that the previous
employee’s name and user ID is still showing. Each new employee should simply
be added to the bottom of the list.

Understanding the code

Listbox1.items.add(foremane & “ “ & Surname & & "’s ID is " & userID)

Task 3 – Using Text Boxes for Display


Create a simple program that will ask a user for two test results. It will then calculate
and display their total mark for the tests in a textbox.

Screen Layout Design

Design Code in Visual Basic


• Declare variables Dim Test1 As Integer
• RECEIVE test1 FROM KEYBOARD Dim …
• RECEIVE test2 FROM KEYBOARD
• SET totalMark TO test1 + test 2 Test1 = …
• SEND toalMark TO DISPLAY …

TotalMark = …

Textbox1.Text = TotalMark

• Create the above HCI


• Double click the button and enter the code filling in any parts that are missing (use
input boxes to receive values for test 1 and test 2).
• Run the program to test it is working.

Understanding the code


Notice the order of the code

Textbox1.Text = TotalMark

This is different than when we have used textboxes to assign values where the textbox
and the variable would be in the order

Test1 = Textbox1.Text

The order is very important.

Task 4 – Using labels for Display


Adapt the program you created in task 3 to send the output to a label instead of a
textbox.

Screen Layout Design

• Open Task 3.
• Make the changes to the form design shown above
• Change the last line of code from

Textbox1.Text = TotalMark

To

Label3.Text = TotalMark
Label3.Visible = True

• Run your program to test that it works.

Understanding the code

Label3.Text = TotalMark
Label3.Visible = True

Designing the HCI Extension Task – Adding Clear Button and Quit Buttons
User friendly programs – Clear and Quit Buttons
Adding a clear and a quit button can also improve the user friendliness of your
program.

Clear Button
If you have decided to use textboxes it may be useful to the user to have a clear button
in order from them to be able to clear any previous entries and start again (ie without
having to press Stop debugging and start debugging again!).

There is no code in VB to clear a textbox so what we need to do is place ‘nothing’ into


the textbox (we do this by opening and then closing quotes with no space in between –
like this …

Textbox1.Text = “”

(Note – there is code to clear a listbox… it is listbox1.items.clear())

Quit Button
In VB the word ‘End’ will stop a program from running.

A good program will usually give the user the option to change
their mind.

Extension Task 1 – Adding a Clear Button

Clear Button Program Code


Private Sub Button2_Click(…
'this procedure clears the three text boxes
TextBox1.Text = ""
TextBox2.Text = ""
TextBox1.Focus()
End Sub

Quit Button Program Code


Private Sub Button3_Click(…
'this procedure allows the user to quit
Dim Reply As Integer
Reply = MsgBox("Really Quit?", vbQuestion + vbYesNo, "Quit")
If reply = vbYes Then End
End Sub
• Open the program you created in Arithmetic Task 1 – Adding two numbers (if you
don’t have this then don’t worry – just open any other form that has textboxes on it).
• Add two new buttons and change the text property of one to Clear and the other to
Quit.
• Double click the Clear button and enter the relevant code above.
• Run the program to test that the new clear button works. Remember to enter some
numbers into the textboxes first.
• Double click the Quit button and enter the relvant code above
• Run the program to test that the new quit button works (you should get a message
box like the one shown below).
• Save your changes (do not worry about changing the file name).

Understanding the code – Quit Button

Reply = MsgBox("Really Quit?", vbQuestion + vbYesNo)

This will result in the following message box

If reply = vbYes Then End

Program Design – Designing the Code


This lesson will cover –
• contemporary design notations
• graphical to illustrate selection and iteration
• pseudocode to exemplify programming constructs

Designing the code


Programmers use a variety of methods for describing the program structure.
Three common methods are pseudocode, flow charts and structure diagrams.
There are many others, but we will only consider pseudocode and structure diagrams.

Pseudocode
Pseudocode is a numbered list of instructions written in normal human language (in this
case, English). It doesn’t go into all the details, but it gives the main steps.
Pseudocode is read from top to bottom.

Think about making tea. Here is a list of instructions for this task –

• Get a mug out of the cupboard


• Put a teabag in it the mug
• Boil the kettle
• Pour boiling water from the kettle into the mug
• Stir

Structure Diagrams
A structure diagram is a visual representation – read from left to right. Notice that it has
the same main steps as the Pseudocode.

Task 1 – Design of everyday tasks


For each of the examples below, show both the pseudocode and the structure diagram
that are required to design the solution –
• Making a cheese and tomato sandwich.
• Drawing a square.

Writing Pseudocode
It is a good idea to follow some sort of standard when writing pseudocode. So far in
programming we have looked at input, assignment and output statements. In
pseudocode these could be written as follows:

Input – RECEIVE … FROM …


Assignment – SET … TO …
Output – SEND … TO ..

For example
• Declare variables
• RECEIVE test1 FROM KEYBOARD
• RECEIVE test2 FROM KEYBOARD
• SET totalMark TO test1 + test 2
• SEND toalMark TO DISPLAY

Task 2 – Design of simple programming tasks


For each of the examples below, show both the pseudocode and the structure diagram
that are required to design the solution. Try to ensure your pseudocode follows the
standard shown above.

• Take in and add two numbers together.


• Take in 2 numbers and multiply them
• Calculate the area of a rectangle.
• Take in 2 numbers and divide the first number by the second
• Take in 3 numbers and find the average
• Calculate the volume of a cuboid.

Selection – Simple Conditional Statements


This lesson will cover –
• use of selection constructs including simple conditional statements
• use of comparison operators

Conditional Statements
You have already learned that program lines are carried out in sequence – one line after
the other. However, often when writing programs you only want the computer to
perform an action (or set of actions) if a certain condition is met (ie only give a “you
have passed” message if the user scored above 50%).

To do this we need to use a conditional statement. You have already used these in
Scratch. The blocks looked like this –

If…Then If…Then…Else
Block Block

They take a similar format in VB, look at the examples below –

If…Then Example If…Then…Else Example


If mark >= 50 Then If mark >= 50 Then
MsgBox("You have passed!") MsgBox("You have
passed!") Else
End If MsgBox("You have failed")
End If
Comparison Operators
These are the symbols that we use to make a comparison in VB. The most
commonly ones used are. They are used when comparing numbers or text.

Symbol Meaning Example


= Equals to If password = ”bananas” Then …
> Greater than If mark > 100 Then …
< Less than If percentage < 50 Then …
>= Greater than or equal to If age >=18 Then …
<= Less than or equal to If number <= 49 Then …

Task 1 – Have I passed


Create a program that will award a Pass if a mark entered is 50 or more.

Screen Layout Design

Design Code in Visual Basic


Main Steps Private Sub btnFindOut_Click(…
• Declare Variables ‘ this procedure will dislay the
• RECEIVE mark FROM KEYBOARD appropriate Pass or Fail message
• IF mark >= 50 THEN
• SEND [“pass”] TO DISPLAY Dim mark As Integer
• END IF
mark = textbox1.Text

If mark >= 50 Then


textbox2.Text = "Pass"
End If

End Sub

• Create the above HCI.


• Double click the button and enter the code above.
• Start debugging to see how the input box works.

Extension
Adapt the code so that it displays “fail” in the textbox when a user has not scored above
50.

• Insert the two lines of code where shown below

If mark >= 50 Then


textbox2.Text = "Pass"
Else
textbox2.Text = "Fail"
End If
• Run the program to test that the new code works .

Task 2 – Password Check


Create a program which will ask the user to enter a password. The program will display
a message if the correct password is entered.

Screen Layout Design

Design Code in Visual Basic


Main Steps Private Sub btnEnter_Click(…
• Declare Variables ' This program…
• SET password TO “bananas”
• RECEIVE userEntry FROM Dim Password As String
KEYBOARD Dim UserEntry As String
• IF userEntry = password THEN
• Send ["You have entered the Password = "bananas"
correct password"] TO DISPLAY
• END IF UserEntry = Textbox1.Text

If UserEntry = Password Then


MsgBox("You have entered the correct
password")
End If
End Sub

• Create the above HCI.


• Double click the button and enter the code above.
• Run the program to test it works.
• Adapt the program to display “Invalid password – access denied” if the user gets the
password wrong.
• Run the program again to test that the new message is displayed when expected.

Conditional Statements in Program Design

Conditional Statements in Structure Diagrams


When representing conditional statements in pseudocode it is crucial to use indentation
to show the steps to be performed as part of the condition being met or not. You must
also include a line to terminate the statement.

Look at the example below for the password program you have just created.

Password Check
• Declare Variables
• SET password TO “bananas”
• RECEIVE userEntry FROM KEYBOARD
• IF userEntry = password THEN
• Send ["You have entered the correct password"] TO DISPLAY
• ELSE
• Send ["Invalid password – access denied"] TO DISPLAY
• END IF

Conditional Statements in Structure Diagrams


The condition, which is usually referred to as a Decision in this type of diagram is
represented using a diamond shape.

This structure diagram shows the same program as above.

Simple Conditional Statement Tasks


Task 3 – 2 plus 2
Create a program that will ask the user what the answer to 2 plus 2 is and display a well
done message if they answer correctly or a message asking the user to try again if they
get it wrong. If you have time adapt the user interface of this program to make it
suitable for young children (ie use appropriate fonts, colours and include a suitable
picture).

Task 4 – Picture based questions


Create a program that asks the user a short response
question relating to a topic and picture of your choice. An example is getting user to
guess the flag.

Task 5 – Temperature
Create a program that asks the user for the temperature at 6am, 12.30pm and 6pm for
a given day. It then calculates the average temperature and displays this along with
whether the average temperature for the day was hot or cold (The temperature is hot if
it is 17 or above, and cold if it is below 17).

Task 6 – Wage Calculator


Create a program to work out a user’s weekly wage. The user should be asked for the
number of hours they worked that week and their rate per hour. Employees who work
more than 30 hours receive a £25 bonus. The program should display the workers
basic wage (ie their wage without bonus), whether they have been awarded a bonus
and their final weekly wage (including any bonuses that they are due).
Simple Conditional Statements Extension Tasks
Extension Task 1
Adapt the temperature program so that the backcolour of the form changes depending
on whether it is a hot or a cold day as an additional enhancement to your program. The
form should be blue for a cold day and yellow for a hot day.

Hint: To change the backcolour of a form to blue, use the following code –

Me.BackColor = Color.Blue

Extension Task 2
Adapt the 2 plus 2 program to show a happy face on the form when the user gets the
answer correct or a sad face when the user gets the answer wrong.

Hint: to do this you will need to add a picturebox and import two pictures (one saved as
happy, the other saved as sad) as project resource files. To change the picture to the
happy face, use the following code –

PictureBox1.Image = My.Resources.happy

Selection – Multiple Conditions


This lesson will cover –
• Handling multiple conditions thought the use of ElseIf

Multiple Conditions – Branching

There are times when you want to select from a range of options. For example when
you are awarding grades you may give students a different grade (A-F) depending on
what percentage mark they achieved.

This is known as branching and one way to deal with this in VB is to use ElseIf.

ElseIf example
SIf Age1 > Age2 Then
MsgBox("Person 1 is oldest")
ElseIf Age1 < Age2 Then
MsgBox("Person 2 is oldest")
Else
MsgBox("These people are the same age")
End If
Task 1 – Who is older
Create a program that takes in the ages of two people and tells us whether person 1 is
oldest, person 2 is oldest or if they are the same age.

Screen Layout Design

Design Code in Visual Basic


Main Steps Private Sub btnEnter_Click(…
• Declare Variables ' This program…
• RECEIVE Age1 FROM KEYBOARD
• RECEIVE Age2 FROM KEYBOARD Dim Age1 As Integer
• IF Age1 > Age2 THEN Dim Age2 As Integer
• Send ["Person 1 is oldest"] TO
DISPLAY Age1 = InputBox("Please enter the
• ELSEIF Age2 > Age1 THEN age of the first person")
• Send ["Person 2 is oldest"] TO Age2 = InputBox("Please enter the
DISPLAY age of the second person")
• ELSE
• Send ["These people are the same If Age1 > Age2 Then
age"] TO DISPLAY MsgBox("Person 1 is oldest")
• END IF ElseIf Age1 < Age2 Then
MsgBox("Person 2 is oldest")
Else
MsgBox("These people are the
same age")
End If

End Sub

• Create the above HCI.


• Double click the button and enter the code above.
• Run the program to test that it works.

Multiple Conditions Tasks


Task 2 – What type of number?
Create a program that asks the user to enter a whole number and then tells them
whether the number is positive, negative or the number zero.

Task 3 – Grade
Create a program that will display the award that someone achieved in an exam based
on their percentage mark. The criteria for awarding each of the grades is as follows:

Mark as percentage Award


70-100 A
60-69 B
50-59 C
0-50 Fail

Some of the code for the conditional statement is given below

If mark < 50 Then


…………
ElseIf mark < 60 ……
…………

Task 4 – Birth Stone


Create a program that asks a user to enter their birth month and then tells them what
their birthstone is. Use the following information to help you.

Birth Month Birthstone


January Garnet
February Amethyst
March Aquamarine
April Diamond
May Emerald
June Pearl
July Ruby
August Peridot
September Sapphire
October Opal
November Topaz
December Tanzanite

Multiple Conditions Extension Task


Adapt Task 1 – Who is older so that it asks for the user’s names and displays these in
the messages instead of ‘person 1’, ‘person 2’, ‘these people’ in the appropriate place.

Selection – Methods for Data Input


This lesson will cover –
• Different methods for receiving user selection from the keyboard including
• Radio buttons
• Check boxes
• Combo boxes
Sometimes when receiving inputs it is useful to restrict what users are allowed to
enter and to give them a selection to choose from. This can help improve the user
experience and reduce the chances of your program crashing due to unexpected
data.

Different input methods that can be used to restrict what the user is allowed to enter
include
• Radio buttons
• Check boxes and
• Combo boxes

Radio buttons
Radio buttons (sometimes called option buttons) are used when you want to restrict
the user to selecting one option only. For example you can’t have a pizza which is
deep pan and thin crust!

Radio buttons look circular in shape.

Check boxes
Check boxes are useful if you want to allow the user to select more than one choice
at a time. For example if you were ordering a pizza – you would want to be able to
add as many toppings as you wanted.

Check boxes look square in shape.

Note: Group boxes are required when you have a program with a large number of
radio buttons or check boxes relating to different choices. This enables you to put all
of the options that are related to the same selection together.

Comboboxes
Another method for restricting the user to one choice is to use a combobox.

These are often referred to as drop down menus as they provide the user with a
dropdown list from which they can choose one item from.

The user’s selection from the combobox is read in as text.

Task 1 – Pizza Base Choice


Create a program that allows the user to choose a base for their pizza. The two choices
are deep pan or thin crust.
Screen Layout Design

Design Code in Visual Basic


Main Steps Private Sub btnOrder_Click(…
• Declare variables ' This program…
• IF option1 checked THEN
• SEND ["You have chosen Thin Crust If Option1.Checked = True Then
Pizza"] TO DISPLAY MsgBox("You have chosen Thin
• ELSE Crust Pizza")
• SEND ["You have chosen Thin Crust Else
Pizza"] TO DISPLAY MsgBox("You have chosen Deep
• END IF Pan Pizza")
End If

End Sub

• Create the above HCI.


• Double click the button and enter the code above.
• Run the program to test it works.

Task 2 – Pizza Toppings Choice


Create a program that allows the user to choose what toppings they would like for their
pizza.

Screen Layout Design

Design Code in Visual Basic


Main Steps Private Sub btnEnter_Click(…
• Declare variables ' This program…
• IF checkbox1 is checked THEN
• SEND checkbox1 text TO If checkbox1.Checked = True Then
DISPLAY Listbox1.Items.Add(checkbox1.text)
• END IF End If
• IF checkbox2 is checked THEN
• SEND checkbox2 text TO If checkbox2.Checked = True Then
DISPLAY …
• END IF End If
• IF checkbox3 is checked THEN
• SEND checkbox3 text TO If …
DISPLAY
• END IF
• IF checkbox4 is checked THEN End Sub
• SEND checkbox3 text TO
DISPLAY
• END IF

• Create the above HCI.


• Double click the button and enter the code above, filling in any parts that are
missing.
• Run the program to test it works.

Task 3 – Concert ticket


Create a form to enable user to purchase tickets to

Screen Layout Design

To populate the combobox with options, click on the small box to the
right of the Items property.

Key in the options you want to display into the


collection editor (one option per line). Click OK.

You should also change the text property to Select how many.

Design Code in Visual Basic


Main Steps Private Sub Button1_Click(…
• Declare Variables Dim TicketCost As Integer
• SET ticketCost TO 45 Dim Tickets As Integer
• RECEIVE tickets FROM KEYBOARD Dim Total As Integer
• SET total TO tickets * ticketCost
• SEND total TO DISPLAY TicketCost = 45
Tickets = ComboBox1.Text

Total = Tickets * TicketCost

MsgBox("Your total to pay is £" & Total)


End Sub

• Create the above HCI (you can choose which fonts, colours, etc to use and even
include a picture of your chosen artist).
• Double click on button1 to enter the code window.
• Enter the VB code above, correct any errors.
• Run the program using suitable test data to ensure it works.

Methods for Data Input Tasks


Task 4 – Coffee Shop Order
Write a program that asks the user to select either a tea, coffee or hot chocolate from
options given. The program should then display a message confirming the choice of
drink.

Task 5 – Favourite Subject


Create a program that asks the user to select their favourite subject from a list of 4
subjects which includes computing. The program should display the message You
have made an excellent choice if the user selects computing and the message Why?
if any other choice is made.

Task 6 – School Show Tickets


Create a program that asks the user to select which type of ticket they would like to buy
for the school show (Adult, Child or Concession). It will then ask how many tickets they
would like to purchase (to a maximum of 5), and calculates the total cost they have to
pay. Adult tickets cost £5 each, child tickets cost £3 each and concession tickets cost
£4 each.

Methods for Data Input Extension Task


Adapt your pizza toppings task so that rather than the items appearing in a listbox a
picture is displayed when that option is selected.

Screen Layout Design

Design Code in Visual Basic


Main Steps – Extra Cheese Checkbox Private Sub
• IF checkbox1 is checked THEN checkbox1_CheckedChanged(…
• SET cheesepic.visible TO True ' This event is invoked when the
• ELSE Cheese check box is ticked
• SET cheesepic.visible TO False If checkbox1.checked = True Then
• END IF PicureBox1.Visible = True
Else
PicureBox1.Visible = False
End If

End Sub

• Adapt the screen layout so that it looks like the one above. You will need to insert 4
different pictutre boxes with relevant pictures. Set the visible property of each of
these to false.
• This time you are going to add code to the event of the checkbox being
checked/unchecked. Double click checkbox1 and enter the code above.
• Double click the other checkboxes in turn to generate the code for these action
events. Copy and paste the code, editing where necessary.
• Run the program to test that it works.

Iteration – Fixed Loops


This lesson will cover –
• iteration using fixed loops
Iteration
You have already learned that program lines are normally carried out in sequence.
However, often when writing programs it is useful to have one or more lines of a
program repeated several times (this is know as iteration). In this situation we need to
use a loop.

A loop is the process of repeating an instruction, or a set of instructions, a number of


times and it is a very powerful tool in programming.

There are two main types of loop you need to know about
s Fixed Loops
s Conditional loops

You have already used these in Scratch. The blocks looked like this –

Fixed Loop conditional loop

In this unit we are going to learn about fixed loops.

Fixed loops
Fixed loops are useful when you know beforehand how many times the lines of code
will need to be repeated. For example, take in the test scores for all the members of a
class of 20 pupils, record the highest temperature each day for a week (7 days).

Task 1 – Message Display


You are going to create a program to display a message 10 times. In the first version of
this program we will look at how someone who didn’t now about loops might approach
this task.

Screen Layout Design


Design Code in Visual Basic
Main Steps Private Sub button1_Click(…
• Add message to list box ListBox1.Items.Add("Hello There")
• Add message to list box ListBox1.Items.Add("Hello There")
• Add message to list box ListBox1.Items.Add("Hello There")
• Add message to list box ListBox1.Items.Add("Hello There")
• Add message to list box ListBox1.Items.Add("Hello There")
• Add message to list box ListBox1.Items.Add("Hello There")
• Add message to list box ListBox1.Items.Add("Hello There")
• Add message to list box ListBox1.Items.Add("Hello There")
• Add message to list box ListBox1.Items.Add("Hello There")
• Add message to list box ListBox1.Items.Add("Hello There")
End Sub

• Create the above HCI.


• Double click the button and enter the code.
• Run the program to test it is working.

Task 2 – Message Display V2


Here is a second version of the program that uses a FOR…NEXT loop to cut down the
amount of coding required.

Design Code in Visual Basic


Main Steps Private Sub Button1_Click(…
• Declare variables
• FOR index = 1 TO 10 DO Dim index As Integer
• SEND message TO DISPLAY
• END FOR For index = 1 To 10

ListBox1.Items.Add("Hello
There")

Next

End Sub

• Open message display


• Change the code to the code above.
• Run the program to check that it works.

Understanding the code

Dim index As Integer

For index = 1 To 10

ListBox1.Items.Add("Hello There")
Next

Task 3 – Message Display V3


Alter the code created in Task 11 so that
• the user is able to choose the message they would like to display
• the user is able to choose the number of times they would like to display the
message
• there is a blank line displayed between each message.

Design Code in Visual Basic


Main Steps Private Sub Button1_Click(…
• Declare variables
• RECEIVE message FROM Dim index As Integer
KEYBOARD Dim Message As String
• RECEIVE value FROM KEYBOARD Dim Value As Integer
• FOR index = 1 TO value DO
• SEND message TO DISPLAY Message = Inputbox("What message
• SEND blank TO DISPLAY would you like to display?")
• END FOR
Value = Inputbox("How many times
wold you like to display your
message?")

For index = 1 To value

ListBox1.Items.Add(Message)
ListBox1.Items.Add(“”)

Next

End Sub

• Open Message Display.


• Make the changes to the code highlighted in bold above.
• Now run your program to ensure that it works.

Loops in Program Design

Loops in Structure Diagrams


When representing a loop in pseudocode it is crucial to indent the steps within the loop,
and to terminate the loop.

Look at the example below of a program that works out the total bill for items
purchased.

Shopping Receipt
• Declare variables
• SET total TO 0
• RECEIVE NumberOfItems FROM KEYBOARD
• FOR counter = 1 TO NumberOfItems DO
• RECEIVE ItemCost FROM KEYBOARD
• SET total TO total + ItemCost
• END FOR
• SEND total TO DISPLAY

Loops in Structure Diagrams


A loop is represented using a more curved shape box. Any steps within the loop are
shown as subordinates to the loop.

This structure diagram shows the same program as above.

Task 4 – Shopping Basket


Create a program that will calculate the total cost of a number of shopping items
purchased. It will ask the user how many items they have first, before asking them to
enter the price of each item. It will then display the total cost.

Screen Layout Design

Program Design Code in Visual Basic


• Declare variables Private Sub Start_Click(…
• SET total TO 0 ‘ this program will …
• RECEIVE NumberOfItems FROM
KEYBOARD Dim NumberOfItems As Integer
• FOR counter = 1 TO NumberOfItems Dim ItemCost As Single
DO Dim Total As Single
• RECEIVE ItemCost FROM Dim Index As Integer
KEYBOARD
• SET total TO total + ItemCost Total = 0
• END FOR
• SEND total TO DISPLAY NumberOfItems = InputBox("please
enter number of items purchased")

For Index = 1 To NumberOfItems


ItemCost = InputBox("Please
enter the cost of one item in
pounds £")
Total = Total + ItemCost
Next

Textbox1.Text = Total
End Sub

• Create the above HCI.


• Double click the button and enter the code.
• Run the program to test it is working.

Task 5 – Test Marks


Create a program to enable a student to enter their score in 5 tests (each marked out of
20). This program will make use of the Index value to give the user prompts and to
display the information. The program should also work out the student’s average score
and display this.

Screen Layout Design

Program Design Code in Visual Basic


• Declare variables Private Sub Start_Click(…
• SET Total TO 0 ‘ this program will …
• FOR index = 1 TO 5 DO
• RECEIVE score FROM KEYBOARD Dim Score As Integer
• SEND test number and score TO Dim Total As Integer
DISPLAY Dim Average As Integer
• SET Total TO Total + Score Dim Index As Integer
• END FOR
• SET Average TO Total/5 Total = 0
• SEND Average TO DISPLAY
For Index = 1 To 5
Score = InputBox("Enter your score
for test " & Index)
ListBox1.Items.Add("Test " & Index &
vbTab & Score)
Total = Total + Score
Next

Average = Total/5

ListBox1.Items.Add("Your average mark


for the 5 tests was " & Average)
End Sub

• Create the above HCI.


• Double click the button and enter the code.
• Run the program to test it is working. Your output should look
something like this…
Fixed Loop Tasks
Task 6 – Punishment Exercise
Your Computing teacher has given you 100 lines for forgetting
your homework. Create a program that displays “I must complete my Computing
homework on time” 100 times.

Task 7 – Football Tournament


Create a program to enable a user to enter the names of six teams that took part in a
Sunday league, and the number of goals scored by each team. The program should
display the names of the teams along with any goals scored. The program should also
calculate and display the total number of goals scored that day.

Task 8 – Subject Test Marks


Create a program to enable a student to enter the name of four subjects and their test
marks (out of 100) for each subject. The subjects and marks should be displayed in a
listbox. The program should also work out the student’s average mark and display this.
The algorithm for the task is given below:

• Declare variables
• SET Total TO 0
• FOR index = 1 TO 4 DO
• RECEIVE SubjectName FROM KEYBOARD
• RECEIVE TestMark FROM KEYBOARD
• SEND SubjectName and TestMark TO DISPLAY
• SET Total TO Total + TestMark
• END FOR
• SET Average TO Total/4
• SEND Average TO DISPLAY

Fixed Loop Extension Task – Multiplication Tables

Create a program which uses a loop to display a multiplication table. The user should
be able to choose which multiplication table they would like to display.

The chosen multiplication table should be displayed in the form:

2x1=2
2x2=4
….
2 x 10 = 20

Hints: you will need to use 3 variables (eg counter, multiplier and answer).

Your interface may look something like this…


Iteration – Conditional Loops
This lesson will cover –
• Iteration/repetition using conditional loops

Conditional Loops
You know that loops are used in programming to repeat a set of
instructions. However, the For…Next loop is useful for repeating
instructions only if the programmer knows beforehand the number of
times the loop will need to be repeated. It is often not known how
many times a repetition is required.

A conditional loop (sometimes referred to as a Do…Loop) allows the


program to check various conditions before allowing the loop to
proceed each time.

There are several variations of the Do..Loop. Different types of


conditional loop include:

• Do…Loop Until
• Do...Loop While
• Do While…Loop
• Do Until…Loop

The structure chosen will depend on:

• whether the condition is to be checked at the start of the loop (Do


While…Loop and Do Until…Loop), or at the end (Do…Loop Until
and Do…Loop While)
• whether the statements are to be executed as long as the
condition is true (Do While…Loop and Do…Loop While) or as long
as the condition is false (Do…Loop Until and Do Until…Loop)

Task 1 – Over 100


Create a program that asks the user to enter a number, and then adds up the total, until
the total is greater than 100.

Screen Layout Design

Program Design Code in Visual Basic


• Declare variables Private Sub Start_Click(…
• SET total TO 0 ‘ this program will …
• REPEAT
• RECEIVE number FROM Dim number As Integer
KEYBOARD Dim total As Integer
• SET total TO total + number
• SEND total TO DISPLAY Total = 0
• UNTIL total > 100
Do
number = InputBox("Please enter a
number to be added")
total = total + number
TextBox1.Text = total
Loop Until total > 100

End Sub

• Create the above HCI.


• Double click the button and enter the code.
• Run the program to test it is working.

Task 2 – Class Register


Create a program that will enable a teacher to enter a list of names of pupils in his
class. The program should keep asking the user to enter pupil names until the user
enters ‘stop’.

Screen Layout Design

Program Design Code in Visual Basic


• Declare variables Private Sub Start_Click(…
• REPEAT ‘ this program will …
• RECEIVE name FROM KEYBOARD
• SEND name TO DISPLAY Dim name As String
• UNTIL name = “stop”
Do
name = InputBox("Please enter the
name of pupil to be added to the
list or enter ‘stop’ to finish")
ListBox1.Items.Add(name)
Loop Until name = "stop"
End Sub

• Create the above HCI.


• Double click the button and enter the code.
• Run the program to test it is working.

Extension: currently the program adds the word ‘stop’ to the bottom of list. Make
changes to the code so that this word does not appear in the list (there is more than one
solution to this problem).

Task 3 – Capital of France


Create a program that asks the user to enter the answer to the question “What is the
Capital of France?” until they enter the correct response. The program will then tell the
user they are correct and how many attempts they took.

Screen Layout Design

Program Design Code in Visual Basic


• Declare variables Private Sub Start_Click(…
• SET counter TO 0 ‘ this program will …
• REPEAT
• RECEIVE answer FROM Dim answer As String
KEYBOARD Dim counter As String
• SET counter TO counter + 1
• UNTIL answer = “Paris” counter = 0
• SEND [“Well done – you took counter
attempts”] TO DISPLAY Do
answer = InputBox("What is the
Capital of France?")
counter = counter + 1
Loop Until answer = "Paris"

MsgBox("Well done – you took " &


counter & " attempts.")
End Sub

• Create the above HCI.


• Double click the button and enter the code.
• Run the program to test it is working.

Conditional Loop Tasks


Task 3 – Quiz Question
Create a program to ask the user a question of your choice until they get the answer
correct.

Task 4 – Shopping list


Create a program that enables a user to keep entering the name of items on their
shopping list until they have no more items to enter. The program should provide the
user with a numbered list of the items that they want to purchase.

Task 5 – Twenty’s Plenty


Create a program that asks the user to enter numbers and adds them together until the
total is exactly 20. When a total of 20 is reached the program should display a
congratulations message that tells the user how many numbers they entered to reach
the goal.
Conditional Loop Extension Task – Different Types of Loop
Adapt task 1 – over 100 to explore the different types of loop

The structure for the other 3 types of loop is shown below….

Do Until condition Do Do While condition


line(s) of code to be line(s) of code to be line(s) of code to be
repeated repeated repeated
Loop Loop While condition Loop

You may need to adapt your condition slightly for some of the loops.

Write a short report summarising the 4 different types of loop.

Vous aimerez peut-être aussi