Download as pdf or txt
Download as pdf or txt
You are on page 1of 25

Unit 3

DECISION MAKING
Decision Statements (Conditional Statement)
Applications need a mechanism to test conditions, and they take a different course of
action depending of the outcome of the test. Visual Basic Provides three statement that
allow you to alter the course of the application based on the outcome of a condition:
 If…Then
 If…Then…Else
 Select Case

IF…THEN STATEMENTS
The If…Then statement tests an expression, which is known as a condition. If the
condition is true, the program executes the statement(s) that follow the Then keyword up
to the End If statement, which terminates the conditional statement. The If…Then
statement can have a single-line or a multiple-line syntax. To execute one statement
conditionally, use the single-line syntax as follows:
If condition then statement
To execute multiple statements conditionally, embed the statements within an If and
End If statement, as follows:
If condition Then
` Statement
` Statement
End If
Conditions are logical expressions that evaluate to a True/False value and they
usually contain comparison operators-equals (=), different (<>), less than (<), greater
than (>), less than or equal to (<=), and so on-and logical operators-And, Or, Xor, and Not.
Here are a few examples of valid conditions:
If (age1 < age2) And (age1 > 12) Then …
If score1 = score2 Then …
The parentheses are not really needed in the first sample expression, but they make
the code a little easier to read and understand.
The expressions can get quite complicated. The following expression evaluates to
True if the date1 variable represents a date earlier than the year 2005 and either one of
the score1 and score2 variables exceeds 90:
If (date1 < #1/1/2005) And (score1 >90 or score2 > 90) Then
` statements
End If

IF…THEN…ELSE STATEMENTS
A variation of the If…Then statement is If…Then…Else statement, which executes the first
block of statements if the condition is True and another block of statements if the
condition is False. The syntax of the If…Then...Else statement is as follows:
If condition Then
statementblock1
Else
statementblock2
End If

BCA405-GUI Programming: Govt. Zirtiri Residential Science College


Page 1
Visual Basic evaluates the condition; if it’s true, VB executes the first block of
statements and then jumps to the statement following the End If statement. If the
condition is False, Visual Basic ignores the first block of statements and executes the block
following the Else keyword.
A third variation of the If…Then…Else statement uses several conditions, with the
ElseIf keyword:
If condition1 Then
statementblock1
ElseIf condition2 Then
statementblock2
ElseIf condition3 Then
statementblock3
Else
statementblock4
End If
You can have any number of ElseIf clauses. The conditions are evaluated from the
top, and if one of them is true, the corresponding block of statements is executed. The Else
clause, which is optional, will be executed if none of the previous expressions is true.
Listing is an example of an If statement with ElseIf clauses.

LISTING: Multiple ElseIF statements


score = InputBox(“Enter score”)
If score < 50 Then
Result = “Failed”
ElseIf score < 75 Then
Result = “Pass”
ElseIf score < 90 Then
Else
Result = “Excellent”
End If
MsgBox Result

SELECT CASE STATEMENTS:


An alternative to the efficient but difficult to-read code of the multiple ElseIf
structure is the Select Case structure, which compares the same expression to different
values. The advantages of the Select Case statement over multiple If…Then…ElseIf
statement is that it makes the code easier to read and maintain.
The Select Case instruction evaluates a single expression at the top of the structure. The
result of the expression is then compared with several values; if it matches one of them,
the corresponding block of statement is executed. Here’s the syntax of the Select Case
statement:
Select Case Expression
Case value1
‘statement block1
Case value2
‘ statement block2
.
.

BCA405-GUI Programming: Govt. Zirtiri Residential Science College


Page 2
.
Case Else
Statement blockN
End Select
A Practical example based on the Select Case statement is shown in below:

Using the select Case statement


Dim Message As String
Select Case Now. Dayof week
Case DayofWeek.Monday
Message=”Have a nice weekend”
Case Else
Message= “Welcome back!”
End Select
MsgBox(message)
In the listing, the expression that’s evaluated at the beginning of the statement is the Now.
DayOfWeek method. This method returns a member of the DayOfWeek enumeration, and
you can use the names of these member in yours code to make it easier to read. The value
of this expression is compared with the values that follow each Case keyword. If they
match, the block of statement following the End Select statement.

LOOP STATEMENTS
Loop statements allow you to execute one or more lines of code repetitively. Many task
consists of operation that must be repeated over and over again, and loop statements are
an important part of any programming language. Visual Basic supports the following loop
statements:
 For..Next
 Do…loop
 While …End while

FOR NEXT LOOP
Unlike the other two loops, the For …Next loop requires that you know the number of
time that the statement in the loop will be executed. The For…Next loop has the following
syntax:
For counter = start to end [Step increment]
‘ statements
Next [counter]
The keywords in the square brackets are optional. The arguments counter, start, end and
increment are all numeric. The loop is executed as many times as required for the counter
variable’s value to reach ( or exeed) the end value, The variable that appears next to the
For In executing a For…Next loop, Visual basic does the following:
1. Set the counter variable equal to the start variable (this is the control variable’s
initial value).
2. Test to see whether counter is greater than end. If so it exists the loop without
executing the statements in the loop’s body, not even once. If increment is
negative, Visual Basic tests to whether the counter value is less than the end value.
If it is it exist the loop.

BCA405-GUI Programming: Govt. Zirtiri Residential Science College


Page 3
3. Executes the statements in the block.
4. Increase the counter variable by the amount specified with the increment
argument following the step keyword. If the increment argument isn’t specified,
counter is increased by 1. If step is a negative value, counter is decreased
accordingly.
5. Continues with step 2.

The For..Next loop scans all the elements of the numeric array data and calculates their
average.
Iterating an array with a For next loop
Dim I As Integer, total as Double
For i=0 To data.Length
Total = total+data(i)
Next i
Debug,Writeline (total/ Data.Length)

FOR EACH….NEXT LOOPS


This is a variation of the classic For loop and it’s used to iterate through the items of a
collection of array. Let’s say you have declared an array of strings like the following :
Dim months() As string=_
{“January”, “February”, “March”, “April”, “May”, “June”}

You can iterate through the month names with a For Each loop like one that follows:
For each month As String in months
Debug.Writeline(month)
Next
The month control variable need not be declared if the infer option is on. The
compiler will figure out the type

DO Loops
The Do Loop statement executes a block of statements for as long as the condition
is True or until a condition becomes True. Visual Basic evaluates an expression, and if it’s
True, the statements in the loop body are executed. The expression is evaluated either at
the beginning of the loop or at the end of the loop. If the expression is False, the program’s
execution continues with the statement following the loop. These two variations use the
keywords While and Until to specify how long the statement will be executed. To execute a
block of statements while a condition is True, use the following syntax:
Do While condition
Statement-block
Loop
To execute a block of statements until the condition becomes True, use the following
syntax:
Do Until condition
Statement-block
Loop
When Visual Basic executes these loops, it first evaluates condition. If condition is
False, a Do…While loop is skipped but a Do…Until loop is executed. When the loop
statement is reached, Visual Basic evaluates the expression again; it repeats the statement

BCA405-GUI Programming: Govt. Zirtiri Residential Science College


Page 4
block of the Do…While loop if the expression is True or repeats the statement of the
Do…Until loop if the expression is False. In short, the Do…While loop is executed when the
condition is True, and the Do…Until loop is executed when the condition is False.
A last variation of the Do statement, the Do…Loop statement, allows you to always
evaluate the condition at the end of the loop, even in a While loop. Here’s the syntax of
both types of loop, with the evaluation of the condition at the end of the loop.
Do
Statement-block
Loop While condition
Do
Statement-block
Loop Until condition
As you can guess, the statement in the loop’s are executed at least once, even in the
case of the While loop, because no testing takes place as the loop is entered.
Example:
1. Do While intX < 3
intX += 1
Loop

2. Do Until intX = 3
intX += 1
Loop
and
3. Do
intX += 1
Loop Until intX = 3
While Loops
The While...End While loop executes a block of statements as long as a condition is
True. The has the following syntax:
While condition
Statement-block
End While
If condition is True , the statements in the block are executed. When the End While
statement is reached, control is return to the While statement, which evaluates condition
again. If condition is still True, the process is repeated. If condition is False, the program
resumes with the statement following End While.
The loop is below prompts the user for numeric data. The user can type a negative
value to indicate he’s done entering values and terminate the loop. As long as the user
enters positive numeric values, the program keeps adding them to the total variable.
LISTING: Reading an unknown number of values
Dim number, total As Double
Number = 0
While number => 0
total = total +number
number = InputBox(“Please another value”)
End while

BCA405-GUI Programming: Govt. Zirtiri Residential Science College


Page 5
Sometimes, the condition that determines when the loops will terminate can’t be
evaluated at the top of the loop’s body. In the case, we declare a Boolean value and set it to
True or False fom within the loop’s body. Here’s the outline of such a loop:
Dim repeatLoop As Boolean
repeatLoop = True
While repeatLoop
Statements
If condition Then
repeatLoop = True
Else
repeatLoop = False
End If
End While
You may also see an odd loop statement like the following ones:
While True
Statements
End While
It’s also common to express the True condition in one of the following two forms:
While 1 = 1
or
While True

Nested Control Structure


You can place, or nest, control structures inside other control structures (such as an
If…Then block within a For…Next loop) or nest multiple If…Then blocks within one
another. Control structures in Visual Basic can be nested in as many levels as you want.
When you nest control structures, you must make sure that they open and close
within the same structure. In other words, you can’t start a For…Next loop in an If
statements and close the loop after the corresponding End If. The following code segments
demonstrate how to nest several flow-control statements:
For a = 1 to 100
Statements
If a = 99 Then
Statements
End If
While b < a
Statements
If total <=0 Then
Statements
If total <= 0 Then
Statements
End While
For c = 1 to a
Statements
Next c
Next a

BCA405-GUI Programming: Govt. Zirtiri Residential Science College


Page 6
The exit and Continue statements
The exit statement allows you to prematurely exit from a block of statements in a control
structure, from a loop, or event from a procedure. Suppose that you have a For Next Loop
that calculates the square root of a series of numbers. Because the squareroot of negative
numbers cant’ be calculated (the Math.Sqrt method will generate a runtime error), you
might want to halt the operation if the array contains an invalid value. To Exit the loop
prematurely, use the Exit For statements as follows:
For I = 0 To UBound(nArray)
If narray(i) < 0 Then
msgBox(Can’t complete calculations” & vbCrLf &
“Item “ & i.ToString & “ is negative! “
Exit For
End If
Next

Sometimes you may need to continue with the following Iteration instead of exiting the
loop(in other words, skip the body of the loop and continue with the following value). In
these cases, you can use the Continue statement (Continue For for For….next loops,
Continue while for while loops, and so on.

VB.Net- STRING
A string is nothing but a collection of characters. In very simple terms, String may be
defined as the array of characters. When it comes to an understanding variable, Integer is
the very first thing we learn about. An integer is the data type that stores the integer value,
in the same way, char is the data type that stores single character and similarly, a string is
the data type that allows the storage of the set of characters in a single variable.

Declaration and Initialization of VB.Net


To bring string in actual use, we will first need to declare the string. Once it is declared we
can use it numerous of times as required. Below is the syntax to declare a string in VB .net.
Dim Str as String
Now, once the name of the variable is declared we have to put some value in it so that it
could be used in the program. We can assign the value to the variable either by taking
input from a user in run time or we can assign the value manually
Str=“Latin”
Here the value has been assigned to the variable str. While assigning the string value to the
variable we have to make sure that the values have to be written in double quotes. Once
the values are assigned, we can use it anywhere in the program.

Working with VB.Net String Functions


Some of the common function of strings are given below:
Sl. String Description Example
No Function
Asc This string function in VB.Net is used in Input
order to get the integer value of the first Dim Str as String
letter of the string. Its integer value is Str=“Latin”
actually the integer value of that Asc(Str)
character. Output: 76

BCA405-GUI Programming: Govt. Zirtiri Residential Science College


Page 7
Format This function is used to arrange the Input
string in a particular format Dim ChangedTime As
Date = #03/23/2019
4:10:43 PM#
Dim ChangedTime as the
string
ChangedTime =
Format(TestDateTime,
"h:m:s")

Output: 04:10:43 PM
Join This VB.Net String function is used to Input
join two substrings.
Dim ItemList() As String
= {“Apple”, “Banana”,
“Guava”}
Dim JoinItemList as
string = Join(ItemList, ",
")

Output: Apple, Banana,


Guava
LCase This function will convert all the Input
characters of the string into a lowercase Dim Uppercase as String
character. = “HELLO WORLD”
Dim Lowercase as String
= LCase(Uppercase)

Output: hello world


Left This function will return the specific Input
characters from left as requested by Dim CheckStr as string =
mentioning any number “Hey Jim”
Dim ResultStr as string =
Left(CheckStr, 3)

Output: Hey
Len This String function in VB.Net will Input
return the numbers of characters in a Dim StrWords as String =
string. “You are a hero!”
Dim WordCount as
Integer = Len(StrWords)
Output: 15
Right This function will return the specified Input
number of characters from a string from Dim CheckStr as string =
the right side. “Hey Jim”
Dim ResultStr as string =
Right(CheckStr, 3)
Output: Jim

BCA405-GUI Programming: Govt. Zirtiri Residential Science College


Page 8
Split This String function in VB.Net is used to Input
split the string. Dim CheckStr as String =
“How are you?”
Dim OutputStr as String
= Split(CheckStr)

Output: {“How”, “are”,


“you?”}, it is the array of
string actually.
StrReverse This function will be used to reverse the Input
value of the string.
Dim CorrectStr as String
= “Apple”
Dim ReverseString as
String =
StrReverse(CorrectStr)

Output: elppA

UCase This VB.Net String function will turn all Input


the lowercase characters of the string
into uppercase. Dim LowercaseStr as
String = “Hello Jim”
Dim UppercaseStr as
String =
UCase(LowercaseStr)

Output

HELLO JIM

VB.Net- ARRAY
An array stores a fixed-size sequential collection of elements of the same type. An
array is used to store a collection of data, but it is often more useful to think of an array as
a collection of variables of the same type.
All arrays consist of contiguous memory locations. The lowest address corresponds to the
first element and the highest address to the last element.

Types of Array:
1. Fixed size Array:
In this type of array, arraysize is fixed at the beginning. Changin the size is not allowed
later on.
Creating Arrays in VB.Net
To declare an array in VB.Net, you use the Dim statement. For example,
BCA405-GUI Programming: Govt. Zirtiri Residential Science College
Page 9
Dim intData(30) ' an array of 31 elements
Dim strData(20) As String ' an array of 21 strings
Dim twoDarray(10, 20) As Integer 'a two dimensional array of integers
Dim ranges(10, 100) 'a two dimensional array
You can also initialize the array elements while declaring the array. For example,
Dim intData() As Integer = {12, 16, 20, 24, 28, 32}
Dim names() As String = {"Karthik", "Sandhya", "Shivangi", "Ashwitha", "Somnath"}
Dim miscData() As Object = {"Hello World", 12d, 16ui, "A"c}
The elements in an array can be stored and accessed by using the index of the array. The
following program demonstrates this:
Module arrayApl
Sub Main()
Dim n(10) As Integer ' n is an array of 11 integers
Dim i, j As Integer
' initialize elements of array n
For i = 0 To 10
n(i) = i + 100 ' set element at location i to i + 100
Next i
' output each array element's value
For j = 0 To 10
Console.WriteLine("Element({0}) = {1}", j, n(j))
Next j
Console.ReadKey()
End Sub
End Module
When the above code is compiled and executed, it produces the following result:
Element(0) = 100
Element(1) = 101
Element(2) = 102
Element(3) = 103
Element(4) = 104
Element(5) = 105
Element(6) = 106
Element(7) = 107
Element(8) = 108
Element(9) = 109
Element(10) = 110

2. Dynamic Arrays
Dynamic arrays are arrays that can be dimensioned and re-dimensioned as per the need of
the program. You can declare a dynamic array using the ReDim statement.
Syntax for ReDim statement:
ReDim [Preserve] arrayname(subscripts)
Where, The Preserve keyword helps to preserve the data in an existing array, when you
resize it, arrayname is the name of the array to re-dimension, subscripts specifies the
new dimension.
Module arrayApl
Sub Main()

BCA405-GUI Programming: Govt. Zirtiri Residential Science College


Page 10
Dim marks() As Integer
ReDim marks(2)
marks(0) = 85
marks(1) = 75
marks(2) = 90
ReDim Preserve marks(10)
marks(3) = 80
marks(4) = 76
marks(5) = 92
marks(6) = 99
marks(7) = 79
marks(8) = 75
For i = 0 To 10
Console.WriteLine(i & vbTab & marks(i))
Next i
Console.ReadKey()
End Sub
End Module
When the above code is compiled and executed, it produces the following result:
0 85
1 75
2 90
3 80
4 76
5 92
6 99
7 79
8 75
90
10 0

3. Multi-Dimensional Arrays
VB.Net allows multidimensional arrays. Multidimensional arrays are also called
rectangular
arrays. You can declare a 2-dimensional array of strings as:
Dim twoDStringArray(10, 20) As String
or, a 3-dimensional array of Integer variables:
Dim threeDIntArray(10, 10, 10) As Integer
The following program demonstrates creating and using a 2-dimensional array:
Module arrayApl
Sub Main()
' an array with 5 rows and 2 columns
Dim a(,) As Integer = {{0, 0}, {1, 2}, {2, 4}, {3, 6}, {4, 8}}
Dim i, j As Integer
' output each array element's value '
For i = 0 To 4
For j = 0 To 1
Console.WriteLine("a[{0},{1}] = {2}", i, j, a(i, j))

BCA405-GUI Programming: Govt. Zirtiri Residential Science College


Page 11
Next j
Next i
Console.ReadKey()
End Sub
End Module
When the above code is compiled and executed, it produces the following result:
a[0,0]: 0
a[0,1]: 0
a[1,0]: 1
a[1,1]: 2
a[2,0]: 2
a[2,1]: 4
a[3,0]: 3
a[3,1]: 6
a[4,0]: 4
a[4,1]: 8

4. Jagged Array
A Jagged array is an array of arrays. The following code shows declaring a jagged array
named scores of Integers:
Dim scores As Integer()() = New Integer(5)(){}
The following example illustrates using a jagged array:
Module arrayApl
Sub Main()
'a jagged array of 5 array of integers
Dim a As Integer()() = New Integer(4)() {}
a(0) = New Integer() {0, 0}
a(1) = New Integer() {1, 2}
a(2) = New Integer() {2, 4}
a(3) = New Integer() {3, 6}
a(4) = New Integer() {4, 8}
Dim i, j As Integer
' output each array element's value
For i = 0 To 4
For j = 0 To 1
Console.WriteLine("a[{0},{1}] = {2}", i, j, a(i)(j))
Next j
Next i
Console.ReadKey()
End Sub
End Module
When the above code is compiled and executed, it produces the following result:
a[0][0]: 0
a[0][1]: 0
a[1][0]: 1
a[1][1]: 2
a[2][0]: 2
a[2][1]: 4

BCA405-GUI Programming: Govt. Zirtiri Residential Science College


Page 12
a[3][0]: 3
a[3][1]: 6
a[4][0]: 4
a[4][1]: 8

VB.NET COLLECTION
Collection classes are specialized classes for data storage and retrieval. These classes
provide support for stacks, queues, lists, and hash tables. Most collection classes
implement the same interfaces.

Collection classes serve various purposes, such as allocating memory dynamically to


elements and accessing a list of items on the basis of an index, etc. These classes create
collections of objects of the Object class, which is the base class for all data types in VB.Net.

Various Collection Classes and Their Usage

The following are the various commonly used classes of the System.Collection
namespace.
Class Description and Usage
ArrayList It represents ordered collection of an object that can be indexed individually.
It is basically an alternative to an array. However, unlike array, you can add
and remove items from a list at a specified position using an index and the
array resizes itself automatically. It also allows dynamic memory allocation,
add, search and sort items in the list.
Hashtable It uses a key to access the elements in the collection.
A hash table is used when you need to access elements by using key, and you
can identify a useful key value. Each item in the hash table has
a key/value pair. The key is used to access the items in the collection.
SortedList It uses a key as well as an index to access the items in a list.
A sorted list is a combination of an array and a hash table. It contains a list of
items that can be accessed using a key or an index. If you access items using
an index, it is an ArrayList, and if you access items using a key, it is a
Hashtable. The collection of items is always sorted by the key value.
Stack It represents a last-in, first out collection of object.
It is used when you need a last-in, first-out access of items. When you add an
item in the list, it is called pushing the item, and when you remove it, it is
called popping the item.
Queue It represents a first-in, first out collection of object.
It is used when you need a first-in, first-out access of items. When you add an
item in the list, it is called enqueue, and when you remove an item, it is
called deque.
BitArray It represents an array of the binary representation using the values 1 and 0.
It is used when you need to store the bits but do not know the number of bits
in advance. You can access items from the BitArray collection by using
an integer index, which starts from zero.

PROCEDURES

BCA405-GUI Programming: Govt. Zirtiri Residential Science College


Page 13
Procedures are the basic building blocks of every application. A procedure language is one
that requires you to specify how to carry out specific tasks by writing procedures. A
procedure is a series of statements that tell the computer how to carry out a specific task.
The task could be the calculation of a loan’s monthly payment or the retrieval of weather
data from a remote server. In any case, the body of statements from a unit of code that can
be invoked by name, not unlike scripts or macro commands but much more flexible and
certainly more complex.

FUNCTIONS
A function is similar to a subroutine or procedure, but a function returns a result. Because
they return values, functions – like variables – have types. The value you pass back to the
calling program from a function is called the return value, and its type determines the type
of the function. Functions accept arguments, just like subroutines. The statements that
make up a function are placed in a set of Function…End function statements, as shown
here:
Function NextDay( ) As Date
Dim thenextDay As date
theNextDay = Now.AddDay(1)
Return theNextDay
End Function
Function are called like subroutines – by name – but their return value is usually assigned
to a variable. To call the NextDay() function, use a statement like this
Dim tomorrow As Date = NextDay()
The Function keyword is followed by the function name and the As keyword that specifies
its type, similar to a variable declaration .The result of a function is returned to the calling
program with the return statement, which is followed by the value you want to return
from your function. This value, which is usually a variable, must be of the same type as the
function. You can also a value to the calling routine by assigning the result to the name of
the function. The following is an alternate method of coding the NextDay() function:
Function Nextday() As Date
NextDay = Now.AddDays(1)
End Function
Similar to the naming of variables, a custom function has a name that must be unique in its
scope( which is also true for subroutines, of course). If you declare a function in a form, the
function name must be unique in form. If you declare a function as Public or Friend, its
name must be unique in the project.
You can call functions in the same way that you call subroutines, but the result won’t be
stored anywhere. For example, the function Convert() might convert the text in a text box
to uppercase and return the number of characters it converted. Normally, you’d call this
function as follows:
nChars = convert()
If you don’t care about the return value – you only want to update the text on a Textbox
control – You would call the convert() function with the following statement:
Convert()
Most of the procedures in an application are functions, not subroutines. The reason is that
a function can return (at the very least) a True/False value that indicates whether it
completed successfully or not.

BCA405-GUI Programming: Govt. Zirtiri Residential Science College


Page 14
Defining a Function
The Function statement is used to declare the name, parameter and the body of a function.
The syntax for the Function statement is −

[Modifiers] Function FunctionName [(ParameterList)] As ReturnType


[Statements]
End Function
Where,
Modifiers − specify the access level of the function; possible values are: Public, Private,
Protected, Friend, Protected Friend and information regarding overloading, overriding,
sharing, and shadowing.
FunctionName − indicates the name of the function
ParameterList − specifies the list of the parameters
ReturnType − specifies the data type of the variable the function returns

Example
Following code snippet shows a function FindMax that takes two integer values and
returns the larger of the two.

Function FindMax(ByVal num1 As Integer, ByVal num2 As Integer) As Integer


' local variable declaration */
Dim result As Integer

If (num1 > num2) Then


result = num1
Else
result = num2
End If
FindMax = result
End Function

Function Returning a Value


In VB.Net, a function can return a value to the calling code in two ways −
 By using the return statement
 By assigning the value to the function name

The following example demonstrates using the FindMax function −

Module myfunctions
Function FindMax(ByVal num1 As Integer, ByVal num2 As Integer) As Integer
' local variable declaration */
Dim result As Integer

If (num1 > num2) Then


result = num1
Else
result = num2
End If

BCA405-GUI Programming: Govt. Zirtiri Residential Science College


Page 15
FindMax = result
End Function
Sub Main()
Dim a As Integer = 100
Dim b As Integer = 200
Dim res As Integer

res = FindMax(a, b)
Console.WriteLine("Max value is : {0}", res)
Console.ReadLine()
End Sub
End Module
When the above code is compiled and executed, it produces the following result −
Max value is : 200

Recursive Function
A function can call itself. This is known as recursion. Following is an example that
calculates factorial for a given number using a recursive function −
Module myfunctions
Function factorial(ByVal num As Integer) As Integer
' local variable declaration */
Dim result As Integer
If (num = 1) Then
Return 1
Else
result = factorial(num - 1) * num
Return result
End If
End Function
Sub Main()
'calling the factorial method
Console.WriteLine("Factorial of 6 is : {0}", factorial(6))
Console.WriteLine("Factorial of 7 is : {0}", factorial(7))
Console.WriteLine("Factorial of 8 is : {0}", factorial(8))
Console.ReadLine()
End Sub
End Module
When the above code is compiled and executed, it produces the following result −
Factorial of 6 is: 720
Factorial of 7 is: 5040
Factorial of 8 is: 40320

Param Arrays
At times, while declaring a function or sub procedure, you are not sure of the number of
arguments passed as a parameter. VB.Net param arrays (or parameter arrays) come into
help at these times.
The following example demonstrates this −
Module myparamfunc

BCA405-GUI Programming: Govt. Zirtiri Residential Science College


Page 16
Function AddElements(ParamArray arr As Integer()) As Integer
Dim sum As Integer = 0
Dim i As Integer = 0
For Each i In arr
sum += i
Next i
Return sum
End Function
Sub Main()
Dim sum As Integer
sum = AddElements(512, 720, 250, 567, 889)
Console.WriteLine("The sum is: {0}", sum)
Console.ReadLine()
End Sub
End Module
When the above code is compiled and executed, it produces the following result −
The sum is: 2938

Passing Arrays as Function Arguments


You can pass an array as a function argument in VB.Net. The following example
demonstrates this −
Module arrayParameter
Function getAverage(ByVal arr As Integer(), ByVal size As Integer) As Double
'local variables
Dim i As Integer
Dim avg As Double
Dim sum As Integer = 0
For i = 0 To size - 1
sum += arr(i)
Next i
avg = sum / size
Return avg
End Function
Sub Main()
' an int array with 5 elements '
Dim balance As Integer() = {1000, 2, 3, 17, 50}
Dim avg As Double
'pass pointer to the array as an argument
avg = getAverage(balance, 5)
' output the returned value '
Console.WriteLine("Average value is: {0} ", avg)
Console.ReadLine()
End Sub
End Module
When the above code is compiled and executed, it produces the following result −
Average value is: 214.4

Subroutines

BCA405-GUI Programming: Govt. Zirtiri Residential Science College


Page 17
A Subroutine is a block of statements that carries out a well-defined task. Subroutines
perform actions and they don’t return any result. Functions, on the other hand, perform
some calculations and return a value. This is the only difference between subroutines and
functions. Both subroutines and functions can accept arguments. The block of statements
is placed within a set of Sub…End Sub statements and can be invoked by name. The
following subroutine displays the current date in a message box:
Sub ShowDate( )
MsgBox( “Today’s date is “ & Now( ). ToShortDateString)
End Sub
To use it in your code, you can just enter the name of the function in a line of its own:
ShowDate
The statements in a subroutine are executed, and when the End Sub statement is reach,
control returns to the calling code. It’s possible to exit a subroutine prematurely by using
the Exit Sub statement.
All variables declared within a subroutine are local to that subroutine. When the
subroutine exists, all variables declared in it cease to exist.
Most procedures also accept and act upon arguments. The ShowDate() subroutine
displays the current date in a message box. If you want to display any other date, you have
to implement it differently and add an argument to the subroutine:
Sub ShowDate( Byval aDate As Date)
msgBo(aDate.ToShortdateString)
End Sub
aDate is a variable that holds the date to be displayed; its type is date. The ByVal keyword
means that the subroutine sees a copy of the variable, not the variable itself. What this
means practically is that the subroutine can’t change the value of the variable passed by
the calling code.

Defining Sub Procedures


The Sub statement is used to declare the name, parameter and the body of a sub
procedure. The syntax for the Sub statement is −
[Modifiers] Sub SubName [(ParameterList)]
[Statements]
End Sub
Where,
Modifiers − specify the access level of the procedure; possible values are - Public, Private,
Protected, Friend, Protected Friend and information regarding overloading, overriding,
sharing, and shadowing.
SubName − indicates the name of the Sub
ParameterList − specifies the list of the parameters

Example
The following example demonstrates a Sub procedure CalculatePay that takes two
parameters hours and wages and displays the total pay of an employee −
Module mysub
Sub CalculatePay(ByRef hours As Double, ByRef wage As Decimal)
'local variable declaration
Dim pay As Double
pay = hours * wage

BCA405-GUI Programming: Govt. Zirtiri Residential Science College


Page 18
Console.WriteLine("Total Pay: {0:C}", pay)
End Sub
Sub Main()
'calling the CalculatePay Sub Procedure
CalculatePay(25, 10)
CalculatePay(40, 20)
CalculatePay(30, 27.5)
Console.ReadLine()
End Sub
End Module
When the above code is compiled and executed, it produces the following result −
Total Pay: $250.00
Total Pay: $800.00
Total Pay: $825.00

Passing Parameters by Value


This is the default mechanism for passing parameters to a method. In this mechanism,
when a method is called, a new storage location is created for each value parameter. The
values of the actual parameters are copied into them. So, the changes made to the
parameter inside the method have no effect on the argument.

In VB.Net, you declare the reference parameters using the ByVal keyword. The following
example demonstrates the concept −
Module paramByval
Sub swap(ByVal x As Integer, ByVal y As Integer)
Dim temp As Integer
temp = x ' save the value of x
x = y ' put y into x
y = temp 'put temp into y
End Sub
Sub Main()
' local variable definition
Dim a As Integer = 100
Dim b As Integer = 200
Console.WriteLine("Before swap, value of a : {0}", a)
Console.WriteLine("Before swap, value of b : {0}", b)
' calling a function to swap the values '
swap(a, b)
Console.WriteLine("After swap, value of a : {0}", a)
Console.WriteLine("After swap, value of b : {0}", b)
Console.ReadLine()
End Sub
End Module
When the above code is compiled and executed, it produces the following result −
Before swap, value of a :100
Before swap, value of b :200
After swap, value of a :100
After swap, value of b :200

BCA405-GUI Programming: Govt. Zirtiri Residential Science College


Page 19
It shows that there is no change in the values though they had been changed inside the
function.

Passing Parameters by Reference


A reference parameter is a reference to a memory location of a variable. When you pass
parameters by reference, unlike value parameters, a new storage location is not created
for these parameters. The reference parameters represent the same memory location as
the actual parameters that are supplied to the method.

In VB.Net, you declare the reference parameters using the ByRef keyword. The following
example demonstrates this −
Module paramByref
Sub swap(ByRef x As Integer, ByRef y As Integer)
Dim temp As Integer
temp = x ' save the value of x
x = y ' put y into x
y = temp 'put temp into y
End Sub
Sub Main()
' local variable definition
Dim a As Integer = 100
Dim b As Integer = 200
Console.WriteLine("Before swap, value of a : {0}", a)
Console.WriteLine("Before swap, value of b : {0}", b)
' calling a function to swap the values '
swap(a, b)
Console.WriteLine("After swap, value of a : {0}", a)
Console.WriteLine("After swap, value of b : {0}", b)
Console.ReadLine()
End Sub
End Module
When the above code is compiled and executed, it produces the following result −
Before swap, value of a : 100
Before swap, value of b : 200
After swap, value of a : 200
After swap, value of b : 100

MAJOR ERROR TYPES


Error types can be broken down into three major categories: syntax, execution, and logic.
This section shows you the important differences among these three types of errors and
how to correct them.

SYNTAX ERRORS
Syntax errors, the easiest type of errors to spot and fix, occur when the code you have
written cannot be understood by the compiler because instructions are incomplete,
supplied in unexpected order, or cannot be processed at all. An example of this would be
declaring a variable of one name and misspelling this name in your code when you set or
query the variable. The development environment in Visual Studio 2010 has a very

BCA405-GUI Programming: Govt. Zirtiri Residential Science College


Page 20
sophisticated syntax-checking mechanism, making it hard, but not impossible, to have
syntax errors in your code. It provides instant syntax checking of variables and objects and
lets you know immediately when you have a syntax error.
Suppose you try to declare a variable as Private in a procedure. Visual Studio 2010
underlines the declaration with a blue wavy line indicating that the declaration is in error.
If the integrated development environment (IDE) can automatically correct the syntax
error, you’ll see a little orange rectangular box at the end of the blue wavy line, as shown
in Figure 10-1 (minus the color), indicating that AutoCorrect options are available for this
syntax error. AutoCorrect is a feature of Visual Studio 2010 that provides error-correction
options that the IDE will suggest to correct the error.

When you hover your mouse over the code in error, you’ll receive a ToolTip, telling you
what the error is, and a small gray box with a red circle and a white exclamation point.

EXECUTION ERRORS
Execution errors (or runtime errors) occur while your program is executing. These errors
are often caused because something outside of the application, such as a user, database, or
hard disk, does not behave as expected. In .NET, you will read about error handling or
exception handling. If you talk to a programmer who has not worked in prior languages,
they will use the term exception versus error.
Developers need to anticipate the possibility of execution errors and build appropriate
error-handling logic. Implementing the appropriate error handling does not prevent
execution errors, but it does enable you to handle them by either gracefully shutting down
your application or bypassing the code that failed and giving the user the opportunity to
perform that action again.
One way to prevent execution errors is to anticipate the error before it occurs, and then
use error handling to trap and handle it. You must also thoroughly test your code before
deploying it. Most execution errors can be found while you are testing your code in the
development environment. This enables you to handle the errors and debug your code at
the same time.

LOGIC ERRORS
Logic errors (or semantic errors) lead to unexpected or unwanted results because you did
not fully understand what the code you were writing would do. Probably the most
common logic error is an infinite loop:
Private Sub PerformLoopExample()

BCA405-GUI Programming: Govt. Zirtiri Residential Science College


Page 21
Dim intIndex As Integer
Do While intIndex < 10
‘perform some logic
Loop
End Sub
If the code inside the loop does not set intIndex to 10 or above, this loop just keeps going
forever.
Logic errors can be the most difficult to find and troubleshoot, because it is very difficult to
be sure that your program is completely free of them.
Another type of logic error occurs when a comparison fails to give the result you expect.
Say you made a comparison between a string variable, set by your code from a database
field or from the text in a file, and the text entered by the user. You do not want the
comparison to be case sensitive, so you might write code like this:
If strFileName = txtInput.Text Then
..perform some logic
End If
However, if strFileName is set to Index.HTML and txtInput.Text is set to index.html, the
comparison fails. One way to prevent this logic error is to convert both fields being
compared to either uppercase or lowercase. This way, the results of the comparison would
be True if the user entered the same text as that contained in the variable, even if the case
were different. The next code fragment shows how you can accomplish this:
If strFileName.ToUpper = txtInput.Text.ToUpper Then
..perform some logic
End If
The ToUpper method of the String class converts the characters in the string to all
uppercase and returns the converted results. Because the Text property of a text box is
also a string, you can use the same method to convert the text to all uppercase. This would
make the comparison in the previous example equal.

EXCEPTION: EXCEPTION HANDLING AND USER DEFINED EXCEPTION.


An exception is a problem that arises during the execution of a program. An exception is a
response to an exceptional circumstance that arises while a program is running, such as
an attempt to divide by zero.
Exceptions provide a way to transfer control from one part of a program to another.
VB.Net exception handling is built upon four keywords: Try, Catch, Finally and Throw.
 Try: A Try block identifies a block of code for which particular exceptions will be
activated. It's followed by one or more Catch blocks.
 Catch: A program catches an exception with an exception handler at the place in a
program where you want to handle the problem. The Catch keyword indicates the
catching of an exception.
 Finally: The Finally block is used to execute a given set of statements, whether an
exception is thrown or not thrown. For example, if you open a file, it must be
closed whether an exception is raised or not.
 Throw: A program throws an exception when a problem shows up. This is done
using a Throw keyword.
Syntax
Assuming a block will raise an exception, a method catches an exception using a
combination of the Try and Catch keywords. A Try/Catch block is placed around the code

BCA405-GUI Programming: Govt. Zirtiri Residential Science College


Page 22
that might generate an exception. Code within a Try/Catch block is referred to as
protected code, and the syntax for using Try/Catch looks like the following:
Try
[ tryStatements ]
[ Catch [ exception [ As type ] ]
[ catchStatements ]
[ Finally
[ finallyStatements ] ]
End Try
You can list down multiple catch statements to catch different type of exceptions in case
your try block raises more than one exception in different situations.

Exception Classes in .Net Framework

Exception Class Description


System.IO.IOException Handles I/O errors.
System.IndexOutOfRangeException Handles errors generated when a method refers to
an array index out of range.
System.ArrayTypeMismatchException Handles errors generated when type is
mismatched with the array type.
System.NullReferenceException Handles errors generated from deferencing a null
object.
System.DivideByZeroException Handles errors generated from dividing a dividend
with zero.
System.InvalidCastException Handles errors generated during typecasting.
System.OutOfMemoryException Handles errors generated from insufficient free
memory.
System.StackOverflowException Handles errors generated from stack overflow.

HANDLING EXCEPTIONS
VB.Net provides a structured solution to the exception handling problems in the form of
try and catch blocks. Using these blocks the core program statements are separated from
the error-handling statements.
These error handling blocks are implemented using the Try, Catch and
Finally keywords. Following is an example of throwing an exception when dividing by
zero condition occurs:
Module exceptionProg
Sub division(ByVal num1 As Integer, ByVal num2 As Integer)
Dim result As Integer

BCA405-GUI Programming: Govt. Zirtiri Residential Science College


Page 23
Try
result = num1 \ num2
Catch e As DivideByZeroException
Console.WriteLine("Exception caught: {0}", e)
Finally
Console.WriteLine("Result: {0}", result)
End Try
End Sub
Sub Main()
division(25, 0)
Console.ReadKey()
End Sub
End Module
When the above code is compiled and executed, it produces the following result:
Exception caught: System.DivideByZeroException: Attempted to divide by zero.
at ...
Result: 0

Creating User-Defined Exceptions


You can also define your own exception. User-defined exception classes are derived from
the ApplicationException class. The following example demonstrates this:
Module exceptionProg
Public Class TempIsZeroException : Inherits ApplicationException
Public Sub New(ByVal message As String)
MyBase.New(message)
End Sub
End Class
Public Class Temperature
Dim temperature As Integer = 0
Sub showTemp()
If (temperature = 0) Then
Throw (New TempIsZeroException("Zero Temperature found"))
Else
Console.WriteLine("Temperature: {0}", temperature)
End If
End Sub
End Class
Sub Main()
Dim temp As Temperature = New Temperature()
Try
temp.showTemp()
Catch e As TempIsZeroException
Console.WriteLine("TempIsZeroException: {0}", e.Message)
End Try
Console.ReadKey()
End Sub
End Module

BCA405-GUI Programming: Govt. Zirtiri Residential Science College


Page 24
When the above code is compiled and executed, it produces the following result:
TempIsZeroException: Zero Temperature found

Throwing Objects
You can throw an object if it is either directly or indirectly derived from the
System.Exception class.
You can use a throw statement in the catch block to throw the present object as:
Throw [ expression ]
The following program demonstrates this:
Module exceptionProg
Sub Main()
Try
Throw New ApplicationException("A custom exception _
is being thrown here...")
Catch e As Exception
Console.WriteLine(e.Message)
Finally
Console.WriteLine("Now inside the Finally Block")
End Try
Console.ReadKey()
End Sub
End Module
When the above code is compiled and executed, it produces the following result:
A custom exception is being thrown here...
Now inside the Finally Block

BCA405-GUI Programming: Govt. Zirtiri Residential Science College


Page 25

You might also like