Introduction to VB
Introduction to VB
2
Chapter 4 Flow Control (4) ................................................................................................... 26
4.1 For...Next statement ............................................................................................ 26
4.2 Increase / Decrease the counter by a different value ......................................... 28
4.3 Inspecting the values of variables in Visual Basic IDE .......................................... 29
4.4 Exit For and Continue For statements ................................................................. 30
4.5 Nesting For...Next statements ............................................................................. 31
4.6 Miscellaneous Examples ...................................................................................... 34
4.7 Official For...Next statement syntax .................................................................... 37
Exercise 4 ......................................................................................................................... 38
3
Chapter 1 Console Applications
Console applications are not as interactive as GUI applications, so it is not a first choice for
casual users. However, console applications can preferable for advanced users. A
comparison of these two types of applications is made below:
*
The “cmd” command refers to the program “C:\Windows\System32\cmd.exe” in your Windows installation.
To run the “cmd” command, press Win+R and, type “cmd”, then press Enter.
4
1.1.3 Creating a console application in Visual Basic 2010
To create a console
application, select the
item “Console Application”
in the New Project dialog.
A console application is
simpler to create than a
GUI application. Just write
all your code inside
Sub Main in Module1.vb.
The console in Visual Basic programs can be accessed by the Console object. Here are its
few commonly used methods:
5
1.2.1 Console.WriteLine, Console.Write, and vbCrLf
Calling Console.WriteLine without any argument simply moves the cursor to the next line.
The vbCrLf constant also moves the cursor to the next line. The use of vbCrLf in the
Console methods is similar to its use in MsgBox statement.
The example below shows the differences of Console.WriteLine and Console.Write. See
the captured output below to check your understanding.
Sub Main()
Console.WriteLine("Console.WriteLine results")
Console.WriteLine("=========================")
Console.WriteLine("Item 1")
Console.WriteLine("Item 2" & vbCrLf)
Console.WriteLine(2.345)
Console.WriteLine("Item " & 4)
Console.WriteLine()
Console.WriteLine()
Console.WriteLine("Console.Write results")
Console.WriteLine("=====================")
Console.Write("Item 1")
Console.Write("Item 2" & vbCrLf)
Console.Write(2.345)
Console.Write("Item " & 4)
Console.ReadLine()
End Sub
End Module
*
Console.WriteLine(str) behaves exactly the same as Console.Write(str & vbCrlf).
6
Class Work 1.2.1
Write a program that produces the given output. Use Console.WriteLine only. No vbCrLf.
It is easy!
End Sub
1.2.2 Console.Clear
Console.Clear is used to clear the content of the console. After the console is cleared, the
cursor goes to the top-left corner.
1.2.3 Console.ReadLine
The Console.ReadLine method reads a line of characters from the console and returns a
string. To add a prompt, use Console.Write immediately before Console.ReadLine.
Again, to convert the string into a number, use the Val function.
Example 1.2.2 Console.ReadLine with prompt: Find the n-th triangle number.
Module Module1
Sub Main()
Console.ReadLine()
End Sub
End Module
7
Class Work 1.2.2
Write programs that produce the output shown below. The shaded texts are user inputs.
End Sub
Cylinder
========
Enter the base radius: 10
Enter the height: 5
End Sub
8
Enrichment
When we write a console application, we often need to align the output into columns. We
use the formatting functions of Console.Write and Console.WriteLine, like the example
below:
*
String.Format and Strings.Format are two different functions. Do not mix them up.
9
1.4 Virtual consoles in GUI programs
Sometimes, it is useful to display a console inside a GUI application, especially when the
output message consists of multiple lines of text. Two ways to implement a virtual console
are demonstrated here:
1.4.1 TextBox
A TextBox can display multiple lines of text when its Multiline property is set to True. You
may simulate Console.WriteLine and Console.Write with the following statements:
Note: set the ReadOnly property of a text box to Do not use the statement
TextBox1 &= str & vbCrLf
True to prevent the contents from changing. because it performs poorly.
10
1.4.2 ListBox
A ListBox can also display multiple lines of text. However, you must add the text with
whole lines.
11
Exercise 1
1. Write a program that produces the output below. The shaded text is the user input.
Calculations: [ ]
.
Classification of results:
BMI Classification
<18.5 Underweight
18.5 – 23.9 Average
24.0 – 27.9 Overweight
>= 28 Obese
3. Write a program that plays the rock, paper and scissors game. Refer the sample
outputs below. The shaded texts are user inputs.
12
Chapter 2 Timer control
In your program, you may want to require the user to finish a task (e.g. do some
calculations) within a specific time. In this case, the Timer control can be used.
The Timer controls works by generating the Tick event after a specified time. The user
interface of the Timer control is shown in the screenshot below*.
*
The description of Interval property in the screenshot is incorrect. The Tick event is generated instead.
13
2.2 Using the Timer control
Here are the properties, events and methods of the Timer control.
Name Description
Enabled Whether the Timer will generate ticks.
Properties The time between two ticks, in milliseconds. The value of
Interval
Interval must be at least one.*
Raised when the specified timer interval has elapsed and
Events Tick
the timer is enabled.
Start Starts the timer. Same as setting Enabled to True.
Methods
Stop Stops the timer. Same as setting Enabled to False.
ButtonStart
LabelTicks ButtonStop
*
The exact interval between two ticks is slightly longer than the time interval given in the Interval property.
This makes time measurements inaccurate. To fix this problem, refer to your project notes.
14
One of the common techniques for using a Timer control is to create a countdown timer.
Please see the example below:
15
The example below is a sliding text demonstration.
Timer1.Interval = 200
Timer1.Enabled = True
End Sub
End Class
16
Exercise 2
1. Write a program that generates addition questions. When the “Start” button is
pressed, two two-digit numbers (e.g. 35+ 82) are generated, and the user is required
to enter the sum within 10 seconds. Output the following message after sum is
entered or the time is out: ([###] means the actual answer.)
*
Simon is an electronic game of memory skill invented by Ralph H. Baer and Howard J. Morrison, with
software programming by Lenny Cope. It is manufactured and distributed by Milton Bradley.
17
Chapter 3 Flow Control (3)
In the past, we have learned to do decision making with If...Then...Else statements. Usually,
we make decision based on the value of a variable, such as the marks of a test, or a
randomly drawn number.
Consider the lucky draw example in Book 2. We can make the program more readable by
using the Select...Case statement. The modified program is shown below:
The example above is a typical use of Select...Case statement, which works with integers.
Now we go to the details.
18
3.2 Select...Case statement syntax
statements1
Case expressionlist2 testexpression Yes
matches statements1
statements2 expressionlist1
Case Else No
elsestatements
testexpression Yes
End Select matches
expressionlist2
statements2
If none of the expression lists are matched, then the statements below “Case Else” are
executed. The existence of Case Else in Select...Case statements is not required.
*
The words “testexpression”, “expressionlist1”, “expressionlist2” are to be replaced by
actual values or expressions, like those in
Example 3.1.1.
19
3.2.2 Expression lists
Each expression list contains one or more expression clauses. Each clause can take one of
the following forms:
Case "angel"
Case 0 To 100
Case Is > 0
Case "A" To "Z", "a" To "z"
Case 1 To 4, 7 To 9, 11, 13, Is > maxNumber
3.2.3 Examples
20
Below is another example of Select...Case statement, which works with decimals. You are
reminded that it is impossible to denote in a Case statement.
In the example above, the mark 80 matches “80 To 100”, therefore the grade is “A”. The
other matching expression list, “70 To 80”, is simply ignored.
It is also possible to match strings and other data types in Select...Case statements, e.g.
Case "apples", "nuts" To "soup" (Note: capital letters are less than small letters.)
However, Select...Case statement with strings are not useful in practice.
21
Class Work 3.2.1
Complete the programs below by writing down a statement in each empty row.
Console.WriteLine("Normal")
Console.WriteLine("A six!!!")
End Select
BMI Classification
<18.5 Underweight
≥18.5 and <24 Average
≥24 and <28 Overweight
≥28 Obese
Lbl_Classification.Text = "Underweight"
Lbl_Classification.Text = "Average"
Lbl_Classification.Text = "Overweight"
Lbl_Classification.Text = "Obese"
End Sub
22
3.3 Similarity of Select...Case statement and If...Then...Else statement
We read an example in Book 1 again (see below). You can see that the If...Then...Else
statement can be converted into Select...Case statement below.
grade = "C"
No
Else
grade = "D" Yes
marks>=50? grade = "C"
End If
MsgBox("Your grade is: " & grade) No
grade = "D"
23
However, If...Then...Else statements are not always convertible to Select...Case statements.
For example, you cannot do a good conversion* if two or more variables are involved:
In the other way, Select...Case statements can always be converted into If...Then...Else
statements. Commas are converted into operator Or, and the expression “a To b” is
converted into “[var] >= a And [var] <= b”.
Here is the official syntax of the Select...Case statement. The parts inside [] are optional.
When you enter your code into the Visual Basic IDE, it will do the following changes
automatically:
Change “Select” into “Select Case” if the word Case is not already there
Add the missing keyword “Is”
It is actually possible to convert with the statement “Select Case True” followed by the conditions
*
as the cases. However, this is not recommended because it makes the code hard to read.
24
Exercise 3
In this exercise, you may choose to write either a console application or a GUI application.
1. Write a program that the user will enter the amount of pocket money he/she spends
per week. Then the program will output a message according to the table below. You
must use Select...Case statement in your program to do the task.
(You are not required to consider negative values in your program.)
2. Write a program that the user enters a string. By using Select...Case statement,
output the following message according to the conditions below.
(Hint: use a string function to extract the first character of the string.)
Condition Message
Starts with an upper case letter The string starts with an upper case letter.
Starts with a lower case letter The string starts with a lower case letter.
Starts with a digit The string starts with a digit.
Others The string starts with something strange.
25
Chapter 4 Flow Control (4)
Next [counter]
statements
*
Common names of counter variables are i, j and k.
†
Declaring a variable counter before For...Next statement is NOT a requirement in Visual Basic. If the counter
is not declared, Visual Basic simply creates a variable for the counter automatically, and limits the scope of
the variable to the For...Next statement. Note: these features are not present in programming languages C
and Pascal.
26
The next example investigates the value of the counter variable (i) during and after the
For...Next statement.
And the next example calculates the value of the first 10 triangle
numbers. Note the string concatenations in this example.
27
4.2 Increase / Decrease the counter by a different value
In Visual Basic, it is possible to set the counter to increase or decrease at a certain value
after every iteration, using the Step keyword.
For i = 10 To 1 Step -1
statements
Next
You may also make the counter increase or decrease by a decimal. However, in this case
some round-off error may occur, and your loop may run for a wrong number of iterations.
Write down the For statement if you want the counter variable [i] to be the values in the
list below. The first question is done for you as an example:
28
4.3 Inspecting the values of variables in Visual Basic IDE
To understand the use of For...Next statements, it is useful to use the Locals window in the
Visual Basic IDE. The Locals window inspects the value of all local variables.
Instead of running the whole program, press F8 (Step Into) to run the program step by step.
The screen captures below shows the progress of a running program.
29
4.4 Exit For and Continue For statements
Sometimes, we want to change the control flow of For...Next statement based on some
decisions. There are two statements for this purpose.
Statement Description
Exit For Breaks the loop immediately. Control goes outside the loop.
Continue For Starts the next iteration immediately.
Example 4.4.1 Check whether a string contains a positive integer (Exit For)
Dim i, l As Integer, s, c As String
For i = 1 To l
c = Mid(s, i, 1)
If c < "0" Or c > "9" Then
Exit For
End If
Next
Console.ReadLine()
30
4.5 Nesting For...Next statements
Like If...Then...Else statement, For...Next statement can be nested. Of course, you need to
use different counter variables for each layer of For...Next statement.
The next example shows how nesting works. You should note how Console.Write and
Console.WriteLine produce a table here.
The value of the counter in the outer loop can be used in the For statement in the inner
loop. See the example below:
31
Example 4.5.3 Printing a triangle pattern
Console.Write("Enter the number of rows: ")
Dim numRows As Integer = Val(Console.ReadLine())
For i = 1 To numRows
numStars = i * 2 - 1
numSpaces = numRows - i
For j = 1 To numSpaces
Console.Write(" ")
Next
For j = 1 To numStars
Console.Write("*")
Next
Console.WriteLine()
Next
Console.ReadLine()
32
Enrichment
Dim i, j As Integer
Console.Write(" |")
For i = 1 To numCols
Console.Write("{0,4}", i)
Next
Console.WriteLine()
Console.Write("-----+")
For i = 1 To numCols
Console.Write("----")
Next
Console.WriteLine("--")
For i = 1 To numRows
Console.Write("{0,4} |", i)
For j = 1 To numCols
Console.Write("{0,4}", i * j)
Next
Console.WriteLine()
Next
Console.ReadLine()
33
4.6 Miscellaneous Examples
sum = 0
For i = 1 To n
sum += i * i
Next
Console.WriteLine("The sum of the first " &
n & " squares is " & sum & ".")
Console.ReadLine()
*
StrReverse function does the exactly same thing.
34
Example 4.6.3 Clapping game “Sevens”*
Dim i As Integer
Console.WriteLine("Answers of Game ""Sevens""")
Console.WriteLine("[ * = Clap ]")
Console.WriteLine()
For i = 1 To 100
If i Mod 7 = 0 Or InStr(i, "7") > 0 Then
Console.Write(" * ")
Else
Console.Write(i & " ")
End If
If i Mod 10 = 0 Then
Console.WriteLine()
End If
Next
Console.ReadLine()
*
“Sevens” (拍七) is a hand clapping game. Participants sit in a round. The first people reads “One”, and the
second people reads “Two”, so on. However, if the number is divisible by 7 or contains the digit 7, then the
people supposed to read the number should clap hands instead. Doing wrong things loses the game.
35
Example 4.6.4 Fibonacci Series
Dim a, b, c, i, n As Integer
Console.WriteLine("Fibonacci Series")
Console.WriteLine("================")
Console.Write("How many terms do you want? ")
n = Val(Console.ReadLine())
If n <= 0 Then
Console.WriteLine("Please enter a positive number.")
Else
Console.WriteLine("The first " & n &
" terms of the Fibonacci series are:")
Console.Write("1") ' First term
If n >= 2 Then
Console.Write(", 1") ' Second term
End If
If n >= 3 Then
' Third term onwards
a = 1
b = 1
For i = 3 To n
c = a + b
a = b
b = c
Console.Write(", " & b)
Next
End If
End If
Console.ReadLine()
36
Enrichment
Here is the official syntax of the For...Next statement. The parts inside [] are optional.
When a For...Next loop starts, Visual Basic evaluates start, end, and step. Changing the
value of these inside the loop does not affect the loop itself.
The table below shows the behaviour of the compiler depending on whether the datatype
is present and whether the counter variable is already declared.
A counter
The
variable is Counter defines a new local variable that’s scoped to the entire
datatype
already For...Next loop.
is present.
defined.
No Yes No. Counter is the variable that's already defined. If the scope of
counter isn't local to the procedure, a compile-time warning
occurs.
No No Yes. The data type is inferred from the start, end, and step
expressions.
Yes Yes Yes, but only if the existing counter variable is defined outside the
procedure. That separately defined counter variable remains as a
separate variable. If the existing counter variable is defined local
to the procedure, a compile-time error occurs.
Yes No Yes.
37
Exercise 4
1. (a) Write a program that prints out the first 10 triangle numbers.
(b) Write a program that prints out the first 100 triangle numbers, 10 in a row.
2. Write a program that prints the numbers from 1 to 100. But for multiples of three
print “Fizz” instead of the number, and for the multiples of five print “Buzz”. For
numbers which are multiples of both three and five print “FizzBuzz”.*
3. Write a program that prints the numbers from 11 to 100, skipping all multiples of 2, 3,
5 and 7. (These numbers are in fact prime numbers from 11 to 100.)
4. Write a program that finds the sum of the first n triangle numbers. The value of n
should be inputted by the user.
5. Write a program that prints the following pattern. The number of rows (maximum 9)
should be selected by the user.
*
You may attempt this question in the following ways: (a) using one If…Then…ElseIf…Else statement;
(b) using nested If…Then…Else statements.
38
6. Write a program that prints an addition table (compare this to a multiplication table).
(Note: any number less than 10 should have a space character before it.)
7. Write a program to find all 3-digit numbers that have the following property:
The number is equal to the sum of the cubes of its digits.
e.g. . You may print out the result in any format.*
(Hint: There are totally 4 answers, including 371.)
8. (a) Write a program that list out the positive factors of a number.
(e.g. the positive factors of 6 are 1, 2, 3, and 6.)
(b) Write a program that finds out all “perfect numbers” from 1 to 1000. A “perfect
number” is a number equal to the sum of all its positive factors excluding itself.
Print the result in the following way:
6 = 1 + 2 + 3
28 = 1 + 2 + 4 + 7 + 14
…
*
You may also attempt this question in Microsoft Excel and Microsoft Access.
39
Chapter 5 Arrays
Imagine you create a program that works with a large number of data (e.g. the weight of
all students in your class). Before you work with the data, you need to store the data into
variables in your program. Let’s say, the variables are w1, w2, w3, w4, w5, etc…
Now you store data into the variables. Since the names of all the variables are different,
you need to enter one line for each datum. If a class has 36 students, then we have to
write 36 lines for 36 variables!
Instead, we group all the variables w1, w2, w3, w4, w5, etc… into one single array, w, with
indices from 1 to 36. We have therefore elements w(1), w(2), w(3), etc…, and these
elements can be processed with a single For...Next statement:
40
5.2 Declaring an array
Declaring an array in Visual Basic is very simple – in the Dim statement, just add a pair of
parentheses next to the name of variable, and put a number n inside, like
Dim w(36) As Double. In this way, an array of n+1 elements with the same data type is
created. The first element starts with index zero, and the elements of the array are w(0),
w(1), w(2), …, w(n).
array w
There is no way to remove the zero-indexed element, but you are always free to ignore it.
The Length property returns the size of an array. For example, w(36) has a length of 37.
Note that the zero-indexed element is also counted.
In Visual Basic, you can give arrays initial values, like the statement below.
Note that the first element has an index of zero. Adding a number inside the bracket is
not allowed. (VB will calculate the size for you.) The statement above means the following:
41
5.5 Working with arrays
Arrays are simple to declare and use. Now we learn a few simple algorithms using arrays.
Note: In most examples, you must set values for the array num first. See 5.4 for how to
write such a statement. Results can be printed by using Console.WriteLine or otherwise.
The simplest algorithm is perhaps to calculate the sum and average of a set of numbers.
When we calculate the sum and average, we need an array of numbers (i.e. the data). The
size of the data can be calculated using the Length property if needed.
The first example illustrates the calculations on a one-based array (i.e. smallest index is 1).
Example 5.5.1a Find the sum and average of a set of numbers (one-based array)
' Input: num (array of numbers, one-based)
Dim sum, average As Double, i As Integer
Dim n As Integer = num.Length – 1 ' n = count of data
sum = 0
For i = 1 To n
sum += num(i)
Next
average = sum / n
The next example illustrates the calculations on a zero-based array (i.e. smallest index is 0).
Example 5.5.1b Find the sum and average of a set of numbers (zero-based array)
' Input: num (array of numbers, zero-based)
Dim sum, average As Double, i As Integer
sum = 0
For i = 0 To num.Length - 1
sum += num(i)
Next
average = sum / num.Length
42
5.5.2 Calculate the weighted mean
In secondary 3 you learn about weighted mean. Note that the code for zero-based array
can also be used unmodified for one-based array. (Why?)
43
Enrichment
44
Enrichment
The Sieve of Eratosthenes is an algorithm to find prime numbers. Here are the steps:
(a) Get a table of numbers (e.g. from 1 to 100). Cross out 1, which is not prime.
(b) Locate the next number which is not crossed out. That number is a prime number.
(c) Cross out all multiples of the number you obtain in (b), but not the number itself.
(d) Repeat steps (b) and (c) until the number obtained in (b) is larger than the square root
of the maximum number in your table.
(e) The numbers which are not crossed out are prime numbers.
Note: For 1 to 100, the numbers you located in step (b) should be 2, 3, 5 and 7. Therefore,
all multiples of 2, 3, 5 and 7 are crossed out.
For i = 2 To maxNo
p(i) = True
Next i
Console.Write(" {0,7}", i)
j = j + 1
If j = 10 Then
j = 0
Console.WriteLine()
End If
Next i
45
Enrichment
You can use arrays which have more than one dimension. For example, you can use a
two-dimensional array to store the values of a table. See the example below:
For i = 1 To 9
For j = 1 To 9
m(i, j) = i * j
Next
Next
Two dimensional arrays are useful to store information such as marks of students in
multiple subjects, colours of the pixels of a picture, values in the Minesweeper game, etc.
46
Exercise 5
1. Let the user input five numbers. Store the result in an array. Then find the total and
the mean (average).
(a) Throw a die 1000 times. Print out the frequencies of each number.
(b) Throw two dice 1000 times and add up the value. Print out the frequencies.
5. Shuffle a deck of 52 cards. For simplicity, you may assume that the values on the
cards are “1” to “52”. Print out the result in a space separated list.
(Hint: check “Fisher–Yates shuffle” in Wikipedia for shuffling algorithms.)
47
Alphabetical Index
A E S
algorithm .................................. 42 Exit For (statement) ...................30 Select...Case (statement) .... 18, 19
array.......................................... 40 expression list ...................... 19
element ............................... 40
F Step (keyword) .......................... 28
index .................................... 40 For...Next (statement) .........26, 28
initialization ......................... 41 counter variable ...................26 T
two-dimensional array......... 46 iteration ................................26 TextBox (control) ....................... 10
loop ......................................26 Timer (control) .......................... 13
C nesting ..................................31 Enabled (property) ............... 14
cmd ............................................. 4 Interval (property) ................ 14
Console (object) .......................... 5
G Start (method) ...................... 14
Console.Clear ......................... 5 GUI applications ..........................4 Stop (method) ...................... 14
Console.ReadLine .................. 5 Tick (event)........................... 14
I
Console.Write .................... 5, 9
Console.WriteLine ............. 5, 9
If...Then...Else (statement) ........23 V
Val (function) ............................... 7
Console application................. 4, 5 L
Continue For (statement) ......... 30 vbCrLf (constant) ......................... 6
ListBox (control).........................11
Locals window ...........................29
48