introduction to visual basic (part 2)lwc1/vbnet_2017/vbnet_part2.pdf · chapter3 them i vbnet exer...

67
VISUAL VISUAL BASIC BASIC Introduction to Copyright © HKTA Tang Hin Memorial Secondary School 2016 2016 edition second print 2

Upload: trinhmien

Post on 24-Mar-2019

222 views

Category:

Documents


0 download

TRANSCRIPT

VISUALVISUALBASICBASIC

Introduction to

Copyright © HKTA Tang Hin Memorial Secondary School 2016

2016 editionsecond print

2

. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .

. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .

. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .

. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .

. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .

. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .

. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .

. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .

. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .

. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .

. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .

. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .

. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .

. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .

. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .

. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .

. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .

. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .

. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .

. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .

. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .

. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .

. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .

. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .

. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .

. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .

367

89

151720

2124

2627293032

33343842

444850575963

65

Table of ContentsChapter 1 More on Operators

1.1 Assignment operatorsExercise 1

Chapter 2 Procedures2.1 Function2.2 Sub2.3 More about parametersExercise 2

Chapter 3 Mathematics in VB.NETExercise 3

Chapter 4 Random Numbers4.1 Rnd function4.2 Simulating dice4.3 Random integers in a rangeExercise 4

Chapter 5 Do…Loop Statement5.1 Learning by examples5.2 Exit Do and Continue DoExercise 5

Chapter 6 String Operations6.1 String functions6.2 Details of string functions6.3 Comparison of strings6.4 String matchingExercise 6

Glossary

Chapter 1 More on OperatorsWe have learnt how to do calculation and make decisions in VB.NET. In this chapter,we will learn a few extra operators.

Order of operationsAs listed in the last chapter, the evaluation of expressions in Visual Basic is ordered byits operator precedence below.

11(Highest)

Exponentiation ^

10 Unary identity and negation (unary)+ (unary)–

9 Multiplication and floating-pointdivision

* /

8 Integer division \

7 Modulus arithmetic Mod

6 Addition and subtraction + –

5 String concatenation &

4 Relational/comparison operators = <> < <= > >=

3 Negation Not

2 Conjunction And

1 (Lowest) Inclusive disjunction Or

Now we continue to the operators that was not introduced before, i.e. \ , Mod , & , andthe unary operators.

More on Operators 3

Division with remaindersThe operators \ and Mod are used for division with remainders. \ means getting thequotient of the division, and Mod means getting the remainder.

Here are a few examples:

VB.NET Expression Result VB.NET Expression Result

75 \ 8 9 75 Mod 8 3

-75 \ 8 -9 -75 Mod 8 -3

75 \ -8 -9 75 Mod -8 3

-75 \ -8 9 -75 Mod -8 -3

Now we discuss about the signs of the results. In the example above, we find that thesigns of both 75 (dividend) and 8 (divisor) are considered in \ , but only the sign of 75is considered in Mod .

Now we go to floating point numbers. The results may not be obvious at all.

VB.NET Expression Result VB.NET Expression Result

31.25 \ 4.5 7 31.25 Mod 4.5 4.25

31.25 \ 5.5 5 31.25 Mod 5.5 3.75

The \ operator converts numbers into integers before division, while Mod does not.Floating point numbers are converted to integers in a way not obvious to us: 4.5 isrounded off to 4, but 5.5 is rounded off to 6.

Do not use \ and Mod with floating-point numbers unless you knowwhat are you doing.

Unary operatorsThere are two unary operators in VB.NET, namely identity ( + ) and negation( - ). Theycorrespond to the positive and the negative signs of Mathematics respectively.

In fact, only the unary - is useful.

4 Introduction to Visual Basic (Part 2)

String concatenationTo join strings together, i.e. concatenate the strings, we use the & operator or the +operator. & is preferred over + because & is defined for strings only. In contrast, + isused mainly for addition. Here are a few examples:

VB.NET Expression Result

"note" & "pad" "notepad"

5 & 4 * 6 "524"

As shown in the example, & converts it’s operands into strings implicitly. Note that theconversion is not done in + , so unintended results and even errors may happen.

No space is added to the strings during a concatenation.

Class workEvaluate the following VB.NET expressions:

VB.NET Expression Result

"con" & "cent" & "rated"

4 * 3 & 5 * 2

9 - 25 / 2 * 3

9 - 25 \ 2 * 3

-35 Mod 3 ^ 3

a a a ( )123

a

12

More on Operators 5

1.1 Assignment operatorsOne of the most common operations in a program is to increase and decrease the valueof a variable. See the following example for an idea.

In the example, the statement applesSold = applesSold + 1 increases the value ofthe variable applesSold by 1. You may also write applesSold += 1 instead, i.e.

In the second example, += is an assignment operator, which adds a certain value to avariable. -= , *= , /= , \= , ^= and &= are also assignment operators, which have similarmeanings.

Class WorkExpress the following actions into VB.NET code:

Action VB.NET statement

Increase x by 100

Decrease y by 5

Multiple product by -3

Add “sugar” to the end of the str1

' Assigns the value 10 to the variable.applesSold = 10' The following statement increases "applesSold" by one.applesSold = applesSold + 1' The variable now holds the value 11.

' Assigns the value 10 to the variable.applesSold = 10' The following statement increases "applesSold" by one.applesSold += 1' The variable now holds the value 11.

6 Introduction to Visual Basic (Part 2)

Exercise 1Write a program that accepts the hour of a day (from 0 to 23). Then calculate thehour three hours later.

The output of the program should match the sample below:

Enter the hour (0-23): 22Three hours later, the time is 1:00

Write a program that accepts the hours (from 0 to 23) of the start time and the endtime. Find the difference of the time, provided that the difference is between 1and 24 hours (inclusive).

The output of the program should match the sample below:

Enter the start hour (0-23): 22Enter the end hour (0-23): 12The time elapsed is 14 hours.

1.

2.

Exercise 7

Chapter 2 ProceduresWhen we perform some operations repeatedly, we group the operations together intoprocedures. This avoids the problem of copying the same, or similar code, everywherein your source, as seen in the example below:

The repeating parts of the code above can be made better using procedures. In VisualBasic.NET, a procedure that returns a value is called a Function , and a procedurewithout a return value is called a Sub .

You have already encountered a few procedures before. Sub Main() ,Console.WriteLine , Console.Write and Console.ReadLine are all procedures.

Module Module1 Sub Main() Console.Write("Enter the base of triangle one: ") Dim base1 As Double = Console.ReadLine() Console.Write("Enter the height of triangle one: ") Dim height1 As Double = Console.ReadLine() Console.WriteLine("The area of triangle one is {0}.", base1 * height1 / 2)

Console.WriteLine()

Console.Write("Enter the base of triangle two: ") Dim base2 As Double = Console.ReadLine() Console.Write("Enter the height of triangle two: ") Dim height2 As Double = Console.ReadLine()

Console.WriteLine("The area of triangle two is {0}.", base2 * height2 / 2)

Console.ReadLine() End SubEnd Module

8 Introduction to Visual Basic (Part 2)

2.1 FunctionA Function is a procedure that returns a value. Here is the syntax of a function:

The following are some components of a function:

Component Details

Name of thefunction

Give the function a name that describes what the function do.Usually, we name function with a few words in CamelCase, e.g.AreaOfTriangle. If the name is valid for a variable, then it is alsovalid for a function.

Parameterlist

Usually the inputs of the function. The list is written in a commaseparated list of parameters, or is empty if there is no parameter.Details will be discussed later in this chapter.

Returnstatement

Ends the function immediately, and outputs a return value to thecaller. Multiple Return statements can be present in a singlefunction, and this is useful with If… Then… Else statements.

Return type The data type (Integer, Double or others) of the return value.

Function NameOfFunction(parameterList) As ReturnType ... Return returnValue ...End Function

Function 9

Example: area of a triangleHere is a function that calculates the area of a triangle:

The area of triangle one is 6.The area of triangle two is 15.

In VB.NET, no procedures can be put inside other procedures. They aresupposed to be inside a Module only.

As the first example, the function above is very simple. It is still agood idea to write a function because we do not want to enter theformula twice. Writing the same code multiple times makes it moreprobable to introduce bugs.

Module Module1 Function AreaOfTriangle(base As Double, height As Double) As Double Return base * height / 2 End Function

Sub Main() Dim base1 As Double = 3 Dim height1 As Double = 4 Console.WriteLine("The area of triangle one is {0}.", AreaOfTriangle(base1, height1))

Dim base2 As Double = 5 Dim height2 As Double = 6 Console.WriteLine("The area of triangle two is {0}.", AreaOfTriangle(base2, height2))

Console.ReadLine() End SubEnd Module

10 Introduction to Visual Basic (Part 2)

Example: inputting valuesHere is a function that allow the user to enter numbers:

Enter the base: 4Enter the height: 8The area of the triangle is 16.

You may have already noticed that AreaOfTriangle in the last example can also beused in this example.

Module Module1 Function ReadDoubleWithPrompt(prompt As String) As Double Console.Write(prompt) Return Console.ReadLine() End Function

Sub Main() Dim base As Double = ReadDoubleWithPrompt("Enter the base: ") Dim height As Double = ReadDoubleWithPrompt("Enter the height: ")

Console.WriteLine("The area of the triangle is {0}.", base * height / 2) Console.ReadLine() End SubEnd Module

Function 11

Example: converting marks into gradesHere is an example using If… Then statements in functions.

Enter the mark: 50The grade is C.

Remember to return a value in all cases.

Module Module1 Function GetGradeByMark(mark As Double) As String If mark >= 80 Then Return "A" End If If mark >= 70 Then Return "B" End If If mark >= 50 Then Return "C" End If Return "F" End Function

Sub Main() Console.Write("Enter the mark: ") Dim mark As Double = Console.ReadLine()

Console.WriteLine("The grade is {0}.", GetGradeByMark(mark)) Console.ReadLine() End SubEnd Module

12 Introduction to Visual Basic (Part 2)

You may find the If… Then statements cumbersome to read. In this case, you may usesingle line If statements:

If [condition] Then [statement]

(Note: single line If statement is usually bad. The use here is an exception.)

Parameters, parameter list and argumentsAs shown in the examples, the parameter list is having a syntax similar to Dimstatement, which is:

Each part of the parameter list is a parameter. A parameter is a special variable thatreceives data from callers. You can have any number of parameters in a function. Somefunctions have no parameter (e.g. Console.ReadLine ), and some have a lot ofparameters.

When you use the function, you are going to call it. The place you call the function iscalled the caller or the call site. Each time you call the function, you can supplydifferent arguments to the same function. For example:

The arguments of your function call should match the definitions of the function.

Function GetGradeByMark(mark As Double) As String If mark >= 80 Then Return "A" If mark >= 70 Then Return "B" If mark >= 50 Then Return "C" Return "F"End Function

name1 As dataType1, name2 As dataType2, ...

Dim area1 As Double = AreaOfTriangle(base1, height1)Dim area2 As Double = AreaOfTriangle(base2, height2)

Function 13

Class WorkConsider the following declarations of the functions below:

Write down the code that calculate the following:

Write down a Function statement for the following. Remember to name thefunction and parameters properly.

1.

If a student passes with 69 marks in Chinese and 49 marks in English.

The area of triangle with sides 13, 14 and 15.

The square of the 15th Fibonacci number.

If a student failed any subject with chi marks in Chinese and eng marks inEnglish.

(a)

(b)

(c)

(d)

2.

A function that finds the perimeter of a rectangle, where the width and theheight of the rectangle are given.

A function that finds the percentage change, where the original value and thenew value are given.

A function that check if the student gets a pass in all subjects: Chinese,English and Mathematics.

A function that checks if the content of a string is a number, e.g. "12345" .

(a)

(b)

(c)

(d)

' Returns the n-th Fibonacci number.Function FibonacciNumber(n As Integer) As Integer

' Returns the area of the triangle with sides a, b and c.Function AreaOfTriangle(a As Double, b As Double, c As Double) As Double

' Returns if both subjects pass.Function IsBothPass(chi As Double, eng As Double) As Boolean

14 Introduction to Visual Basic (Part 2)

2.2 SubA Sub is a procedure that does not return a value. Here is the syntax:

Like a function, Return statements can be used in a Sub . Since no value is beingreturned, the Return statement is just the single word Return .

You can use Return statements in Sub Main(). By exiting Sub Main(),these Return statements end the program immediately.

Sub NameOfSub(parameterList) ... Return ' Use only if you need to return early. ...End Sub

Sub 15

Example

Enter the mark of subject 1: 45FailEnter the mark of subject 2: 50Pass

Module Module1 Sub ProcessMark(mark As Double) If mark < 0 Or mark > 100 Then Console.WriteLine("Invalid mark: {0}", mark) Return End If

If mark >= 50 Then Console.WriteLine("Pass") Else Console.WriteLine("Fail") End If End Sub

Sub Main() Console.Write("Enter the mark of subject 1: ") Dim mark1 As Double = Console.ReadLine() ProcessMark(mark1)

Console.Write("Enter the mark of subject 2: ") Dim mark2 As Double = Console.ReadLine() ProcessMark(mark2)

Console.ReadLine() End SubEnd Module

16 Introduction to Visual Basic (Part 2)

2.3 More about parameters

What happens when I change the value of aparameter inside a Function or Sub?Unless you specify otherwise (see the section below), the arguments are passed byvalue. It means copies of the variables are passed into the procedure. If anyparameters is changed in the procedure, only the copy is changed. The original value isnot changed together with the copy.

Changing the value of an argument passed by value inside a procedureis bad for readability, because what the variable actually stores maybecome different from what its name suggests. Do this with care.

Appendix: Passing arguments by referenceTo allow procedures to change the value of the original argument, you can set theparameter to pass by reference. In VB.NET, this is done by adding the ByRef keywordbefore the parameter.

Passing parameters by reference is used mainly

to allow the use of more than one output value in a function (the parameterspassed by reference are outputs).

to avoid the performance penalty of copying a large data structure.

However, with the internal use of reference types in VB.NET, we usually do not incurthe performance penalty by passing “by value”.

More about parameters 17

Example: ByRef keyword

After PassByVal: 1After PassByRef: 10

Module Module1 ' x is passed to PassByVal by value. Sub PassByVal(x As Integer) x = 10 End Sub

' x is passed to PassByVal by reference. Sub PassByRef(ByRef x As Integer) x = 10 End Sub

Sub Main() Dim value As Integer = 1

' The value doesn't change here when passed by value. PassByVal(value) Console.WriteLine("After PassByVal: {0}", value)

' The value DOES change when passed ByRef. PassByRef(value) Console.WriteLine("After PassByRef: {0}", value)

Console.ReadLine() End SubEnd Module

18 Introduction to Visual Basic (Part 2)

Example: using a sub to swap numbers

Before swap: x = 3, y = 4After swap: x = 4, y = 3

Appendix: Value type and reference type in .NETSome data types are stored internally as a reference to some underlying data, e.g.String . These are known as reference types in .NET platform. In contrast, Integer ,Single , Double and Boolean are value types.

This has some implications on passing arguments in procedures, which are discussed inhttps://msdn.microsoft.com/en-us/library/eek064h4.aspx and http://net-informations.com/faq/general/valuetype-referencetype.htm.

Module Module1 Sub SwapIntegers(ByRef first As Integer, ByRef second As Integer) Dim tempValue As Integer = first first = second second = tempValue End Sub

Sub Main() Dim x As Integer = 3 Dim y As Integer = 4 Console.WriteLine("Before swap: x = {0}, y = {1}", x, y)

SwapIntegers(x, y) Console.WriteLine("After swap: x = {0}, y = {1}", x, y)

Console.ReadLine() End SubEnd Module

More about parameters 19

Exercise 2Write two functions to calculate the area and the perimeter of a rectangle from itslength and width. Use these functions to create a program that produce outputthat matches the following sample:

Enter the length of the rectangle: 10Enter the width of the rectangle: 8The area of the rectangle is 80, and the perimeter is 36.

Write a function that checks if a child is eligible for free entry. The child is eligiblefor free entry if he or she is aged under 3 and is shorter than 90 cm. Use thefunction to create a program that produce output that matches the followingsample:

Enter the age: 2Enter the height (in cm): 90The child is NOT eligible for free entry.

Enter the age: 1Enter the height (in cm): 89.5The child is eligible for free entry.

1.

2.

20 Introduction to Visual Basic (Part 2)

Chapter 3 Mathematics in VB.NETThis chapter introduces some mathematical functions and constants used in VB.NET.

Mathematical functions

Function Description Example Result

Math.Sqrt Finds the square root. Math.Sqrt(4) 2

Math.Max Returns the larger oftwo numbers.

Math.Max(2, 5) 5

Math.Min Returns the smaller oftwo numbers.

Math.Min(2, 5) 2

Math.Round Rounds off to thenearest integer, or to aspecified number ofdecimal places.

Math.Round(11.56)Math.Round(11.56, 1)

1211.5

Math.Floor(or Int)

Rounds down to thenearest integer.

Math.Floor(2.3)Math.Floor(-2.3)

2-3

Math.Ceiling Rounds up to thenearest integer.

Math.Ceiling(2.3)Math.Ceiling(-2.3)

3-2

Math.Truncate(or Fix)

Finds the integral part. Math.Truncate(2.3)Math.Truncate(-2.3)

2-2

Math.Abs Finds the absolute value(remove negative sign).

Math.Abs(-4)Math.Abs(3)

43

Math.Sign The sign of the number(positive: 1, zero: 0,negative: -1).

Math.Sign(-5) -1

Mathematics in VB.NET 21

Mathematical constants

Constant Description Data type Value

Math.PI The value of π. Double 3.141592653589793

Data types used in mathematics functionsHere are the data types of the inputs and outputs of the mathematical functions.

Function Input data type Output datatype

Math.Sqrt, Math.Round,Math.Floor, Math.Ceiling,Math.Truncate

Double Same as the input

Math.Max, Math.Min Double, Single, IntegerNote: both inputs must havethe same data type.

Same as the input

Math.Abs, Int, Fix Double, Single, Integer Same as the input

Math.Sign Double, Single, Integer Integer

Appendix: related mathematical symbols

VB.NET expression Mathematical expression

Math.Max(x, y) max(x,y)

Math.Min(x, y) min(x,y)

Math.Floor(x) ⌊x⌋ or [x]

Math.Ceiling(x) ⌈x⌉

Math.Abs(x) |x|

Math.Sign(x) sgn(x)

22 Introduction to Visual Basic (Part 2)

Class WorkConvert each of the following expressions into a VB.NET statement:

Mathematical expression VB.NET statement

a =√x +1 a = Math.Sqrt(x + 1)

r =√x2 +x −3

V = πr3 [Take π = Math.PI]

a =max(x,y2 −1)

p =min(0.5,√1−x2)

x = √1+√1+a

43

Mathematics in VB.NET 23

Exercise 3Write a program that calculates the total surface area of a circular cone. The

formula of the total surface area A is A = πr (√r2 +h2 +r), where r is the base

radius, and h is the height.

Round off the answer to four decimal places. The output of the program shouldmatch the sample below:

Enter the base radius: 1.2Enter the height: 3.4The total surface area is 18.1165 square units.

Write a function that calculate the area of a triangle by the length of its threesides, namely a, b and c. The formula for the area A is

A = √s(s−a)(s− b)(s− c), where s = . (This is known as Heron’s

formula.)

Then write a program to use the function to calculate the area of a triangle, asshown in the sample below.

Enter the length of side 1: 13Enter the length of side 2: 14Enter the length of side 3: 15The area of the triangle is 84 square units.

1.

2.

a+b+c

2

24 Introduction to Visual Basic (Part 2)

Write a program to check if a non-negative integer is a square number. Theprogram should not accept decimals or negative numbers.

The output of the program should match the sample below:

Enter a number: 22 is NOT a square number.

Enter a number: 2525 is a square number.

Enter a number: -3You should enter a non-negative integer.

Enter a number: 6.25You should enter a non-negative integer.

3.

Exercise 25

Chapter 4 Random NumbersRandom numbers are an important aspect of programs. In computer games, randomnumbers are used to simulate dice. Some algorithms requires the use of randomnumbers to do calculations. Random numbers are also used to generate the secret keys,which is needed for encryption to work.

How do computer generate random numbersThere are two kinds of random number generators. The first kind is called pseudo-random number generators (PRNGs), which does not use a real random source.Randomness is simulated using an algorithm.

The second kind of random number generator gather randomness (or entropy) fromsome physical phenomenon, such as radioactive source or atmospheric noise. This kindof generators provides true randomness comparable to dice. However, the speed ofgeneration of randomness is slow, because sources of randomness is limited incomputers. A notable web site which use this kind of RNG is https://www.random.org.

In VB.NET, a few PRNGs are provided in the language. We will study one of them:Rnd() and Randomize() , to learn how to use random numbers in programs.

26 Introduction to Visual Basic (Part 2)

4.1 Rnd functionThe Rnd function returns a number less than one, but greater than or equal to zero, i.e.

0 ≤ x < 1

The syntax is of Rnd function is simply Rnd() , and it returns a random number in theSingle data type. The following program outputs a result of Rnd ten times. Repeatrunning the program to see what is wrong.

0.70554750.5334240.57951860.28956250.3019480.77474010.014017640.76072360.814490.7090379

Sub Main() Console.WriteLine(Rnd()) Console.WriteLine(Rnd()) Console.WriteLine(Rnd()) Console.WriteLine(Rnd()) Console.WriteLine(Rnd()) Console.WriteLine(Rnd()) Console.WriteLine(Rnd()) Console.WriteLine(Rnd()) Console.WriteLine(Rnd()) Console.WriteLine(Rnd())

Console.ReadLine()End Sub

Rnd function 27

Seeding the Rnd function with Randomize()To make the Rnd function generate different sequence of numbers, we call theRandomize function before using the Rnd function. Randomize gives a seed to therandom number generator used by Rnd . Randomize should be called only once in thewhole program.

After the corrections, the program looks like:

This time the outputs are different every time the program is run:

0.80796450.1011730.25127150.14930370.097724380.2624110.92600490.89976170.77237580.7103807

Sub Main() Randomize()

Console.WriteLine(Rnd()) Console.WriteLine(Rnd()) ...End Sub

28 Introduction to Visual Basic (Part 2)

4.2 Simulating diceIn this section, we use Rnd function to simulate a die (singular of dice). What we needto do is the following:

Dim value As Integer = Int(Rnd() * 6) + 1

It is okay to put + 1 either inside or outside the brackets.

If we are doing this in strict mode, then we do the following:

Dim value As Integer = CInt(Int(Rnd() * 6)) + 1

The function CInt converts a number into Integer data type. In strictmode, the conversion from Single to Integer must be done manually.

If you use CInt, remember to put it outside Int. CInt must be doneafter the rounding-off by Int. Otherwise, CInt itself rounds off thenumber in a different way.

To illustrate this statement, we list all possible values of Rnd() in the table below:

Rnd() Rnd() * 6 Int(Rnd() * 6) Int(Rnd() * 6) + 1

≥ 0 and < ≥ 0 and < 1 0 1

≥ and < ≥ 1 and < 2

≥ and <

≥ and <

≥ and <

≥ and < 1

16

16

26

26

36

36

46

46

56

56

Simulating dice 29

4.3 Random integers in a rangeWe can modify the statement Int(Rnd() * 6) + 1 to generate random integers thatfall with in a certain range. Take Int(Rnd() * 4) + 8 as an example:

Rnd() Rnd() * 4 Int(Rnd() * 4) Int(Rnd() * 4) + 8

≥ 0 and < ≥ 0 and < 1

≥ and <

≥ and <

≥ and < 1

From the table, we know that the statement generates random integers from 8 to 11inclusive. Also, “4” is the number of possible outcomes, and “8” is the minimumoutcome.

The total number of possible outcomes can be calculated by max −min+1, where max and min are the maximum and minimum outcome respectively. Therefore, wecan generate integers inside a range using the formula below:

[variable] = Int(Rnd() * (max – min + 1)) + min

Or in strict mode:

[variable] = CInt(Int(Rnd() * (max – min + 1))) + min

You can create a function with the code above, to avoid repeating theformula every time you use it.

14

14

24

24

34

34

30 Introduction to Visual Basic (Part 2)

Class workWrite a Visual Basic statement to generate the random numbers below:

Random number VB code

An integer from 1 to 6 inclusive Int(Rnd() * 6) + 1

An integer from 1 to 5 inclusive

An integer from 10 to 20 inclusive

An integer from 25 to 30 inclusive

An integer from 50 to 100 inclusive

An integer from 0 to 2 inclusive

An integer from −5 to 5 inclusive

The sum of the values of 2 dice (thepossible values of each die are 1 to 6)

Random integers in a range 31

Exercise 4Write a program that throws two dice, one for the player and the other for thecomputer. Display the values of both dice. Also, compare the values of the dice,and the one with the larger value wins. Output “You win!”, “You lose!” or “Draw!”depending on the value of the dice.

The output of the program should match the sample below:

Player: 4Computer: 2You win!

Write a program that asks the player to do additions. The computer generates tworandom numbers from 11 to 99, and ask the user to enter the sum.

The output of the program should match the sample below:

What is the result of 34 + 56 ? 90You are correct!

What is the result of 26 + 47 ? 63You are wrong!

Modify the program in the previous question, that the program generates a randomsign in addition to two random numbers. You may start working with only “+” and“−” sign, and continue with “×” and “÷” later. You can also change the limits of thenumbers, and even let the user decides them.

Some special considerations should be made for subtraction anddivision.

1.

2.

3.

32 Introduction to Visual Basic (Part 2)

Chapter 5 Do…Loop StatementTo make a program to feel like a real program you need some looping, i.e. repeatingthe execution of some instructions. Now we learn the Do… Loop statement, which isthe most versatile of all loop structures.

The syntax of a Do… Loop statement is listed below:

The Do… Loop statement repeats the execution of the statements inside indefinitely,While or Until some condition is true. Each time the statements inside are executedis called an iteration.

The condition can be put either after Do or after Loop . If the condition is put after Do ,then the condition is tested in the first iteration. And the condition is not satisfied, theloop will not be run even once.

In the other way, if the condition is put after Loop , then the condition is not tested inthe first iteration. In this case, the loop is guaranteed to run at least once.

Of course, you can also choose not to include a condition at all. In this case theDo… Loop statement ends only with some other means (e.g. by a Exit Do statement,which is introduced later).

Do { While | Until } condition [ statements ]Loop-or-Do [ statements ]Loop { While | Until } condition-or-Do [ statements ]Loop

Do…Loop Statement 33

5.1 Learning by examplesTo learn looping it is easiest to learn by examples.

Example: playing a game againIn this example, the computer ask whether a user should play a game again or not. Ifthe user presses “Y”, then the game is played again. Otherwise, the game quits.

Lucky dice - you win if you roll a 6.You have rolled 4. You lose!Do you want to play again? (Y/N) YYou have rolled 5. You lose!Do you want to play again? (Y/N) yYou have rolled 6! You win!Do you want to play again? (Y/N) n

Sub Main() Randomize() Console.WriteLine("Lucky dice - you win if you roll a 6.")

Dim playAgain As String Do Dim die As Integer = CInt(Int(Rnd() * 6)) + 1 If die = 6 Then Console.WriteLine("You have rolled 6! You win!") Else Console.WriteLine("You have rolled {0}. You lose!", die) End If

Console.Write("Do you want to play again? (Y/N) ") playAgain = Console.ReadLine() Loop While playAgain = "Y" Or playAgain = "y"End Sub

34 Introduction to Visual Basic (Part 2)

Some of you might have asked: what will happen if I enter something other than “Y” or“N”? In the program above, it simply treats the answer as an “N”.

Of course, you may like to repeat the question in this case. This can be done withnested loops. For example:

Lucky dice - you win if you roll a 6.You have rolled 3. You lose!Do you want to play again? (Y/N) abDo you want to play again? (Y/N) yesDo you want to play again? (Y/N) yYou have rolled 2. You lose!Do you want to play again? (Y/N) noDo you want to play again? (Y/N) n

Sub Main() Randomize() Console.WriteLine("Lucky dice - you win if you roll a 6.")

Dim playAgain As String Do Dim die As Integer = CInt(Int(Rnd() * 6)) + 1 If die = 6 Then Console.WriteLine("You have rolled 6! You win!") Else Console.WriteLine("You have rolled {0}. You lose!", die) End If

Do Console.Write("Do you want to play again? (Y/N) ") playAgain = Console.ReadLine() Loop Until playAgain = "Y" Or playAgain = "y" Or playAgain = "N" Or playAgain = "n" Loop While playAgain = "Y" Or playAgain = "y"End Sub

Learning by examples 35

To make the program more maintainable, we can break down the program intoprocedures. Besides being easier to read, individual procedure can also be copied intodifferent programs, saving time for development.

For example, the previous program can be rewritten in the following way:

Sub DoLuckyDraw() Dim die As Integer = CInt(Int(Rnd() * 6)) + 1 If die = 6 Then Console.WriteLine("You have rolled 6! You win!") Else Console.WriteLine("You have rolled {0}. You lose!", die) End IfEnd Sub

Function ShouldPlayAgain() As Boolean Dim playAgain As String Do Console.Write("Do you want to play again? (Y/N) ") playAgain = Console.ReadLine() Loop Until playAgain = "Y" Or playAgain = "y" Or playAgain = "N" Or playAgain = "n" Return playAgain = "Y" Or playAgain = "y"End Function

Sub Main() Randomize() Console.WriteLine("Lucky dice - you win if you roll a 6.") Do DoLuckyDraw() Loop While ShouldPlayAgain()End Sub

36 Introduction to Visual Basic (Part 2)

Example: reversing the digits of an integerThe following example shows how a Do… Loop statement is used to do calculations.Note: arguments are passed to reverseDigits by value.

Enter an integer: 13579After reversing the digits, the result is 97531.

It is easier to get the last digit of an integer than the first digit.

Function reverseDigits(n As Integer) As Integer Dim reversed As Integer = 0 Do While n <> 0 Dim digit = n Mod 10 n \= 10 reversed = reversed * 10 + digit Loop Return reversedEnd Function

Sub Main() Console.Write("Enter an integer: ") Dim n As Integer = Console.ReadLine() Console.WriteLine("After reversing the digits, the result is {0}.", reverseDigits(n)) Console.ReadLine()End Sub

Learning by examples 37

5.2 Exit Do and Continue DoExit Do means to exit the Do… Loop statement immediately. Control is transferred tothe statement after the loop.

Continue Do means to bypass everything in the current iteration. Control goes to thenext iteration if the loop condition is satisfied.

Example: total and average marks

Dim totalMarks As Double = 0Dim numSubjects As Integer = 0

Do Console.Write("Enter the mark of the next subject (-1 to quit): ") Dim mark As Double = Console.ReadLine()

If mark = -1 Then Exit Do End If

If mark < 0 Or mark > 100 Then Console.WriteLine("Invalid mark ignored.") Continue Do End If

totalMarks += mark numSubjects += 1Loop

Console.WriteLine()Console.WriteLine("Number of subjects: {0}", numSubjects)Console.WriteLine("Total marks: {0}", totalMarks)Console.WriteLine("Average mark: {0}", totalMarks / numSubjects)Console.ReadLine()

38 Introduction to Visual Basic (Part 2)

Enter the mark of the next subject (-1 to quit): 23Enter the mark of the next subject (-1 to quit): 80Enter the mark of the next subject (-1 to quit): 106Invalid mark ignored.Enter the mark of the next subject (-1 to quit): 66.5Enter the mark of the next subject (-1 to quit): -1

Number of subjects: 3Total marks: 169.5Average mark: 56.5

Exit Do and Continue Do are usually used with If… Thenstatements.Use Exit Do if you want to quit a loop in the middle of aniteration.Use Continue Do to skip data that you do not want to process.

Exit Do and Continue Do 39

Example: high-low guessing gameFinally we have a more advanced example: a game utilizing everything we have learnt.Try to figure out the logic behind the game!

Function GetRandomInteger() As Integer Return CInt(Int(Rnd() * 100)) + 1End Function

Sub Main() Randomize()

Console.WriteLine("Number guessing game") Console.WriteLine("====================") Console.WriteLine("The computer will pick and show a random number from 1 to 100.") Console.WriteLine("You need to guess whether the next number is higher or lower.") Console.WriteLine("Try to guess correctly as long as you can.") Console.WriteLine()

Dim score As Integer = 0 Dim num As Integer = GetRandomInteger() Do Console.Write("The number is {0}. Higher / lower (H/L)? ", num) Dim choice As String = Console.ReadLine() Do While choice <> "H" And choice <> "h" And choice <> "L" And choice <> "l" Console.Write("Please enter ""H"" or ""L"". Higher / lower (H/L)? ") choice = Console.ReadLine() Loop

Dim nextNum As Integer = GetRandomInteger() If nextNum = num Then Console.WriteLine("The number is {0}. You lose no matter what you guess!", nextNum) Exit Do End If If nextNum > num And (choice <> "H" And choice <> "h") Or nextNum < num And (choice <> "L" And choice <> "l") Then Console.WriteLine("The number is {0}. You have lost!", nextNum) Exit Do End If

num = nextNum score += 1 Loop

Console.WriteLine() Console.WriteLine("Your score: {0}", score) Console.ReadLine()End Sub

40 Introduction to Visual Basic (Part 2)

Number guessing game====================The computer will pick and show a random number from 1 to 100.You need to guess whether the next number is higher or lower.Try to guess correctly as long as you can.

The number is 23. Higher / lower (H/L)? HThe number is 37. Higher / lower (H/L)? SPlease enter "H" or "L". Higher / lower (H/L)? HThe number is 93. Higher / lower (H/L)? LThe number is 78. Higher / lower (H/L)? LThe number is 29. Higher / lower (H/L)? HThe number is 47. Higher / lower (H/L)? LThe number is 4. Higher / lower (H/L)? HThe number is 47. Higher / lower (H/L)? HThe number is 40. You have lost!

Your score: 7

Feel free to use Exit Do and Continue Do to express your intent in thecode. You should write the exact logic you are thinking of.

Exit Do and Continue Do 41

Exercise 5Write a program that draws random prizes. There should be a 70% chance to win a“small prize”, a 25% chance to win a “big prize”, and a 5% chance to win a “JUMBOprize”. After the lucky draw you should ask the user whether to draw again.

The output of the program should match the following sample:

Lucky Draw==========You have won a JUMBO prize!Draw again? (Y/N) YYou have won a small prize!Draw again? (Y/N) n

Write a program that play the number guessing game. The program shouldgenerate a random secret number from 1 to 100, and let the user guess it.

It is okay for skip the number of guesses in your first version, and add it back later.

Number Guessing Game====================The computer has a secret number between 1 and 100.Guess the number in as few tries as possible.

Enter your guess: 50Too large!Enter your guess: 25Too small!Enter your guess: 37Too small!Enter your guess: 44Correct! You have guessed 4 times.

1.

2.

42 Introduction to Visual Basic (Part 2)

Write a program that plays rock-paper-scissors. The program should continue toplay until the player ends the program. You can follow the sample output below:

ROCK, PAPER and SCISSORSType END to end the game.

Rock, paper or scissors? (R/P/S/END) RThe computer played SCISSORS. You have won!The score is now 1:0

Rock, paper or scissors? (R/P/S/END) CPlease enter "R", "P" or "S".

Rock, paper or scissors? (R/P/S/END) SThe computer played ROCK. You have lost!The score is now 1:1

Rock, paper or scissors? (R/P/S/END) PThe computer played PAPER. Draw!The score is now 1:1

Rock, paper or scissors? (R/P/S/END) END

Write a program that finds the greatest common divisor (GCD) of two integersusing Euclidean algorithm.

Write a function that returns the first digit of an integer. (If the number isnegative, ignore its sign.)

3.

4.

5.

Exercise 43

Chapter 6 String OperationsIn this chapter, we learn about strings and text manipulation in VB.NET.

Strings and charactersText is stored in computer programs in the form of strings.

A string is a sequence of characters. There are different types of characters, such asletters, digits, punctuation marks, symbols, white spaces, and control characters.

How is text stored in computers?Unlike humans, computers do not recognise text by its image or sound. Instead, text isconverted into numbers, and computers store the numbers instead. A scheme that mapscharacters into numbers is called a character set.

We also have a concept of character encoding, which tells how text in a particularcharacter set is stored in memory. The concept of character encoding is particularlyimportant for Unicode, which has different character encodings for the same characterset. For other character sets, we can simply use these two terms interchangeably. A fewcommon character sets are introduced below:

ASCII

ASCII, the American Standard Code for Information Interchange, is an old characterset which is still significant nowadays. ASCII is still significant because most charactersets (including Big5, GBK, and Unicode) are backwards compatible with ASCII. We usethe term compatible because these character sets contain an exact copy of theUS-ASCII character set.

ASCII consists of 128 characters, and each character is assigned a code point. However,only code points 32 to 126 are “printable”, i.e. used for text. The rest of the charactersare called control characters.

44 Introduction to Visual Basic (Part 2)

Here is the list of ASCII printable characters. You are supposed to remember the codepoint of letters and digits, but not the special symbols.

Table 1. ASCII table (printable characters only)

32 48 64 80 96 112

+0 (sp) 0 @ P ` p

+1 ! 1 A Q a q

+2 " 2 B R b r

+3 # 3 C S c s

+4 $ 4 D T d t

+5 % 5 E U e u

+6 & 6 F V f v

+7 ' 7 G W g w

+8 ( 8 H X h x

+9 ) 9 I Y i y

+10 * : J Z j z

+11 + ; K [ k {

+12 , < L \ l |

+13 - = M ] m }

+14 . > N ^ n ~

+15 / ? O _ o

For the control characters, only CR (13) and LF (10) are significant in VB.NET. InWindows, the character sequence CR + LF moves the cursor to the next line. In VB.NET,this sequence can be referred as the constant vbCrLf .

String Operations 45

Big5 and GBK

In the past, different character sets were used to store text in different languages. Weused Big5 for traditional Chinese and GBK for simplified Chinese.

Unfortunately, with the exception of ASCII, we cannot mix text with differentcharacter sets together. Worse still, text at those times was often communicatedwithout specifying a character set, or even specifying a wrong character set. When thishappened, the text cannot be read unless the actual character set is selected.

If a wrong character set is used to read text, the text appears garbled. See the figurebelow for an example of selecting a wrong character set. This continues to happen forsome web sites today, like the one in the figure.

Figure 1. (Left) A web page rendered with a wrong character set. (Right) The same web page

after selecting the right character set. Source:

https://market.cloud.edu.tw/content/primary/math/ch_dc/tea_page/pauran/basic.htm

46 Introduction to Visual Basic (Part 2)

Unicode

Finally, Unicode is made to encode text in different languages simultaneously with asingle system. There are three mainstream character encodings in Unicode, namelyUTF-8, UTF-16, and UTF-32. Here is a comparison of the character encodings:

Character encoding Size of code unit (bytes) Size of a character(bytes)

ASCII 1 1

Big5 1 1 or 2

GBK 1 1 or 2

UTF-8 1 1, 2, 3 or 4

UTF-16 2 2 or 4

UTF-32 4 4

Strings in .NET platformStrings in .NET platform are encoded in UTF-16. In UTF-16, characters with Unicodecode point 65535 or below are encoded with one code unit (2 bytes), and others areencoded with two code units (4 bytes).

If a character is encoded in two code units, then it behaves like two separate charactersin VB.NET. In these cases, string functions related to characters, the length of stringand position of characters do not work properly. Unfortunately, these specialcharacters include Chinese names and Emojis, which are quite commonly used.

See http://www.unicode.org/charts/PDF/U20000.pdf to see a list of Chinese charactersand http://unicode.org/emoji/charts/full-emoji-list.html for the list of Emojis.

If your application handles text in other languages, then the situation is even morecomplex because of combining diacritical marks. The concepts involved are tooadvanced to discuss here.

String Operations 47

6.1 String functionsA few essential string functions are listed here. First, we learn a function that returnsthe length of the string:

Function Syntax and Meaning Example Result

Len Len(str)Returns the length of the string,i.e. its number of characters.

Len("Very good!")Len("鄧顯")

102

Next, a few functions that extract a part of a string are introduced:

Function Syntax and Meaning Example Result

Left Left(str, Length)Returns a specified number ofcharacters from the left of thestring.

Left("Wonder", 3) "Won"

Right Right(str, Length)Returns a specified number ofcharacters from the right of thestring.

Right("Wonder", 2) "er"

Mid Mid(str, Start)Mid(str, Start, Length)Returns a specified number ofcharacters from a string. If Lengthis not supplied, all characters fromposition Start is returned.

Mid("Block", 2, 3)Mid("clever", 3)

"loc""ever"

Trim Trim(str)Removes white space characters atthe beginning and at the end of astring.

Trim(" I win! ") "I win!”

Then, we learn functions that do transformations on a string:

Function Syntax and Meaning Example Result

UCase UCase(str)Converts a string to upper case.

UCase("good!") "GOOD!"

LCase LCase(str)Converts a string to lower case.

LCase("sMaRt") "smart"

48 Introduction to Visual Basic (Part 2)

Next, we have functions that convert characters to and from their Unicode code point:

Function Syntax and Meaning Example Result

AscW AscW(str)Returns the Unicode code point ofthe first character of the string.

AscW("A") 65

ChrW ChrW(charCode)Returns the character with thegiven Unicode code point.

ChrW(65) "A"

Finally, we have functions that search for a string within another string:

Function Syntax and Meaning Example Result

String.StartsWith [str1].StartsWith(str2)Returns True if str1 starts withstr2, False otherwise.

"example".StartsWith("ex")"example".StartsWith("ple")

TrueFalse

String.EndsWith [str1].EndsWith(str2)Returns True if str1 ends withstr2, False otherwise.

"example".EndsWith("ex")"example".EndsWith("ple")

FalseTrue

InStr InStr(Start, Str1, Str2)InStr(Str1, Str2)Returns an integer which is the startposition of the first occurrence ofStr2 within Str1. Returns zero ifStr2 is not found.

InStr("aabc", "ab")InStr("abc", "d")InStr(1,"rear","r")InStr(2,"rear","r")

2014

String functions 49

6.2 Details of string functionsIn this section, we discuss the details of functions Len , Left , Right , Mid , Trim , AscWand ChrW . String matching will be discussed in another section.

In some string functions, there are boundary cases that need to be discussed. Aboundary case is a special case that one or more input is at or just beyond its maximumor minimum limits. For example, if the valid mark is from 0 to 100, we consider -1, -0.1,0, 100, 100.1 and 101 as the boundary cases.

If you intend to write a real application, use string functions that workproperly in Unicode. In the functions discussed here, only UCase andLCase work properly.

Len functionLen function means to return the number of characters in the string. An empty string( "" ) has a length of 0. Here is an example:

Dim TestString As String = "Hello World"Dim TestLength As Integer = Len(TestString) ' Returns 11.

50 Introduction to Visual Basic (Part 2)

Left and Right functionsLeft and Right extract the specified number of characters from the left and right ofthe given string respectively. Some special cases are described here:

Condition Left / Right returns

Length ≥ length of string Returns the whole string.

Length = 0 Returns an empty string ("").

Length < 0 Exception. Results in runtime error ifnot handled.

It does not make sense to pass a negative length to string functions.However, if you pass a variable as the length, you need to check forunexpected cases.

Exception handling is not included in this book. Anyway, exceptions instring functions are not meant to be handled.

Here is an example:

Dim TestString As String = "Hello World!"Dim result As String

result = Left(TestString, 5) ' Returns "Hello".result = Left(TestString, 100) ' Returns "Hello World!".result = Left(TestString, 0) ' Returns "".

result = Right(TestString, 5) ' Returns "orld!".result = Right(TestString, 100) ' Returns "Hello World!".result = Right(TestString, 0) ' Returns "".

Details of string functions 51

Mid functionMid function extracts the specified number of characters beginning from the givenstarting position. The position is one-based, i.e. the first character of a string has aposition of 1. Some special cases are described here:

Condition Mid returns

Length is not specified Returns everything starting from thegiven position.

Start = 1 Return is same as Left.

Start > length of string Returns an empty string ("").

Start ≤ 0 or Length < 0 Exception. Results in runtime error ifnot handled.

Here is an example:

Dim TestString As String = "Mid Function Demo"Dim result As String

result = Mid(TestString, 1, 3) ' Returns "Mid".result = Mid(TestString, 14, 4) ' Returns "Demo".result = Mid(TestString, 5) ' Returns "Function Demo".

52 Introduction to Visual Basic (Part 2)

Trim functionTrim function removes white spaces in the beginning and the end of the string. This isused for sanitising user inputs because users may add unneeded spaces to the input.

The spaces at the middle of the strings are not removed.

However, we should note that “white space” in this function also includes ideographicspace (code point 12288), which is commonly used in CJK (Chinese, Japanese andKorean) text.

If you want to remove white spaces at the beginning of the string only,use LTrim. For the end of the string, use RTrim.

UCase and LCase functionsUCase and LCase functions convert all letters in the strings to upper case and lowercase respectively. Other characters, such as digits, are not affected.

In addition to “a” to “z”, a lot of characters have an upper case or alower case variant. For example, the upper case variant of the symbol“π” is “Π”.

Beware of UCase("i") and LCase("I"). In Turkish, they evaluate to"İ" and "ı" respectively.

Dim TestString As String = " Visual Basic "

' Returns "Visual Basic".Dim result As String = Trim(TestString)

Dim TestString As String = "Hello World 1234!"Dim result As String

result = UCase(TestString) ' Returns "HELLO WORLD 1234!".result = LCase(TestString) ' Returns "hello world 1234!".

Details of string functions 53

AscW and ChrW functionsAscW returns the Unicode code point of the first character of the string. And ChrWreturns a character corresponding to the Unicode code point. However, these functionswork only if the character has a Unicode code point of 65535 or below.

Class WorkEvaluate the following VB.NET expressions. In this exercise, UCase and LCase areexecuted in American English.

VB.NET expression Result

Right("S.2", 1) & Left("Cactus", 1)

UCase(LCase("TeStInG"))

Len(Mid(Trim(" very good "), 7, 4))

AscW("E")

ChrW(AscW("Z") + 20)

AscW(UCase("basic"))

AscW(Mid(vbCrLf, 2))

Dim code As Integercode = AscW("A") ' Returns 65.code = AscW("Apple") ' Returns 65.code = AscW("a") ' Returns 97.code = AscW("0") ' Returns 48.code = AscW(vbCrLf) ' Returns 13.

Dim character As Stringcharacter = ChrW(65) ' Returns "A".character = ChrW(97) ' Returns "a".character = ChrW(51) ' Returns "3".character = ChrW(33) ' Returns "!".

54 Introduction to Visual Basic (Part 2)

Integrated example: ROT13 cipherHere we implement a toy cipher called “ROT13” (rotate characters by 13 places). WhileROT13 cannot safely keep secrets, it can be used to hide spoilers.

Module Module1 Function RotateCharBy13(ch As String) As String If ch >= "A" And ch <= "Z" Then Return ChrW((AscW(ch) - 65 + 13) Mod 26 + 65) End If If ch >= "a" And ch <= "z" Then Return ChrW((AscW(ch) - 97 + 13) Mod 26 + 97) End If Return ch End Function

Sub Main() Console.WriteLine("ROT13 - Rotate by 13 places") Console.WriteLine("Enter the text to process:") Dim s As String = Console.ReadLine()

Console.WriteLine() Console.WriteLine("Processed text:")

Dim length = Len(s) Dim pos = 1 Do Until pos > length Console.Write(RotateCharBy13(Mid(s, pos, 1))) pos += 1 Loop Console.WriteLine()

Console.ReadLine() End SubEnd Module

Details of string functions 55

Now see the cipher into action. The second ROT13 operation cancels the first.

ROT13 - Rotate by 13 places===========================Enter the text to process:Visual Basic is awesome!

Processed text:Ivfhny Onfvp vf njrfbzr!

ROT13 - Rotate by 13 places===========================Enter the text to process:Ivfhny Onfvp vf njrfbzr!

Processed text:Visual Basic is awesome!

RotateCharBy13 in this example is not a robust implementationbecause the behavior is undefined if multiple characters are passed toch. However, the fix of this problem is too complicated to be discussedin this book.

56 Introduction to Visual Basic (Part 2)

6.3 Comparison of stringsStrings are compared in a way similar to how words are ordered in a dictionary. A wordappearing in the beginning of the dictionary is considered less than a word in the endof the dictionary, e.g. “apple” is less than “umbrella”. We call this lexicographicalorder.

To see which string is greater, the first characters of the two strings are compared. Ifthe characters are different, then the comparison is finished. Otherwise, the secondcharacters are compared, so on. If all the characters of both strings are equal, then thestrings are equal. However, if the characters of only one of the strings are used up inthe comparison, and all the compared characters are equal, then the longer string isgreater.

Here are a few results of string comparison (written as Boolean expressions that aretrue).

Comparison result Reason

"banana" < "cat" The first characters are different, with “b” lessthan “c”.

"formal" < "forward" The fourth characters are different, with “m” lessthan “w”.

"other" < "otherwise" All characters from “other” are used up.

"car" = "car" All characters are the same.

If the strings compared contain capital letters, digits, symbols, Chinese characters, etc.,the comparison is more complex. Different comparison methods produce differentresults even for comparing the same strings.

In this section, we discuss only binary comparison of strings in VB.NET, which is thedefault method. It means the strings are compared with their UTF-16 encoded values,code unit by code unit. For characters encoded with one UTF-16 code unit, this meansto compare their Unicode code point.

Comparison of strings 57

You can refer to the ASCII table for the Unicode code point of letters, digits and somesymbols. And you are expected to recite a few facts:

Note: you are not required to recite the ASCII table except for the facts listed above.

Class workEvaluate the following VB.NET expressions. Strings are compared using binarycomparison. Note: results are either True or False .

VB.NET expression Result

"pointer" >= "pointing"

"Flower" < "flower"

ChrW(100) > "Delicious"

Trim(" Visual Basic ") <= " Visual Basic "

Mid("okay", 2, 2) > Mid("okay", 4, 2)

Len("human") < 5 Or Strings.Right("able", 2) = "le"

“A” is the smallest capital letter, and “Z” is the largest capital letter. Comparisonof small letters is similar.

“0” is the smallest of the digits, and “9” is the largest.

Capital letters are always less than small letters

Digits are always less than letters, capital or small.

White space is less than all other characters, except for control characters such asCR or LF.

Chinese characters have a Unicode code point of 12288 or more. For example, “鄧”has a Unicode code point of 37159 (or U+9127). However, the Unicode code pointsof Chinese characters are not ordered in a specific order.

1.

2.

3.

4.

5.

6.

58 Introduction to Visual Basic (Part 2)

6.4 String matchingIn this section, we discuss a few string matching functions.

Details of string comparison apply to string matching. In addition,String.StartsWith and InStr may give incorrect results on arbitraryUTF-16 strings.

String.StartsWith and String.EndsWith methodsString.StartsWith and String.EndsWith are methods of String , which check if astring starts with or ends with certain substring respectively. The return values of theremethods are Boolean , i.e. either True or False .

Note: a method is a procedure associated with an object. Despite the difference in thename, a method is essentially the same as other procedures.

The following example checks a file by its name to see if it is a Microsoft Word file.

Enter the name of the file: test.docxIt is a DOCX file.

Console.Write("Enter the name of the file: ")Dim filename As String = Console.ReadLine()

Dim filenameUpper As String = UCase(filename)If filenameUpper.EndsWith(".DOCX") Then Console.WriteLine("It is a DOCX file.")ElseIf filenameUpper.EndsWith(".DOC") Then Console.WriteLine("It is a DOC file.")Else Console.WriteLine("It is not a Microsoft Word file.")End If

String matching 59

InStr functionTo locate one string within another string, you can use the InStr function. The syntaxof the InStr function is as follows:

The meanings of the parameters are listed below:

Parameter Meaning

Start(Optional)

The starting position of the search. Matches before Start areignored. If omitted, then Start is 1. The position is one-based.

String1 The string to be searched in. Also known as haystack.

String2 The string to search for. Also known as needle.

And here is the return:

Condition InStr returns

String2 is found within String1. Position where the first match begins (one-based)

String2 is not found. 0

String1 is empty. 0

Start > length of String1. 0

String2 is empty, but String1 isnot empty.

Start

Start < 1 Exception. Results in runtime error if nothandled.

[variable =] InStr(String1, String2)[variable =] InStr(Start, String1, String2)

60 Introduction to Visual Basic (Part 2)

To see how the InStr function works, it is best to read an example:

Enter a string: Seeing InStr work is eeeasy.Enter the substring to search for: ee"ee" is found in positions 2, 22, 23.

Console.Write("Enter a string: ")Dim str1 As String = Console.ReadLine()

Console.Write("Enter the substring to search for: ")Dim str2 As String = Console.ReadLine()

Dim pos As Integer = InStr(str1, str2)If pos > 0 Then Console.Write("""{0}"" is found in positions {1}", str2, pos) Do pos = InStr(pos + 1, str1, str2) If pos = 0 Then Exit Do End If Console.Write(", {0}", pos) Loop Console.WriteLine(".")Else Console.WriteLine("""{0}"" is not found.", str2)End If

String matching 61

Class WorkEvaluate the following VB.NET expressions. Strings are compared and matched usingbinary comparison.

VB.NET expression Result

"abc".StartsWith("ab")

"35th".EndsWith("TH")

Instr("aeroplane", "a")

Instr(3, "aeroplane", "a")

Instr(8, "aeroplane", "a")

Instr("ab", "able")

Left("flyer", InStr("flyer", "y"))

Mid("Zepellin", InStr("Zepellin", "l"))

62 Introduction to Visual Basic (Part 2)

Exercise 6Write a program that asks the user to enter his/her name and class. Then outputthe sentence “[Name] is a Secondary [x] student.”, where [Name] is the name of thestudent, and [x] is the form of the student.

The class should contain one digit followed by one letter (in either upper case orlower case). If not, output “Is [class] really a class?” instead.

Here are some sample outputs:

Enter the name: Darius LuiEnter the class: 4FDarius Lui is a Secondary 4 student.

Enter the name: Mary KwokEnter the class: 1+Is 1+ really a class?

Write a program to see if a word is a palindrome, i.e. the word reads the sameforward and backwards. The program should produce the following output:

Enter a word: madamThe word is a palindrome.

Enter a word: programThe word is not a palindrome.

Modify the program in the previous question to ignore letter cases, spaces, andpunctuations. Now it should identify palindrome sentences like “Borrow or rob?”.

1.

2.

3.

Exercise 63

Write a program that reads a date in the format D/M/Y (e.g. 21/2/2013, 5/11/2013),and then output a sentence like “Day: 21, Month: 2, Year: 2013”.

The date always comes with two “/” symbols. In this question, you can output thethree substrings without validation. Note: the validation part of this question is agood exercise, but please leave it out before you finish the next chapter.

Enter a date: 21/2/2013Day: 21, Month: 2, Year: 2013

Write a Caesar cipher. The Caesar cipher encodes a message by rotating each letterin the message three places down the alphabet. Your program should be able toencode and decode messages, like the sample output below:

Caesar Cipher=============Encode or Decode? (E/D) EEnter the message: THE FIVE BOXING WIZARDS JUMP QUICKLYResult: QEB CFSB YLUFKD TFWXOAP GRJM NRFZHIV

Caesar Cipher=============Encode or Decode? (E/D) DEnter the message: QEB CFSB YLUFKD TFWXOAP GRJM NRFZHIVResult: THE FIVE BOXING WIZARDS JUMP QUICKLY

Write a program that reverses the order of words in the input. You can assume thattwo words are always separated by a space character. Here is a sample output:

Enter a sentence: string processing is difficultOrder of words reversed: difficult is processing string

(a) Write a Vigenère cipher.

(b) Modify the cipher to make it stronger. (Note: this is an open-ended question.)

4.

5.

6.

7.

64 Introduction to Visual Basic (Part 2)

Glossaryargument

A piece of data that is passed into a procedure.

ASCIIAmerican Standard Code for Information Interchange, a popular character set.

assignment operatorAn operator that assigns a value to a variable.

Big5A character encoding used in Taiwan, Hong Kong, and Macau for Traditional Chinese

characters.

callThe action of using a procedure.

call siteThe position of the code that calls a procedure. Also known as caller.

characterA minimal unit of text. Can be a letter, a digit, a punctuation mark, a white space,

and other things.

character setA set of characters where each character corresponds to a unique number.

CJKChinese, Japanese and Korean languages.

concatenateThe operation to join two strings together.

controlThe position where the next computer instruction is executed.

control charactersA character which is not a written symbol. Examples are CR and LF. Also known as

non-printing character.

Glossary 65

GBKGuojia Biaozhun Kuozhan, a character encoding for simplified Chinese characters.

Despite the name, GBK is not an official standard.

iterationWhen a block of statements is executed multiple times, each repetition of these

statements is called an iteration.

lexicographical orderA mathematical order similar to how dictionary order words.

loopingExecuting a block of statements multiple times.

methodA procedure in the context of objects.

nested loopPutting a loop within another loop.

parameterA special variable defined in a procedure, that can receive data from call sites.

PRNGPseudo-random number generator, that does not use a random source. It simulate

randomness using an algorithm.

procedureA part of a program, that is packaged as a single unit. Also known as subroutine,

function or subprogram.

seedA number used to initialize a random number generator. In VB.NET the current time

is used for seeding.

stringA sequence of characters.

UnicodeThe character set that can be used to represent text in different languages

simultaneously.

66 Introduction to Visual Basic (Part 2)

UTF-16One of the character encoding under Unicode. Used to store strings in .NET platform.

Glossary 67