Unit 3
Unit 3
Unit – 3
Decisions and Conditions : If Statement, If-then-else, Select case:-
Decisions and Conditions:-
• Loop statements allow you to execute one or more lines of code
repetitively.
• Visual Basic supports the following loop statements:
• A loop can be executed either while the condition is True or until the
condition becomes True.
• These two variations use the keywords While and Until to specify how
long the statements are executed.
• To execute a block of statements while a condition is true, use the
following syntax :
Do While condition
• statement block
• Loop
• Loop
• Or
• Do
• statements
• 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 to reach the end value.
• While ………Wend : The while……wend loop executes a block of
statements while a condition is True. The while…..wend loop has the
following syntax :
While condition
• statement – block
• Wend
• If condition is true, all statements are executed and when the Wend
statement is reached, control is returned 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 the Wend statement.
• An application needs a built-in capability to test conditions and take a
different course of action depending on the outcome of the test. Visual
Basic provides three control flow, or decision, structures :
• If……Then : The If….Then structure tests the condition specified, and if
it’s True, executes the statement(s) that follow.
• The If structure can have a single-line or a multiple-line syntax.
• statement block-1
• Else
• statement block-2
• End If
• Select Case : The Select Case structure compares one expression to
different values.
• The advantage of the Select Case statement over multiple
If…..Then…..Else statements is that it makes the code easier to read and
maintain.
• The Select Case structure tests a single expression, which is evaluated
once at the top of the structure.
• The result of the test is then compared with several values, and if it
matches one of them, the corresponding block of statements is executed.
The syntax is :
• Select Case expression
• Case value1
• .
• Statement block-1
• Case value2
• Statement block-2
• .
• Case Else
• Statement block
• End Select
Looping Statements:-
The Do Loop
The Do Loop statements have four different forms, as shown below:
a)
Do While condition
Block of one or more VB statements
Loop
b)
Do
Block of one or more VB statements
Loop While condition
c)
Do Until condition
Block of one or more VB statements
Loop
d)
Do
Block of one or more VB statements
Loop Until condition
Example
Do while
counter <=1000
num.Text=counter
counter =counter+1
Loop
* The above example will keep on adding until counter > 1000
Example
Dim sum, n as Integer
Private Sub Form_Activate()
List1.AddItem "n" & vbTab & "sum"
Do
n=n+1
sum=sum+n-resize
List1.AddItem n & vbTab & sum
If n=100 Then
Exit Do
End If
Loop
End Sub
Explanation
In the above example, we compute the summation of 1+2+3+4+……
+100. In the design stage, you need to insert a ListBox into the form for
displaying the output, named List1. The program uses the AddItem method to
populate the ListBox. The statement List1.AddItem "n" & vbTab & "sum" will
display the headings in the ListBox, where it uses the vbTab function to create a
space between the headings n and sum.
The For....Next Loop
The For....Next Loop event procedure is written as follows:
Next
Example
Example
Private Sub Command1_Click()
Example
Private Sub Form_Activate( )
For n=1 to 10
If n>6 then
Exit For
Else
Print n
Enf If
Next
End Sub
Sometimes the user might want to get out from the loop before the whole
repetitive process is executed, the command to use is Exit For. To exit a
For….Next Loop, you can place the Exit For statement within the loop; and it is
normally used together with the If…..Then… statement. Its usages is shown in
Example.
Example
Private Sub Form_Activate ( )
For firstCounter= 1to 5
Print "Hello"
For secondCounter=1 to 4
Print "Welcome to the VB tutorial"
Next secondCounter
Next firstCounter
Print"Thank you"
End Sub
The above loop means that while the condition is not met, the loop will
go on. The loop will end when the condition is met. Let’s examine the program
listed in example.
Example
Dim sum, n As Integer
Private Sub Form_Activate()
List1.AddItem "n" & vbTab & "sum"
While n <> 100
n=n+1
Sum = Sum + n
List1.AddItem n & vbTab & Sum
Wend
End Sub
Exit Statement
Syntax
VB
Exit { Do | For | Function | Property | Select | Sub | Try | While }
Statements
Exit Do
Immediately exits the Do loop in which it appears. Execution continues with the
statement following the Loop statement. Exit Do can be used only inside a Do
loop. When used within nested Do loops, Exit Do exits the innermost loop and
transfers control to the next higher level of nesting.
Exit For
Immediately exits the For loop in which it appears. Execution continues with
the statement following the Next statement. Exit For can be used only inside a
For...Next or For Each...Next loop. When used within nested For loops, Exit For
exits the innermost loop and transfers control to the next higher level of nesting.
Exit Function
Immediately exits the Function procedure in which it appears. Execution
continues with the statement following the statement that called the Function
procedure. Exit Function can be used only inside a Function procedure.
To specify a return value, you can assign the value to the function name on a
line before the Exit Function statement. To assign the return value and exit the
function in one statement, you can instead use the Return Statement.
Exit Property
Immediately exits the Property procedure in which it appears. Execution
continues with the statement that called the Property procedure, that is, with the
statement requesting or setting the property's value. Exit Property can be used
only inside a property's Get or Set procedure.
To specify a return value in a Get procedure, you can assign the value to the
function name on a line before the Exit Property statement. To assign the return
value and exit the Get procedure in one statement, you can instead use the
Return statement.
Exit Select
Immediately exits the Select Case block in which it appears. Execution
continues with the statement following the End Select statement. Exit Select can
be used only inside a Select Case statement.
Exit Sub
Immediately exits the Sub procedure in which it appears. Execution continues
with the statement following the statement that called the Sub procedure. Exit
Sub can be used only inside a Sub procedure.
Exit Try
Immediately exits the Try or Catch block in which it appears. Execution
continues with the Finally block if there is one, or with the statement following
the End Try statement otherwise. Exit Try can be used only inside a Try or
Catch block, and not inside a Finally block.
Exit While
Immediately exits the While loop in which it appears. Execution continues with
the statement following the End While statement. Exit While can be used only
inside a While loop. When used within nested While loops, Exit While transfers
control to the loop that is one nested level above the loop where Exit While
occurs.
The If...Then selection structure performs an indicated action only when the
condition is True; otherwise the action is skipped.
If <condition> Then
statement
End If
Method 1
Method 2
If < condition 1 > Then
statements
Else
If < condition 2 > Then
statements
Else
If < condition 3 > Then
statements
Else
Statements
End If
End If
EndIf
e.g.: Assume you have to find the grade using nested if and display in a text box
average = txtAverage.Text
Select Case average
Case 100 To 75
txtGrade.Text ="A"
Case 74 To 65
txtGrade.Text ="B"
Case 64 To 55
txtGrade.Text ="C"
Case 54 To 45
txtGrade.Text ="S"
Case 44 To 0
txtGrade.Text ="F"
Case Else
MsgBox "Invalid average marks"
End Select
It is possible to use individual variables to store each of our data items. For
example, if our application analyzes student grades, we can use a separate
variable for each student's grade, such as englishGrade1, englishGrade2, etc.
This approach has three major limitations:
We have to know at design time exactly how many grades we have to handle.
It is difficult to maintain. Each new grade that we add requires that the
application be modified, recompiled, and redeployed.
By using an array, you can refer to these related values by the same name, and
use a number that’s called an index or subscript to identify an individual
element based on its position in the array. The indexes of an array range from 0
to one less than the total number of elements in the array. When you use Visual
Basic syntax to define the size of an array, you specify its highest index, not the
total number of elements in the array. You can work with the array as a unit, and
the ability to iterate its elements frees you from needing to know exactly how
many elements it contains at design time.
VB
' Change the size of an existing array to 16 elements and retain the current
values.
ReDim Preserve numbers(15)
' Redefine the size of an existing array and reset the values.
ReDim numbers(15)
The following illustration shows the students array. For each element of the
array:
The index of the element represents the grade (index 0 represents kindergarten).
The value that’s contained in the element represents the number of students in
that grade.
Diagram showing an array of the numbers of students
The following example contains the Visual Basic code that creates and uses the
array:
VB
Module SimpleArray
Public Sub Main()
' Declare an array with 7 elements.
Dim students(6) As Integer
Creating an array
You can define the size of an array in several ways:
VB
VB
VB
' Assign a new array size and retain the current values.
ReDim Preserve cargoWeights(20)
' Assign a new array size and retain only the first five values.
ReDim Preserve cargoWeights(4)
' Assign a new array size and discard all current element values.
ReDim cargoWeights(15)
For more information, see the ReDim Statement.
The following example shows some statements that store and retrieve values in
arrays.
VB
Module Example
Public Sub Main()
' Create a 10-element integer array.
Dim numbers(9) As Integer
Dim value As Integer = 2
When you create an array by using an array literal, you can either supply the
array type or use type inference to determine the array type. The following
example shows both options.
VB
VB
VB
Dim arr = {{1, 2.0}, {3, 4}, {5, 6}, {7, 8}}
For additional examples, see How to: Initialize an Array Variable in Visual
Basic.
VB
Module IterateArray
Public Sub Main()
Dim numbers = {10, 20, 30}
VB
Module IterateArray
Public Sub Main()
Dim numbers = {{1, 2}, {3, 4}, {5, 6}}
VB
Module IterateWithForEach
Public Sub Main()
' Declare and iterate through a one-dimensional array.
Dim numbers1 = {10, 20, 30}
Array size
The size of an array is the product of the lengths of all its dimensions. It
represents the total number of elements currently contained in the array. For
example, the following example declares a 2-dimensional array with four
elements in each dimension. As the output from the example shows, the array's
size is 16 (or (3 + 1) * (3 + 1).
VB
Module Example
Public Sub Main()
Dim arr(3, 3) As Integer
Console.WriteLine(arr.Length)
End Sub
End Module
' The example displays the following output:
' 16
VB
Module Example
Dim arr(99) As Integer
Console.WriteLine(arr.Length)
Redim arr(50)
Console.WriteLine(arr.Length)
End Sub
End Module
' The example displays the following output:
' 100
' 51
There are several things to keep in mind when dealing with the size of an array.
TABLE 1
Notes
Dimension Length The index of each dimension is 0-based, which means it
ranges from 0 to its upper bound. Therefore, the length of a given dimension is
one greater than the declared upper bound of that dimension.
Length Limits
The length of every dimension of an array is limited to the maximum value of
the Integer data type, which is Int32.MaxValue or (2 ^ 31) - 1. However, the
total size of an array is also limited by the memory available on your system. If
you attempt to initialize an array that exceeds the amount of available memory,
the runtime throws an Out Of Memory Exception.
Every array inherits from the System.Array class, and you can declare a variable
to be of type Array, but you cannot create an array of type Array. For example,
although the following code declares the arr variable to be of type Array and
calls the Array.CreateInstance method to instantiate the array, the array's type
proves to be Object[].
VB
Module Example
Public Sub Main()
Dim arr As Array = Array.CreateInstance(GetType(Object), 19)
Console.WriteLine(arr.Length)
Console.WriteLine(arr.GetType().Name)
End Sub
End Module
' The example displays the following output:
' 19
' Object[]
Also, the ReDim Statement cannot operate on a variable declared as type Array.
For these reasons, and for type safety, it is advisable to declare every array as a
specific type.
You can find out the data type of either an array or its elements in several ways.
You can call the GetType method on the variable to get a Type object that
represents the run-time type of the variable. The Type object holds extensive
information in its properties and methods.
You can pass the variable to the TypeName function to get a String with the
name of run-time type.
The following example calls the both the GetType method and the TypeName
function to determine the type of an array. The array type is Byte(,). Note that
the Type.BaseType property also indicates that the base type of the byte array is
the Array class.
VB
Module Example
Public Sub Main()
Dim bytes(9,9) As Byte
Console.WriteLine($"Type of {nameof(bytes)} array:
{bytes.GetType().Name}")
Console.WriteLine($"Base class of {nameof(bytes)}:
{bytes.GetType().BaseType.Name}")
Console.WriteLine()
Console.WriteLine($"Type of {nameof(bytes)} array: {TypeName(bytes)}")
End Sub
End Module
' The example displays the following output:
' Type of bytes array: Byte[,]
' Base class of bytes: Array
'
' Type of bytes array: Byte(,)
Dimension of an Array
Student
Name(1) Name(2) Name(3) Name(4)
Name
Declaring Array
We can use Public or Dim statement to declare an array just as the way we
declare a single variable. The Public statement declares an array that can be
used throughout an application while the Dim statement declares an array that
could be used only in a local procedure.
When you declare an array, you need to be aware of the number of elements
created by the Dim keyword. In the Dim arrayName(subscript)
statement, subscript actually is a constant that defines the maximum number of
elements allowed. More importantly, subs start with 0 instead of 1. Therefore,
the Dim arrangeName(10) statement creates 11 elements numbered 0 to 11.
There are two ways to overcome this problem, the first way is by uisng the
keyword Option Base 1, as shown in Example 1.
Example 1
Option Base 1
Dim CusName(10) as String
will declare an array that consists of 10 elements if the statement Option Base
1 appear in the declaration area, starting from CusName(1) to CusName(10).
Otherwise, there will be 11 elements in the array starting from CusName(0)
through to CusName(10)
The second way is to specify the lower bound and the upper bound of the
subscript using To keyword. The syntax is
Example 2
declares an array that consists of the first element starting from Count(100) and
ends at Count(500)
Example 3
Dim studentName(1 to 10) As String
Dim num As Integer
Private Sub addName()
For num = 1 To 10
studentName(num) = InputBox("Enter the student name","Enter Name", "",
1500, 4500)
If studentName(num)<>"" Then
Form1.Print studentName(num)
Else
End
End If
Next
End Sub
**The program accepts data entry through an input box and displays the entries
in the form itself.
Example 4
Dim studentName(1 to 10) As String
Dim num As Integer
Private Sub addName( )
For num = 1 To 10
studentName(num) = InputBox("Enter the student name")
List1.AddItem studentName(num)
Next
End Sub
Private Sub Start_Click()
addName
End Sub
**The program accepts data entries through an InputBox and displays the items
in a list box.
Example 5
will create an array of four rows and six columns, as shown in the following
table:
Year 7 8 9 10 11 12
Footba StuGame StuGame StuGame StuGames StuGames StuGames
ll s(1,7) s(1,8) s(1,9) (1,10) (1,11) (1,12)
Example 6
In this example, we want to summarize the first half-yearly sales volume for
four products. Therefore, we declare a two dimension array as follows:
Besides that, we want to display the output in a table form. Therefore, we use a
list box. We named the list box listVolume. AddItem is a listbox method to
populate the listbox.
The code
Private Sub cmdAdd_Click()
Dim prod, mth As Integer ' prod is product and mth is month
Dim saleVol(1 To 4, 1 To 6) As Integer
Const j = 1
listVolume.AddItem vbTab & "January" & vbTab & "February" & vbTab &
"March" _
& vbTab & "Apr" & vbTab & "May" & vbTab & "June"
listVolume.AddItem vbTab &
"____________________________________________"
For prod = 1 To 4
For mth = 1 To 6
saleVol(prod, mth) = InputBox("Enter the sale volume for" & " " & "product" &
" " & prod & " " & "month" & " " & mth)
Next mth
Next prod
For i = 1 To 4
listVolume.AddItem "Product" & "" & i & vbTab & saleVol(i, j) & vbTab &
saleVol(i, j + 1) & vbTab & saleVol(i, j + 2) _
& vbTab & saleVol(i, j + 3) & vbTab & saleVol(i, j + 4) & vbTab & saleVol(i, j
+ 5)
Next i
End Sub
Basically, you can create either static or dynamic arrays. Static arrays must
include a fixed number of items, and this number must be known at compile
time so that the compiler can set aside the necessary amount of memory. You
create a static array using a Dim statement with a constant argument:
' This is a static array.
Dim Names(100) As String
Visual Basic starts indexing the array with 0. Therefore, the preceding array
actually holds 101 items.
Most programs don't use static arrays because programmers rarely know at
compile time how many items you need and also because static arrays can't be
resized during execution. Both these issues are solved by dynamic arrays. You
declare and create dynamic arrays in two distinct steps. In general, you declare
the array to account for its visibility (for example, at the beginning of a module
if you want to make it visible by all the procedures of the module) using a Dim
command with an empty pair of brackets. Then you create the array when you
actually need it, using a ReDim statement:
Sub PrintReport()
' This array is visible only to the procedure.
ReDim Customers(1000) As String
' ...
End Sub
If you don't specify the lower index of an array, Visual Basic assumes it to be 0,
unless an Option Base 1 statement is placed at the beginning of the module. My
suggestion is this: Never use an Option Base statement because it makes code
reuse more difficult. (You can't cut and paste routines without worrying about
the current Option Base.) If you want to explicitly use a lower index different
from 0, use this syntax instead:
When you're resizing an array, you can't change the number of its dimensions
nor the type of the values it contains. Moreover, when you're using ReDim
Preserve on a multidimensional array, you can resize only its last dimension:
Finally, you can destroy an array using the Erase statement. If the array is
dynamic, Visual Basic releases the memory allocated for its elements (and you
can't read or write them any longer); if the array is static, its elements are set to
0 or to empty strings.
You can use the LBound and UBound functions to retrieve the lower and upper
indices. If the array has two or more dimensions, you need to pass a second
argument to these functions to specify the dimension you need:
UDT structures can include both static and dynamic arrays. Here's a sample
structure that contains both types:
Type MyUDT
StaticArr(100) As Long
DynamicArr() As Long
End Type
...
Dim udt As MyUDT
' You must DIMension the dynamic array before using it.
ReDim udt.DynamicArr(100) As Long
' You don't have to do that with static arrays.
udt.StaticArr(1) = 1234
The memory needed by a static array is allocated within the UDT structure; for
example, the StaticArr array in the preceding code snippet takes exactly 400
bytes. Conversely, a dynamic array in a UDT takes only 4 bytes, which form a
pointer to the memory area where the actual data is stored. Dynamic arrays are
advantageous when each individual UDT variable might host a different number
of array items. As with all dynamic arrays, if you don't dimension a dynamic
array within a UDT before accessing its items, you get an error 9—"Subscript
out of range."