0% found this document useful (0 votes)
3 views

Introduction to VB

Uploaded by

chiyanjapeter7
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
3 views

Introduction to VB

Uploaded by

chiyanjapeter7
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 48

Introduction to

A revised course with


- Concise concepts
- Hands on class
TextBox1
work
- Plenty of examples
- Programming exercises

Copyright © HKTA Tang Hin Memorial Secondary School 2012-14


Contents

Chapter 1 Console Applications .............................................................................................. 4


1.1 Introduction to Console Applications .................................................................... 4
1.1.1 Console applications .................................................................................. 4
1.1.2 Comparison of console applications and GUI applications ....................... 4
1.1.3 Creating a console application in Visual Basic 2010 .................................. 5
1.2 Console object ....................................................................................................... 5
1.2.1 Console.WriteLine, Console.Write, and vbCrLf ......................................... 6
1.2.2 Console.Clear ............................................................................................. 7
1.2.3 Console.ReadLine ....................................................................................... 7
1.3 Aligning output in the console ............................................................................... 9
1.4 Virtual consoles in GUI programs ........................................................................ 10
1.4.1 TextBox .................................................................................................... 10
1.4.2 ListBox ...................................................................................................... 11
Exercise 1 ......................................................................................................................... 12

Chapter 2 Timer control........................................................................................................ 13


2.1 Introduction to Timer control .............................................................................. 13
2.2 Using the Timer control ....................................................................................... 14
Exercise 2 ......................................................................................................................... 17

Chapter 3 Flow Control (3) ................................................................................................... 18


3.1 Introduction to Select...Case statement .............................................................. 18
3.2 Select...Case statement syntax ............................................................................ 19
3.2.1 Select...Case statement ........................................................................... 19
3.2.2 Expression lists ......................................................................................... 20
3.2.3 Examples .................................................................................................. 20
3.3 Similarity of Select...Case statement and If...Then...Else statement ................... 23
3.4 Official syntax Select...Case statement ................................................................ 24
Exercise 3 ......................................................................................................................... 25

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

Chapter 5 Arrays ................................................................................................................... 40


5.1 Introduction to arrays .......................................................................................... 40
5.2 Declaring an array ................................................................................................ 41
5.3 Length property of arrays .................................................................................... 41
5.4 Initial values in arrays .......................................................................................... 41
5.5 Working with arrays ............................................................................................. 42
5.5.1 Calculating the sum and averages of a set of numbers ........................... 42
5.5.2 Calculate the weighted mean .................................................................. 43
5.5.3 Find the largest (or smallest) number in an array ................................... 43
5.5.4 Find the frequency of letters in a string .................................................. 44
5.5.5 Find prime numbers using the Sieve of Eratosthenes ............................. 45
5.6 Introduction to arrays with two or more dimensions ......................................... 46
Exercise 5 ......................................................................................................................... 47

Alphabetical Index ................................................................................................................... 48

3
Chapter 1 Console Applications

1.1 Introduction to Console Applications

1.1.1 Console applications

Console applications are programs


that interact with users using a text
only interface.

The most used console application is


perhaps the “Command Prompt” in
Microsoft Windows. It can be
opened by finding “Command
Prompt” in the Start Menu, or by
running the “cmd” command*.

1.1.2 Comparison of console applications and GUI 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:

Console applications GUI applications


Text only, which is less interactive Interactive graphical elements like buttons,
images, list boxes, etc…
Harder to use Easier to use
Easier to code Harder to code
The output can be saved into a text file. Very difficult to save the output.
Possible to do batch processing. (e.g. Batch processing is uncommon (possible
process 100 images with one command.) only for specially designed programs).

*
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.

1.2 Console object

The console in Visual Basic programs can be accessed by the Console object. Here are its
few commonly used methods:

Method Description Example


WriteLine Outputs a string to the console, and Console.WriteLine("str")
moves the cursor to the next line Console.WriteLine()
Write Outputs a string to the console, but do Console.Write("str")
not move the cursor to the next line.
Clear Clear the content of the console. Also Console.Clear()
moves the cursor to the top-left corner.
ReadLine Reads a line from the console (press Dim s As String
Enter to finish input). s = Console.ReadLine()
In this book, ReadLine method is also
used to prevent the console from closing
after running the program.

5
1.2.1 Console.WriteLine, Console.Write, and vbCrLf

Console.WriteLine and Console.Write are used to output text to the console.


Console.WriteLine moves the cursor to the next line, while Console.Write does not.*

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.

Example 1.2.1 Console.WriteLine and Console.Write


Module Module1

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.

Output Visual Basic Program


This is my first Sub Main()
console program.

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.Write("Enter the number n: ")


Dim n As Integer = Val(Console.ReadLine())

Console.WriteLine("The " & n & "th triangle number is " &


n * (n + 1) \ 2)

Console.ReadLine()

End Sub

End Module

In the notes, Console.ReadLine is also used


at the end of Sub Main. This prevents the console from closing when the program ends.

7
Class Work 1.2.2

Write programs that produce the output shown below. The shaded texts are user inputs.

Enter the number n: 12


The square of n is 144.
Sub Main()
Dim n As Double

End Sub

(Hint: In the question below, use the constant Math.PI)

Cylinder
========
Enter the base radius: 10
Enter the height: 5

The volume is 1570.7963267949,


and the total surface area is 942.477796076938.
Sub Main()
Dim r, h As Double

End Sub

8
Enrichment

1.3 Aligning output in the console

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:

Example 1.3.1 Console.WriteLine accepting arguments


Console.WriteLine("{0} and {1} are good friends.", "David", "Peter")
Console.WriteLine("{1} * {1} = {0}", 9 * 9, 9)
Console.ReadLine()

In the first statement, {0} is replaced by


“David”, and {1} is replaced by “Peter”.

In the second statement, {0} is replaced by


the result of 9*9, and {1} is replaced by 9. Extra arguments can be added if needed.

Alignment is done in the following example:

Example 1.3.2 Aligning output with Console.WriteLine


Console.WriteLine("{0,-8}|{1,6}", "Left", "Right")
Console.WriteLine("{0,-8}|{1,6}", 234, 567)
Console.WriteLine("{0,-8}|{1,6}", -3.5, 987654)
Console.ReadLine()

In the example above, {0,-8} left aligns argument 0 to 8 places,


and {1,6} right aligns argument 1 to 6 places.

We can also do the same kind of formatting to GUI applications


using String.Format* function. For example,

s = String.Format("{1} * {1} = {0}", 9 * 9, 9)

writes the result “9 * 9 = 81” to variable s.

*
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:

Console TextBox (TextBox1)


Console.WriteLine(str) TextBox1.AppendText(str & vbCrLf)
Console.Write(str) TextBox1.AppendText(str)
Console.Clear() TextBox1.Text = ""
Alternative: TextBox1.Clear()

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.

Example 1.4.1 Virtual console with a text box


Public Class Form1

Private Sub Button1_Click(...) Handles Button1.Click


Dim x As Double = Val(TextBox1.Text)
TextBox2.AppendText("The square root of " & x & " is " &
Math.Sqrt(x) & vbCrLf)
End Sub
End Class

10
1.4.2 ListBox

A ListBox can also display multiple lines of text. However, you must add the text with
whole lines.

Console ListBox (ListBox1)


Console.WriteLine(str) ListBox1.Items.Add(str)
Console.Write(str) -
Console.Clear() ListBox1.Items.Clear()

Note: A list box provides an interface to select


Set the font to “Courier New” or
one or more items in a list. The use of list boxes “Consolas” if you want your
virtual consoles to look realistic.
is out of the scope of this book.

Example 1.4.2 Virtual console with a list box


Public Class Form1

Private Sub Button1_Click(...) Handles Button1.Click


Dim x As Double = Val(TextBox1.Text)
ListBox1.Items.Add("The square root of " & x & " is " &
Math.Sqrt(x) & vbCrLf)
End Sub
End Class

11
Exercise 1

1. Write a program that produces the output below. The shaded text is the user input.

Enter the number n: 12


The square of n is 144, and the cube of n is 1728.

2. Rewrite the BMI Calculator (an exercise in Book 1) as a console program.


Inputs: mass (in kg) and height (in cm)

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.

Rock, Paper or Scissors? [R|P|S] R


The computer played Paper. You have lost.
Rock, Paper or Scissors? [R|P|S] R
The computer played Scissors. You have won!!!
Rock, Paper or Scissors? [R|P|S] R
The computer played Rock. This is a draw.

12
Chapter 2 Timer control

2.1 Introduction to 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.

And here is a simple timer that uses the Timer control:

Example 2.2.1 Simple timer


' Note: Timer1 has an Interval of 1000 and is not Enabled.
Public Class Form1

Private Sub Timer1_Tick(...) Handles Timer1.Tick


LabelTicks.Text = Val(LabelTicks.Text) + 1
End Sub

Private Sub ButtonStart_Click(...) Handles ButtonStart.Click


Timer1.Enabled = True
End Sub

Private Sub ButtonStop_Click(...) Handles ButtonStop.Click


Timer1.Enabled = False
End Sub
End Class

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:

Example 2.2.2 Simple countdown timer


' Note: Timer1 has an Interval of 1000 and is not Enabled.
Public Class Form1

Private Sub ButtonStartGame_Click(...) Handles


ButtonStartGame.Click
LabelTimeLeft.Text = Val(TextBox1.Text)
ButtonWin.Enabled = True
Timer1.Enabled = True
End Sub

Private Sub Timer1_Tick(...) Handles Timer1.Tick


Dim timeleft As Integer = Val(LabelTimeLeft.Text) - 1
LabelTimeLeft.Text = timeleft
If timeleft <= 0 Then
Timer1.Enabled = False ' Disable timer before MsgBox!!!
ButtonWin.Enabled = False
MsgBox("You've lost!")
End If
End Sub

Private Sub ButtonWin_Click(...) Handles ButtonWin.Click


Timer1.Enabled = False ' Disable timer before MsgBox!!!
ButtonWin.Enabled = False
MsgBox("You've won!")
End Sub
End Class
TextBox1

This example illustrates how ButtonStartGame


Timer controls are used to ButtonWin
LabelTimeLeft
measure time. You are advised
to remember this algorithm
Remember to disable the timer
and use it in your own program. after use, otherwise unwanted
Ticks will be generated. Do this
BEFORE any MsgBox statement!

15
The example below is a sliding text demonstration.

Example 2.2.3 Sliding text


Public Class Form1

Dim prepend As String = " " ' spaces


Dim dispLen As Integer = 15

Dim msg As String, pos As Integer

Private Sub Timer1_Tick(...) Handles Timer1.Tick


pos += 1
If pos > Len(msg) Then pos = 1 - dispLen

If pos > 0 Then


Label1.Text = Mid(msg, pos, dispLen)
Else
Label1.Text = Strings.Left(prepend, 1 - pos) &
Strings.Left(msg, dispLen - 1 + pos)
End If
End Sub

Private Sub Form1_Load(...) Handles MyBase.Load


msg = InputBox("Enter a message:", ,
"A quick brown fox jumps over the lazy dog." )
pos = 1 - dispLen
Label1.Text = Strings.Left(prepend, dispLen)

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.)

Condition Output message


The user enters a correct answer. Correct!
The user enters a wrong answer. Wrong. The correct answer is [###].
Time runs out. Time is up. The correct answer is [###].

2. Create a computer version of the Simon*


Enrichment

memory game (see the picture). The


game consists of four coloured buttons
(red, blue, yellow, green). The game play
is as follows:
(a) Once the “Start Game” button is
pressed, the computer creates a list
of one random button, and play the
list (by flashing the button).
(b) The player is required to replay the
list in the correct order. If all buttons are pressed correctly, then the computer
adds another random button to the end of the list, and plays the whole list of
buttons one by one.
(c) If any of the buttons are wrongly pressed, then it is simply a Game Over.

Note: See http://neave.com/simon/ for a working example.

*
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)

3.1 Introduction to Select...Case statement

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:

Example 3.1.1 Lucky draw (Select...Case)


Public Class Form1

Private Sub Form1_Load(sender As


System.Object, e As System.EventArgs)
Handles MyBase.Load
Randomize()
End Sub

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


System.EventArgs) Handles Button1.Click
Dim draw As Integer = Int(Rnd() * 100) + 1
LabelDraw.Text = draw
Select Case draw
Case 1 To 50
LabelPrize.Text = "No Prize"
Case 51 To 75
LabelPrize.Text = "Small Prize"
Case 76 To 90
LabelPrize.Text = "Middle Prize"
Case 91 To 99
LabelPrize.Text = "Big Prize!"
Case Else
LabelPrize.Text = "JUMBO Prize!!!"
End Select
End Sub
End Class

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

3.2.1 Select...Case statement

The syntax of a Select...Case statement is shown here*:

Select Case testexpression


Case expressionlist1 previous code

statements1
Case expressionlist2 testexpression Yes
matches statements1
statements2 expressionlist1

Case Else No

elsestatements
testexpression Yes
End Select matches
expressionlist2
statements2

You can see the flowchart for the No

execution of the Select...Case statement elsestatements

above. Only the statement below the


first matched expression list is executed.
next code to run

The matching process stops at the first


match.

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:

Expression Clause Meaning Examples


expression Is equal to the expression 100
expression1 To expression2 Between expression1 and expression2 15 To 19
(inclusive) "A" To "Z"
Is [ =/</<=/>/>=/<> ] expression Satisfies the given condition Is > 200
Is <= "ba"

Multiple clauses are separated by commas. Here are some examples:

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

Here is an example using Select...Case statement, which works with strings.

Example 3.2.1 Pass or fail


Dim grade As String

Console.Write("Enter the grade (A-F): ")


grade = Console.ReadLine()

Select Case grade


Case "A" To "E"
Console.WriteLine("Pass")
Case "F"
Console.WriteLine("Fail")
Case Else
Console.WriteLine("Not a valid grade")
End Select
Console.ReadLine()

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.

Example 3.2.2 Grading the results (with validation)


Dim marks As Double
Dim grade As String

Console.Write("Enter the marks: ")


marks = Val(Console.ReadLine())

Select Case marks


Case 80 To 100
grade = "A"
Case 70 To 80
grade = "B"
Case 50 To 70
grade = "C"
Case 0 To 50
grade = "D"
Case Else
grade = "Error"
End Select

If grade = "Error" Then


Console.WriteLine("The mark must be between 0 and 100." )
Else
Console.WriteLine("Your grade is: " & grade)
End If
Console.ReadLine()

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.

Value of die (x) Result


1 To 5 Normal
6 A six!!!

Dim x As Integer = Int(Rnd() * 6)


Select Case x

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

Private Sub Button1_Click(...) Handles Button1.Click


Dim mass As Double = Val(TextBox_Mass.Text)
Dim height As Double = Val(TextBox_Height.Text) / 100
Dim BMI As Double = mass / height ^ 2

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.

Example 3.3.1a Grading the results


start
(If...Then...Else)
Dim marks As Integer
Dim grade As String input marks
marks = Val(InputBox("Enter the marks:"))
If marks >= 80 Then
Yes
grade = "A" marks>=80? grade = "A"

ElseIf marks >= 70 Then No


grade = "B"
Yes
ElseIf marks >= 50 Then marks>=70? grade = "B"

grade = "C"
No
Else
grade = "D" Yes
marks>=50? grade = "C"
End If
MsgBox("Your grade is: " & grade) No

grade = "D"

Example 3.3.1b Grading the results (Select...Case)


output grade
Dim marks As Integer
Dim grade As String
marks = Val(InputBox("Enter the marks:")) end
Select Case marks
Case Is >= 80
grade = "A"
Case Is >= 70
grade = "B"
Case Is > 50
grade = "C"
Case Else
grade = "D"
End Select
MsgBox("Your grade is: " & grade)

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:

If height >= 160 And sex = "M" Then

Conversion is difficult or impossible in the following case:

If marks >= 0 And marks < 50 Then

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”.

3.4 Official syntax Select...Case statement

Here is the official syntax of the Select...Case statement. The parts inside [] are optional.

Select [ Case ] testexpression


[ Case expressionlist
[ statements ] ]
[ Case Else
[ elsestatements ] ]
End Select

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.)

Pocket Money ($) Message


0 You didn't spend any money. Are you lying?
>0 and <$100 Below average. What a good student!
≥$100 and <$200 Average.
≥$200 Above average. Consider to spend less!

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)

4.1 For...Next statement previous code

For...Next statement is used to repeat a


counter = start
block of instruction a specified number of
times. A typical For...Next statement looks
like the one below:
No
counter <= end? next code to run
For counter = start To end
statements Yes

Next [counter]
statements

In the loop above, we say that the counter


counts from start to end, taking a
increase
counter by 1
different value in each iteration. (See the

diagram for details.) Consider the example below:

Example 4.1.1 The first 10 square numbers


Dim i As Integer
For i = 1 To 10
Console.WriteLine(i * i)
Next
Console.ReadLine()

In the program, we declare variable i and use it as the counter*.


The value of i counts from 1 to 10, and the Console.WriteLine
statement is executed each value of i. Therefore, the value of the
first 10 square numbers (i*i) is printed out.†

*
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.

Example 4.1.2 The value of the counter variable


Console.WriteLine("-- Start of Loop --")
Dim i As Integer
For i = 3 To 7
Console.WriteLine("i = " & i)
Next
Console.WriteLine("-- End of Loop --")
Console.WriteLine("i = " & i)
Console.ReadLine()

During the loop, the value of i goes from 3 to 7, increasing


by one in each iteration. After the loop, the value of i increased
from 7 to 8. In fact i > 7 (i.e. 8 > 7) is the exact reason for the loop to end.

And the next example calculates the value of the first 10 triangle
numbers. Note the string concatenations in this example.

Example 4.1.3 Triangle numbers


Dim i, t As Integer
For i = 1 To 10
t = i * (i + 1) / 2
Console.WriteLine("i = " & i & ", t = " & t)
Next
Console.ReadLine()

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 example, the following statement counts from 10 down to 1.

For i = 10 To 1 Step -1
statements
Next

And the following iterates every odd number from 1 to 100:

For i = 1 To 100 Step 2


statements
Next
Enrichment

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.

Dim i As Single ' Try changing Single to Double


For i = 7 To 10 Step 0.3 ' This will run incorrectly
Console.WriteLine("i = " & i)
Next

Class Work 4.2.1

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:

Values of variable i For statement


1, 2, 3, …, 100 For i = 1 To 100
-3, -2, -1, 0, 1, 2, 3
7, 6, 5, 4, 3, 2
101, 103, 105, …, 199
100, 98, 96, 94, …, 2
1, 4, 7, 10, …, 100

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

Console.Write("Enter a string: ")


s = Console.ReadLine()
l = Len(s)

For i = 1 To l
c = Mid(s, i, 1)
If c < "0" Or c > "9" Then
Exit For
End If
Next

If l > 0 And i > l Then


Console.WriteLine("It is a positive integer.")
Else
Console.WriteLine("It is not a positive integer.")
End If

Console.ReadLine()

Example 4.4.2 Skip numbers containing digit 4 (Continue For)


Dim i As Integer
For i = 1 To 100
If InStr(i, 4) Then
Continue For
End If
Console.Write(i & " ")
If i Mod 10 = 0 Then
Console.WriteLine()
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.

Example 4.5.1 Nesting For...Next statements


Dim i, j As Integer
For i = 1 To 5
For j = 1 To 7
Console.Write(i & "-" & j & " ")
Next
Console.WriteLine()
Next
Console.ReadLine()

The value of the counter in the outer loop can be used in the For statement in the inner
loop. See the example below:

Example 4.5.2 Nesting For...Next statements (2)


Dim i, j As Integer
For i = 1 To 6
For j = i To 6
Console.Write(j)
Next
Console.WriteLine()
Next
Console.ReadLine()

31
Example 4.5.3 Printing a triangle pattern
Console.Write("Enter the number of rows: ")
Dim numRows As Integer = Val(Console.ReadLine())

Dim i, j, numStars, numSpaces As Integer

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()

Class Work 4.5.1

Write a program that produces the output shown


below. The shaded texts are user inputs.

Enter the number of rows: 4


#
##
###
####
Console.Write("Enter the number of rows: ")
Dim numRows As Integer = Val(Console.ReadLine())
Dim i, j As Integer

32
Enrichment

Example 4.5.4 Multiplication table


Dim numCols As Integer = 12
Dim numRows As Integer = 14

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

Example 4.6.1 Finding the sum of squares


Dim i, n, sum As Integer
Console.Write("Enter the value of n: ")
n = Val(Console.ReadLine())

sum = 0
For i = 1 To n
sum += i * i
Next
Console.WriteLine("The sum of the first " &
n & " squares is " & sum & ".")
Console.ReadLine()

Example 4.6.2 Reverse the contents of a string*


Public Class Form1

Private Sub Button1_Click(...) Handles Button1.Click


Dim i As Integer, s As String
s = ""
For i = Len(TextBox1.Text) To 1 Step -1
s &= Mid(TextBox1.Text, i, 1)
Next
Label1.Text = s
End Sub
End Class

*
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

4.7 Official For...Next statement syntax

Here is the official syntax of the For...Next statement. The parts inside [] are optional.

For counter [ As datatype ] = start To end [ Step step ]


[ statements ]
[ Continue For ]
[ statements ]
[ Exit For ]
[ statements ]
Next [ counter ]

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.

Enter the value of n: 10


The sum of the first 10 triangle numbers is 220.

5. Write a program that prints the following pattern. The number of rows (maximum 9)
should be selected by the user.

Enter the number of rows: 6


1
121
12321
1234321
123454321
12345654321

*
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

5.1 Introduction to 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!

Console.WriteLine("Enter the weights (in kg) of 36 students:")


Dim w1 As Double = Console.ReadLine()
Dim w2 As Double = Console.ReadLine()
Dim w3 As Double = Console.ReadLine()
Dim w4 As Double = Console.ReadLine()
Dim w5 As Double = Console.ReadLine()
(31 more lines)...

This is simply not good!

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:

Example 5.1.1 Iterate an array with a For...Next statement


Dim w(36) As Double, i As Integer
Console.WriteLine("Enter the weights (in kg) of 36 students:")
For i = 1 To 36
w(i) = Console.ReadLine()
Next i

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).

w(0) w(1) w(2) w(3) ... … … w(34) w(35) w(36)

array w

There is no way to remove the zero-indexed element, but you are always free to ignore it.

5.3 Length property of arrays

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.

Dim w(36) As Double


Console.WriteLine(w.Length) ' Outputs "37"

5.4 Initial values in arrays

In Visual Basic, you can give arrays initial values, like the statement below.

Dim num() As Integer = {0, 1, 3, 6, 10}

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:

Dim num(5) As Integer


num(0) = 0
num(1) = 1
num(2) = 3
num(3) = 6
num(4) = 10

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.

5.5.1 Calculating the sum and averages of a set of numbers

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?)

Example 5.5.2 Find the weighted mean (zero-based array)


' Input: num, w (array of numbers, zero-based)
Dim sum, sumW, wmean As Double, i As Integer
sum = 0
sumW = 0
For i = 0 To num.Length - 1
sum += num(i) * w(i)
sumW += w(i)
Next
wmean = sum / sumW

5.5.3 Find the largest (or smallest) number in an array

Another common algorithm is to find the maximum or minimum number in a set of


numbers. Again, we need an array of numbers to use the algorithm.

Example 5.5.3a Find the maximum number (zero-based array)


' Input: num (array of numbers, zero-based)
Dim max As Double, i As Integer
max = num(0)
For i = 1 To num.Length - 1
' Change ">" into "<" to find the smallest number
If num(i) > max Then
max = num(i)
End If
Next

If the array is one-based, change the following statements:

Example 5.5.3b Find the maximum number (one-based array)


max = num(1)
For i = 2 To num.Length - 1

43
Enrichment

5.5.4 Find the frequency of letters in a string

Example 5.5.4 Calculate the frequency of letters in a string.


Private Sub Button1_Click(...) Handles Button1.Click
Dim freq(26) As Integer ' Initialized with 0 by VB
Dim c As Integer

' Calculate the frequencies


Dim i As Integer
For i = 1 To Len(TextBox1.Text)
c = AscW(UCase(Mid(TextBox1.Text, i, 1)))
If c >= 65 And c <= 90 Then
freq(c - 64) += 1
Else
freq(0) += 1
End If
Next

' Display the result


TextBox2.Text = ""
For i = 1 To 26
TextBox2.AppendText(ChrW(i + 64) & ":" & freq(i) & " ")
If i Mod 13 = 0 Then TextBox2.AppendText(vbCrLf)
Next
TextBox2.AppendText("Others:" & freq(0))
End Sub

44
Enrichment

5.5.5 Find prime numbers using the Sieve of Eratosthenes

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.

Example 5.5.5 Sieve of Eratosthenes


Dim maxNo As Integer = 1000
Dim sqrtMaxNo As Integer = Math.Floor(Math.Sqrt(maxNo))

Dim p(maxNo) As Boolean


Dim i, j As Integer

For i = 2 To maxNo
p(i) = True
Next i

' Apply the sieve


For i = 2 To sqrtMaxNo
If Not p(i) Then Continue For
For j = 2 * i To maxNo Step i
p(j) = False
Next j
Next i

' Print out the result


Console.WriteLine("The prime numbers up to " & maxNo & " are:")
j = 0
For i = 2 To maxNo
If Not p(i) Then Continue For

Console.Write(" {0,7}", i)
j = j + 1
If j = 10 Then
j = 0
Console.WriteLine()
End If
Next i

45
Enrichment

5.6 Introduction to arrays with two or more dimensions

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:

Example 5.6.1 Storing values in a two-dimensional array


Dim m(9, 9) As Integer
Dim i, j As Integer

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).

2. Given “Dim n() As Integer = {1,30,10,2,5,33,88,99,22,11}”. Find


the index of 88 using a computer program, and then print out the index.

3. Do the following computer simulations:

(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.

4. Find the value of the 1000th prime number.


(You may assume that the answer is less than 10000.)

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

You might also like