Unit III Visual Basic
Unit III Visual Basic
Control Structure
Prgrams are not monolithic sets of commands that carry out the same
calculation every time they are executed. Instead, they adjust their behavior
depending on the data supplied or based on the result of a test condition. Visual
basic 6.0 provides three-control flow, or decision structures to take a course of
action depending on the outcome of the test. They are:
IF … Then
If … Then … Else
Select Case
IF Blocks in VB6.0
The If control flow blocks provide a great way for decision making where one or
more statements are executed depending upon a condition.
If-Then
In case of If-Then block, the condition is first checked. The condition can either
be True or False. If it is True, the statements inside the If-Then block is
executed. Otherwise, it does not execute the code in the If-Then block, the If-
Then structure is skipped. It starts executing the statements just after the 'End
if' phrase.
Syntax:
If Condition Then
statements
End If
If-Else
An If-Else block has two parts. If the condition is True then the first part is
executed, otherwise the control goes to the second part and starts executing
the lines of statements in the second part of the If-Else block.
Syntax:
If Condition Then
statements1
Else
statements2
End If
Output: 50
Nested If-Else
If you have programmed in other languages, you might probably know about
nested if-else control flow block. In VB it is the same concept. See the
syntax and the examples to capture the concept.
In nested if-else, the structure is little changed, little advanced better to say,
from the simple If-Block. Here if the first condition does not satisfy, it looks
for the next condition preceded by the ElseIf term, if that too does not
satisfy, it looks for the next, and it goes on until the end of the structure.
Syntax:
If Condition Then
statements
ElseIf Condition then
statements
ElseIf Condition Then
statements
.......................
......................
Else
statements
End If
Example:
a = Val(InputBox("Enter a no."))
If a > 0 Then
Print "Positive"
ElseIf a < 0 Then
Print "Negative"
Else
Print "Zero"
End If
In a nested if-else block, one If-Block can reside in another. See the example
below.
Example:
If a > 0 Then
Print "Positive"
If a > 2 Then
Print "Greater than 2"
Else
Print "Less than 2"
End If
Else
If a < 0 Then
Print "Negative"
End If
End If
Example:
The Select Case block provides an efficient way for decision making which is
used to execute one block of statement(s) among a list of statement blocks
according to the determined value of an expression. The expression is preceded
by the "Select Case" phrase. The choices are made based on the value of this
expression
Syntax:
Example:
One block of statement(s) will be executed depending upon the value of num.
If num=0 then, Case 0 will be evaluated and if num =1 then Case 1 will be
evaluated.
See the other forms of Select Case Structure in the following programs.
Example:
Example:
Do Loops
Loops are used to execute a block of statements repeatedly based on a condition.
i) Do While...Loop
ii) Do...Loop While
iii) Do...Loop Until.
The repeated execution of the statements inside the loop goes on as long as the
condition is true. When the condition becomes False, it exits the loop.
Syntax:
Do While Condition
statement(s)
Loop
Example: To print from 0 to 9.
The program first checks the condition. If num is less than 10, the statements
inside the Do While...Loop are executed. Again, the condition is checked. If it is
True, the statements are executed. In this way, the iterative execution goes on.
When the value of num becomes 10, the loop ends.
This loop structure first executes the statements and after that tests the condition
for the repeated execution.
Syntax:
Do
statement(s)
Output: 11
The Do...Loop Untill structure executes the statements repeatedly until the
condition is met. It is an infinite loop if the condition does not satisfy. In this
case, the program cannot be stopped. Press Ctrl+Break key combination to
force it to stop. The loop continues until the condition is met. The repeated
execution of the statements stops when the condition is met.
Syntax:
Do
statement(s)
Example:
Dim x As Integer
x=0
Do
x=x+1
Loop Until x > 10
MsgBox x
For...Next Loops
For...Next loop structure is useful when a block of statements are to be executed for
unknown number of times. But if a block of statements are to be executed for specified
number of times then a For … Next loop is better choice. Unlike a Do loop, a For loop uses
a variable called a counter that increases or deceases in value during each repetition of the
loop.
Syntax
Statements
Next [counter]
The argument counter, start, end, and increment are all numeric. The increment
argument can be either positive or negative If increment is positive, start must
be less than or equal to end or the statements in the loop will not execute. If
increment is negative, start must be greater than or equal to end for the body
of the loop to execute. If Step isn‟t set, then increment defaults to 1.
Dim i As Integer
For i = 0 To 10
Print i
Next i
Dim i As Integer
For i = 0 To 6 Step 2
Print i
Next i
Dim i As Integer
For i = 10 To 0 Step -3
Print i
Next i
Output:
10
7
4
1
Syntax
Statements
Next element
Output:
0
1
2
If num = 4 Then
Exit Do
End If
Loop
Output:
0
1
2
3
Output:
Example:
Example:
Output:
If you assign Check1.Value =1 then the CheckBox is checked and if
Check1.Value = 0 then it is unchecked. If Check1.Value = 2 then the checkbox
is grayed.
Example: The previous program can also be written in the following way.
Output:
If chkCoffee.Value = 1 Then
Print "Coffee"
End If
If chkPizza.Value = 1 Then
Print "Pizza"
End If
If chkChocolate.Value = 1 Then
Print "Chocolate"
End If
End Sub
Output:
Syntax:
Select Case expression
Case value0
statements
Case value1
statements
Case value2
statements
...........
...............
Case else
statements
End select
Example:
Dim num As Integer
num = Val(Text1.Text)
Select Case num
Case 0
Print "You have entered zero"
Case 1
Print "You have entered one"
Case 2
Print "You have entered two"
Case Else
Print "The number you entered is greater than 2"
End Select
One block of statement(s) will be executed depending upon the value of num.
If num=0 then, Case 0 will be evaluated and if num =1 then Case 1 will be
evaluated.
See the other forms of Select Case Structure in the following programs.
Example:
Dim score As Integer
score = Val(Text1.Text)
Select Case score
Case 900 To 1000
Print "First position"
Case 800 To 899
Print "Second position"
Case 700 To 799
Print "Third position"
Case Else
Print "No position, try again"
End Select
Example:
Dim num As Integer
num = Val(Text1.Text)
Select Case num
Case Is > 0
Print "Positive number"
Case Is < 0
Print "Negative number"
Case 0
Print "Zero"
End Select
Example:
Select Case value
Case 0, 1, 2, 3, 4, 5
Print "The values are 0,1,2,3,4,5"
Case Else
Print "Other values"
End Select
Arrays
An array is a collection of items of the same data type. All items have the same
name and they are identified by a subscript or index. When you need to work
with several similar data values, you can use array to eliminate the difficulties
of declaring so many variables. For example, if you want to compute the daily
sales and sum the sales amount after 30 days, you don't need to have 30
variables. Just simply declare an array of size 30 and get your work done !
Declaring an array
Syntax: Dim Variable_Name(index) As [Type]
Example:
Dim month(10) As Integer '11 elements
'or
Dim month(1 to 12) as Integer '12 elements
Types of array
The array used in the example is a one-dimensional and fixed-size array. An
array can have more than one dimension. The other types of arrays are multi-
dimensional arrays, Dynamic arrays and Control arrays.
Fixed-Size Array: We know the total number of items the array in the above
example holds. So that is a Fixed-Size array.
The LBound and UBound functions
The LBound and Ubound functions return the lower bound and upper bound of
an array respectively.
Example:
MsgBox "Lower bound = " & a & " Upper bound = " & b
End Sub
Initializing an array
You can use For Loop to initialize an array.
Example:
Dim day(10) As Integer, i As Integer
For i = 0 To 10
day(i) = InputBox("Enter day value")
Next i
You can also initialize each array item separately in the way a variable is
initialized.
Example: This program inputs the Sale amount of each day and sums the total
amount of 5 days.
For i = 1 To 5
SaleDay(i) = InputBox("Enter Sale amount of Day " & i)
Sale = Sale + SaleDay(i)
Next i
End Sub
Multi-Dimensional Arrays:
An array can be multi-dimensional that means, it can have more than one
dimension. A list of data is represented in a one-dimensional array where a
multi-dimensional array represents a table of data. An array can be two
dimensional, three dimensional and so on. We generally don't need an array of
more than two dimensions, it is enough to use one and two dimensional arrays.
You can use a higher dimensional array when the program is too complex. A
two dimensional array takes the row-column form.
Declaration:
Dim value(5, 5) As Integer 'two dimensional
'Or,
Dim value(1 to 5, 1 to 5) As Double
Dim number(6, 9, 8) As Integer 'three dimensinoal
Initialization:
To initialize the array elements, you first need to recognize the array elements.
For example, the array 'value(2, 2)' has 9 elements. They are
value(0,0), value(0,1),value(0,2), value(1,0), value(1,1), value(1,2), value(2,0
), value(2,1), value(2,2). For the initialization, you may wish to use For Loop or
initialize each element like variables. Using For Loop is a better choice as it
reduces the number of lines of code. But sometimes, separately initializing each
element like a variable is much more convenient. And it also depends on the
type of program you are writing.
'initializiation of matrix2
matrix2(0, 0) = Val(Text5.Text)
matrix2(0, 1) = Val(Text6.Text)
matrix2(1, 0) = Val(Text7.Text)
matrix2(1, 1) = Val(Text8.Text)
Next j
Print ""
Next i
End Sub
Static array
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:
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:
Dynamic Array
In case of a fixed size array, we have seen that the size of the array is fixed or
unchanged, but there may be some situations where you may want to change
the array size. A dynamic arraycan be resized at run time whenever you want.
Declaring dynamic arrays
1. Declare the array with empty dimension list.
Example : Dim arr() As Integer
Example:
Note: Unlike the Dim and Static statements, the ReDim statements are
executable. So a ReDim statement can only be in a procedure and when you
execute the ReDim statement, all the values stored in the array are lost. You
can use the ReDim statement repeatedly to change the array size.
Example:
For i = 0 To 2
arr(i) = InputBox("Enter the value")
Next i
Output: If the input values through InputBox are 5,6,7 then the following will be
printed on the form.
5 6 7 9