130
Download and Setup
Download VB Express and install it on your computer at home.
[Link]
If you don’t run Windows as your operating system you can try using Mono
[Link]
Your first program
aq
Start a new Project and select Console Application. Type the following code:
module module1
sub main()
end sub
end module
[Link]()
ht
[Link]("Hello World!")
us
(Press F5 to run the code)
.M
Tasks
0.1 – Write a program that displays the message “Hello Dave”
M
0.2 – Write a program that displays the message “My name is Dave and I live in Brussels” (replace
Dave and Brussels with your own information)
0.3 – Write a program that displays the lyrics to your national anthem. Each line of the song should
be on a fresh line.
[Link] (A-Level Computer Science/AICT) in LGS,GSIS,Apples For help and Guidance
Contact : 0321-5275281
131
Example Program 1 – Sequence
Module Module1
Sub Main()
[Link]("This is the first line of the program. It will be executed
first.")
[Link]()
[Link] = [Link]
[Link]("But then the colour changes to Red.")
[Link]()
[Link] = [Link]
[Link]("And the background goes white")
[Link]()
aq
[Link]()
[Link]("But it's okay. We can reset it")
[Link]()
[Link] = [Link]
[Link]("The order of lines of code is important")
[Link]()
End Sub ht
[Link]("We start at the top and work down")
us
End Module
.M
Tasks
1.1) Display the words red, amber, green on a fresh line each in order on the screen. Colour the
words appropriately.
M
1.2) Displaythe names of the colours of the rainbow. Each on a separate line, coloured and in order.
[Link] (A-Level Computer Science/AICT) in LGS,GSIS,Apples For help and Guidance
Contact : 0321-5275281
132
Example Program 2 - Assignment - Integer, byte, real, boolean, character, string, date/time.
Module Module1
Sub Main()
Dim theNumber As Integer
Dim theWord As String
theWord = "Bird"
theNumber = 9
[Link](theWord & " is the word")
[Link]("And the number is " & theNumber)
aq
[Link]()
theWord = "Cat"
[Link]("Enter a number>")
theNumber = Int([Link]())
theNumber)
[Link]() ht
[Link]("Now " & theWord & " is the word and the number is " &
us
End Sub
End Module
.M
M
[Link] (A-Level Computer Science/AICT) in LGS,GSIS,Apples For help and Guidance
Contact : 0321-5275281
133
Example Program 3 - Arithmetic - +, –, /, x, DIV, MOD
Module Module1
Sub Main()
Dim number1, number2, total As Integer
[Link]("Enter first number")
number1 = Int([Link]())
[Link]("Enter second number")
number2 = Int([Link]())
total = number1 + number2
aq
[Link]("The total is " & total)
[Link]()
End Sub
End Module
ht
us
Tasks
3.1) Write a program that divides a number entered by the user by 2
.M
3.2) Write a program that displays the 7 times table
3.3) Write a program that displays any times table the user requests
M
[Link] (A-Level Computer Science/AICT) in LGS,GSIS,Apples For help and Guidance
Contact : 0321-5275281
134
Example Program 4 – Selection
Dim intInput As Integer
[Link]("Enter an integer…")
intInput = Val([Link]())
If intInput = 1 Then
[Link]("Thank you.")
ElseIf intInput = 2 Then
[Link]("That's fine.")
ElseIf intInput = 3 Then
[Link]("Too big.")
aq
Else
[Link]("Not a number I know.")
End If
[Link]()
ht
1. Write a program to ask the user what 24+9 is. Say “Excellent” if they get it right.
us
2. Write a program to ask the user “how many in a bakers dozen?” and say “most
.M
excellent” if they get it right.
M
3. Write a program to ask the user to enter their age. If their age is under 18 then say
“Sorry, this film is not for you”.
4. Write a program to ask the user for two numbers. Compare the first with the second
and then print out one of three messages. Either the numbers are equal, the first is
bigger, or the second is bigger. You will need more than one IF to solve this one.
5. Write a program which asks the user to enter their password. If they enter the word
“PASSWORD” then display the message “Welcome to the treasure”, otherwise
display a message which says “go away, it’s all mine”.
6. Write a program which asks the user to enter a number between 1 and 10. If the
number entered is out with this range then display a message “Sorry…out of range”.
[Link] (A-Level Computer Science/AICT) in LGS,GSIS,Apples For help and Guidance
Contact : 0321-5275281
135
Example Program 5 - Relational operators - =, <, >, <>, <=, >=
Module Module1
Sub Main()
Dim age As Integer
[Link]("What is your age?")
age = Int([Link]())
If age > 16 Then
[Link]("You can drive!")
Else
aq
[Link]("You are too young to drive")
End If
[Link]()
End Sub
End Module
ht
us
The symbols we can use to test for conditions are as follows:
< Less than
.M
<= Less Than or Equal To
> Greater than
M
>= Greater Than or Equal To
== IS Equal To
!= Not Equal To
[Link] (A-Level Computer Science/AICT) in LGS,GSIS,Apples For help and Guidance
Contact : 0321-5275281
136
Example Program 6 - Boolean operators - NOT, AND, OR
Module Module1
Sub Main()
Dim age, points As Integer
[Link]("What is your age?")
age = Int([Link]())
[Link]("How many points do you have on your licence?")
points = Int([Link]())
If age > 16 And points < 9 Then
aq
[Link]("You can drive!")
Else
[Link]("You are not eligable for a driving licence")
End If
[Link]()
End Sub
ht
us
End Module
.M
M
[Link] (A-Level Computer Science/AICT) in LGS,GSIS,Apples For help and Guidance
Contact : 0321-5275281
137
Moderation Exercise 1 – Central Heating
The heating system in a school should be switched on if the average temperature is less than
17 degrees Celsius (˚C). The average temperature is found from the temperatures in the Art,
English and Music Departments. You are required to write a program that allows the user to
input the three temperatures. The program calculates and displays the average temperature
then displays ‘Heating should be on.’ or ‘Heating should be off.’ as appropriate.
aq
You may practice this task at home, but won’t be able to refer to any notes or files when assessed.
ht
Submit the following for marking in 1 word document:-
1. Your code listing
us
2. Screenshots for suitable test data
.M
M
[Link] (A-Level Computer Science/AICT) in LGS,GSIS,Apples For help and Guidance
Contact : 0321-5275281
138
Example Program 7 - Logical bitwise operators - NOT, AND, OR, XOR
Dim a, b, c, d, e, f, g As Boolean
a = 23 > 14 And 11 > 8
b = 14 > 23 And 11 > 8
' The preceding statements set a to True and b to False.
c = 23 > 14 Or 8 > 11
d = 23 > 67 Or 8 > 11
' The preceding statements set c to True and d to False.
e = 23 > 67 Xor 11 > 8
f = 23 > 14 Xor 11 > 8
g = 14 > 23 Xor 8 > 11
aq
' The preceding statements set e to True, f to False, and g to False.
Dim x, y As Boolean
x = Not 23 > 14
y = Not 23 > 67
ht
' The preceding statements set x to False and y to True.
us
Tasks
1) Adapt the example program so that there is output of the result of
each comparison to the screen
.M
M
[Link] (A-Level Computer Science/AICT) in LGS,GSIS,Apples For help and Guidance
Contact : 0321-5275281
139
Example Program 8 - Built-in functions - Arithmetic functions: round, truncation.
Dim num As Double
Dim rounded As Integer
Dim squarert As Double
Dim trunc As Integer
[Link]("Enter a real number")
num = [Link]()
rounded = [Link](num)
squarert = [Link](num)
aq
[Link]("round: " & rounded & vbNewLine & "Square Root: " & squarert)
trunc = [Link](num)
ht
[Link]("The number truncated is " & trunc)
[Link]("This is not always the same as rounded")
[Link]()
us
Tasks
.M
1) Write a program that asks for 5 numbers, calculates the mean average and then rounds it
down. Display the result on screen.
M
[Link] (A-Level Computer Science/AICT) in LGS,GSIS,Apples For help and Guidance
Contact : 0321-5275281
140
Example Program 9 - String handling functions length, position, substring,
concatenation.
Dim theString As String
theString = "Hello Dave, you're my wife now!"
[Link](theString)
[Link]([Link]) 'display the string's length
[Link]([Link]) 'display the string in upper case
[Link]([Link]) 'display the string in lower case
[Link]([Link]("Dave")) 'is Dave there?
[Link]([Link]("D")) 'position of D
aq
[Link]([Link](12)) 'displays the substring starting at
position 12
Dim newString As String
ht
newString = "Speak to Dave! " & theString 'string concatenation
[Link](newString)
us
[Link]() 'pause and wait so user can read output.
.M
Tasks
1. Write a program that checks a username against a stored value. How the user enters the
M
username should NOT be case sensitive.
2. Adapt program 1 so that it also takes in a password. If the user enters spaces after the
password the computer will trim them out automatically.
3. Write a program that will check a phone number is of the correct length.
4. Write a program that asks for a user’s full name in one inputbox/textbox but then stores the
first and second names in different variables.
[Link] (A-Level Computer Science/AICT) in LGS,GSIS,Apples For help and Guidance
Contact : 0321-5275281
141
Example Program 10 - String conversion functions to/from integer, real,
date/time.
Dim theInt, theReal, theDate As String
theInt = "23021980"
theReal = "230.21980"
theDate = "23-02-1980"
'whole numbers
[Link](theInt)
[Link](theInt + "1")
[Link](Convert.ToInt32(theInt))
[Link]((Convert.ToInt32(theInt) + 1))
aq
[Link]()
'real numbers
[Link](theReal)
[Link](theReal + "1")
ht
[Link]([Link](theReal))
[Link]([Link](theReal) + 1)
[Link]()
us
'dates
[Link](theDate)
[Link](theDate + "1")
[Link]([Link](theDate))
.M
[Link]([Link](theDate).AddDays(1))
[Link]() 'pause and wait so user can read output.
M
Tasks
1) Using the toString function, recreate the example program in reverse
[Link] (A-Level Computer Science/AICT) in LGS,GSIS,Apples For help and Guidance
Contact : 0321-5275281
142
Example Program 11 - Repetition
Module Module1
Sub Main()
Dim theNumber As Integer
theNumber = 7
'a loop
For x = 1 To 10
[Link]("7 x " & x & " = " & (7 * x))
Next
aq
'the end of the loop
[Link]() 'pause so user can see
End Sub
End Module
ht
us
Tasks
1. Write a program which asks for your name and then displays it 5 times on the
.M
screen.
2. Write a program to display the name of the town you live in 10 times.
3. Write a program to ask for a person’s favourite CD and the artist. Both should
M
be displayed on the same line 5 times.
4. Write a program to ask for a number and display its multiplication table 1 to
100
5. Write a program that asks the user for a number 5 times and adds them all up
to give a total.
[Link] (A-Level Computer Science/AICT) in LGS,GSIS,Apples For help and Guidance
Contact : 0321-5275281
143
Section 12 - Flowcharts
A flowchart is another way of breaking down a program in the form of a
diagram.
The following are recognised flowchart symbols:
aq
ht
Task 12.1 Create a program from the following flowchart:
us
.M
M
[Link] (A-Level Computer Science/AICT) in LGS,GSIS,Apples For help and Guidance
Contact : 0321-5275281
144
Task 12.2 Create a program for the following flowchart:
aq
ht
us
.M
M
Task 12.3 - Write a flowchart for example program 6
Task 12.4 – Write a flowchart for example program 11
[Link] (A-Level Computer Science/AICT) in LGS,GSIS,Apples For help and Guidance
Contact : 0321-5275281
145
Example Program 13 – Procedures & Functions
Module Module1
'this is a procedure
Sub timestable(ByRef number As Integer)
For x = 1 To 10
[Link](number & " x " & x & " = " & (number * x))
Next
End Sub
'this is a function (functions return a value)
Function adder(ByRef a As Integer, ByVal b As Integer)
adder = a + b
Return adder
aq
End Function
Sub Main()
timestable(7) 'this is a call (executes a procedure or function)
different data
timestable(9)
ht
timestable(3) 'this is a second call to the same procedure but now with
us
[Link]()
[Link]()
Dim x As Integer
.M
x = adder(2, 3) 'call to function adder which returns a value
[Link]("2 + 3 = " & x)
[Link]("4 + 6 = " & adder(4, 6)) 'you can simply the code by
putting the call directly into the print statement
M
[Link]()
End Sub
End Module
Tasks
1) Write a function for calculating the volume of a cuboid
2) Write a function for calculating the volume of a sphere
3) Write a procedure for checking a user’s password
[Link] (A-Level Computer Science/AICT) in LGS,GSIS,Apples For help and Guidance
Contact : 0321-5275281
146
Section 14 – By Ref vs. By Val
Parameters can be passed by reference (byref) or by value (byval).
If you want to pass the value of the variable, use the ByVal syntax. By passing the value of the
variable instead of a reference to the variable, any changes to the variable made by code in the
subroutine or function will not be passed back to the main code. This is the default passing
mechanism when you don’t decorate the parameters by using ByVal or ByRef.
If you want to change the value of the variable in the subroutine or function and pass the revised
value back to the main code, use the ByRef syntax. This passes the reference to the variable and
allows its value to be changed and passed back to the main code.
aq
ht
us
.M
M
[Link] (A-Level Computer Science/AICT) in LGS,GSIS,Apples For help and Guidance
Contact : 0321-5275281
147
Moderation Exercise 2 – Car Hire
Tervuren Car Hire Company has a range of cars for rent. Charges start at £20 a day for the
cheapest to £70 a day for the most expensive. The company requires a program that gives
customers printed details of charges. The program asks the user for a car make, model and
daily rate 1 then displays a table of daily charges for between one and fourteen days. If the
make is VW, a message indicating a gift of a free road atlas is displayed.
An example of output is shown below. The output from your program may look different but
must meet the specification.
aq
TERVUREN CAR HIRE COMPANY
Enter car make. VW
ht
Enter car model. Golf
Enter daily rate. 22
Days Charge (£)
us
1 22
2 44
3 66
4 88
5 110
.M
6 132
7 154
8 176
9 198
10 220
M
11 242
12 264
13 286
14 308
YOU GET A FREE ROAD ATLAS WITH THIS HIRE.
You may practice this task at home, but won’t be able to refer to any notes or files when assessed.
Submit the following for marking in 1 word document:-
1. Your code listing
2. Screenshots for suitable test data
1
Daily rates are in whole numbers of pounds.
[Link] (A-Level Computer Science/AICT) in LGS,GSIS,Apples For help and Guidance
Contact : 0321-5275281
148
Example Program 15 - Constants
'a constant is a value that doesn't change
'using them greatly improves the readability of your code
'number constants
Const conPi = 3.14159265358979
Const conMaxPlanets As Integer = 9
'string constants
Const conVersion = "07.10.A"
Const conCodeName = "Enigma"
'try assigning a new value to one of your constants
aq
'to make a constant available to the whole program "Public" should precede it
'and it should be placed inside the module but outside the procedure
'try it
'there are string constants created by VB
[Link]("Pi is" &
[Link]("Pi is" &
[Link]("Pi is" &
ht
conPi)
vbCr & conPi)
vbTab & conPi)
us
[Link]()
.M
M
[Link] (A-Level Computer Science/AICT) in LGS,GSIS,Apples For help and Guidance
Contact : 0321-5275281
149
Example Program 16 - Data Structures
Visual Basic has many data type such as Integer, String, Double, Single, etc. Aside from those intrinsic
data type that has been provided by VB, you can create your own data type by combining several
different types. This UDT is useful to create single variable contain several useful information. It is
usually useful for database record. You define the UDT using syntax:
Type VariableType
Variable1 as varType1
Variable2 as varType2
….
VariableN as varTypeN
End Type
aq
After that you can declare any name as this new variable type and use it as ordinary variable.
ht
Note: Special for this project, please do not copy and paste from this tutorial. Type the code
manually so that you may understand the different between UDT and normal variable.
us
Create new console project
In the general declaration section, type:
.M
Private Type City
Name As String
Population As Long
M
Diameter As Double ' in km
Year As Integer
End Type
Sub Main()
Dim myRecord As City
[Link] = [Link]()
[Link] = [Link]()
[Link] = [Link]()
[Link] = [Link]()
[Link]([Link] & " city has population of " & _ [Link] & "
million people " & vbCr & " and diameter of " & [Link] & " km in year " & _
[Link]
End Sub
Tasks
1) Run the program and try the data for some real city. You see that UDT combine several data
type into single unit.
2) Adapt the program so each input has a suitable prompt
[Link] (A-Level Computer Science/AICT) in LGS,GSIS,Apples For help and Guidance
Contact : 0321-5275281
150
Other Built-in Data Types
We are familiar with int, double, boolean, string and char already.
There are also bytes and dates/times.
Byte
Bytes are 8-bit (1 byte) unsigned integers ranging in value from 0 to 255 ( 0 to 2^8-1). The You can
declare Byte variables using the BYTE keyword with the DIM statement. For example:
DIM I AS BYTE
Byte variables are particularly useful for storing small, unsigned integral quantities like the number
of days in a month. You should not use Byte variables in FOR/NEXT loops, as they are highly
aq
inefficient.
Enumerated: is a data type consisting of a set of named values called elements
Enum CardSuit
Clubs
Diamonds ht
us
Hearts
Spades
End Enum
.M
Enum DayOfWeek
Monday = 1
Tuesday = 2
Wednesday = 3
M
Thursday = 4
Friday = 5
Saturday = 6
Sunday = 7
End Enum
Enum Result
Win = 3
Lose = 1
Draw = 0
End Enum
[Link] (A-Level Computer Science/AICT) in LGS,GSIS,Apples For help and Guidance
Contact : 0321-5275281
151
Records
In VB, Records are known as structures. They allow you to combine several data items (or fields) into
one variable. For example in college instead of having a separate variable to store information about
each fact about a student, you would create a student record with fields to store each fact (or field!):
Structure student 'record declaration
dim id as integer 'field
dim name as string 'field
aq
dim DoB as date 'field
End Structure
Sub Main()
ht
us
dim newStudent as student
[Link]("insert the id")
.M
[Link] = [Link]()
[Link]("insert the name")
M
[Link] = [Link]()
[Link]("insert the Date of Birth")
[Link] = [Link]()
[Link]("new record created: " & [Link] & " " & [Link] & " " &
[Link])
End Sub
But why should we use Records? Well it makes for much neater code, without having to declare
dozens of variables, we could declare a couple of students. You'll also see how neat your code can
become when using arrays of records.
[Link] (A-Level Computer Science/AICT) in LGS,GSIS,Apples For help and Guidance
Contact : 0321-5275281
152
Tasks
1) Test the above code
2) Add an additional field to the record
3) Create a record structure for cars and test it with a main method
4) Create a record structure for pets and test it with a main method
aq
ht
us
.M
M
[Link] (A-Level Computer Science/AICT) in LGS,GSIS,Apples For help and Guidance
Contact : 0321-5275281
153
Example Program 17 – 1 dimensional arrays
Dim countries(5) As String
Dim randomNum As Integer
countries(1) = "Scotland"
countries(2) = "Belgium"
countries(3) = "Netherlands"
countries(4) = "Germany"
countries(5) = "France"
Randomize()
randomNum = Int(Int((5 * Rnd()) + 1))
[Link]("You should go to " & countries(randomNum) & " on holiday.")
aq
[Link]()
Tasks
ht
us
1) Write a program which will set up an array to hold 50 numbers. Call the array numbers. Display
the array's contents across the screen. They should all be 0.
2) Create a program that stores an array of car records. At least 5 cars and 4 fields per record.
.M
3) Create a program that stores an array of 5 people records. The information should be entered by
the user.
M
4) Adapt program 2 to now do a linear search for a certain car and display it’s details.
For help and Guidance
[Link] (A-Level Computer Science/AICT) in LGS,GSIS,Apples Contact : 0321-5275281
154
Example Program 18a – Read from a text file
Dim objStreamReader As [Link]
Dim strLine As String
'Pass the file path and the file name to the StreamReader constructor.
objStreamReader = New [Link]("H:\[Link]")
'Read the first line of text.
strLine = [Link]
'Continue to read until you reach the end of the file.
Do While Not strLine Is Nothing
'Write the line to the Console window.
aq
[Link](strLine)
'Read the next line.
strLine = [Link]
Loop
'Close the file.
[Link]()
ht
us
[Link]()
Tasks
.M
1) Write a program that reads the students’ names from a txt file and displays them on the
screen
2) Write a program that reads 10 team names from a txt file and stores them in an array
M
3) Write a program that reads 5 song titles from a csv file and displays them on the screen
4) Write a program that reads 20 team names from a csv file into an array, then displays the
array on screen
[Link] (A-Level Computer Science/AICT) in LGS,GSIS,Apples For help and Guidance
Contact : 0321-5275281
155
Example Program 18b – Write to a text file
Dim objStreamWriter As [Link]
'Pass the file path and the file name to the StreamWriter constructor.
objStreamWriter = New [Link]("H:\[Link]")
'Write a line of text.
[Link]("Hello World")
'Write a second line of text.
[Link]("From the StreamWriter class")
'Close the file.
[Link]()
aq
Tasks
ht
1) Write a program that asks for 5 names and then writes then to a file
2) Write a program that writes the colours of the rainbow to a csv file
3) Write a program that reads a hiscore table from a file, asks the user to add a new hiscore,
us
then writes this new hiscore table to the file.
.M
M
[Link] (A-Level Computer Science/AICT) in LGS,GSIS,Apples For help and Guidance
Contact : 0321-5275281
156
Example Program 19 - Read/write records from/to a file of records.
Imports [Link]
Imports [Link]
Module Module1
Structure person
Dim name As String
Dim age As Integer
Dim alive As Boolean
End Structure
Dim File As String
aq
Sub Main()
Dim student1 As person
[Link] = "John"
[Link] = 17
[Link] = True
Dim student2 As person
[Link] = "Emily" ht
us
[Link] = 16
[Link] = True
File = "H:\[Link]" 'location of the file
.M
' write file
FileOpen(1, File, [Link], [Link])
FilePut(1, student1)
FilePut(1, student2)
FileClose(1)
M
' read file
FileOpen(1, File, [Link], [Link])
FileGet(1, student1)
FileGet(1, student2)
FileClose(1)
'display data
[Link]("Student1: " & [Link] & vbTab & [Link] & vbTab
& [Link])
[Link]("Student2: " & [Link] & vbTab & [Link] & vbTab
& [Link])
[Link]()
End Sub
End Module
Tasks
1) Amend the program so that there is a write procedure and a read procedure which are
called
2) Amend the program so that the 2 student are stored in an array of people, then write and
read the array to the file
[Link] (A-Level Computer Science/AICT) in LGS,GSIS,Apples For help and Guidance
Contact : 0321-5275281
157
Example Program 20 - Validation
Dim mark As Integer
Do
[Link]("Enter a mark between 0 and 10")
mark = Val([Link]())
If (mark > 10) Or (mark < 0) Then [Link]("That was not a valid
mark")
Loop Until (mark >= 0) And (mark <= 10) ' keeps going until a valid mark is entered
[Link]("Well done!")
[Link]()
aq
Tasks
1) Write a program that validates a user is old enough to drive (older than 17, younger than 80)
ht
2) Write a program that checks that a telephone number entered is long enough (string length)
3) Write a program that checks that both a username and password is correct before allowing
us
you to proceed.
.M
M
[Link] (A-Level Computer Science/AICT) in LGS,GSIS,Apples For help and Guidance
Contact : 0321-5275281
158
Example Program 21 – 2 dimensional arrays
' Declare two-dimensional array of strings.
Dim values(,) As String = New String(,) {{"ant", "aunt"},
{"Sam", "Samantha"},
{"clozapine", "quetiapine"},
{"flomax", "volmax"},
{"toradol", "tramadol"}}
' Get bounds of the array.
Dim bound0 As Integer = [Link](0)
Dim bound1 As Integer = [Link](1)
' Loop over all elements.
For i As Integer = 0 To bound0
aq
For x As Integer = 0 To bound1
' Get element.
Dim s1 As String = values(i, x)
[Link](s1)
[Link](" "c)
Next
Next
[Link]()
ht
us
[Link]()
.M
Tasks
1) Create a 2d array which stores and displays a grid for noughts and crosses. Allow users to
pick a location and set it to an X or a O.
M
2) 2d array which stores a grid for Battleships. Allows the user to place their 5 ships and isplay
on screen.
[Link] (A-Level Computer Science/AICT) in LGS,GSIS,Apples For help and Guidance
Contact : 0321-5275281
159
Example Program 22 – Enumerated
An Enumeration is basically a new data type (like String or Integer) that you design yourself, which
has an associated list of possible values (known as elements).
You might think it would be better to use a String to hold the current value instead, but there are
several reasons why an Enum is better, such as:
• The list of valid options will be shown in a pop-up list when you are writing code (see the
picture below, after the first Code snippet), so you don't need to remember them or even
type them - instead you can just select them with your mouse or keyboard.
• It is harder to make a typo that causes bugs, as not only are the values shown in the list for
aq
you to pick from, but also valid entries you type will be changed to the case you declared
them - so you can see when the case is not automatically corrected for you.
• If you use Option Explicit (which is highly recommended anyway), any typo's will cause a
message warning you about them.
•
ht
They take less memory than Strings, and code that uses them runs faster than the String
equivalent.
us
Enum Importance
Critical = 4
Important = 3
None = 0
.M
Regular = 2
Trivial = 1
End Enum
Sub Main()
M
Dim value As Importance = [Link]
' Select the enum and print a value.
Select Case value
Case [Link]
[Link]("Not true")
Return
Case [Link]
[Link]("True")
Exit Select
End Select
End Sub
[Link] (A-Level Computer Science/AICT) in LGS,GSIS,Apples For help and Guidance
Contact : 0321-5275281
160
Section 23 - Set operators
Union
' Create two arrays of integer values.
Dim ints1() As Integer = {5, 3, 9, 7, 5, 9, 3, 7}
Dim ints2() As Integer = {8, 3, 6, 4, 4, 9, 1, 0}
' Get the set union of the two arrays.
Dim union As IEnumerable(Of Integer) = [Link](ints2)
' Display the resulting set's values.
Dim output As New [Link]
For Each num As Integer In union
[Link](num & " ")
aq
Next
[Link]([Link]())
[Link]()
Range
ht
' Generate a sequence of integers from 1 to 10
' and project their squares.
us
Dim squares As IEnumerable(Of Integer) = [Link](1,
10).Select(Function(x) x * x)
Dim output As New [Link]
For Each num As Integer In squares
.M
[Link](num)
Next
' Display the output.
[Link] ([Link]())
M
[Link]()
Intersection
' Create two integer arrays.
Dim id1() As Integer = {44, 26, 92, 30, 71, 38}
Dim id2() As Integer = {39, 59, 83, 47, 26, 4, 30}
' Find the set intersection of the two arrays.
Dim intersection As IEnumerable(Of Integer) = [Link](id2)
Dim output As New [Link]
For Each id As Integer In intersection
[Link](id)
Next
' Display the output.
[Link] ([Link])
[Link]()
[Link] (A-Level Computer Science/AICT) in LGS,GSIS,Apples For help and Guidance
Contact : 0321-5275281
161
Difference (Distinct)
Module Module1
Sub Main()
Dim products() As Product =
{New Product With {.Name = "apple", .Code = 9},
New Product With {.Name = "orange", .Code = 4},
New Product With {.Name = "apple", .Code = 9},
New Product With {.Name = "lemon", .Code = 12}}
' Exclude duplicates.
Dim noduplicates = [Link](New ProductComparer())
For Each product In noduplicates
aq
[Link]([Link] & " " & [Link])
Next
[Link]()
End Sub
End Module
ht
us
Public Class Product
Public Property Name As String
Public Property Code As Integer
End Class
.M
' Custom comparer for the Product class
Public Class ProductComparer
Implements IEqualityComparer(Of Product)
Public Function Equals1(
M
ByVal x As Product,
ByVal y As Product
) As Boolean Implements IEqualityComparer(Of Product).Equals
' Check whether the compared objects reference the same data.
If x Is y Then Return True
'Check whether any of the compared objects is null.
If x Is Nothing OrElse y Is Nothing Then Return False
' Check whether the products' properties are equal.
Return ([Link] = [Link]) AndAlso ([Link] = [Link])
End Function
Public Function GetHashCode1(
ByVal product As Product
) As Integer Implements IEqualityComparer(Of Product).GetHashCode
' Check whether the object is null.
If product Is Nothing Then Return 0
' Get hash code for the Name field if it is not null.
Dim hashProductName =
If([Link] Is Nothing, 0, [Link]())
' Get hash code for the Code field.
Dim hashProductCode = [Link]()
[Link] (A-Level Computer Science/AICT) in LGS,GSIS,Apples For help and Guidance
Contact : 0321-5275281
162
' Calculate the hash code for the product.
Return hashProductName Xor hashProductCode
End Function
End Class
aq
ht
us
.M
M
[Link] (A-Level Computer Science/AICT) in LGS,GSIS,Apples For help and Guidance
Contact : 0321-5275281
163
Membership (Contains)
' Create an array of strings.
Dim fruits() As String = {"apple", "banana", "mango", "orange",
"passionfruit", "grape"}
' This is the string to search the array for.
Dim fruit As String = "mango"
' Determine if the array contains the specified string.
Dim hasMango As Boolean = [Link](fruit)
Dim text As String = IIf(hasMango, "does", "does not")
' Display the output.
aq
[Link] ("The array " & text & " contain " & fruit)
[Link]()
ht
us
.M
M
[Link] (A-Level Computer Science/AICT) in LGS,GSIS,Apples For help and Guidance
Contact : 0321-5275281
164
Example Program 24 - Linear search
Sub Main()
Dim array1 As Integer() = New Integer(19) {}
Dim randomNumber As Random = New Random()
Dim index As Integer
' creates string containing 11 random numbers
For index = 0 To [Link](0)
array1(index) = [Link](1000)
[Link](array1(index) & " ")
Next
[Link]("")
aq
[Link]("What number do you want to search for?")
Dim searchKey As Integer = [Link]
Dim element As Integer = LinearSearch(searchKey, array1)
If element <> -1 Then
Else ht
[Link]("Found Value in index " & element)
us
[Link]("Value Not Found")
End If
[Link]("Press any key to close")
[Link]()
.M
End Sub
Function LinearSearch(ByVal key As Integer, ByVal numbers As Integer()) As Integer
M
Dim n As Integer
' structure iterates linearly through array
For n = 0 To [Link](0)
If numbers(n) = key Then
Return n
End If
Next
Return -1
End Function ' LinearSearch
Tasks
1) Search for the position of a player in a teamsheet (array) by surname
2) Search for the position of a song in a top 10 chart by title and return it’s position
3) Using 2 arrays, create an address book of friends. 1 array for names, 1 for addresses.
Prompt the user for a name and then return that persons address.
4) Add mobile telephone numbers to the previous program (Hint: 3rd array needed)
[Link] (A-Level Computer Science/AICT) in LGS,GSIS,Apples For help and Guidance
Contact : 0321-5275281
165
Example Program 25 - Bubble sort
Sub Main()
[Link]("Enter any sequence of numbers followed by a space.")
'read the array to a string
Dim OurArrayString As String = [Link]()
Dim OurArray As String()
'split the string to an array
OurArray = [Link](" ")
'Start Bubble sort algorithm
Dim i As Integer
aq
Dim j As Integer
For i = 0 To UBound(ourArray) Step 1
'Ubound of an array will be the maximum index of that array
'start another for loop
ht
For j = 0 To UBound(ourArray) - 1
If CInt(OurArray(j + 1)) < CInt(OurArray(j)) Then
us
'Swapping the variables in the array
Dim temp As Integer = CInt(OurArray(j + 1))
OurArray(j + 1) = OurArray(j)
OurArray(j) = temp
.M
End If
Next
Next
M
'display the out in the console window
[Link]("the sorted array will be")
For Each x In OurArray
[Link](x & " ")
Next
[Link]()
End Sub
Tasks
1) Write a program that sorts an array of ages.
2) Write a program that reads in scores from a file, sorts them and displays them
3) Add to this program so that there is a corresponding list of names which is also sorted to go
with the score.
4) Add to this program so that it is possible for a user to add an additional hiscore and it
appears in the correct position when displayed.
[Link] (A-Level Computer Science/AICT) in LGS,GSIS,Apples For help and Guidance
Contact : 0321-5275281
166
Extension Set A: Form Applications
Hello World
[Link]
Form Properties
[Link]
Progress Bar
[Link]
aq
Menu Strip
[Link]
Advanced Message Box
ht
[Link]
us
Web Browser
[Link]
.M
Try Catch
[Link]
M
[Link] (A-Level Computer Science/AICT) in LGS,GSIS,Apples For help and Guidance
Contact : 0321-5275281
167
Extension Set B: COMP1 Revision
1) Create a program that converts decimal to binary and back
2) Create a program that converts decimal to hex and back
3) Create a program that codes a string into its ASCII codes and back
4) Create a program that adds binary numbers
5) Create a program that multiplies binary numbers
aq
6) Create a program that subtracts binary numbers
7) Create a program that converts a decimal number to floating point and back.
ht
8) Create a program that displays a number of bits as bytes, kilobytes, megabytes…..terabytes
9) Create a program that calculates a pictures file size
us
10) Create a program that calculates a sound files size
.M
M
[Link] (A-Level Computer Science/AICT) in LGS,GSIS,Apples For help and Guidance
Contact : 0321-5275281
168
aq
ht
us
.M
M
[Link] (A-Level Computer Science/AICT) in LGS,GSIS,Apples For help and Guidance
Contact : 0321-5275281
1-Sum of two numbers 169
aq
2-program to input(y/n),the program diplays u enterend Y or n,program terminates when user enters
“exit”
ht
us
.M
M
[Link] (A-Level Computer Science/AICT) in LGS,GSIS,Apples For help and Guidance
Contact : 0321-5275281
3-Write a program to print 50 numbers 170
4-write a program to pick any number between 1-6, program terminates when 5 is entered. (Lucky
aq
number game)
ht
us
.M
M
[Link] (A-Level Computer Science/AICT) in LGS,GSIS,Apples For help and Guidance
Contact : 0321-5275281
5-Write a program to print number from 1-20 using FOR…NEXT loop 171
6-use of nested FOR….NEXT loop
aq
ht
us
.M
M
[Link] (A-Level Computer Science/AICT) in LGS,GSIS,Apples For help and Guidance
Contact : 0321-5275281
7- write a program to input marks from the user and displays”congrats”if marks are above 40 and 172
displays “sorry ,you are fail” when marks are less than 40.
aq
8-write a program to input some marks then print “admission granted”if avg is greater than 80 else “try
again”
ht
us
.M
M
[Link] (A-Level Computer Science/AICT) in LGS,GSIS,Apples For help and Guidance
Contact : 0321-5275281
9-write a program to print highest and lowest number out of 10 numbers entered by user 173
aq
10-write a program to input 5 temperatures. Validate the input so that a value between 10 to 50 should
be accepted. ht
us
.M
M
11-write a program to input different number(1-10),using select….case statement,print the
[Link] an error message if number is out of range.
[Link] (A-Level Computer Science/AICT) in LGS,GSIS,Apples For help and Guidance
Contact : 0321-5275281
174
aq
12-write a program that inputs code for movie type and displays its category.e.g
A-adventure movies C-comedy movies F-family movies H-horror movies
S-science fiction movies. Print error message if not within the list.
ht
us
.M
M
[Link] (A-Level Computer Science/AICT) in LGS,GSIS,Apples For help and Guidance
Contact : 0321-5275281
13-write a program to input some numbers and print their sum. The number ends with -1 175
Using do----until loop
aq
ht
us
.M
M
[Link] (A-Level Computer Science/AICT) in LGS,GSIS,Apples For help and Guidance
Contact : 0321-5275281
14-- Write a program to print the numbers and their squares. 176
1 1
2 4
3 9
4 16
aq
15-write a program to print the table of a number which is input by user.
ht
us
.M
M
16-write a program to output whether the number is even or odd
[Link] (A-Level Computer Science/AICT) in LGS,GSIS,Apples For help and Guidance
Contact : 0321-5275281
17- write a program to input a whole number and calculate the number of digits. Out put number 177
of
digits and the whole number.
18- Write a program to input marks of a class of 5 students re-enter marks if it is out of range e.g. less
than 0 or greater than 100 and display the avg marks.
aq
ht
us
.M
19-Temperatures (°C) are being collected in an experiment every hour over a 20 hour period.
Write an algorithm, using pseudocode or otherwise, which inputs each temperature and outputs
how many of the temperatures were above 20°C
how many of the temperatures were below 10°C
M
the lowest temperature that was input
(do yourself)
20-
For help and Guidance
[Link] (A-Level Computer Science/AICT) in LGS,GSIS,Apples Contact : 0321-5275281
178
User defined functions
Write a program to find sum of two numbers with the help of user defined function
aq
Write a program to find the greater number when user enters two numbers. Use functions
ht
us
.M
M
[Link] (A-Level Computer Science/AICT) in LGS,GSIS,Apples For help and Guidance
Contact : 0321-5275281
Arrays 179
Program to input 5 numbers in an array, print sum and search a number.
aq
ht
us
Two dimensional arrays
.M
M
[Link] (A-Level Computer Science/AICT) in LGS,GSIS,Apples For help and Guidance
Contact : 0321-5275281
Create a random number to pick the array element 180
Validation
aq
Write a program to input a number between 0-10,if number is in correct range then print “well done “if
it is out of range, you will have to re-input number until correct number is entered
ht
us
.M
M
[Link] (A-Level Computer Science/AICT) in LGS,GSIS,Apples For help and Guidance
Contact : 0321-5275281
Linear search 181
Search an array element of type string Search an array element of type integer
aq
ht
us
.M
M
[Link] (A-Level Computer Science/AICT) in LGS,GSIS,Apples For help and Guidance
Contact : 0321-5275281
String handling 182
Use of mid () function to get value from a string
Dim aString As String = "SomeString"
Dim bString As String
bString = Mid(aString, 3, 6)
[Link](bString)
[Link]()
Use of string functions and their output
aq
ht
Use of Asc() function which Returns an Integer representing the ASCII character
us
code corresponding to the first letter in a string.
.M
M
The Trim () function trims the empty spaces on both side of the phrase.
The left() function extracts the left portion and right() function extracts the right
portion of a string
[Link] (A-Level Computer Science/AICT) in LGS,GSIS,Apples For help and Guidance
Contact : 0321-5275281
183
aq
ht
us
.M
M
[Link] (A-Level Computer Science/AICT) in LGS,GSIS,Apples For help and Guidance
Contact : 0321-5275281