Académique Documents
Professionnel Documents
Culture Documents
Development
Programming With
Booklet 1
Contents
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.
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.
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.
Setting Up VB
From the Start 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.
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.
• Now enter the following line within the Button1_Click event (remember to leave the
existing VB code as it is).
End Sub
End Class
• 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.
1. Test your program works by clicking on the Click Here on your form. You should get
a message box something like this…
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)
• 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.
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.
Program Code
Public Class Form1
Name = textbox1.text
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
Name = .text
End Sub
End Class
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).
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.
We can now rewrite these to give us a better understanding of what our program will do
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.
It is good practice to include the following 4 lines at the beginning of any program.
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.
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.
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.
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 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).
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)
• 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
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
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.
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.
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.
Listbox1.items.add(foremane & “ “ & Surname & & "’s ID is " & userID)
TotalMark = …
Textbox1.Text = TotalMark
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
• 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
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!).
Textbox1.Text = “”
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.
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 –
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.
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:
For example
• Declare variables
• RECEIVE test1 FROM KEYBOARD
• RECEIVE test2 FROM KEYBOARD
• SET totalMark TO test1 + test 2
• SEND toalMark TO DISPLAY
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
End Sub
Extension
Adapt the code so that it displays “fail” in the textbox when a user has not scored above
50.
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
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).
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
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.
End Sub
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:
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!
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.
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.
End Sub
To populate the combobox with options, click on the small box to the
right of the Items property.
You should also change the text property to Select how many.
• 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.
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.
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 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).
ListBox1.Items.Add("Hello
There")
Next
End Sub
For index = 1 To 10
ListBox1.Items.Add("Hello There")
Next
ListBox1.Items.Add(Message)
ListBox1.Items.Add(“”)
Next
End Sub
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
Textbox1.Text = Total
End Sub
Average = Total/5
• 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
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.
2x1=2
2x2=4
….
2 x 10 = 20
Hints: you will need to use 3 variables (eg counter, multiplier and answer).
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.
• Do…Loop Until
• Do...Loop While
• Do While…Loop
• Do Until…Loop
End Sub
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).
You may need to adapt your condition slightly for some of the loops.